A research graph should be able to finish without an answer. Search can fail, a useful source can be unreadable, or the call budget can run out before the evidence is sufficient. Those outcomes belong in the graph state, not inside a string that the next node might mistake for a source.
The example below wires planning, search, reading, review and reporting into a complete LangGraph. The query plan and source hosts are reviewed inputs. It does not ask a model to invent a plan or an answer: the final node returns an evidence report for answer review. That makes the routing testable before you add a model service.
Make the budget a graph boundary
The flow is START → plan → research → review, with a conditional return to research or a final report. The planner initializes every state field used later. It can route directly to the report when the call budget is zero or the plan is empty.
One search attempt and each page-read attempt count separately, including failures. The limit in this example counts outbound API attempts, not credits, tokens or elapsed seconds. Search and Reader have different credit costs. The calls run sequentially; this code does not imply unlimited throughput or require a high-concurrency plan.
Run the complete graph
The code was checked with langgraph==1.2.14. Save it as research_graph.py. The request adapters use Python’s standard library and the current Search API and Reader API POST contracts. Set SEARCHCANS_API_KEY only when using the live adapters.
import hashlib
import json
import os
from datetime import datetime, timezone
from typing import TypedDict
from urllib.parse import urlsplit
from urllib.request import Request, urlopen
from langgraph.graph import StateGraph, START, END
class ResearchState(TypedDict, total=False):
question: str
approved_queries: list[str]
allowed_hosts: list[str]
max_calls: int
pending: list[str]
calls: int
sources: list[dict]
failures: list[dict]
sufficient: bool
report: dict
def api(path, body):
request = Request("https://www.searchcans.com/api/v1/" + path,
data=json.dumps(body).encode(), method="POST",
headers={"Content-Type": "application/json",
"Authorization": "Bearer " + os.environ["SEARCHCANS_API_KEY"]})
with urlopen(request, timeout=45) as response:
payload = json.load(response)
if (not isinstance(payload, dict) or type(payload.get("code")) is not int
or payload["code"] != 0 or not isinstance(payload.get("data"), dict)):
raise ValueError("API request failed its response contract")
return payload["data"]
def search_web(query):
data = api("search", {"t": "google", "s": query, "country": "us", "p": 1})
rows = data.get("organic")
if not isinstance(rows, list):
raise ValueError("Expected data.organic array")
return [row.get("link") for row in rows if isinstance(row, dict)]
def read_page(url):
data = api("url", {"t": "url", "s": url, "mode": 0, "proxy": 0})
markdown = data.get("markdown")
if not isinstance(markdown, str) or not markdown.strip():
raise ValueError("Missing extracted Markdown")
return markdown
def make_graph(search, read, assess):
def plan(state):
limit = state.get("max_calls", 0)
if type(limit) is not int or not 0 <= limit <= 20:
raise ValueError("Set a finite call budget between zero and twenty")
queries = state.get("approved_queries", [])
if not isinstance(queries, list) or any(not isinstance(q, str) or not q.strip() for q in queries):
raise ValueError("Provide reviewed query strings")
if not isinstance(state.get("question"), str) or not state["question"].strip():
raise ValueError("Provide a research question")
return {"pending": list(dict.fromkeys(queries)), "calls": 0,
"sources": [], "failures": [], "sufficient": False}
def research(state):
query = state["pending"][0]
calls = state["calls"] + 1 # A failed request still uses the attempt budget.
sources, failures = list(state["sources"]), list(state["failures"])
try:
urls = search(query)
if not isinstance(urls, list):
raise ValueError("Search adapter must return a URL list")
except Exception as exc:
failures.append({"query": query, "stage": "search", "error": type(exc).__name__})
urls = []
seen = {source["url"] for source in sources}
for url in urls:
if calls >= state["max_calls"]:
break
try:
u = urlsplit(url) if isinstance(url, str) else None
if (not u or u.scheme != "https" or u.hostname not in state.get("allowed_hosts", [])
or u.username or u.password or any(c.isspace() for c in url)):
raise ValueError("Source outside the reviewed HTTPS host list")
if u.hostname in {"google.com", "www.google.com"} and u.path in {"/goto", "/url"}:
raise ValueError("Unresolved Google intermediary URL")
except ValueError as exc:
failures.append({"query": query, "stage": "selection", "error": str(exc)})
continue
if url in seen:
continue
seen.add(url)
calls += 1
try:
markdown = read(url)
if not isinstance(markdown, str) or not markdown.strip() or len(markdown) > 20000:
raise ValueError("Missing or oversized source; requires separate review")
sources.append({"url": url, "query": query, "markdown": markdown,
"sha256": hashlib.sha256(markdown.encode()).hexdigest(),
"extracted_at": datetime.now(timezone.utc).isoformat()})
except Exception as exc:
failures.append({"query": query, "stage": "read", "error": type(exc).__name__})
return {"pending": state["pending"][1:], "calls": calls,
"sources": sources, "failures": failures}
def review(state):
sufficient = assess(state["question"], state["sources"])
if type(sufficient) is not bool:
raise ValueError("Reviewer must return an explicit boolean")
return {"sufficient": sufficient}
def report(state):
return {"report": {"status": "ready_for_answer_review" if state["sufficient"] else "unresolved",
"calls": state["calls"], "remaining_queries": state["pending"],
"sources": [{k: s[k] for k in ("url", "sha256", "extracted_at")} for s in state["sources"]],
"failures": state["failures"]}}
def route(state):
return "report" if state["sufficient"] or not state["pending"] or state["calls"] >= state["max_calls"] else "research"
graph = StateGraph(ResearchState)
for name, node in [("plan", plan), ("research", research), ("review", review), ("report", report)]:
graph.add_node(name, node)
graph.add_edge(START, "plan")
graph.add_conditional_edges("plan", route, {"research": "research", "report": "report"})
graph.add_edge("research", "review")
graph.add_conditional_edges("review", route, {"research": "research", "report": "report"})
graph.add_edge("report", END)
return graph.compile()
if __name__ == "__main__":
app = make_graph(search_web, read_page, lambda question, sources: False)
result = app.invoke({"question": "How does Python's perf_counter work?",
"approved_queries": ["site:docs.python.org time perf_counter"],
"allowed_hosts": ["docs.python.org"], "max_calls": 3},
config={"recursion_limit": 100})
print(json.dumps(result["report"], indent=2))
Review the evidence instead of counting tool calls
The demonstration reviewer returns False deliberately. Finding text is not proof that the research question has been answered. Replace that callback with a task-specific review of required passages, source dates and unresolved conflicts. Returning True means “ready for answer review”; it is not an automated truth score.
Keep web content outside executable instructions and model-control prompts. The host list limits which sources can be selected, but an allowed page can still contain hostile instructions, incorrect statements or irrelevant text. Inspect the source evidence before a model uses it. A live deployment also needs controlled redirects, network/egress restrictions and URL validation across the fetch path; a hostname check in this tutorial is not a complete SSRF defence.
The source ledger retains the requested URL, query, extraction time and content hash. The hash identifies the text received; it does not prove authorship, freshness or factual correctness. Google /goto and /url links are rejected while their publisher identity remains unresolved. Do not decode an opaque token into a guessed URL or call an empty source list successful research.
Check the routes without spending on a model
Local fixtures exercise an empty plan, a zero budget, a failed search, a failed read, duplicate URLs, an unresolved intermediary link and a positive reviewer decision. They verify that no extra API attempt starts after the budget is exhausted and that failure records survive into the report. The fixtures use synthetic source text, not live competitor content, and establish control flow only.
For the smaller node-level budget check, use the LangGraph search-node guide. For the framework’s routing semantics, see the LangGraph Graph API documentation. Add model planning or synthesis only after these boundaries pass, and evaluate the resulting answers separately.