> 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/developer-guide/classic-api/core-api/agents-and-context-graphs.md).

# Agents & Context Graphs

Manage the core agent definitions and context graphs that power your organization's AI services. Agents define the persona and behavior of your AI; context graphs define the conversational flow and state management.

{% hint style="info" %}
**API Terminology** In the API, context graphs are called `service_hierarchical_state_machine`. Throughout this documentation we use the platform name "Context Graph" and note the API field name where relevant. See [Core Concepts](/developer-guide/getting-started/core-concepts.md) for more on how agents, context graphs, and services relate.
{% endhint %}

| Platform Name | API Name                             |
| ------------- | ------------------------------------ |
| Context Graph | `service_hierarchical_state_machine` |
| Agent         | `agent`                              |

{% hint style="info" %}
**Enterprise deployments**: The Platform API also has workspace-scoped agents with richer configuration for voice and EHR workflows. See [Platform API: Agents](/developer-guide/platform-api/workspaces/agents.md).
{% endhint %}

## How Agents and Context Graphs Relate to Services

Agents and context graphs are the building blocks of services. A service combines:

* An **Agent** (persona, identity, behaviors, communication style)
* A **Context Graph** (the state machine that defines conversational flow)
* **Version Sets** that pin specific versions of each for deployment

```mermaid
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#D4E2E7", "primaryTextColor": "#100F0F", "primaryBorderColor": "#083241", "lineColor": "#575452", "textColor": "#100F0F", "clusterBkg": "#F1EAE7", "clusterBorder": "#D7D2D0"}}}%%
flowchart TB
  A[Agent v2] --> S[Service]
  CG[Context Graph v3] --> S
  S --> VS1["Version Set: release"]
  S --> VS2["Version Set: staging"]
```

Both agents and context graphs are **versioned**. You create the resource first, then create versions of it. Services reference specific versions through version sets.

## Agent Management

### Create an Agent

Create a new agent definition for the organization. This creates the agent container. You must then create at least one version before the agent can be used in a service.

**Permission required:** `Organization:CreateAgent`

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/agent" method="post" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import { AmigoClient } from '@amigo-ai/sdk'

// See the Authentication guide for client configuration
const client = new AmigoClient({ ...config })

const agent = await client.agents.createAgent({
  body: { agent_name: 'Support Agent' },
})

console.log(agent.id) // newly created agent ID
```

{% endtab %}

{% tab title="Python" %}

```python
from amigo_sdk import AmigoClient
from amigo_sdk.generated.model import OrganizationCreateAgentRequest

# See the Authentication guide for client configuration
client = AmigoClient()

agent = client.agents.create_agent(
    body=OrganizationCreateAgentRequest(agent_name="Support Agent")
)

print(agent.id)  # newly created agent ID
```

{% endtab %}
{% endtabs %}

### List Agents

Retrieve agents for the organization. Supports filtering by deprecation status and ID.

**Permission required:** `Organization:GetAgent` (only agents the caller has permission for are returned)

Query parameters:

* `deprecated`: filter by deprecation status
* `id`: filter by specific agent IDs (repeatable)
* `limit`: results per page (integer)
* `continuation_token`: pagination token (integer)

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/agent" method="get" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
const agents = await client.agents.getAgents()

for (const agent of agents.agents) {
  console.log(agent.id, agent.agent_name)
}
```

{% endtab %}

{% tab title="Python" %}

```python
agents = client.agents.get_agents()

for agent in agents.agents:
    print(agent.id, agent.agent_name)
```

{% endtab %}
{% endtabs %}

### Create an Agent Version

Create a new version of an agent. For the first version, all fields must be provided. For later versions, only supply the fields you want to change. Other fields carry forward from the previous latest version.

**Permission required:** `Organization:CreateAgentVersion`

Fields that can be set per version:

| Field                    | Description                                            |
| ------------------------ | ------------------------------------------------------ |
| `initials`               | The agent's display initials                           |
| `identity`               | Information about the agent's identity                 |
| `background`             | A description of the agent's background                |
| `behaviors`              | Behavioral guidelines the agent follows                |
| `communication_patterns` | Descriptions of the agent's communication style        |
| `voice_config`           | Voice configuration (set to `null` to leave unchanged) |

