# Dynamic Behaviors

Manage organization-scoped, versioned sets of trigger-based behaviors that activate during conversations. This page documents the core API endpoints for creating, updating, and managing Dynamic Behavior Sets and their versions.

{% hint style="info" %}
**API Terminology** In the API, these are called "Dynamic Behavior Sets" (`dynamic_behavior_set`). In our conceptual documentation and platform UI, we refer to them as "Dynamic Behaviors" - configurable rules that inject instructions or modify tool availability based on conversation context. See [Conceptual Docs: Dynamic Behaviors](https://docs.amigo.ai/agent/dynamic-behavior) for the architectural perspective.
{% endhint %}

## Overview

Dynamic Behavior Sets are versioned collections of trigger-action rules that activate during conversations when specific patterns are detected. Each set contains:

* **Conversation Triggers**: Natural-language descriptions of conversation patterns that activate the behavior (matched via semantic similarity).
* **Actions**: Operations performed when a trigger fires. Two action types are supported:
  * `inject-instruction`: Injects additional instructions into the agent's context.
  * `change-tool-candidates`: Modifies the set of tools available to the agent.

### Key Properties

* **Organization-scoped**: Each behavior set belongs to a single organization.
* **Versioned**: Each set maintains a version history. New versions are created with incremented version numbers.
* **Service-bound**: Behavior sets are applied to one or more services and activated via version sets.
* **Activatable**: Sets have an `is_active` flag that controls whether they are eligible for invocation.

### How They Relate to Services

Dynamic Behavior Sets are applied to services through **version sets**. When a conversation is created with a specific version set, the platform evaluates the associated behavior sets' triggers against each user message. When a trigger matches, the corresponding actions execute within that interaction.

```
Service: "Health Coach"
├─ Version Set: "release"
│   └─ Behaviors: [
│       "Emergency Response Protocol",
│       "Calorie Target Guidance"
│     ]
└─ Version Set: "staging"
    └─ Behaviors: [
        "Emergency Response Protocol",
        "Calorie Target Guidance",
        "Medication Side Effects Guide"   // Testing new behavior
      ]
```

For more on configuring version sets, see [Version Sets & Promotion](https://docs.amigo.ai/developer-guide/operations/devops/version-sets-best-practices). For data access and table schemas, see [Dynamic Behaviors Data Access](https://docs.amigo.ai/developer-guide/classic-api/data-access/organization-tables/dynamic-behaviors).

### Trigger Evaluation Flow

{% @mermaid/diagram content="%%{init: {"flowchart": {"useMaxWidth": true, "nodeSpacing": 20, "rankSpacing": 30}, "theme": "base", "themeVariables": {"primaryColor": "#D4E2E7", "primaryTextColor": "#100F0F", "primaryBorderColor": "#083241", "lineColor": "#575452", "textColor": "#100F0F", "clusterBkg": "#F1EAE7", "clusterBorder": "#D7D2D0"}}}%%
flowchart LR
M\[User Message] --> E\[Evaluate Triggers<br/>semantic similarity]
E -->|Match| A{Action Type}
E -->|No match| N\[Continue normally]
A -->|inject-instruction| I\[Inject / Override<br/>agent instructions]
A -->|change-tool-candidates| T\[Add / Replace<br/>available tools]
I --> R\[Agent responds<br/>with modified context]
T --> R

```
style M fill:#D4E2E7,stroke:#083241,color:#100F0F,stroke-width:2px
style E fill:#F0DDD9,stroke:#AA412A,color:#100F0F,stroke-width:2px
style A fill:#F0DDD9,stroke:#AA412A,color:#100F0F,stroke-width:2px
style I fill:#DDE3DB,stroke:#2c3827,color:#100F0F,stroke-width:2px
style T fill:#DDE3DB,stroke:#2c3827,color:#100F0F,stroke-width:2px
style R fill:#E8E2EB,stroke:#C5BACE,color:#100F0F,stroke-width:2px
style N fill:#F1EAE7,stroke:#D7D2D0,color:#100F0F,stroke-width:2px" %}
```

### Typical Lifecycle

1. Create a behavior set with an initial version (name, triggers, actions).
2. Apply it to one or more services.
3. Test in a staging version set.
4. Activate the set (`is_active: true`) and promote to release.
5. Create new versions as triggers or actions evolve.
6. Query invocation history to verify trigger accuracy.

### Action Types

#### Inject Instruction

Adds or overrides the agent's instructions when a trigger fires.

```json
{
  "type": "inject-instruction",
  "instruction": "If the user mentions chest pain, immediately recommend calling emergency services.",
  "overrides_instructions": false
}
```

| Field                    | Type    | Description                                                                      |
| ------------------------ | ------- | -------------------------------------------------------------------------------- |
| `type`                   | string  | Must be `"inject-instruction"`                                                   |
| `instruction`            | string  | The instruction text to inject                                                   |
| `overrides_instructions` | boolean | If `true`, replaces the state's original instruction. If `false`, appends to it. |

#### Change Tool Candidates

Modifies the tools available to the agent when a trigger fires.

```json
{
  "type": "change-tool-candidates",
  "tool_call_specs": [
    {
      "tool_id": "670a1234567890abcdef1234",
      "version_constraint": ">=1.0.0",
      "additional_instruction": "Use this tool to look up drug interactions",
      "result_persistence": "persisted-preferred"
    }
  ],
  "overrides_existing_tool_call_specs": false
}
```

| Field                                | Type    | Description                                                        |
| ------------------------------------ | ------- | ------------------------------------------------------------------ |
| `type`                               | string  | Must be `"change-tool-candidates"`                                 |
| `tool_call_specs`                    | array   | List of tool call specifications to add or replace                 |
| `overrides_existing_tool_call_specs` | boolean | If `true`, replaces existing tool specs. If `false`, adds to them. |

## Create a Dynamic Behavior Set

Create a new dynamic behavior set along with its initial version. The initial version defines the triggers and actions that will be active when the set is activated.

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

```bash
curl --request POST \
     --url 'https://api.amigo.ai/v1/<YOUR-ORG-ID>/dynamic_behavior_set/' \
     --header 'Authorization: Bearer <AUTH-TOKEN>' \
     --header 'Accept: application/json' \
     --header 'Content-Type: application/json' \
     --data '{
  "name": "Emergency Response Protocol",
  "tags": {"category": "safety", "priority": "high"},
  "applied_to_services": ["6618791275130b73714e8d1c"],
  "initial_version": {
    "is_active": true,
    "conversation_triggers": [
      "The user mentions feeling suicidal or self-harm",
      "The user describes a medical emergency"
    ],
    "actions": [
      {
        "type": "inject-instruction",
        "instruction": "Immediately provide emergency hotline numbers and recommend the user call 911.",
        "overrides_instructions": true
      }
    ]
  }
}'
```

{% endtab %}

{% tab title="Python SDK" %}

```python
from amigo_sdk import AmigoClient

with AmigoClient() as client:
    result = client.dynamic_behavior_set.create(
        name="Emergency Response Protocol",
        tags={"category": "safety", "priority": "high"},
        applied_to_services=["6618791275130b73714e8d1c"],
        initial_version={
            "is_active": True,
            "conversation_triggers": [
                "The user mentions feeling suicidal or self-harm",
                "The user describes a medical emergency",
            ],
            "actions": [
                {
                    "type": "inject-instruction",
                    "instruction": "Immediately provide emergency hotline numbers and recommend the user call 911.",
                    "overrides_instructions": True,
                }
            ],
        },
    )
    print(f"Created: {result.dynamic_behavior_set_id}")
```

{% endtab %}

{% tab title="TypeScript SDK" %}

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

const client = new AmigoClient({ ...config });
const result = await client.dynamicBehaviorSet.create({
  name: "Emergency Response Protocol",
  tags: { category: "safety", priority: "high" },
  applied_to_services: ["6618791275130b73714e8d1c"],
  initial_version: {
    is_active: true,
    conversation_triggers: [
      "The user mentions feeling suicidal or self-harm",
      "The user describes a medical emergency",
    ],
    actions: [
      {
        type: "inject-instruction",
        instruction:
          "Immediately provide emergency hotline numbers and recommend the user call 911.",
        overrides_instructions: true,
      },
    ],
  },
});
console.log(`Created: ${result.dynamic_behavior_set_id}`);
```

{% endtab %}
{% endtabs %}

**Response (201):**

```json
{
  "dynamic_behavior_set_id": "6618791275130b73714e8d1c"
}
```

{% hint style="info" %}
**Rate Limit:** 200 requests per minute.
{% endhint %}

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

## List Dynamic Behavior Sets

Retrieve dynamic behavior sets matching the given filters. Only sets the authenticated user has `DynamicBehaviorInstruction:GetDynamicBehaviorInstruction` permission for are returned.

Common filters:

* `id=<id>` (repeatable) - filter by specific IDs
* `is_active=true|false` - filter by active status
* `applied_to_service=<service_id>` (repeatable) - filter by associated service
* `creator=<org_id,user_id>` (repeatable) - filter by creator
* `tag=key:value` (repeatable; `value` may be `*` for any value or empty for null)
* `sort_by=+updated_at|-updated_at` (repeatable)
* `limit` (0-50, default 50), `continuation_token` (int, default 0)

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

```bash
curl --request GET \
     --url 'https://api.amigo.ai/v1/<YOUR-ORG-ID>/dynamic_behavior_set/?limit=10&is_active=true' \
     --header 'Authorization: Bearer <AUTH-TOKEN>' \
     --header 'Accept: application/json'
```

{% endtab %}

{% tab title="Python SDK" %}

```python
from amigo_sdk import AmigoClient

with AmigoClient() as client:
    result = client.dynamic_behavior_set.list(limit=10, is_active=True)
    for dbs in result.dynamic_behavior_sets:
        print(f"{dbs.name} (ID: {dbs.id}, active: {dbs.is_active})")
```

{% endtab %}

{% tab title="TypeScript SDK" %}

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

const client = new AmigoClient({ ...config });
const result = await client.dynamicBehaviorSet.list({
  limit: 10,
  is_active: true,
});
result.dynamic_behavior_sets?.forEach((dbs) => {
  console.log(`${dbs.name} (ID: ${dbs.id}, active: ${dbs.is_active})`);
});
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
**Rate Limit:** 500 requests per minute.
{% endhint %}

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

## Search Dynamic Behavior Sets

Search for dynamic behavior sets by text query. The query matches against set names and the triggers of the latest version. Returns the top 50 results sorted by relevance.

{% hint style="info" %}
**Rate Limit:** 50 requests per minute.
{% endhint %}

{% openapi src="<https://api.amigo.ai/v1/openapi.json>" path="/v1/{organization}/dynamic\_behavior\_set/search" method="get" %}
<https://api.amigo.ai/v1/openapi.json>
{% endopenapi %}

## Update a Dynamic Behavior Set

Update a dynamic behavior set's metadata, service associations, or active status. All fields are optional; only provided fields are updated.

```bash
curl --request POST \
     --url 'https://api.amigo.ai/v1/<YOUR-ORG-ID>/dynamic_behavior_set/<BEHAVIOR-SET-ID>/' \
     --header 'Authorization: Bearer <AUTH-TOKEN>' \
     --header 'Accept: application/json' \
     --header 'Content-Type: application/json' \
     --data '{
  "is_active": false,
  "tags": {"category": "safety", "status": "deprecated"}
}'
```

{% hint style="warning" %}
If `is_active` is set to `true`, the update will fail with HTTP 409 if another active set with the same name already exists.
{% endhint %}

{% hint style="info" %}
**Rate Limit:** 500 requests per minute.
{% endhint %}

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

## Delete a Dynamic Behavior Set

Permanently delete a dynamic behavior set.

{% hint style="warning" %}
Deletion is permanent. Deactivate a set (`is_active: false`) instead if you may need it again.
{% endhint %}

{% hint style="info" %}
**Rate Limit:** 500 requests per minute.
{% endhint %}

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

## Get Invocations

Retrieve the invocation history for a dynamic behavior set - a record of when and where the behavior's triggers fired during conversations. Useful for verifying trigger accuracy and auditing activation frequency.

Common filters:

* `limit` (1-30, default 30)
* `continuation_token` (int, default 0)
* `sort_by=+invoked_at|-invoked_at` (repeatable)

{% hint style="info" %}
Only invocations from messages that the authenticated user has the `Conversation:GetMessage` permission for are returned.
{% endhint %}

{% hint style="info" %}
**Rate Limit:** 50 requests per minute.
{% endhint %}

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

## Create a Version

Create a new version of an existing dynamic behavior set. Each version defines a complete set of triggers and actions. Version numbers are automatically incremented.

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

```bash
curl --request POST \
     --url 'https://api.amigo.ai/v1/<YOUR-ORG-ID>/dynamic_behavior_set/<BEHAVIOR-SET-ID>/version/' \
     --header 'Authorization: Bearer <AUTH-TOKEN>' \
     --header 'Accept: application/json' \
     --header 'Content-Type: application/json' \
     --data '{
  "conversation_triggers": [
    "The user mentions feeling suicidal or self-harm",
    "The user describes a medical emergency",
    "The user mentions harming others"
  ],
  "actions": [
    {
      "type": "inject-instruction",
      "instruction": "Immediately provide crisis resources: 988 Suicide & Crisis Lifeline, 911 for emergencies.",
      "overrides_instructions": true
    }
  ]
}'
```

{% endtab %}
{% endtabs %}

**Response (201):**

```json
{
  "new_version_number": 3
}
```

{% hint style="info" %}
You can optionally pass `?version=<n>` as a query parameter to assert the expected version number. If the next version does not match, the request returns HTTP 400.
{% endhint %}

{% hint style="info" %}
**Rate Limit:** 200 requests per minute.
{% endhint %}

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

## Get Versions

Retrieve the version history for a dynamic behavior set.

Common filters:

* `version=<constraint>` - exact version number, or `"latest"` for the most recent
* `limit` (1-10, default 10)
* `continuation_token` (int, default 0)
* `sort_by=+version|-version` (repeatable)

{% hint style="info" %}
**Rate Limit:** 1000 requests per minute.
{% endhint %}

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

## Related

* Core API -> [Services](https://docs.amigo.ai/developer-guide/classic-api/core-api/services) (version sets and behavior application)
* Best Practices -> [Version Sets & Promotion](https://docs.amigo.ai/developer-guide/operations/devops/version-sets-best-practices)
* Data Access -> [Dynamic Behaviors Tables](https://docs.amigo.ai/developer-guide/classic-api/data-access/organization-tables/dynamic-behaviors)
* Getting Started -> [Authentication](https://docs.amigo.ai/developer-guide/getting-started/authentication)
