Skip to main content
In this short lesson we demonstrate how to use LangGraph conditional edges to route between multiple execution paths in an agentic workflow. The example is intentionally simple: based on the user’s question, the graph either performs a web search using Tavily or answers directly with an LLM. Both paths converge into a final formatting step. This tutorial covers:
  • 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.
Setup and imports. We create separate clients to avoid name collisions and read model/limit config from environment variables.
Typed shared state The graph always starts with a question. Nodes may add other optional fields as they execute.
Node implementations Below are the four node functions used in the graph. Each returns a dictionary of fields to merge into the shared state.
  1. classify_intent — decide whether the question requires a web search or can be answered directly. It returns {"intent": "search"} or {"intent": "answer"}.
  1. search_web — call the Tavily client to retrieve search results for the question and return them under search_results.
  1. answer_direct — call the OpenAI Responses API to produce a direct draft answer (no web lookup).
  1. format_output — shared terminal node that formats the output based on the intent. If intent == "search", it summarizes Tavily results; otherwise it returns the LLM draft.
Node summary Wiring the StateGraph
  • Start at classify_intent.
  • Add a conditional edge from classify_intent that routes to either search_web or answer_direct.
  • Both of those nodes then converge into format_output, which is the terminal node.
Run the graph with two example questions to observe the routing behavior.
Inspecting the graph visualization If you want to inspect the control flow produced by the graph without rendering an image, you can print the Mermaid source for the diagram and paste it into any Mermaid renderer or editor.
Conclusion This pattern scales naturally to more complex agentic systems. You can add more routes, tool calls, validation steps, or memory writes while keeping the same state-driven routing model. Conditional edges keep control flow explicit and make branching logic easy to reason about during orchestration.

Watch Video

Practice Lab