{% hint style="info" %}
**Version Query Parameter** The optional `version` query parameter is an optimistic concurrency check: it asserts the expected version number of the new version being created. If specified and the next version in the database does not equal that value, the endpoint returns 409 Conflict (for the first version, the value must be 1). Fields not supplied always carry forward from the previous latest version; the parameter never selects a base version.
{% endhint %}

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/agent/{agent\_id}/" method="post" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import { agentId } from '@amigo-ai/sdk'

const version = await client.agents.createAgentVersion({
  agentId: agentId('agent_abc123'),
  body: {
    initials: 'SA',
    identity: { name: 'Support Agent' },
    background: 'A helpful customer support agent.',
    behaviors: ['Be concise and helpful.'],
    communication_patterns: ['Use a friendly, professional tone.'],
  },
})

console.log(version.id, version.version)
```

{% endtab %}

{% tab title="Python" %}

```python
from amigo_sdk.generated.model import OrganizationCreateAgentVersionRequest

version = client.agents.create_agent_version(
    agent_id="agent_abc123",
    body=OrganizationCreateAgentVersionRequest(
        initials="SA",
        identity={"name": "Support Agent"},
        background="A helpful customer support agent.",
        behaviors=["Be concise and helpful."],
        communication_patterns=["Use a friendly, professional tone."],
    ),
)

print(version.id, version.version)
```

{% endtab %}
{% endtabs %}

### Delete an Agent

Mark an agent as deprecated. The agent and its versions are not physically deleted, but new services cannot use this agent and inactive services cannot be activated with it.

{% hint style="warning" %}
**Active Service Check** This endpoint returns an error if an active service still uses this agent. Ongoing conversations using the agent continue to work.
{% endhint %}

**Permission required:** `Organization:DeleteAgent`

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/agent/{agent\_id}/" method="delete" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import { agentId } from '@amigo-ai/sdk'

await client.agents.deleteAgent({
  agentId: agentId('agent_abc123'),
})
```

{% endtab %}

{% tab title="Python" %}

```python
client.agents.delete_agent(agent_id="agent_abc123")
```

{% endtab %}
{% endtabs %}

### Get Agent Versions

Retrieve the version history of an agent.

**Permission required:** `Organization:GetAgent`

Query parameters:

* `version`: filter by specific version number
* `limit`: results per page (integer)
* `continuation_token`: pagination token (integer)
* `sort_by`: sort order (repeatable)

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/agent/{agent\_id}/version" method="get" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import { agentId } from '@amigo-ai/sdk'

const versions = await client.agents.getAgentVersions({
  agentId: agentId('agent_abc123'),
})

for (const v of versions.agent_versions) {
  console.log(v.version, v.created_at)
}
```

{% endtab %}

{% tab title="Python" %}

```python
versions = client.agents.get_agent_versions(agent_id="agent_abc123")

for v in versions.agent_versions:
    print(v.version, v.created_at)
```

{% endtab %}
{% endtabs %}

## Context Graph Management

{% hint style="info" %}
**API Field Name** Context Graphs are called `service_hierarchical_state_machine` in the API. All endpoint paths and request/response fields use this name.
{% endhint %}

### Create a Context Graph

Create a new context graph for the organization. This creates the container. You must then create at least one version before it can be used in a service.

**Permission required:** `Organization:CreateServiceHierarchicalStateMachine`

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/service\_hierarchical\_state\_machine" method="post" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
const graph = await client.contextGraphs.createContextGraph({
  body: { state_machine_name: 'Onboarding Flow' },
})

console.log(graph.id) // newly created context graph ID
```

{% endtab %}

{% tab title="Python" %}

```python
from amigo_sdk.generated.model import (
    OrganizationCreateServiceHierarchicalStateMachineRequest,
)

graph = client.context_graphs.create_context_graph(
    body=OrganizationCreateServiceHierarchicalStateMachineRequest(
        state_machine_name="Onboarding Flow"
    )
)

print(graph.id)  # newly created context graph ID
```

{% endtab %}
{% endtabs %}

### List Context Graphs

Retrieve context graphs for the organization. Supports filtering by deprecation status and ID.

**Permission required:** `Organization:GetServiceHierarchicalStateMachine` (only context graphs the caller has permission for are returned)

Query parameters:

