Building Full-Stack Agent Services with Graph-Based Orchestration

    This article explains how to build full-stack AI agent services using graph-based orchestration. It breaks down five core components—graph-based behavior modeling, an asynchronous service layer with dual endpoints, two streaming granularities, an interactive client interface, and containerized cloud deployment—and shares practical implementation tips, common pitfalls, and recommendations for moving agent applications from prototype to production reliably.

    1. Why Agent Services Need a Complete Toolkit

    Agent development over the past two years has exposed a structural gap between model capabilities and engineering delivery. A single agent prototype may run with only a few dozen lines of code, but serving real users requires solving session state management, tool-call orchestration, concurrent request handling, incremental output streaming, frontend interaction, logging, and monitoring all at once. A common industry practice is to assemble these capabilities piecemeal, which leads to reinventing the wheel in every place and makes consistent standards hard to establish.

    As a result, an “end-to-end toolkit” approach has been widely adopted: it integrates agent definition, the service layer, the client, and a graphical interface into a single project skeleton. Developers only need to replace the core graph definition and prompts to get a runnable service. From a general technical perspective, this article abstracts five core building blocks of such a toolkit and presents the key engineering points for each.

    2. Core Building Block 1: Describing Agent Behavior with Graphs

    Traditional chain-based orchestration handles linear flows well, but real business logic is often a mesh of “branches + loops + conditional rollbacks.” Graph-based orchestration models an agent as a set of nodes and edges: nodes carry out specific computation (model inference, tool calls, data retrieval), while edges define transition conditions.

    1. from typing import TypedDict, Annotated
    2. import operator
    3. class AgentState(TypedDict):
    4. messages: Annotated[list, operator.add]
    5. route: str
    6. def build_graph():
    7. # Nodes: inference, tools, aggregation
    8. # Edges: conditional branching decides whether to enter the tool node; after tool execution, return to the inference node
    9. ...

    This modeling approach brings three direct benefits. First, state can be declared explicitly, making persistence and checkpoint recovery easier. Second, loops can be expressed naturally, which suits the iterative “think-act-observe” pattern. Third, it is highly visual, so during debugging you can see exactly which node is stuck. In practice, it is recommended to design a version number for the state and write a checkpoint to checkpoint storage after each node executes, so the service can resume unfinished sessions after a restart.

    3. Core Building Block 2: Asynchronous Service Layer and Dual-Endpoint Design

    The service layer is typically built on an asynchronous web framework, and the key design is to expose both streaming and non-streaming endpoints. The non-streaming endpoint waits for the complete result and returns it in one shot, which suits batch processing and background tasks. The streaming endpoint pushes results incrementally, significantly improving time to first token and the user experience.

    1. @app.post("/invoke")
    2. async def invoke(req: Request):
    3. result = await agent.ainvoke(req.state)
    4. return {"output": result}
    5. @app.post("/stream")
    6. async def stream(req: Request):
    7. async def gen():
    8. async for chunk in agent.astream(req.state):
    9. yield encode(chunk)
    10. return StreamingResponse(gen(), media_type="text/event-stream")

    Asynchronous design (async/await) is key to handling high concurrency. Three points deserve special attention. First, if tool calls involve blocking third-party requests, they should be executed in a thread pool to avoid blocking the event loop. Second, set a timeout and a maximum number of iteration steps for each request to prevent the agent from falling into an infinite loop and exhausting resources. Third, reuse external resources with connection pools, and configure rate limiting and circuit breaking at the gateway layer.

    4. Core Building Block 3: Choosing Between Two Streaming Granularities

    Streaming output is generally divided into two granularities: token-level streaming and message-level streaming. Token-level streaming delivers each fragment generated by the model immediately, offering the lowest latency and suiting chat scenarios with a typewriter effect, but the frontend must handle a large number of tiny fragments and the order in which they are assembled. Message-level streaming delivers complete messages or tool calls as units, which is semantically clearer and makes it easier for the frontend to render structured cards, tool execution status, and citation sources.

    A reasonable approach is to support both: default to token-level streaming to ensure a smooth experience, while using event types to distinguish “content increments,” “tool status,” and “end markers,” so the frontend can dispatch and handle events accordingly. The event protocol should include a session identifier, message sequence number, and error code, making it easier to realign context after reconnection.

    5. Core Building Block 4: Interactive Interface and Client

    A lightweight chat interface can greatly reduce integration and debugging costs. With a declarative UI framework, just a few dozen lines of code can implement a message list, an input box, streaming rendering, and session switching. On the client side, it is recommended to encapsulate a unified SDK that hides endpoint differences and exposes only two methods, send() and stream(), while handling retries, timeouts, and incremental assembly internally.

    The interface layer should also take on three responsibilities: displaying the tool-call process (improving explainability), supporting interruption of generation, and allowing users to roll back to a previous turn and ask again. These capabilities are especially important for debugging prompts and tool descriptions.

    6. Core Building Block 5: Containerization and Cloud Deployment

    For delivery, it is recommended to provide image build files and orchestration files so that a single command can spin up three containers: the service, storage, and interface. For cloud deployment, a combination of general-purpose capabilities can be used: a container platform hosts service instances with automatic scaling, object storage holds checkpoints and file artifacts, a message queue smooths out peaks and fills valleys for long-running tool tasks, and logging services plus monitoring and alerting track latency, error rate, and token consumption.

    In the Baidu AI Cloud environment, the above capabilities can be selected by general category, combined with key management and access control to isolate permissions. In production, always disable debug endpoints, enable authentication, validate input length and content, and set quotas for model invocation costs.

    7. Implementation Advice and Common Pitfalls

    First, define the state and tool contracts before writing prompts to avoid repeated refactoring later. Second, tool descriptions should clearly state applicable and non-applicable scenarios, since most “the agent won’t behave” problems stem from vague descriptions. Third, prepare a fallback path for the streaming pipeline, reverting to a one-shot return when pushing fails. Fourth, build an evaluation set and include accuracy, average number of steps, and time to first token in regression testing. Fifth, log node durations and summaries of tool inputs to make it easier to locate performance bottlenecks.

    In summary, treating an agent service as a five-layer engineering effort—orchestration, interfaces, streaming, interface, and deployment—rather than a single script is the dividing line for stable delivery. Once you master this skeleton, your team can focus its energy on business graph design and building the tool ecosystem, truly shortening the distance from prototype to production.