# 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, while 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" but note the API field name where relevant. See [Core Concepts](https://docs.amigo.ai/developer-guide/getting-started/core-concepts) for more on the relationship between agents, context graphs, and services.
{% 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](https://docs.amigo.ai/developer-guide/platform-api/platform-api/agents).
{% endhint %}

## How Agents & 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** (state machine defining the conversational flow)
* **Version Sets** that pin specific versions of each for deployment

{% @mermaid/diagram content="%%{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'

const client = new AmigoClient({ orgId: 'org_1234', apiKey: 'key', apiSecret: 'secret' })

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

client = AmigoClient(org_id="org_1234", api_key="key", api_secret="secret")

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 subsequent 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** Pass `version` as a query parameter to specify a base version to diff against. If omitted, the latest version is used as the base.
{% 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',
        goal: 'Greet the user and understand their needs.',
        action_guidelines: ['Introduce yourself warmly.'],
        boundary_constraints: [],
        intra_state_navigation_guidelines: [],
        exit_conditions: [{ condition: 'User states their goal', next_state: 'terminal' }],
        tool_call_specs: [],
      },
      {
        type: 'action',
        name: 'terminal',
        goal: 'Wrap up the conversation.',
        action_guidelines: ['Thank the user.'],
        boundary_constraints: [],
        intra_state_navigation_guidelines: [],
        exit_conditions: [],
        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",
                "goal": "Greet the user and understand their needs.",
                "action_guidelines": ["Introduce yourself warmly."],
                "boundary_constraints": [],
                "intra_state_navigation_guidelines": [],
                "exit_conditions": [{"condition": "User states their goal", "next_state": "terminal"}],
                "tool_call_specs": [],
            },
            {
                "type": "action",
                "name": "terminal",
                "goal": "Wrap up the conversation.",
                "action_guidelines": ["Thank the user."],
                "boundary_constraints": [],
                "intra_state_navigation_guidelines": [],
                "exit_conditions": [],
                "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.service_hierarchical_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.service_hierarchical_state_machine_versions:
    print(v.version, v.created_at)
```

{% endtab %}
{% endtabs %}

## Typical Workflow

{% @mermaid/diagram content="%%{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

* Core API → [Organization Management](https://docs.amigo.ai/developer-guide/classic-api/core-api/organization)
* Core API → [Services](https://docs.amigo.ai/developer-guide/classic-api/core-api/services)
* Core API → [Tools](https://docs.amigo.ai/developer-guide/classic-api/core-api/tools)
* Best Practices → [Version Sets & Promotion](https://docs.amigo.ai/developer-guide/operations/devops/version-sets-best-practices)