* `deprecated`: filter by deprecation status
* `id`: filter by specific IDs (repeatable)
* `limit`: results per page (integer)
* `continuation_token`: pagination token (integer)

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/service\_hierarchical\_state\_machine" method="get" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
const graphs = await client.contextGraphs.getContextGraphs()

for (const graph of graphs.service_hierarchical_state_machines) {
  console.log(graph.id, graph.state_machine_name)
}
```

{% endtab %}

{% tab title="Python" %}

```python
graphs = client.context_graphs.get_context_graphs()

for graph in graphs.service_hierarchical_state_machines:
    print(graph.id, graph.state_machine_name)
```

{% endtab %}
{% endtabs %}

### Create a Context Graph Version

Create a new version of a context graph. The version defines the full state machine including states, transitions, initial states, terminal states, and behavioral guidelines.

**Permission required:** `Organization:CreateServiceHierarchicalStateMachineVersion`

The version must satisfy these constraints:

* Each action state must have at least one action
* Exit condition `next_state` values must reference existing states (not the current state), or reference external state machines
* Required fields include `description`, `states`, `new_user_initial_state`, `returning_user_initial_state`, `terminal_state`, `references`, and global guidelines

| Field                                      | Description                                                      |
| ------------------------------------------ | ---------------------------------------------------------------- |
| `description`                              | A description of this context graph version                      |
| `states`                                   | The internal states in the context graph                         |
| `new_user_initial_state`                   | The starting state for new users (must be an action state)       |
| `returning_user_initial_state`             | The starting state for returning users (must be an action state) |
| `terminal_state`                           | The state when a session ends (must be an action state)          |
| `references`                               | Dictionary of external context graphs this one references        |
| `global_intra_state_navigation_guidelines` | Guidelines for navigating between subgoals and exit conditions   |
| `global_action_guidelines`                 | Guidelines for agent behavior when engaging with users           |
| `global_boundary_constraints`              | Guidelines for what the agent should not do                      |

{% hint style="info" %}
**Dry Run** Pass `dry_run=true` as a query parameter to validate the version without creating it.
{% endhint %}

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/service\_hierarchical\_state\_machine/{service\_hierarchical\_state\_machine\_id}/" method="post" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
const version = await client.contextGraphs.createContextGraphVersion({
  contextGraphId: 'cg_abc123',
  body: {
    description: 'Initial onboarding flow',
    states: [
      {
        type: 'action',
        name: 'greeting',
        objective: 'Greet the user and understand their needs.',
        actions: ['Greet the user', 'Ask what they need'],
        action_guidelines: ['Introduce yourself warmly.'],
        boundary_constraints: [],
        intra_state_navigation_guidelines: [],
        exit_conditions: [{ description: 'User states their goal', next_state: 'terminal' }],
        action_tool_call_specs: [],
        exit_condition_tool_call_specs: [],
      },
      {
        type: 'action',
        name: 'terminal',
        objective: 'Wrap up the conversation.',
        actions: ['Thank the user'],
        action_guidelines: ['Thank the user.'],
        boundary_constraints: [],
        intra_state_navigation_guidelines: [],
        exit_conditions: [],
        action_tool_call_specs: [],
        exit_condition_tool_call_specs: [],
      },
    ],
    new_user_initial_state: 'greeting',
    returning_user_initial_state: 'greeting',
    terminal_state: 'terminal',
    references: {},
    global_intra_state_navigation_guidelines: [],
    global_action_guidelines: ['Be helpful and concise.'],
    global_boundary_constraints: ['Do not share internal system details.'],
  },
})

console.log(version.id, version.version)
```

{% endtab %}

{% tab title="Python" %}

