Coco
Look something up

Graphs and checkpointers

Look up StateGraph and CompiledStateGraph methods, the control flow types interrupt, Command, Send and the policies, the prebuilt nodes, and the checkpointers.

Look up coco_graph, from the trustcoco-graph* distributions.


StateGraph

from coco_graph.graph import StateGraph, START, END, MessagesState, add_messages
MethodSignatureDescription
__init__StateGraph(state_schema, context_schema=None, *, input_schema=None, output_schema=None)Creates a graph builder with typed state.
add_nodeadd_node(node, action=None, *, defer=False, metadata=None, input_schema=None, retry_policy=None, cache_policy=None, destinations=None)Adds a node function or runnable under a name.
add_edgeadd_edge(start_key, end_key)Goes from start_key, or START, or a list of keys, to end_key or END.
add_conditional_edgesadd_conditional_edges(source, path, path_map=None)Goes where path(state) says: a node name, a list of names, or Send objects.
add_sequenceadd_sequence(nodes)Adds nodes in a chain, with edges between them in order.
compilecompile(checkpointer=None, *, cache=None, store=None, interrupt_before=None, interrupt_after=None, debug=False, name=None)Returns a runnable CompiledStateGraph.

CompiledStateGraph

Each method has an async version with an a prefix.

MethodDescription
invokeRuns the graph to the end, or to an interrupt(), and returns the final state.
streamRuns step by step. Takes stream_mode ("values", "updates", "messages", "custom", "checkpoints", "tasks", "debug", or a list), subgraphs, and durability.
get_stateReturns the thread's current StateSnapshot: values, next, config, metadata, created_at, parent_config, tasks, interrupts.
get_state_historyYields the thread's earlier snapshots, newest first.
update_stateWrites values to the thread's state, optionally as_node=....
get_graphReturns a drawable graph, with .draw_mermaid(), .draw_ascii() and .draw_mermaid_png().

Control flow types

From coco_graph.types:

NameDescription
interrupt(value)Pauses inside a node, tool, or middleware, and surfaces value in the snapshot's interrupts. Returns the value passed to Command(resume=...) on resume.
Command(graph=None, update=None, resume=None, goto=())Returned from a node to update state and go to goto, or passed to invoke() with resume=... to resume.
Send(node, arg)Runs node with input arg, from a conditional edge or Command(goto=[Send(...)]), for fan-out.
RetryPolicyRetryPolicy(initial_interval=0.5, backoff_factor=2.0, max_interval=128.0, max_attempts=3, jitter=True, retry_on=default_retry_on).
TimeoutPolicySets a node's timeout.
CachePolicyCaches a node's result, with key_func and ttl.
Overwrite(value)Bypasses a channel's reducer and replaces its value.

Prebuilt nodes

From coco_graph.prebuilt:

NameDescription
ToolNodeRuns the tool calls in the last AIMessage in parallel, with wrap_tool_call, awrap_tool_call and handle_tool_errors.
tools_conditionA conditional edge that goes to "tools" when the last AIMessage has tool calls, and to END otherwise.
ValidationNodeValidates tool call arguments against their schemas without running the tools.
InjectedStateAnnotated[dict, InjectedState], or InjectedState("field"), gives a tool the graph state in a parameter the model doesn't see. Also in coco.tools.
InjectedStoreAnnotated[BaseStore, InjectedStore()] gives a tool the graph's store. Also in coco.tools.
ToolRuntimeGives a tool its state, context, config, store, stream_writer and tool_call_id. Also in coco.tools.

Checkpointers

Every checkpointer implements BaseCheckpointSaver: get_tuple, list, put, put_writes, delete_thread, and their async versions.

from coco_graph.checkpoint.memory import InMemorySaver
from coco_graph.checkpoint.postgres import PostgresSaver
from coco_graph.checkpoint.postgres.aio import AsyncPostgresSaver
from coco_graph.checkpoint.sqlite import SqliteSaver
from coco_graph.checkpoint.sqlite.aio import AsyncSqliteSaver

DB_URI = "postgresql://user:pass@localhost:5432/db"

# In memory
memory = InMemorySaver()

# SQLite and PostgreSQL, synchronous
with SqliteSaver.from_conn_string("checkpoints.db") as saver:
    ...

with PostgresSaver.from_conn_string(DB_URI) as pg_saver:
    pg_saver.setup()  # Run once to create or migrate the checkpoint tables
    ...


# SQLite and PostgreSQL, async
async def main():
    async with AsyncSqliteSaver.from_conn_string("checkpoints.db") as async_saver:
        ...

    async with AsyncPostgresSaver.from_conn_string(DB_URI) as async_pg_saver:
        await async_pg_saver.setup()
        ...

See Conversations for when to use each.

On this page