> For the complete documentation index, see [llms.txt](https://docs.amigo.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.amigo.ai/agent/context-graphs.md).

# Context Graphs

{% hint style="info" %}
**API naming:** The Classic API represents Context Graphs as `service_hierarchical_state_machine` resources; see [Agents and Context Graphs](https://docs.amigo.ai/developer-guide/classic-api/core-api/agents-and-context-graphs). Platform services bind separate agent and Context Graph versions through version sets; see [Services](https://docs.amigo.ai/developer-guide/platform-api/workspaces/services).
{% endhint %}

Context graphs define the authored workflow available to an agent: states, transitions, objectives, guidance, boundaries, and state-bound tool specifications. Model-driven navigation still has probabilistic failure modes, so use simulations and runtime safety controls rather than treating graph text as a formal guarantee.

## The State-Based Architecture

Context graphs differ from scripted dialog trees and unconstrained prompt-only agents in three ways:

1. **States, not scripts**: The graph defines states and transitions, not a fixed sequence of utterances. Model-driven states select among authored actions and exits from the available conversation context.
2. **Variable authoring detail**: Different regions can carry different amounts of objective, guidance, boundaries, guardrails, and tool configuration. These instructions steer behavior; they do not by themselves make model output deterministic.
3. **Incomplete by design**: Context graphs define workflow shape but not the full performance. The complete picture combines the graph's structure, the agent's identity and directives, state-level guidance, available tools, selected memory context, and channel policy.

The agent navigates the graph by evaluating which state to enter next based on the conversation so far, the patient's data, and the constraints defined on each transition.

Context graphs allow agents to:

* **Make safety intent reviewable** - place escalation guidance, boundary constraints, and state-specific guardrails next to the workflow step they govern.
* **Carry workflow state across turns** - track the current state and, for data-collection states, collected and remaining fields.
* **Vary guidance by task risk** - author more explicit constraints for sensitive steps and broader objectives for exploratory ones.
* **Reuse structure across supported channels** - apply channel overrides where voice and text behavior should differ.
* **Inspect observed paths** - use traces and simulation evidence to find untested or poorly performing states.

## From Protocol to Practice

Context graphs can encode clinical protocols and service workflows as state machines that an author reviews against the source protocol. Explicit states and exits make authored intent and observed navigation paths inspectable. They do not expose hidden model reasoning or replace clinical, compliance, and release review.

## Varying Constraint by State

"Context density" is an authoring heuristic, not a persisted state property. Authors vary constraint using the fields the runtime actually reads: objectives, actions, navigation guidance, boundary constraints, typed guardrails, exit conditions, tool bindings, and turn policy.

Use more explicit guidance and narrower exits for sensitive steps, and broader objectives for conversational steps. Validate the resulting behavior in simulations; added prompt detail is not equivalent to deterministic phrasing or a hard policy control.

## Bounded Multi-State Traversal

Within a turn, navigation can leave an action state, pass through decision and annotation states, and land on an engageable action or data-collection state. Decision states select an authored exit; annotation states inject authored internal guidance without a user-facing turn. The navigator detects loops and enforces an iteration cap instead of allowing an arbitrary number of internal transitions.

```mermaid
flowchart LR
    A1["Action state"] --> D["Decision state"]
    D --> N["Annotation state"]
    N --> A2["Action state"]
    D --> C["Data-collection state"]
```

Initial and terminal states are configured as action states. A turn can nevertheless engage through a data-collection state, so do not infer that every user-visible turn begins and ends on an action state. Traces record observed states, transitions, and actions; they do not expose hidden chain-of-thought reasoning.

## Integration with Memory and State Guidance

Context graphs do not run in isolation. At each state, the agent can receive selected [Functional Memory](/agent/memory.md) context and applies the state's authored guidance, turn policy, and tool specifications. Conditional behavior should be visible in states and transitions so teams can review and simulate it directly.

{% content-ref url="/pages/Kii5Ga5iQp6e9fEKbQ0t" %}
[Dynamic Behaviors](/agent/context-graphs/dynamic-behaviors.md)
{% endcontent-ref %}

## State Types Reference

Each state type serves a specific purpose in managing conversation flow and agent behavior.

| State Type          | Purpose                                                                               | Typical Use                                                                                                         |
| ------------------- | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| **Action**          | Deliver user-facing responses within guardrails                                       | Conversational turns, report delivery                                                                               |
| **Decision**        | Select among authored exits using current inputs                                      | Routing between workflows, escalation decisions                                                                     |
| **Annotation**      | Inject preset guidance into the agent's reasoning, then advance to a fixed next state | Steer reasoning between states without an extra model turn (for example, inject a reminder before a sensitive step) |
| **Data Collection** | Collect structured fields from the caller with surface fallback                       | Insurance intake, demographic verification, medication lists                                                        |

Data-collection states define fields to gather, a completion transition, turn limits, and an optional [surface](/channels/surfaces.md) fallback. The fallback can build a form from remaining fields after the configured number of turns; creation and delivery still depend on entity context and a supported Surface channel.

The same graph can support voice and text runtimes, but channel capabilities and delivery semantics differ. Use channel overrides and test each enabled channel separately.

### Designing a State

Each state definition should answer five questions before it ships to production:

1. **Objective** - What outcome must be true before the state can exit?
2. **Guidance** - Which ordered actions or prompts keep the model on the intended path?
3. **Boundaries** - Which behaviors are forbidden, especially for safety or compliance?
4. **Exit criteria** - What explicit signals trigger each transition, and which state follows?
5. **Tooling and memory configuration** - Which tool calls are exposed in this state, and should active memory retrieval be skipped?

State tool-call specs gate workflow tools bound to that state. Runtime-provided system tools and shared platform tools can also be exposed when the service and channel enable them, so state bindings are not a universal inventory of every callable tool. Turn policy can further block supported system tools such as forwarding.

### Action State Extensions

Action states support several optional workflow controls. The asynchronous and channel-specific controls include:

* **Wait conditions** - A state can declare a `wait_for` condition that pauses the context graph. The agent stays in the current state, constrained to empathetic small-talk, until the condition clears (e.g., a surface submission or human approval).
* **Surface templates** - A state can include a surface spec that requests [surface](/channels/surfaces.md) creation on state entry. Creation requires valid entity context and a successful platform request.
* **Channel overrides** - Per-channel overrides for objective and action guidelines. When the same context graph runs across voice and SMS, overrides let each channel tailor behavior without duplicating the entire state definition.
* **Completion-gated navigation** - A tool call spec can set `navigate_on_completion`. After a successful result, the engine re-evaluates navigation without waiting for another user message. The navigator can remain in the state or select another valid state; this option does not guarantee that every completion advances.

### Tool Dispatch Configuration

Each tool a state binds carries three independent dispatch axes that control *when* the tool runs, *how* its result re-enters the conversation, and *whether* the work is tied to the turn that asked for it. All three default to the historical behavior, so existing services are unaffected.

* **Execution** - `blocking` (default) awaits the tool inline within the turn, so its result is in hand before the agent continues; `background` dispatches it off-turn so the agent keeps the floor and the result arrives later. Use `background` for work that can take longer than the caller should wait in silence.
* **Delivery** - `interrupt` (default) surfaces the result as soon as it is ready, as a fresh continuation turn; `queue` folds the result silently into the next user turn instead. Two combinations are rejected when you save the context-graph version: a `background` tool may not use `queue` (a fire-and-forget result that never surfaces is a silent dead-end), and a tool in the terminal state may not be `background` (there is no later turn to deliver into).
* **Lifecycle** - `independent` (default) lets a `background` task continue after the launching turn; later delivery still depends on the channel and conversation remaining deliverable. `coupled` ties the task to the turn that launched it: if the user sends another message or the conversation closes first, the task is cooperatively superseded and its result is dropped. This axis is currently meaningful for background work on text and chat paths; voice uses its own teardown behavior.

The lifecycle axis decides what happens to a `background` result once the conversation has moved on:

```mermaid
flowchart TD
    D["Turn N dispatches a\nbackground tool"] --> R["Tool runs off-turn\n(agent keeps the floor)"]
    R --> C{"Tool completes"}
    C -->|"independent (default)"| DEL["Deliver the result\n(whenever ready)"]
    C -->|"coupled, conversation moved on\n(new turn or ended)"| DROP["Drop the result\n(task superseded)"]
    C -->|"coupled, still the same turn"| DEL
    style DEL fill:#f9f9f9,stroke:#333
    style DROP fill:#fff,stroke:#999,stroke-dasharray: 5 5
```

## Automated Optimization Through Agent Forge

[Agent Forge](/reference/agent-forge.md) lets coding agents inspect, author, validate, and apply Context Graph configuration. Use simulation and production evidence to propose changes, then review the diff and rerun relevant suites before promotion. Forge does not make graph optimization automatic or guarantee that a configuration change improves outcomes.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.amigo.ai/agent/context-graphs.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
