- environment setup and imports,
- the shared typed state for the graph,
- node implementations (intent classification, web search, direct answer, formatting),
- wiring the StateGraph with conditional edges,
- running two example invocations to observe routing,
- and printing the Mermaid source for visualization.
Before running the code, set your
OPENAI_API_KEY and TAVILY_API_KEY environment variables. For local testing you can also set them in the script using os.environ.setdefault(...).Never commit your API keys to version control. Use environment variables or a secrets manager in production.
question. Nodes may add other optional fields as they execute.
- classify_intent — decide whether the question requires a web search or can be answered directly. It returns
{"intent": "search"}or{"intent": "answer"}.
- search_web — call the Tavily client to retrieve search results for the question and return them under
search_results.
- answer_direct — call the OpenAI Responses API to produce a direct draft answer (no web lookup).
- format_output — shared terminal node that formats the output based on the
intent. Ifintent == "search", it summarizes Tavily results; otherwise it returns the LLM draft.
Wiring the StateGraph
- Start at
classify_intent. - Add a conditional edge from
classify_intentthat routes to eithersearch_weboranswer_direct. - Both of those nodes then converge into
format_output, which is the terminal node.