Build agents
In this sectionTask-oriented guides for building, deploying and monitoring production agents. Step-by-step instructions, complete code examples and best practices.
- 26 pages
- About 147 min to read all
Guides are hands-on, task-oriented instructions that walk you through solving specific problems. Unlike concepts, which explain how 10xGraph works, guides show you how to do something: build a graph, add tools, set up memory, handle errors, or deploy to production.
Guides assume you have read Get started.
Six most common tasks
Start here if you are building an agent for the first time. These cover the decisions you make in almost every project.
-
Build a graph: Construct and wire nodes, edges, and routing logic. Shows when to use a custom
StateGraphvs a prebuilt agent. -
Configure an agent: Choose a model and provider (OpenAI, Google, Anthropic, or an OpenAI-compatible server), set system prompts, reasoning, retries and fallbacks.
-
Add tools to an agent: Write tool functions, understand how the LLM sees the schema (from your type hints and docstring), inject dependencies like
stateordb, and handle errors. -
Set up checkpointing and memory: Keep thread state across restarts: in-memory for development, SQLite for one server, Postgres and Redis for production.
-
Stream and monitor runs: Use
astream()to send tokens and messages as they arrive. -
Secure and serve your agent: Serve the graph with
10xgraph-api, turn on auth and request limits, and work through the production checklist. Guides here end with a “Run it in production” section that links to the relevant server page.
How guides are organized
Agents and graphs
Build the core graph logic. These guides cover the fundamental patterns: constructing graphs by hand, choosing when to use prebuilt agents, and customizing state and nodes.
- Build a graph: StateGraph, nodes, edges, and routing
- Configure an agent: Model selection, system prompts, provider options
- Use custom state: Extend AgentState with your own fields
- Use custom nodes: Write nodes that are not agents or tool dispatchers
- Get structured output: Output a typed, validated schema from an agent
- Visualize a graph: Inspect and draw your compiled graph
Prebuilt agents
Seven prebuilt agents cover common patterns. The set is closed: new patterns are built with StateGraph and Agent.
- Prebuilt agents overview: Quick comparison and when to use each
- ReactAgent: The standard tool-calling loop
- RAGAgent: Retrieval-augmented generation with vector stores
- PlanActReflectAgent: Plan, act, reflect, revise cycle
- SupervisorTeamAgent: Supervisor routing tasks to specialists
- SwarmAgent: Peer agents that hand off to each other
- StructuredOutputAgent: Guaranteed typed output
- AudioAgent: Realtime audio input and streaming
Tools and MCP
Give your agents the ability to take action. Covers writing custom tools, using prebuilt tools, Model Context Protocol (MCP), and emitting progress during long-running operations.
- Use the @tool decorator: Write tools that the LLM can call
- Prebuilt tools: Handoff and memory tools, plus the fetch, search, file and calculator tools deprecated in 1.1
- Memory tools: Store and retrieve long-term facts
- Use MCP: Model Context Protocol servers and clients
- Emit tool progress: Show progress for long-running tools
- Harness recipes: Tool search, large results in files, todo and notes state, long runs that resume
State, memory and context
Manage graph state, persistence, and memory. These guides cover how messages accumulate, how to keep history across threads, and when to trim old context.
- Set up checkpointing: Thread state and durability options
- Durability and concurrency: Optimistic concurrency and the per-step save
- Use a memory store: Long-term facts and retrieval
- Use context managers: Trim or summarize old messages automatically
- Use dependency injection: Inject user_id, db, config, and custom parameters into nodes and tools
Multi-agent and control flow
Coordinate multiple agents and implement advanced control flow. Covers handoff patterns, human-in-the-loop approval, and background tasks.
- Handoff between agents: Agent A asks agent B to take over
- Add human approval: Pause runs for human review before proceeding
- Run background tasks: Spawn work that does not block the run
Streaming, media and realtime
Streaming output, images and documents, and realtime audio.
- Stream a graph: Emit messages or tokens as they arrive
- Send media: Images, audio, and documents to models
- Use realtime audio: Bidirectional audio streaming
Safety
Protect against prompt injection and misuse. Covers input validation, guardrails, callbacks, and authorization scopes.
- Validate input and guard prompts: Prevent injection attacks
- Zero-trust agents:
ToolGuard, tool approval and result fencing - Use callbacks: Hooks before/after invoke, on error, and on completion
- Authorization scopes: Read user identity and scopes inside tools
Observability and operations
Monitor agents in production. Covers logging, tracing, metrics, graceful shutdown, and ID generation.
- Use publishers: Stream events to observability platforms
- Send AI traces: OTLP, Arize Phoenix, Logfire and LangSmith
- Metrics with Prometheus and Grafana: Request, task and LLM metrics by push or scrape
- Configure ID generation: Snowflake IDs for distributed systems
- Graceful shutdown: Finish inflight requests before stopping
Agent Skills
Give your own agent Agent Skills: folders with a SKILL.md it loads on demand.
- Give an agent Agent Skills: Add, validate and observe skills on an
Agent
All pages in Build agents
Agents and graphs
- Build a graphBuild a StateGraph agent in Python: add Agent and ToolNode nodes, connect them with edges and conditional routing, compile the graph and run it with invoke.5 min
- How to configure AgentConfigure an Agent node: model and provider, system prompt, tools, reasoning, retries and fallbacks, timeouts, structured output and extra messages.12 min
- Use custom stateExtend AgentState with typed fields such as a ticket ID or sentiment, pass the class to StateGraph, and control how field updates merge with state reducers.7 min
- Write custom nodesWrite graph nodes as plain Python functions, receive state, config and injected services with Inject, and route at runtime by returning a Command with goto.6 min
- Structured outputGet typed output from LLMs with output_schema on an Agent, or use StructuredOutputAgent to validate the reply and ask the model again, up to max_attempts.3 min
- Visualize a graphCall generate_graph() on a compiled graph or GET /v1/graph on the server to get nodes and edges as JSON, then render them as a diagram to debug routing.3 min
Prebuilt agents
- Choose and use prebuilt agentsChoose between the seven prebuilt agents: ReactAgent, PlanActReflectAgent, StructuredOutputAgent, SupervisorTeamAgent, SwarmAgent, RAGAgent and AudioAgent.2 min
- ReactAgentReactAgent implements the ReAct pattern, a simple LLM loop that reasons about what to do and acts by calling tools until it reaches a final answer.4 min
- PlanActReflectAgentPlanActReflectAgent loops a planner, tools and a reflector until the reflector replies [DONE] or max_iterations is reached, so agents finish the task.4 min
- SwarmAgentSwarmAgent enables peer-to-peer multi-agent coordination where any member can hand off to any other member, with no bottleneck at a central supervisor.5 min
- SupervisorTeamAgentSupervisorTeamAgent lets a supervisor LLM route each turn to specialist worker agents, each with its own model and tools, until it says FINISH or max_rounds.4 min
- RAGAgentRAGAgent retrieves documents from a vector store, optionally reranks them with top_k and top_n, then answers the question grounded in the retrieved context.6 min
Tools and MCP
- How to use the @tool decoratorMark Python functions as agent tools with the @tool decorator: set the description and tags, shape parameter schemas, and receive injected config and emit.7 min
- Use prebuilt toolsUse create_handoff_tool and the memory tools in a ToolNode, and see which calculator, fetch, search and file tools are deprecated in 1.1.0 and removed in 2.0.2 min
- Use MCP tools in agentsConnect 10xGraph agents to MCP servers with fastmcp.Client over a config dict, stdio or URL, and mix remote MCP tools with local Python tools in one graph.8 min
- Emit tool progress updatesSend live progress updates from tools during streaming with an emit parameter of type StreamEmitter and emit.progress, which is None under invoke.3 min
- Harness recipesFour patterns for agents that run long and use many tools: tool search, large results in files, todo and notes state, and runs that resume from checkpoints.9 min
Context and dependencies
- Manage conversation contextKeep message history inside the LLM context window by trimming with MessageContextManager or summarizing with SummaryContextManager, and when to pick each.4 min
- How to use dependency injectionGuide to using InjectQ for binding services and injecting them into node functions, tool functions, and agents via Inject[T] parameter defaults.6 min
Control flow
- Route between agents with handoffTransfer control between agents with handoff tools and Command routing, and run a sub-workflow as a tool call that keeps its data in a custom state field.8 min
- Add human approval with interrupt()Pause a running graph for human approval, correction or choice with interrupt() inside a node or tool, then resume the thread with a resume value.6 min
- Use Callbacks and HooksUse CallbackManager to run before_invoke, after_invoke and on_error callbacks on LLM, tool and MCP calls, plus hooks such as on_graph_start and on_checkpoint.6 min
Streaming, media and realtime
- Stream graph responsesStream token-by-token output from a compiled graph with astream(), handle StreamChunk events and delta messages, and pause a streaming run with interrupts.7 min
- Send media to modelsSend images, audio, video and documents to a model from Python using ImageBlock and other content blocks, MediaRef, multimodal_config and storage backends.7 min
- How to build a realtime audio agentBuild a live audio-to-audio agent with AudioAgent and Gemini Live: arealtime sessions, LiveInputQueue, image input, reconnection, and the WebSocket bridge.7 min