Custom graphs
Build your own workflow with StateGraph, typed state and reducers, edges, and the control flow types Send and Command.
Build your own workflow with StateGraph.
create_agent builds a tool-calling loop. When you need another shape, such as a classifier step, branches, or a fan-out, build the graph yourself with StateGraph.
Prerequisites: The framework, installed as in the Quickstart. The example calls no model.
Build a graph
from typing import Annotated
from typing_extensions import TypedDict
from coco_graph.graph import END, START, StateGraph, add_messages
from coco_core.messages import AnyMessage, AIMessage
class WorkflowState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
approved: bool
def classify(state: WorkflowState) -> dict:
last_text = state["messages"][-1].content.lower()
return {"approved": "urgent" not in last_text}
def respond(state: WorkflowState) -> dict:
status = "Processed automatically." if state["approved"] else "Escalated for review."
return {"messages": [AIMessage(content=status)]}
builder = StateGraph(WorkflowState)
builder.add_node("classify", classify)
builder.add_node("respond", respond)
builder.add_edge(START, "classify")
builder.add_edge("classify", "respond")
builder.add_edge("respond", END)
workflow = builder.compile()
output = workflow.invoke({"messages": [{"role": "user", "content": "Standard request"}]})
print(output["messages"][-1].content)It prints Processed automatically. Change the message to one containing urgent and it prints Escalated for review.
Define state
A state schema is a TypedDict, a Pydantic BaseModel, or a dataclass. Each node returns a partial update, and each key decides how updates merge:
- A plain key keeps the last value written.
Annotated[Type, reducer]merges updates with the reducer.add_messagesappends messages, merges streamed chunks, and deletes the ones aRemoveMessagenames.
StateGraph also takes separate input_schema, output_schema and context_schema.
Control the flow
| Tool | Use it to |
|---|---|
add_edge(a, b) | Always go from a to b. |
add_conditional_edges(source, path) | Go where path(state) says: a node name, a list of names, or Send objects. |
Send(node, arg) | Fan out: run node once per Send, each with its own input. |
Command(update=..., goto=...) | Return from a node to update state and choose the next node in one step. |
interrupt(value) | Pause for a person, as in Human in the loop. |
Pass a checkpointer to compile() to keep state across calls and to pause with interrupt().
Related Resources
Built-in middleware
Add call limits, retries and fallbacks, PII redaction, summarization, context editing, and trace scrubbing from coco.agents.middleware.
Tracing
Record runs in memory with CocoTracer, read the latest run, tag runs with a project, and keep payloads out of spans. Nothing leaves the process.