```python
from amigo_sdk.generated.model import (
    OrganizationCreateServiceHierarchicalStateMachineVersionRequest,
)

version = client.context_graphs.create_context_graph_version(
    context_graph_id="cg_abc123",
    body=OrganizationCreateServiceHierarchicalStateMachineVersionRequest(
        description="Initial onboarding flow",
        states=[
            {
                "type": "action",
                "name": "greeting",
                "objective": "Greet the user and understand their needs.",
                "actions": ["Greet the user", "Ask what they need"],
                "action_guidelines": ["Introduce yourself warmly."],
                "boundary_constraints": [],
                "intra_state_navigation_guidelines": [],
                "exit_conditions": [{"description": "User states their goal", "next_state": "terminal"}],
                "action_tool_call_specs": [],
                "exit_condition_tool_call_specs": [],
            },
            {
                "type": "action",
                "name": "terminal",
                "objective": "Wrap up the conversation.",
                "actions": ["Thank the user"],
                "action_guidelines": ["Thank the user."],
                "boundary_constraints": [],
                "intra_state_navigation_guidelines": [],
                "exit_conditions": [],
                "action_tool_call_specs": [],
                "exit_condition_tool_call_specs": [],
            },
        ],
        new_user_initial_state="greeting",
        returning_user_initial_state="greeting",
        terminal_state="terminal",
        references={},
        global_intra_state_navigation_guidelines=[],
        global_action_guidelines=["Be helpful and concise."],
        global_boundary_constraints=["Do not share internal system details."],
    ),
)

print(version.id, version.version)
```

{% endtab %}
{% endtabs %}

### Delete a Context Graph

Mark a context graph as deprecated. The context graph and its versions are not physically deleted, but new services cannot use it and inactive services cannot be activated with it.

{% hint style="warning" %}
**Active Service Check** This endpoint returns an error if an active service still uses this context graph. Ongoing conversations and versions referenced by other context graphs continue to work.
{% endhint %}

**Permission required:** `Organization:DeleteServiceHierarchicalStateMachine`

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/service\_hierarchical\_state\_machine/{state\_machine\_id}/" method="delete" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
await client.contextGraphs.deleteContextGraph({
  contextGraphId: 'cg_abc123',
})
```

{% endtab %}

{% tab title="Python" %}

```python
client.context_graphs.delete_context_graph(context_graph_id="cg_abc123")
```

{% endtab %}
{% endtabs %}

### Get Context Graph Versions

Retrieve the version history of a context graph.

**Permission required:** `Organization:GetServiceHierarchicalStateMachine`

Query parameters:

* `version`: filter by specific version number
* `limit`: results per page (integer)
* `continuation_token`: pagination token (integer)
* `sort_by`: sort order (repeatable)

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/organization/service\_hierarchical\_state\_machine/{service\_hierarchical\_state\_machine\_id}/version" method="get" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

{% tabs %}
{% tab title="TypeScript" %}

```typescript
const versions = await client.contextGraphs.getContextGraphVersions({
  contextGraphId: 'cg_abc123',
})

for (const v of versions.state_machine_versions) {
  console.log(v.version, v.created_at)
}
```

{% endtab %}

{% tab title="Python" %}

```python
versions = client.context_graphs.get_context_graph_versions(
    context_graph_id="cg_abc123"
)

for v in versions.state_machine_versions:
    print(v.version, v.created_at)
```

{% endtab %}
{% endtabs %}

## Typical Workflow

```mermaid
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#D4E2E7", "primaryTextColor": "#100F0F", "primaryBorderColor": "#083241", "lineColor": "#575452", "textColor": "#100F0F", "clusterBkg": "#F1EAE7", "clusterBorder": "#D7D2D0"}}}%%
flowchart TB
  A[Create Agent] --> B[Create Agent Version]
  C[Create Context Graph] --> D[Create Context Graph Version]
  B --> E[Create Service]
  D --> E
  E --> F[Configure Version Set]
  F --> G[Activate Service]
  B -.iterate.-> B
  D -.iterate.-> D

  style A fill:#DDE3DB,stroke:#2c3827,color:#100F0F
  style C fill:#DDE3DB,stroke:#2c3827,color:#100F0F
  style G fill:#F0DDD9,stroke:#AA412A,color:#100F0F
```

1. **Create** the agent and context graph containers
2. **Create initial versions** of each with full configuration
3. **Create a service** referencing the agent and context graph
4. **Configure version sets** (release, staging, dev) to pin specific versions
5. **Iterate** by creating new versions and updating version sets

## Related

* Classic API -> [Organization Management](/developer-guide/classic-api/core-api/organization.md)
* Classic API -> [Services](/developer-guide/classic-api/core-api/services.md)
* Classic API -> [Tools](/developer-guide/classic-api/core-api/tools.md)
* Best Practices → [Version Sets & Promotion](/developer-guide/operations/devops/version-sets-best-practices.md)


---

# 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/developer-guide/classic-api/core-api/agents-and-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.
