Search Tutorials
--Ads--Project 4: Agentic Research Assistant
An agent that searches several sources, chains findings and writes a cited report.
This project builds a research assistant that answers open-ended questions by combining your internal documents with the public web. Given a question like "How does our remote-work policy compare with common practice in Indian tech companies?", it plans, searches the internal index, searches the web, reads, cross-checks and writes a structured report with citations for every claim. It brings together agentic RAG, multi-hop retrieval and citations.
Design
- Internal search tool: hybrid retrieval over your document index (a custom tool you implement).
- Web search tool: the Claude API's server-side web search, which runs on Anthropic's servers and returns cited results. No search API key or scraping code is needed.
- Research agent: the SDK tool runner with both tools and a system prompt that defines the research method and the report format.
- Report output: Markdown with internal citations (
[internal: file]) and web citations collected from the API's citation data.
Web search must be enabled for your organisation in the Claude Console, and each search is billed in addition to tokens. Check current pricing and set max_uses to limit searches per request.
pip install anthropic sentence-transformers rank-bm25 numpy
"""An agentic research assistant over internal documents and the web."""
import json
from datetime import date
from pathlib import Path
import anthropic
from anthropic import beta_tool
from hybrid import HybridRetriever # from the hybrid search lesson
client = anthropic.Anthropic()
records = json.loads(Path("index/chunks.json").read_text(encoding="utf-8"))
internal = HybridRetriever([f"[{r['source']}]\n{r['text']}" for r in records])
@beta_tool
def search_internal(query: str, k: int = 5) -> str:
"""Search the company's internal documents (policies, handbooks, reports).
Search here FIRST for anything about our own company. Results start with the source file
name in square brackets.
Args:
query: Keywords or a short question.
k: Number of passages (1-8).
"""
hits = internal.search(query, k=max(1, min(k, 8)))
return "\n\n".join(text for text, _ in hits) or "No internal results."
WEB_SEARCH = {"type": "web_search_20260209", "name": "web_search", "max_uses": 6}
SYSTEM = f"""You are a careful research assistant for Zentrix Labs. Today is {date.today():%d %B %Y}.
Method:
1. Break the question into the facts you need.
2. Use search_internal for anything about Zentrix Labs. Use web_search for external facts,
practices and data. Search several times with different queries when needed.
3. Prefer authoritative and recent sources. Note disagreements between sources.
4. Stop searching when you can answer well; do not exceed what the question needs.
Report format (Markdown):
# <title>
**Summary**: 3-4 sentences.
## Findings (sections as needed)
## Caveats and open questions
Cite every factual claim: internal facts as [internal: file-name]; web facts are cited
automatically when you use search results. Do not state facts you did not find in a source."""
def research(question: str) -> tuple[str, list[tuple[str, str]]]:
runner = client.beta.messages.tool_runner(
model="claude-opus-5-5",
max_tokens=16000,
output_config={"effort": "high"},
system=SYSTEM,
tools=[search_internal, WEB_SEARCH],
messages=[{"role": "user", "content": question}],
)
final = None
for message in runner:
for block in message.content:
if block.type in ("tool_use", "server_tool_use"):
print(f" [{block.name}] {json.dumps(block.input)[:100]}")
final = message
if final.stop_reason == "refusal":
return "The request could not be completed.", []
report, web_sources = [], []
for block in final.content:
if block.type != "text":
continue
report.append(block.text)
for c in block.citations or []:
url = getattr(c, "url", None)
if url and url not in [u for u, _ in web_sources]:
web_sources.append((url, getattr(c, "title", "") or url))
report.append(f" [{len(web_sources)}]")
return "".join(report), web_sources
if __name__ == "__main__":
question = ("How does our remote work policy compare with common remote and hybrid work "
"practices at technology companies in India? Recommend any changes worth considering.")
report, sources = research(question)
references = "\n".join(f"{i}. [{title}]({url})" for i, (url, title) in enumerate(sources, start=1))
output = f"{report}\n\n## Web references\n{references}\n"
Path("research_report.md").write_text(output, encoding="utf-8")
print(output)
What happens when it runs
[search_internal] {"query": "remote work policy work from home days"}
[web_search] {"query": "hybrid work policy Indian IT companies 2026 days in office"}
[web_search] {"query": "remote work allowance internet reimbursement India tech companies"}
[search_internal] {"query": "internet reimbursement remote"}
# Remote Work at Zentrix Labs Compared with Industry Practice
**Summary**: Zentrix Labs allows up to two remote days per week with manager approval
[internal: remote-work.txt] ...
The agent decided on its own to check the internal policy first, run two web searches for comparison points, and return to the internal index for a detail it needed. Your exact output depends on the documents and on current web results.
Guardrails for a research agent
- Budget:
max_usescaps web searches; also cap the number of runner iterations for runaway loops. - Untrusted web content: web pages can contain prompt-injection attempts. This agent only has read-only tools, which limits the damage; never give a web-reading agent tools that send messages or change data without human confirmation (Prompt Injection).
- Domain control: the web search tool accepts allowed or blocked domain lists when you want to restrict sources.
- Confidential data: internal content can appear in the search queries the agent writes. If that is a concern, tell the agent not to include confidential details in web queries, or disable web search for sensitive topics.
- Long runs: high-effort research can take minutes; run it as a background job and notify the user when the report is ready.
Extensions
- Add the
web_fetchserver tool so the agent can read full pages, not just search snippets. - Add a
get_documenttool to read whole internal documents after a search hit. - Add a final verification pass that checks each claim against its cited source (Faithfulness).
- Stream progress to a web UI so users see which sources are being consulted.
Key takeaways
- A research agent combines custom retrieval tools with server-side web search in one tool runner.
- The system prompt defines the research method, source preferences and a cited report format.
- Web citations come back as structured data; collect them into a reference list.
- Limit searches and iterations, keep tools read-only, and treat web content as untrusted.