Building Graph-Based AI Agents into Production Services
This article explains how to move AI agents beyond a working demo and into a production-ready service. It covers a four-layer architecture that separates agent orchestration, API interfaces, session state, and frontend interaction; how to model reasoning flows with graph structures; dual-channel streaming with both token-level and message-level events; state persistence for replay and recovery; observability and cost governance; and a checklist for security, evaluation, and launch readiness.
Building Graph-Based AI Agents into Production Services
1. Background: Why a Working Demo Is Far from Production-Ready
Over the past two years, agent applications built around large language models have moved from proof of concept toward engineering deployment. In the first phase, many teams can quickly produce a conversational demo: define prompts, attach retrieval, call the model, and print the output to a terminal. But once stakeholders ask for something customers can use, something that handles concurrency, and something that exposes the intermediate steps, the gaps surface all at once:
- Agent logic is tightly coupled with the interface layer, so changing a prompt requires restarting the entire service.
- The system returns results only once, leaving users staring at the frontend for ten-plus seconds with no feedback.
- Multi-turn conversation context has nowhere to live, so sessions are lost when the process restarts.
- A single execution path spans model calls, tool calls, and retrieval calls, making failures impossible to locate.
- With no authentication or quotas, an exposed endpoint becomes a cost black hole.
The core of agent serviceization, then, is not writing another agent. It is placing the agent inside an engineering skeleton with clear layering, observability, and operability. This article follows a main thread of graph-based agent orchestration, service encapsulation, and frontend interaction to present a reusable practice framework.
2. Overall Architecture: A Four-Layer Separation
For a service that can evolve sustainably, it is best to split the system into four layers that communicate only through explicit data contracts.
- Agent orchestration layer: Describes the execution flow as a directed graph (nodes are steps, edges are transition conditions) and handles reasoning, decision-making, and tool dispatch.
- Service interface layer: Exposes capabilities over HTTP and supports both one-shot and incremental response modes.
- Session and state layer: Maintains multi-turn history, intermediate artifacts, and checkpoint information to support recovery and replay.
- Interaction layer: The frontend application renders incremental content, displays step traces, and collects user feedback.
The direct benefit of this layering is replaceability: switching model providers, adjusting the orchestration strategy, or replacing the frontend framework does not trigger a full-chain rewrite.
A sample directory layout could look like this:
agent_project/├── graph/ # Graph orchestration: nodes, edges, state definitions├── api/ # Interface layer: routes, request/response models, auth├── core/ # Shared capabilities: model client, tool registry, logging├── state/ # Session storage and persistence abstraction└── web/ # Interaction layer: incremental rendering and debug panel
3. Agent Orchestration Layer: Expressing Controllable Reasoning with Graphs
Chains suit fixed flows, but real business often requires conditional branches, loops, and human intervention. The value of a graph structure is that it makes all three explicit.
Node design: It is recommended to divide nodes into four types — reasoning nodes (model calls), tool nodes (external capability calls), routing nodes (deciding the next step), and summary nodes (producing the final answer). Each node type takes the same shared state object as input and output, avoiding implicit dependencies between nodes.
State design: The shared state should include messages (conversation history), scratchpad (intermediate reasoning and tool results), route (routing decisions), and meta (latency, token counts, error information). State fields must be serializable, which is the prerequisite for persistence and replay.
Controllability design: Set a maximum iteration count and timeout ceiling for loops to prevent the agent from retrying endlessly when a tool fails; assign idempotency keys to tool nodes to avoid data problems caused by duplicate writes.
# Sample: skeleton of graph orchestration (pseudocode style)from typing import TypedDict, Annotatedclass AgentState(TypedDict):messages: Annotated[list, "conversation history"]scratchpad: Annotated[list, "tool calls and results"]route: strmeta: dictdef build_graph():g = Graph(AgentState)g.add_node("reason", reason_node)g.add_node("tools", tool_node)g.add_node("route", route_node)g.add_node("final", summarize_node)g.add_edge("reason", "route")g.add_conditional_edges("route", router_fn,{"use_tool": "tools", "finish": "final"})g.add_edge("tools", "reason")g.set_entry("reason")return g.compile(checkpointer=state_store)
The key point is the checkpointer: it writes a state snapshot of every step to external storage, giving the service the ability to resume from a checkpoint and replay the process. This is the foundation for troubleshooting and auditing.
4. Service Interface Layer: Dual Channels for Streaming and Non-Streaming
The service layer must serve two kinds of callers: machine-to-machine batch scenarios prefer a complete result returned at once, while human-in-the-loop scenarios prefer incremental output.
Recommended interface split:
POST /invoke: Returns the complete result synchronously, suitable for offline tasks, batch processing, and backend-to-backend calls.POST /stream: Returns results incrementally, suitable for conversational interaction.GET /health: Health check for load balancers and container platform probes.POST /feedback: Collects user ratings for a given execution result, providing data for quality iteration.
Request and response contracts: The request body should include query, thread_id (session identifier), config (runtime parameters such as model and temperature), and options (whether to stream, maximum steps). The response body uniformly includes run_id, status, output, usage, and error. Once the contract is stable, frontend and backend can develop in parallel.
Async and concurrency: Model calls and tool calls are inherently I/O-intensive, so the interface layer should run on an asynchronous framework to avoid synchronous blocking that sharply reduces concurrency. A semaphore should also cap the number of concurrent graph executions per instance to prevent downstream model services from being saturated by bursts.
# Sample: dual-channel interface (pseudocode style)@app.post("/invoke")async def invoke(req: InvokeRequest):result = await graph.ainvoke(build_input(req), config=req.config)return to_response(result)@app.post("/stream")async def stream(req: StreamRequest):async def gen():async for chunk in graph.astream(build_input(req), config=req.config):yield encode(chunk) # incremental fragmentreturn StreamingResponse(gen(), media_type="text/event-stream")
5. Advanced Streaming: Choosing Between Token-Level and Message-Level
In practice, “streaming” has at least two meanings, and mixing them leads to confused frontend rendering logic.
Token-level streaming: Pushes the smallest fragments generated by the model, giving the lowest time-to-first-token and the smoothest user perception. The downside is that fragments are extremely fine; when multiple model calls or tool outputs exist at the same time, the frontend must distinguish their sources itself, and it is hard to express “step transitions.”
Message-level streaming: Pushes one complete message or one step at a time, with clear semantics that make it easy for the frontend to render a trace of “thinking — calling tools — generating the answer.” The downside is the coarser granularity, which makes the wait for a long answer more noticeable.
Recommended approach: Run both channels in parallel. Use message-level events to carry the step trace and tool results, and token-level events to carry the final answer text; at the transport layer, tag events with a type and sequence number so the frontend can deduplicate and order them.
event: stepdata: {"seq":1,"node":"route","status":"running"}event: stepdata: {"seq":2,"node":"tools","status":"done","name":"search"}event: tokendata: {"seq":3,"text":"Based on"}event: donedata: {"seq":99,"usage":{"total_tokens":1284}}
Three engineering details matter here. First, heartbeats: send comment frames to keep the connection alive when there is no output for a long time. Second, reconnection: the client re-subscribes with the run_id and the last sequence number. Third, backpressure: when the client consumes too slowly, intermediate tokens should be dropped rather than buffered without limit.
6. Session State and Persistence
The quality of multi-turn conversation depends on state management. Use thread_id as the partition key and write state snapshots to storage that supports high-concurrency reads and writes; for message history, use a sliding window plus summary compression to control context length, preserving key information while keeping cost in check.
Persistence also brings two additional capabilities. One is replay: re-running the full trace of an execution for regression testing. The other is recovery: after a service instance restarts, an unfinished execution can continue from the latest snapshot instead of making the user ask everything again. Abstracting a storage interface (an in-memory implementation for local development, a distributed implementation for production) makes switching environments cost-free.
7. Observability and Cost Governance
Agent chains are long and highly uncertain, and without observability they cannot be operated. The minimum viable setup includes:
- Structured logs: Assign a
run_idto each execution and thread all logs of model calls, tool calls, and routing decisions through it. - Metrics monitoring: Record time-to-first-token, end-to-end latency, token consumption per turn, tool failure rate, and loop trigger count, and wire them into monitoring and alerting.
- Distributed tracing: Show the latency distribution inside an execution as a call chain to quickly determine whether the model or the tool is slow.
- Cost quotas: Set concurrency and token limits per tenant to prevent runaway bills from abnormal calls.
If general cloud capabilities are used to carry this, they can combine a container platform (deployment and elastic scaling), object storage (session snapshots and evaluation datasets), a message queue (peak shaving and asynchronous tasks), and logging and monitoring services (observation and notification). These are common industry categories and do not point to any specific vendor.
8. Security, Evaluation, and Launch Checklist
Security: Interfaces should require authentication by default, issuing credentials per caller and binding them to quotas; validate the length and format of user input and tool-returned content; follow the principle of least privilege on the tool side, with write operations requiring a second confirmation; mask sensitive information in logs.
Evaluation: Build an offline evaluation set covering typical questions, edge cases, and adversarial inputs; focus on three metric groups — task completion rate, tool-call accuracy, and average steps and latency. Run a regression after every prompt or orchestration change to avoid fixing one scenario while breaking three others.
Launch checklist:
- Are health checks and readiness probes working?
- Are timeouts, retries, and circuit breakers configured at every hop?
- Have streaming heartbeats and reconnection been verified?
- Does state storage have capacity and backup policies?
- Are rate limiting and cost alerts in place?
- Is there a rollback plan and a canary strategy?
9. Conclusion
The difficulty of agent serviceization lies not in any single capability but in engineering completeness: graphs buy flow controllability, layering buys replaceability, dual-channel streaming balances experience and semantics, state persistence buys recoverability and replayability, and observability plus quotas buy operability and cost control. Once this skeleton is in place, the team’s iteration speed will increase significantly, because every change is confined within clear boundaries. To further reduce infrastructure overhead, the layered design above can be carried by general cloud products from Baidu AI Cloud, such as containers, storage, messaging, and monitoring, letting the team focus on orchestration logic and business outcomes themselves.
