feat: add exa-search skill for neural web search, extraction, and find-similar

Adds a new skill sibling to parallel-web that wraps the Exa API. Covers
web search, URL content extraction, and find-similar-by-URL, with academic
source strategy built in (category="research paper" plus scholarly
domain allowlists).

- scientific-skills/exa-search/SKILL.md — routing, setup, academic strategy
- scientific-skills/exa-search/references/{web-search,web-extract,find-similar}.md
- scientific-skills/exa-search/scripts/{exa_search,exa_extract,exa_find_similar}.py
  (CLI wrappers using exa-py; PEP 723 inline deps so `uv run` works without
  a separate install)
- scientific-skills/exa-search/tests/test_exa_search.py — 21 unit tests
  covering CLI plumbing, content-option building, CSV domain splitting,
  result-typing fallbacks, and auth error handling
- docs/scientific-skills.md — index entry under Web Search & Information
  Retrieval, matching the Paperzilla precedent (PR #131)
This commit is contained in:
Teo Gonzalez Collazo committed 2026-04-23 16:15:36 -07:00
1 parent 25e1c0f569
commit d10c002a8c
9 files changed
+1073

No files matched your search

+1
View File
@@ -206,4 +206,5 @@
- **What-If Oracle** - Run structured What-If scenario analysis with multi-branch possibility exploration. Use for speculative questions, scenario planning, risk analysis, contingency planning, strategic options evaluation, stress-testing ideas, and thinking through consequences before committing
### Web Search & Information Retrieval
- **Exa Search** - Neural (embedding-based) web search, URL content extraction, and find-similar-by-URL via the Exa API. Use for semantic search where keyword matching falls short, scholarly filtering via `category="research paper"` plus academic domain allowlists, batch URL extraction with optional LLM summaries, and surfacing pages related to a reference URL (more papers like this one, competitors of this company)
- **Parallel Web** - Search the web, extract URL content, and run deep research using the Parallel Chat API and Extract API. Use for web searches, research queries, and general information gathering with synthesized summaries and citations
+100
View File
@@ -0,0 +1,100 @@
---
name: exa-search
description: "Web toolkit powered by Exa, with neural (embedding-based) search tuned for scientific and technical content. Use this skill when the user needs to search the web, fetch/extract URL content, or find pages similar to a reference URL. Covers: web search (semantic lookups, research, current info — with optional research-paper category and academic domain filtering), URL extraction (fetching pages, articles, academic PDFs, with optional LLM summaries), and find-similar (given a seed URL, surface related papers, articles, or companies via neural embeddings). Use this skill for web-related tasks when the user wants semantic/neural search, scholarly filtering via category=research paper, or similarity retrieval from a seed URL. Triggers on requests to search, look up, fetch a page, extract an article, find papers like <URL>, or find competitors of <company URL>."
compatibility: Requires exa-py Python SDK, an EXA_API_KEY, and internet access.
license: MIT
metadata:
skill-author: Exa
website: https://exa.ai
docs: https://exa.ai/docs
---
# Exa Web Toolkit
A skill for web-powered research tasks backed by [Exa](https://exa.ai): semantic (neural) web search, URL extraction, and find-similar. Exa's index is embedding-based, which makes it well-suited to scientific, technical, and conceptual queries where the right answer isn't obvious from keyword matches alone.
## Routing — pick the right capability
Read the user's request and match it to one of the capabilities below. Read the corresponding reference file for detailed instructions before running commands.
| User wants to... | Capability | Where |
|---|---|---|
| Look something up, research a topic, find current info | **Web Search** | `references/web-search.md` |
| Fetch content from a specific URL (webpage, article, PDF) | **Web Extract** | `references/web-extract.md` |
| Find pages similar to a reference URL (more papers like this one, competitors of this company) | **Find Similar** | `references/find-similar.md` |
| Install or authenticate | **Setup** | Below |
### Decision guide
- **Default to Web Search** for topic lookups, research questions, or "what is X?" queries. When the topic is scientific or technical, pass `--category "research paper"` to bias toward scholarly sources, and/or an academic `--include-domains` allowlist. See `references/web-search.md` for the two-pass academic strategy.
- **Use Web Extract** when the user provides a URL or asks you to read/fetch a specific page. Prefer this over the built-in WebFetch for batch extraction (multiple URLs in one call) and for academic PDFs where you want a focused LLM summary alongside the raw text.
- **Use Find Similar** when the user has a seed URL and wants related content — "more papers like this", "competitors of <company>", "follow-up work to <paper>". This is an Exa specialty: neural embeddings surface semantically related pages that keyword search will miss.
- If the user only describes a topic (no URL), use Web Search, not Find Similar.
### Academic source priority
For technical or scientific queries, prefer academic and scientific sources:
- Peer-reviewed journal articles and conference proceedings over blog posts or news
- Preprints (arXiv, bioRxiv, medRxiv) when peer-reviewed versions aren't available
- Institutional and government sources (NIH, WHO, NASA, NIST) over commercial sites
- Primary research over secondary summaries
Two levers to steer Exa toward scholarly content:
1. `--category "research paper"` biases the neural retrieval itself.
2. `--include-domains` with a scholarly allowlist (arxiv.org, nature.com, pubmed.ncbi.nlm.nih.gov, etc.) restricts the domain pool.
Combine both for strictly academic results. See `references/web-search.md` for the full pattern.
When citing academic sources, include author names and publication year where available (e.g., [Smith et al., 2025](url)) in addition to the standard citation format. If a DOI is present, prefer the DOI link.
---
## Setup
This skill uses the [`exa-py`](https://github.com/exa-labs/exa-py) Python SDK. The scripts in `scripts/` declare their dependencies via PEP 723 inline metadata, so you can run them directly with `uv run` without a separate install step:
```bash
uv run --with exa-py python "$SKILL_PATH/scripts/exa_search.py" --help
```
If you prefer a persistent install:
```bash
uv pip install "exa-py>=1.14.0"
```
### Authentication
All commands read the API key from the `EXA_API_KEY` environment variable. Get a key at [exa.ai/dashboard](https://exa.ai/dashboard).
First, check if a `.env` file exists in the project root and contains `EXA_API_KEY`. If so, load it:
```bash
dotenv -f .env run -- uv run --with exa-py python "$SKILL_PATH/scripts/exa_search.py" "your query"
```
If `dotenv` isn't available, install it: `pip install python-dotenv[cli]` or `uv pip install python-dotenv[cli]`.
If there's no `.env`, export the key for the session:
```bash
export EXA_API_KEY="your-key"
```
Verify by running any script with `--help` — it will exit cleanly if the key is set and auth-check runs only when a real query is made.
### Tracking header
Every script in this skill sets the `x-exa-integration` request header to `scientific-agent-skills` so Exa can attribute usage to this integration. Do not remove this header when adapting the scripts.
---
## Files in this skill
- `SKILL.md` — this file (routing and setup)
- `references/web-search.md` — detailed web search reference with academic strategy
- `references/web-extract.md` — URL content extraction reference
- `references/find-similar.md` — find-similar-by-URL reference
- `scripts/exa_search.py` — CLI wrapper around `client.search_and_contents`
- `scripts/exa_extract.py` — CLI wrapper around `client.get_contents`
- `scripts/exa_find_similar.py` — CLI wrapper around `client.find_similar_and_contents`
@@ -0,0 +1,57 @@
# Find Similar
Find pages similar to: $ARGUMENTS
## When to use
Use **find-similar** when the user already has a reference URL — a specific paper, article, company homepage, or blog post — and wants more like it. Find-similar uses Exa's neural embeddings to surface pages that are semantically related to the seed URL rather than keyword-matched.
Common patterns:
- "Find more papers like this one: <arxiv URL>"
- "Show me competitors of <company URL>"
- "Find follow-up / citation-style work to <paper URL>"
- "What other posts cover the same angle as <blog URL>?"
When the user only describes a topic (no URL), use **web-search** instead.
## Command
Choose a short, descriptive filename (e.g., `similar-to-mixtral`, `egfr-related-work`). Use lowercase with hyphens, no spaces.
```bash
uv run --with exa-py python "$SKILL_PATH/scripts/exa_find_similar.py" "$URL" \
--num-results 10 \
--exclude-source-domain \
--text --highlights \
-o "$FILENAME.json"
```
`--exclude-source-domain` drops results from the same domain as the seed URL. Useful when the seed is from a large site (nature.com, arxiv.org) and you want cross-domain coverage rather than sibling articles on the same platform.
## Refinement options
- `--category "research paper"` when the seed is a scholarly URL and you want only scholarly results back
- `--include-domains` / `--exclude-domains` for tighter filtering on top of the neural match
- `--start-published-date YYYY-MM-DD` to restrict to a time window (e.g., only find recent follow-ups to an older seed paper)
## Academic source strategy
For papers, always add `--category "research paper"`:
```bash
uv run --with exa-py python "$SKILL_PATH/scripts/exa_find_similar.py" "$URL" \
--category "research paper" \
--num-results 15 \
--exclude-source-domain \
--text --highlights \
-o "$FILENAME.json"
```
This biases results toward other scholarly work rather than news write-ups or blog posts about the seed paper.
## Response format
Same conventions as web search:
- Every claim cited inline as `[Author et al., Year](url)` for academic results or `[Source Title](url)` otherwise
- Mandatory **Sources** section at the end, grouped by Academic / Peer-reviewed vs. Other
- Mention the output file path (`$FILENAME.json`) so the user can ask follow-up questions
@@ -0,0 +1,56 @@
# URL Extraction
Extract content from: $ARGUMENTS
## Command
Choose a short, descriptive filename based on the URL or content (e.g., `alphafold-paper`, `nature-editorial`). Use lowercase with hyphens, no spaces.
```bash
uv run --with exa-py python "$SKILL_PATH/scripts/exa_extract.py" "$ARGUMENTS" \
--text \
-o "$FILENAME.json"
```
You can pass multiple URLs as positional arguments — the script batches them in a single `/contents` call, which is faster and cheaper than looping.
Content modes:
- `--text` (default if nothing else is passed) returns full-text content
- `--highlights` returns extracted passages instead of full text
- `--summary "focus area"` returns an LLM summary focused on the given aspect
## Academic content handling
When extracting from academic sources (arXiv, PubMed, journal sites, conference proceedings), prefer `--summary` with a focused query, or combine `--text` with `--summary`:
```bash
uv run --with exa-py python "$SKILL_PATH/scripts/exa_extract.py" "$URL" \
--text \
--summary "abstract, methodology, key findings, and conclusions" \
-o "$FILENAME.json"
```
For arXiv, either the `/abs/` page URL or the raw PDF URL works. Prefer `/abs/` when available — it has cleaner metadata (title, authors, published date) attached to the result.
## Response format
Return content as:
**[Page Title](URL)**
For academic papers, include structured metadata when available:
- **Authors:** list of authors (from the `author` field)
- **Published:** from `published_date`
- **Abstract / Summary:** from `summary` if requested
Then the extracted content, with these rules:
- Keep content verbatim — do not paraphrase or summarize unless `--summary` was used
- Parse lists exhaustively — extract EVERY numbered/bulleted item
- Strip only obvious noise: nav menus, footers, ads
- Preserve all facts, names, numbers, dates, quotes
- For academic papers, preserve figure/table captions and references
**Partial-result handling** — when batching multiple URLs, one or more may fail (paywall, robots.txt, timeout). Report which URLs extracted successfully and which failed, rather than silently dropping failures.
After the response, mention the output file path (`$FILENAME.json`) so the user knows it's available for follow-up questions.
@@ -0,0 +1,123 @@
# Web Search
Search the web for: $ARGUMENTS
## Command
Choose a short, descriptive filename based on the query (e.g., `ai-chip-news`, `crispr-off-target`). Use lowercase with hyphens, no spaces.
```bash
uv run --with exa-py python "$SKILL_PATH/scripts/exa_search.py" "$ARGUMENTS" \
--num-results 10 \
--text --highlights \
-o "$FILENAME.json"
```
`$SKILL_PATH` is the path to this skill directory. The `-o` flag saves the full results to a JSON file so follow-up questions can reuse them without re-querying.
**Search type selection** — `--type` controls retrieval mode:
| Mode | When to use |
|---|---|
| `auto` (default) | Exa picks neural vs. keyword per query. Use this unless you have a reason not to. |
| `neural` | Force semantic/embedding retrieval. Best for conceptual or exploratory queries ("papers that propose *alternatives* to attention"). |
| `fast` | Lowest latency. Use for simple lookups where speed matters more than nuance. |
**Content modes** — add any combination:
- `--text` returns full-text content per result
- `--highlights` returns the most relevant passages (good signal-to-noise, lower token cost than full text)
- `--summary` returns an LLM summary; pass a focus string to direct it, e.g. `--summary "experimental methods and sample size"`
Default to `--highlights` for broad searches (cheaper, more skimmable). Add `--text` only when you need to quote or extract in detail.
**Filtering options** — Exa supports rich filtering via the SDK:
- `--start-published-date YYYY-MM-DD` / `--end-published-date YYYY-MM-DD` for time-sensitive queries
- `--include-domains domain1.com,domain2.com` to restrict to an allowlist
- `--exclude-domains spam.com,low-quality.com` to drop a blocklist
- `--category "research paper"` to bias toward scholarly content (also: `company`, `news`, `pdf`, `github`, `tweet`, `personal site`, `linkedin profile`, `financial report`, `people`)
- `--user-location US` for locale-specific results
## Academic source strategy
For scientific or technical queries, Exa has two strong levers:
### 1. Use `--category "research paper"`
```bash
uv run --with exa-py python "$SKILL_PATH/scripts/exa_search.py" "$ARGUMENTS" \
--category "research paper" \
--num-results 10 \
--text --highlights \
-o "$FILENAME-academic.json"
```
This biases retrieval toward papers indexed as scholarly content (journals, preprint servers, conference proceedings) rather than blogs or news coverage.
### 2. Restrict to scholarly domains
For stricter academic filtering, combine the category with an explicit domain allowlist:
```bash
uv run --with exa-py python "$SKILL_PATH/scripts/exa_search.py" "$ARGUMENTS" \
--category "research paper" \
--include-domains "arxiv.org,biorxiv.org,medrxiv.org,pubmed.ncbi.nlm.nih.gov,ncbi.nlm.nih.gov,nature.com,science.org,cell.com,pnas.org,nih.gov,semanticscholar.org,scholar.google.com,ieee.org,acm.org,springer.com,wiley.com" \
--num-results 15 \
--text --highlights \
-o "$FILENAME-academic.json"
```
### Two-pass pattern for comprehensive coverage
Run **both** an academic-focused search and an unrestricted one, then merge with academic sources first:
1. Academic pass: `--category "research paper"` with the scholarly domain allowlist above.
2. General pass: the standard command without `--category` or `--include-domains`, to catch relevant non-academic sources (news coverage, lab blogs, institutional pages).
Merge results, leading with academic sources. If the query is clearly non-scientific, skip the academic pass.
**When to use the two-search pattern:** Any query involving scientific claims, medical information, research findings, technical mechanisms, statistical data, or anything where primary literature would be more reliable than secondary reporting.
## Parsing results
Parse the JSON output. Each result includes:
- `title`, `url`, `published_date`, `author`
- `score` — Exa's relevance score for the query
- `text` (if `--text`), `highlights` + `highlight_scores` (if `--highlights`), `summary` (if `--summary`)
**Snippet fallback** — any combination of content fields may be present. Cascade through them: prefer `highlights` (tight, pre-selected passages), fall back to `summary`, fall back to a truncated slice of `text`. Never assume exactly one is present.
## Response format
**CRITICAL: Every claim must have an inline citation.** Use markdown links pulling only from the JSON output. Never invent or guess URLs.
For academic sources, use author-year citation style where metadata is available:
- Academic: [Smith et al., 2025](url) or [Smith & Jones, 2024](url)
- Non-academic: [Source Title](url)
Synthesize a response that:
- Leads with findings from peer-reviewed or preprint sources when available
- Clearly distinguishes between claims backed by primary research vs. secondary reporting
- Includes specific facts, names, numbers, dates
- Cites every fact inline — do not leave any claim uncited
- Organizes by theme if multiple topics
- Notes the evidence quality (e.g., "a randomized controlled trial found..." vs. "a blog post reports...")
**End with a Sources section** listing every URL referenced, grouped by type:
```
Sources:
Academic / Peer-reviewed:
- [Smith et al., 2025 — Title of Paper](https://doi.org/...) (Nature, 2025)
- [Jones & Lee, 2024 — Title of Paper](https://arxiv.org/...) (arXiv preprint)
Other:
- [Source Title](https://example.com/article) (Feb 2026)
```
This Sources section is mandatory. Do not omit it. If no academic sources were found, note that and explain why (e.g., the topic is too recent, not yet studied, or inherently non-academic).
After the Sources section, mention the output file path (`$FILENAME.json`) so the user knows it's available for follow-up questions.
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = ["exa-py>=1.14.0"]
# ///
"""Fetch and extract content from URLs using Exa's /contents endpoint.
Example:
uv run exa_extract.py \\
https://arxiv.org/abs/2401.04088 \\
https://www.nature.com/articles/s41586-024-07566-y \\
--text --summary "methods and key findings" \\
-o extracted.json
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from dataclasses import asdict, dataclass, field
from typing import Any
try:
from exa_py import Exa
except ImportError:
print(
"exa_py not installed. Run: uv pip install exa-py (or invoke with: uv run --with exa-py)",
file=sys.stderr,
)
sys.exit(2)
EXA_INTEGRATION_HEADER = "scientific-agent-skills"
@dataclass
class ExtractedDocument:
"""Typed view of a single extracted document for JSON export."""
url: str
id: str | None
title: str | None
author: str | None
published_date: str | None
text: str | None = None
highlights: list[str] = field(default_factory=list)
summary: str | None = None
def _build_contents(text: bool, highlights: bool, summary: str | None) -> dict[str, Any]:
contents: dict[str, Any] = {}
if text:
contents["text"] = True
if highlights:
contents["highlights"] = True
if summary is not None:
contents["summary"] = {"query": summary} if summary else True
if not contents:
# Default to full text when the caller doesn't pick anything.
contents["text"] = True
return contents
def _to_typed(item: Any) -> ExtractedDocument:
return ExtractedDocument(
url=getattr(item, "url", ""),
id=getattr(item, "id", None),
title=getattr(item, "title", None),
author=getattr(item, "author", None),
published_date=getattr(item, "published_date", None),
text=getattr(item, "text", None),
highlights=list(getattr(item, "highlights", None) or []),
summary=getattr(item, "summary", None),
)
def run(args: argparse.Namespace) -> dict[str, Any]:
api_key = os.environ.get("EXA_API_KEY")
if not api_key:
print("EXA_API_KEY environment variable is not set.", file=sys.stderr)
sys.exit(2)
client = Exa(api_key=api_key)
client.headers["x-exa-integration"] = EXA_INTEGRATION_HEADER
contents = _build_contents(args.text, args.highlights, args.summary)
response = client.get_contents(urls=args.urls, **contents)
typed = [_to_typed(item) for item in getattr(response, "results", []) or []]
return {
"urls": list(args.urls),
"num_results": len(typed),
"results": [asdict(doc) for doc in typed],
}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Extract content from URLs with Exa.")
parser.add_argument("urls", nargs="+", help="One or more URLs to extract.")
parser.add_argument("--text", action="store_true", help="Return full-text content.")
parser.add_argument("--highlights", action="store_true", help="Return extracted highlight snippets.")
parser.add_argument(
"--summary",
nargs="?",
const="",
default=None,
help="Return LLM summary. Optional value is a query to focus the summary.",
)
parser.add_argument("-o", "--output", default=None, help="Write JSON to this file (default: stdout).")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
payload = run(args)
text = json.dumps(payload, indent=2, ensure_ascii=False)
if args.output:
with open(args.output, "w", encoding="utf-8") as fh:
fh.write(text)
print(f"Wrote {len(payload['results'])} documents to {args.output}")
else:
print(text)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,182 @@
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = ["exa-py>=1.14.0"]
# ///
"""Find pages similar to a given URL via Exa's find_similar endpoint.
Example:
uv run exa_find_similar.py \\
https://arxiv.org/abs/2401.04088 \\
--num-results 10 \\
--exclude-source-domain \\
--text --highlights \\
-o similar.json
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from dataclasses import asdict, dataclass, field
from typing import Any
try:
from exa_py import Exa
except ImportError:
print(
"exa_py not installed. Run: uv pip install exa-py (or invoke with: uv run --with exa-py)",
file=sys.stderr,
)
sys.exit(2)
EXA_INTEGRATION_HEADER = "scientific-agent-skills"
@dataclass
class SimilarResult:
"""Typed view of a single find-similar result for JSON export."""
title: str | None
url: str
id: str | None
author: str | None
published_date: str | None
score: float | None
text: str | None = None
highlights: list[str] = field(default_factory=list)
summary: str | None = None
def _split_csv(value: str | None) -> list[str] | None:
if not value:
return None
items = [item.strip() for item in value.split(",") if item.strip()]
return items or None
def _build_contents(text: bool, highlights: bool, summary: str | None) -> dict[str, Any] | None:
contents: dict[str, Any] = {}
if text:
contents["text"] = True
if highlights:
contents["highlights"] = True
if summary is not None:
contents["summary"] = {"query": summary} if summary else True
return contents or None
def _to_typed(item: Any) -> SimilarResult:
return SimilarResult(
title=getattr(item, "title", None),
url=getattr(item, "url", ""),
id=getattr(item, "id", None),
author=getattr(item, "author", None),
published_date=getattr(item, "published_date", None),
score=getattr(item, "score", None),
text=getattr(item, "text", None),
highlights=list(getattr(item, "highlights", None) or []),
summary=getattr(item, "summary", None),
)
def run(args: argparse.Namespace) -> dict[str, Any]:
api_key = os.environ.get("EXA_API_KEY")
if not api_key:
print("EXA_API_KEY environment variable is not set.", file=sys.stderr)
sys.exit(2)
client = Exa(api_key=api_key)
client.headers["x-exa-integration"] = EXA_INTEGRATION_HEADER
contents = _build_contents(args.text, args.highlights, args.summary)
kwargs: dict[str, Any] = {
"url": args.url,
"num_results": args.num_results,
"exclude_source_domain": args.exclude_source_domain,
}
if include := _split_csv(args.include_domains):
kwargs["include_domains"] = include
if exclude := _split_csv(args.exclude_domains):
kwargs["exclude_domains"] = exclude
if args.start_published_date:
kwargs["start_published_date"] = args.start_published_date
if args.end_published_date:
kwargs["end_published_date"] = args.end_published_date
if args.category:
kwargs["category"] = args.category
if contents is not None:
response = client.find_similar_and_contents(**kwargs, **contents)
else:
response = client.find_similar(**kwargs)
typed = [_to_typed(item) for item in getattr(response, "results", []) or []]
return {
"url": args.url,
"num_results": len(typed),
"results": [asdict(result) for result in typed],
}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Find pages similar to a URL with Exa.")
parser.add_argument("url", help="Seed URL to find similar pages for.")
parser.add_argument("--num-results", type=int, default=10, help="Number of results (1-100).")
parser.add_argument(
"--exclude-source-domain",
action="store_true",
help="Exclude results from the same domain as the seed URL.",
)
parser.add_argument("--include-domains", default=None, help="Comma-separated allowlist.")
parser.add_argument("--exclude-domains", default=None, help="Comma-separated blocklist.")
parser.add_argument("--start-published-date", default=None, help="ISO date, e.g. 2024-01-01.")
parser.add_argument("--end-published-date", default=None, help="ISO date, e.g. 2024-12-31.")
parser.add_argument(
"--category",
default=None,
choices=[
"company",
"research paper",
"news",
"pdf",
"github",
"tweet",
"personal site",
"linkedin profile",
"financial report",
"people",
],
help="Bias results toward a content category.",
)
parser.add_argument("--text", action="store_true", help="Return full-text content per result.")
parser.add_argument("--highlights", action="store_true", help="Return extracted highlight snippets.")
parser.add_argument(
"--summary",
nargs="?",
const="",
default=None,
help="Return LLM summary. Optional value is a query to focus the summary.",
)
parser.add_argument("-o", "--output", default=None, help="Write JSON to this file (default: stdout).")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
payload = run(args)
text = json.dumps(payload, indent=2, ensure_ascii=False)
if args.output:
with open(args.output, "w", encoding="utf-8") as fh:
fh.write(text)
print(f"Wrote {len(payload['results'])} results to {args.output}")
else:
print(text)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,197 @@
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = ["exa-py>=1.14.0"]
# ///
"""Run an Exa web search and write results to JSON.
Uses the Exa Python SDK. Auth via the EXA_API_KEY environment variable.
Example:
uv run exa_search.py "transformer architectures" \\
--num-results 10 \\
--category "research paper" \\
--include-domains arxiv.org,nature.com \\
--start-published-date 2024-01-01 \\
--text --highlights \\
-o results.json
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from dataclasses import asdict, dataclass, field
from typing import Any
try:
from exa_py import Exa
except ImportError:
print(
"exa_py not installed. Run: uv pip install exa-py (or invoke with: uv run --with exa-py)",
file=sys.stderr,
)
sys.exit(2)
EXA_INTEGRATION_HEADER = "scientific-agent-skills"
@dataclass
class SearchResult:
"""Typed view of a single Exa search result for JSON export."""
title: str | None
url: str
id: str | None
author: str | None
published_date: str | None
score: float | None
text: str | None = None
highlights: list[str] = field(default_factory=list)
highlight_scores: list[float] = field(default_factory=list)
summary: str | None = None
def _split_csv(value: str | None) -> list[str] | None:
if not value:
return None
items = [item.strip() for item in value.split(",") if item.strip()]
return items or None
def _build_contents(text: bool, highlights: bool, summary: str | None) -> dict[str, Any] | None:
contents: dict[str, Any] = {}
if text:
contents["text"] = True
if highlights:
contents["highlights"] = True
if summary is not None:
# Empty string means "use default summary"; any other string is a custom query
contents["summary"] = {"query": summary} if summary else True
return contents or None
def _result_to_typed(item: Any) -> SearchResult:
highlights = list(getattr(item, "highlights", None) or [])
scores = list(getattr(item, "highlight_scores", None) or [])
return SearchResult(
title=getattr(item, "title", None),
url=getattr(item, "url", ""),
id=getattr(item, "id", None),
author=getattr(item, "author", None),
published_date=getattr(item, "published_date", None),
score=getattr(item, "score", None),
text=getattr(item, "text", None),
highlights=highlights,
highlight_scores=scores,
summary=getattr(item, "summary", None),
)
def run(args: argparse.Namespace) -> dict[str, Any]:
api_key = os.environ.get("EXA_API_KEY")
if not api_key:
print("EXA_API_KEY environment variable is not set.", file=sys.stderr)
sys.exit(2)
client = Exa(api_key=api_key)
# Attribute API usage to this skill for integration tracking.
client.headers["x-exa-integration"] = EXA_INTEGRATION_HEADER
contents = _build_contents(args.text, args.highlights, args.summary)
kwargs: dict[str, Any] = {
"query": args.query,
"num_results": args.num_results,
"type": args.type,
}
if args.category:
kwargs["category"] = args.category
if include := _split_csv(args.include_domains):
kwargs["include_domains"] = include
if exclude := _split_csv(args.exclude_domains):
kwargs["exclude_domains"] = exclude
if args.start_published_date:
kwargs["start_published_date"] = args.start_published_date
if args.end_published_date:
kwargs["end_published_date"] = args.end_published_date
if args.user_location:
kwargs["user_location"] = args.user_location
if contents is not None:
response = client.search_and_contents(**kwargs, **contents)
else:
response = client.search(**kwargs)
typed = [_result_to_typed(item) for item in getattr(response, "results", []) or []]
return {
"query": args.query,
"type": args.type,
"num_results": len(typed),
"autoprompt_string": getattr(response, "autoprompt_string", None),
"results": [asdict(result) for result in typed],
}
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Search the web with Exa.")
parser.add_argument("query", help="Natural-language search query.")
parser.add_argument(
"--type",
default="auto",
choices=["auto", "neural", "fast"],
help="Search type. 'auto' lets Exa pick; 'neural' forces semantic; 'fast' is lowest latency.",
)
parser.add_argument("--num-results", type=int, default=10, help="Number of results (1-100).")
parser.add_argument(
"--category",
default=None,
choices=[
"company",
"research paper",
"news",
"pdf",
"github",
"tweet",
"personal site",
"linkedin profile",
"financial report",
"people",
],
help="Bias results toward a content category.",
)
parser.add_argument("--include-domains", default=None, help="Comma-separated allowlist.")
parser.add_argument("--exclude-domains", default=None, help="Comma-separated blocklist.")
parser.add_argument("--start-published-date", default=None, help="ISO date, e.g. 2024-01-01.")
parser.add_argument("--end-published-date", default=None, help="ISO date, e.g. 2024-12-31.")
parser.add_argument("--user-location", default=None, help="Two-letter ISO country code.")
parser.add_argument("--text", action="store_true", help="Return full-text content per result.")
parser.add_argument("--highlights", action="store_true", help="Return extracted highlight snippets.")
parser.add_argument(
"--summary",
nargs="?",
const="",
default=None,
help="Return LLM summary. Optional value is a query to focus the summary.",
)
parser.add_argument("-o", "--output", default=None, help="Write JSON to this file (default: stdout).")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
payload = run(args)
text = json.dumps(payload, indent=2, ensure_ascii=False)
if args.output:
with open(args.output, "w", encoding="utf-8") as fh:
fh.write(text)
print(f"Wrote {len(payload['results'])} results to {args.output}")
else:
print(text)
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,229 @@
"""Unit tests for the exa-search skill scripts.
These tests mock the Exa SDK so they never hit the live API. Run from the
skill root:
python -m unittest discover -s tests -v
Tests cover: CLI argument plumbing, the content-options builder (text /
highlights / summary), CSV splitting for domain lists, the content fallback
cascade, and the x-exa-integration header wiring.
"""
from __future__ import annotations
import importlib.util
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
SKILL_ROOT = Path(__file__).resolve().parent.parent
SCRIPTS_DIR = SKILL_ROOT / "scripts"
def _load_script(name: str):
"""Load one of the scripts as a module regardless of cwd."""
spec = importlib.util.spec_from_file_location(name, SCRIPTS_DIR / f"{name}.py")
assert spec and spec.loader
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
return module
def _fake_result(**overrides):
defaults = {
"title": "Attention Is All You Need",
"url": "https://arxiv.org/abs/1706.03762",
"id": "abc123",
"author": "Vaswani et al.",
"published_date": "2017-06-12",
"score": 0.91,
"text": "Full paper text here",
"highlights": ["The Transformer relies entirely on self-attention"],
"highlight_scores": [0.87],
"summary": None,
}
defaults.update(overrides)
return SimpleNamespace(**defaults)
class BuildContentsTests(unittest.TestCase):
"""The content-options builder is shared logic across all three scripts."""
def setUp(self):
self.search_mod = _load_script("exa_search")
self.extract_mod = _load_script("exa_extract")
def test_search_no_flags_returns_none(self):
self.assertIsNone(self.search_mod._build_contents(False, False, None))
def test_search_text_only(self):
self.assertEqual(self.search_mod._build_contents(True, False, None), {"text": True})
def test_search_highlights_only(self):
self.assertEqual(
self.search_mod._build_contents(False, True, None),
{"highlights": True},
)
def test_search_summary_default_is_boolean_true(self):
self.assertEqual(
self.search_mod._build_contents(False, False, ""),
{"summary": True},
)
def test_search_summary_with_query(self):
self.assertEqual(
self.search_mod._build_contents(False, False, "key findings"),
{"summary": {"query": "key findings"}},
)
def test_search_all_three_combine(self):
self.assertEqual(
self.search_mod._build_contents(True, True, "methods"),
{"text": True, "highlights": True, "summary": {"query": "methods"}},
)
def test_extract_defaults_to_text_when_nothing_specified(self):
self.assertEqual(self.extract_mod._build_contents(False, False, None), {"text": True})
class SplitCsvTests(unittest.TestCase):
def setUp(self):
self.mod = _load_script("exa_search")
def test_none_returns_none(self):
self.assertIsNone(self.mod._split_csv(None))
def test_empty_string_returns_none(self):
self.assertIsNone(self.mod._split_csv(""))
def test_splits_and_trims(self):
self.assertEqual(
self.mod._split_csv("arxiv.org, nature.com ,pubmed.gov"),
["arxiv.org", "nature.com", "pubmed.gov"],
)
def test_ignores_empty_segments(self):
self.assertEqual(self.mod._split_csv("a,, b,"), ["a", "b"])
class ResultTypingTests(unittest.TestCase):
"""Verify the Any → typed-dataclass conversion handles missing fields."""
def setUp(self):
self.mod = _load_script("exa_search")
def test_full_result(self):
item = _fake_result()
typed = self.mod._result_to_typed(item)
self.assertEqual(typed.url, "https://arxiv.org/abs/1706.03762")
self.assertEqual(typed.highlights, ["The Transformer relies entirely on self-attention"])
self.assertEqual(typed.highlight_scores, [0.87])
def test_missing_optional_fields_default_cleanly(self):
item = SimpleNamespace(url="https://example.com")
typed = self.mod._result_to_typed(item)
self.assertEqual(typed.url, "https://example.com")
self.assertIsNone(typed.title)
self.assertIsNone(typed.text)
self.assertEqual(typed.highlights, [])
self.assertEqual(typed.highlight_scores, [])
def test_highlights_only_response(self):
"""Content fallback: when only highlights are present, text/summary must stay None."""
item = _fake_result(text=None, summary=None, highlights=["snippet A", "snippet B"])
typed = self.mod._result_to_typed(item)
self.assertIsNone(typed.text)
self.assertIsNone(typed.summary)
self.assertEqual(typed.highlights, ["snippet A", "snippet B"])
def test_summary_only_response(self):
item = _fake_result(text=None, highlights=[], highlight_scores=[], summary="A summary.")
typed = self.mod._result_to_typed(item)
self.assertIsNone(typed.text)
self.assertEqual(typed.highlights, [])
self.assertEqual(typed.summary, "A summary.")
class IntegrationHeaderAndFlowTests(unittest.TestCase):
"""End-to-end: run() sets the integration header and calls the right SDK method."""
def setUp(self):
self.mod = _load_script("exa_search")
def _run_with_mock(self, argv):
fake_client = MagicMock()
fake_client.headers = {}
fake_client.search_and_contents.return_value = SimpleNamespace(
results=[_fake_result()],
autoprompt_string=None,
)
fake_client.search.return_value = SimpleNamespace(
results=[_fake_result()],
autoprompt_string=None,
)
# Mock at the source module so the import inside the script gets the fake.
# NOTE: the script does `from exa_py import Exa` at module top, so the name
# to patch is the already-imported binding on the script module itself.
with patch.object(self.mod, "Exa", return_value=fake_client) as ctor, \
patch.dict(os.environ, {"EXA_API_KEY": "test-key"}, clear=False):
args = self.mod.build_parser().parse_args(argv)
payload = self.mod.run(args)
return payload, fake_client, ctor
def test_integration_header_is_set(self):
_, client, _ = self._run_with_mock(["what is attention", "--highlights"])
self.assertEqual(client.headers.get("x-exa-integration"), "scientific-agent-skills")
def test_calls_search_and_contents_when_contents_requested(self):
_, client, _ = self._run_with_mock(["query", "--text"])
client.search_and_contents.assert_called_once()
client.search.assert_not_called()
def test_calls_search_when_no_contents_flags(self):
_, client, _ = self._run_with_mock(["query"])
client.search.assert_called_once()
client.search_and_contents.assert_not_called()
def test_domain_filters_are_split_and_passed(self):
_, client, _ = self._run_with_mock(
["q", "--include-domains", "arxiv.org, nature.com", "--exclude-domains", "spam.com"]
)
kwargs = client.search.call_args.kwargs
self.assertEqual(kwargs["include_domains"], ["arxiv.org", "nature.com"])
self.assertEqual(kwargs["exclude_domains"], ["spam.com"])
def test_missing_api_key_exits_with_code_2(self):
# Remove EXA_API_KEY for this call only.
with patch.dict(os.environ, {}, clear=True):
with self.assertRaises(SystemExit) as ctx:
self.mod.run(self.mod.build_parser().parse_args(["q"]))
self.assertEqual(ctx.exception.code, 2)
def test_output_file_written(self):
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "results.json"
fake_client = MagicMock()
fake_client.headers = {}
fake_client.search.return_value = SimpleNamespace(
results=[_fake_result()],
autoprompt_string=None,
)
with patch.object(self.mod, "Exa", return_value=fake_client), \
patch.dict(os.environ, {"EXA_API_KEY": "k"}, clear=False):
rc = self.mod.main(["q", "-o", str(out)])
self.assertEqual(rc, 0)
self.assertTrue(out.exists())
payload = json.loads(out.read_text())
self.assertEqual(payload["num_results"], 1)
self.assertEqual(payload["results"][0]["title"], "Attention Is All You Need")
if __name__ == "__main__":
unittest.main()