# Context

Context is the foundation of how your AI system understands its role, follows rules, and executes tasks. Rather than scattering instructions across your code, the InteractiveAI Platform lets you define, version, and manage all behavioral context from a single place.

The Context page lives under Build > Context in the sidebar. It provides a centralized repository where you create and organize the building blocks that shape your agent's behavior: what it knows, how it responds, which workflows it follows, and what rules it must obey.

### Why Context Matters

Hardcoding behavioral instructions creates friction. Every change requires a code deployment, making iteration slow and risky. The Context repository solves this by decoupling your AI system's behavioral definitions from your application logic:

* **Iterate without deploying.** Update context instantly through the UI or CLI without touching your codebase.
* **Version everything.** Every change creates a new version with full history, enabling rollback and comparison.
* **Control releases with labels.** Use labels like `production` and `staging` to control which version your application fetches.
* **Track usage.** See exactly which context is being used in production through linked generations.
* **Test before shipping.** Use the Playground to validate changes before promoting to production.

### Context Overview

The Context page displays six categories of context types at the top, each represented as a card. Below those cards, a table lists all the Prompts in your project.

<div data-with-frame="true"><figure><img src="/files/BZZBFjW4Iqd9Hy9I1Ala" alt=""><figcaption></figcaption></figure></div>

Each context type has a specific format and purpose:

| Context Type | Format            | Purpose                                          |
| ------------ | ----------------- | ------------------------------------------------ |
| **Policies** | YAML              | Behavior rules with conditions and actions       |
| **Routines** | YAML              | Step-by-step workflows with branching logic      |
| **Glossary** | JSON              | Domain-specific terms, definitions, and synonyms |
| **Macros**   | Markdown          | Reusable text templates and snippets             |
| **Prompts**  | Plain Text / JSON | General-purpose prompt templates                 |

Clicking any category card opens a filtered list showing only context items of that type. Clicking any individual item opens its detail view.

You can search, filter, and paginate the list using the controls at the top of the page. The **+ New Context** button in the top-right corner lets you create a new context item of any type.

***

### Policies

Policies are behavior rules defined as condition-action pairs that govern how your agent responds in specific situations. They are written in YAML format, and each policy contains a set of guidelines that the agent evaluates against incoming requests.

<div data-with-frame="true"><figure><img src="/files/6NsNfAW6TlDo7FkMFtrd" alt=""><figcaption></figcaption></figure></div>

#### How Policies Work

Each guideline within a policy defines four things:

1. **Name**: A human-readable name for the guideline (e.g., "Match brand voice")
2. **Condition**: The situation that triggers this guideline (e.g., "Any long-form content is being generated")
3. **Action**: What the agent should do when the condition is met (e.g., "Follow brand\_voice and tone from brand-vars")
4. **Tools** (Optional): Specifies any tools the agent should use when executing the action

#### Creating a Policy

{% tabs %}
{% tab title="Via the UI" %}

1. Navigate to Build > Context.
2. Click the **Policies** card or click **+ New Context**.
3. If you clicked + New Context, the type will be fixed to Policy when creating inside the Policies folder, if not select it from the options.
4. Enter a **Name** for the policy. You can use `/` notation to create sub-folders (e.g., `onboarding/welcome`).
5. Define your policy in the Context editor using YAML. Click **Insert template** to start from a pre-built structure. You can switch between **Editor** and **Preview** modes.&#x20;
6. Optionally add a JSON Config.
7. Under **Labels**, check "Set the Production label" if this version should go live immediately.
8. Add a **Commit Message** describing the changes.
9. Click **Create**.

<div data-with-frame="true"><figure><img src="/files/gGfNnu41mricpZaBC04R" alt=""><figcaption></figcaption></figure></div>
{% endtab %}

{% tab title="Via the CLI" %}

```bash
# Create a policy from a YAML file
iai policies create content-policies --file policy.yaml --labels production

# List all policies
iai policies list

# Get a specific policy
iai policies get content-policies

# Update a policy (creates a new version)
iai policies update content-policies --file updated-policy.yaml --labels production

# View the JSON schema for policies
iai policies schema
```

For the full CLI reference, see the [CLI Documentation](/cli/iai_policies.md).
{% endtab %}
{% endtabs %}

***

### Routines

Routines are step-by-step conversation workflows with branching logic and terminal states. They are written in YAML format and define the sequence of actions an agent should follow when handling a specific type of request.

<div data-with-frame="true"><figure><img src="/files/FCDeLWMpTlwosHGBffw6" alt=""><figcaption></figcaption></figure></div>

#### How Routines Work

The platform renders routines as interactive **visual diagrams** that make it easy to understand the flow at a glance. The diagram uses color-coded nodes to represent different types of steps:

| Node Type | Color                                       | Description                                                                                                                                                  |
| --------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Start** | <mark style="color:green;">Green</mark>     | The entry point of the routine. Contains the trigger condition that activates this workflow.                                                                 |
| **Chat**  | <mark style="color:purple;">Purple</mark>   | A conversational step where the agent communicates with the user. Contains a `chat_state` that describes what the agent should say or do at this point.      |
| **Tool**  | <mark style="color:$warning;">Orange</mark> | A tool or function invocation. Specifies which tool to call (e.g., `acme:get_customer_by_email`) and includes an instruction for why the tool is being used. |
| **Macro** | <mark style="color:blue;">Blue</mark>       | A reference to a reusable macro template that gets inserted at this point in the conversation.                                                               |
| **Fork**  | <mark style="color:$info;">Gray</mark>      | A decision point where the flow branches based on conditions.                                                                                                |

#### Reading the Diagram

Each node in the diagram is clickable. When you select a node, a **Details** panel opens on the right side showing:

* The node's name and type.
* **Incoming** connections: which node(s) lead to this step, and how many.
* **Chat state** (for Chat nodes): the instruction text that tells the agent what to do at this step.
* **Tools** (for Tool nodes): the specific tool(s) to invoke.
* **Outgoing** connections: which node(s) this step leads to, and how many.

The edges (arrows) between nodes represent **transitions**. Clicking an edge opens a **Transition** panel showing:

* **FROM**: The source node.
* **TO**: The destination node.
* **CONDITION**: The natural-language condition that must be true for this transition to occur (e.g., "The customer's question is answered", "The customer requests a refund", "The refund is over 100 USD or outside the 30-day window").

{% hint style="info" %}
The diagram supports zoom controls and full-screen mode.
{% endhint %}

#### Routine YAML Structure

Routines follow a structured YAML schema. Here is an example:

```yaml
title: API troubleshooting
description: Diagnose and resolve Acme Cloud API issues (401, 429, 5xx).
conditions: The user reports an API error, rate limit, or integration problem.
steps:
  - id: greet
    chat_state: Greet the customer and let them know you can help debug the API issue.

  - id: gather_details
    source: greet
    description: Collect the failing endpoint, HTTP status, timestamp, and request ID.
    chat_state: Ask for the endpoint, status code, and a request ID from the response headers. Remind them not to share the API key.

  - id: check_status_page
    source: gather_details
    tools:
      - acme:get_incident_status
    tool_instruction: Check if there is an active incident for the customer's region.

  - id: incident_path
    source: check_status_page
    condition: There is an active incident affecting the customer's region.
    chat_state: Apologize, share the incident page URL, and give the current ETA.

  - id: diagnose_401
    source: check_status_page
    condition: The status code is 401 or 403.
    chat_state: Walk the customer through rotating the API key and confirming scopes. Never ask them to paste the key.

  - id: diagnose_429
    source: check_status_page
    condition: The status code is 429.
    chat_state: Explain rate limits for their plan (reference the usage_quota glossary term) and suggest exponential backoff.

  - id: diagnose_5xx
    source: check_status_page
    condition: The status code is 5xx.
    tools:
      - acme:fetch_request_trace
    tool_instruction: Pull the trace for the failing request ID.
    chat_state: Share what the trace shows. If not root-caused in 2 exchanges, escalate.

  - id: wrap_up
    source: diagnose_401
    macro: signoff

  - id: wrap_up_429
    source: diagnose_429
    macro: signoff

  - id: wrap_up_5xx
    source: diagnose_5xx
    macro: signoff

```

#### Creating a Routine

{% tabs %}
{% tab title="Via the UI" %}

1. Navigate to **Build > Context**.
2. Click the **Routines** card or click **+ New Context**.
3. Enter a **Name** for the routine.
4. Define the routine steps in the **Context** editor using YAML. Click **Insert template** to start from a pre-built structure.
5. Optionally add a JSON **Config**.
6. Set labels and add a commit message.
7. Click **Create**.

<div data-with-frame="true"><figure><img src="/files/t4QbM7qNqbNStPeITiLy" alt=""><figcaption></figcaption></figure></div>

The platform validates the YAML schema before saving. Once created, the routine is automatically rendered as an interactive diagram.
{% endtab %}

{% tab title="Via the CLI" %}

```bash
# Create a routine from a YAML file
iai routines create billing-inquiry --file routine.yaml --labels production

# List all routines
iai routines list

# Get a specific routine
iai routines get billing-inquiry

# Update a routine (creates a new version)
iai routines update billing-inquiry --file updated-routine.yaml --labels production

# View the JSON schema for routines
iai routines schema
```

For the full CLI reference, see the [CLI Documentation](/cli/iai_routines.md).
{% endtab %}
{% endtabs %}

***

### Glossary

Glossaries define domain-specific terminology that your agent should understand and use correctly. They are written in JSON format and contain a collection of terms, each with a name, description, optional synonyms, and a unique ID.

<div data-with-frame="true"><figure><img src="/files/J1nwYR3ZMJsZFQPx0fG1" alt=""><figcaption></figcaption></figure></div>

#### How Glossaries Work

Each term in a glossary provides the agent with precise definitions so it can use terminology consistently. This is especially valuable for domain-specific language, brand terminology, or technical jargon that the agent might otherwise misinterpret.

A glossary entry contains:

| Field           | Description                                      |
| --------------- | ------------------------------------------------ |
| **Name**        | The canonical name of the term                   |
| **Description** | A clear description and usage guidance           |
| **Synonyms**    | Alternative terms that refer to the same concept |
| **ID**          | A unique machine-readable identifier             |

#### Creating a Glossary

{% tabs %}
{% tab title="Via the UI" %}

1. Navigate to **Build > Context**.
2. Click the **Glossary** card or click **+ New Context**.
3. Enter a **Name** for the glossary.
4. Define the terms in the Context editor using JSON, you can use the template as a guide to get started.

<div data-with-frame="true"><figure><img src="/files/jmpG4t4o04gZwONBl809" alt=""><figcaption></figcaption></figure></div>

5. Set labels and add a commit message.
6. Click **Create**.
   {% endtab %}

{% tab title="Via the CLI" %}

```bash
# Create a glossary from a JSON file
iai glossaries create brand-glossary --file glossary.json --labels production

# List all glossaries
iai glossaries list

# Get a specific glossary
iai glossaries get brand-glossary

# Update a glossary (creates a new version)
iai glossaries update brand-glossary --file updated-glossary.json --labels production

# View the JSON schema for glossaries
iai glossaries schema
```

For the full CLI reference, see the [CLI Documentation](/cli/iai_glossaries.md).
{% endtab %}
{% endtabs %}

***

### Macros

Macros are reusable text templates and snippets written in Markdown format. They provide pre-built blocks of text that your agent can insert into responses, ensuring consistency across conversations.

<div data-with-frame="true"><figure><img src="/files/IjJtlnpTYQDjnIXsZXpe" alt=""><figcaption></figcaption></figure></div>

#### How Macros Work

A macro contains a Markdown template that can include variables using `{{variable_name}}` syntax. At runtime, the agent substitutes the variables with actual values, producing consistent, on-brand responses.

For example, a `brand-cta` macro might look like:

{% code overflow="wrap" %}

```markdown
**Ready to try {{brand_name}}?** [Start your free trial]({{cta_url}}) - no credit card required.
```

{% endcode %}

This macro uses two variables, `brand_name` and `cta_url`, which are automatically detected and displayed in the Variables section of the detail view.

Other common macro examples include greetings, disclaimers, sign-off messages, security notices, and removal notices. Macros are particularly useful when the same text appears across multiple agents or conversation flows and you want to update it in one place.

#### Creating a Macro

{% tabs %}
{% tab title="Via the UI" %}

1. Navigate to **Build > Context**.
2. Click the **Macros** card or click **+ New Context**.
3. Enter a **Name** for the macro.
4. Write the macro content in the **Context** editor using Markdown. Use `{{variable_name}}` for dynamic placeholders.
5. Set labels and add a commit message.
6. Click **Create**.
   {% endtab %}

{% tab title="Via the CLI" %}

```bash
# Create a macro from a text/markdown file
iai macros create brand-cta --file macro.md --labels production

# List all macros
iai macros list

# Get a specific macro
iai macros get brand-cta

# Update a macro (creates a new version)
iai macros update brand-cta --file updated-macro.md --labels production
```

No schema validation is applied to macros. Any text or Markdown content is accepted.

For the full CLI reference, see the [CLI Documentation.](/cli/iai_macros.md)
{% endtab %}
{% endtabs %}

***

### Prompts

Prompts are general-purpose text and chat templates that serve as the foundation for any LLM interaction. Unlike the other context types, prompts have no enforced schema or structure. They are the most flexible context type and support two formats:

* **Plain Text** prompts are single-string templates ideal for completion-style tasks, simple instructions, or any scenario where you need a single block of text with variable placeholders. In the UI, plain text prompts are displayed as a single block of content.

<div data-with-frame="true"><figure><img src="/files/z0cCsV1TzGjkFPeRLSys" alt=""><figcaption></figcaption></figure></div>

* **JSON** prompts define an ordered sequence of messages with roles (`system`, `user`, `assistant`). Use JSON prompts when working with conversational models or when you need to establish context through multi-turn examples. In the UI, JSON prompts display each message in a structured view with the role clearly indicated, making it easy to review the conversation flow.

<div data-with-frame="true"><figure><img src="/files/Bxn4wv9dmTVB22wzWxWp" alt=""><figcaption></figcaption></figure></div>

#### Variables

All context types that support text content (Prompts and Macros) can include variables using `{{variable_name}}` syntax. Variables allow you to insert dynamic values at runtime.

When you define content with variables, the InteractiveAI system automatically detects them and displays them in the Variables section of the detail view.

Variable naming rules:

* Use only letters (a-z, A-Z) and underscores.
* No numbers, spaces, or special characters.
* Case-sensitive: `{{Policy}}` and `{{policy}}` are different variables.

At runtime, your application provides values for these variables when fetching and compiling the prompt.

#### Folder Organization

Prompt names support `/` notation for folder organization (e.g., `support/escalation`, `marketing/email`). Folders appear in the Context list as collapsible groups with a red folder icon, helping you organize large collections of prompts by domain or team.

#### Creating Prompts

{% tabs %}
{% tab title="Via the UI" %}

1. Navigate to Build > Context.
2. Click **+ New Context** (Prompts are available as a type when creating context outside of a specific category folder).
3. Enter a Name for the prompt.
4. Select the **Type**: Plain Text or JSON.
5. Write the prompt content with `{{variable}}` placeholders for dynamic values.
6. Optionally add a JSON Config for LLM parameters, function definitions, or metadata.
7. Set labels and add a commit message.
8. Click **Create**.
   {% endtab %}

{% tab title="Via the InteractiveAI SDK" %}
If you call `create_prompt()` with a name that already exists, the SDK creates a new version of that prompt rather than failing. This allows you to use the same code for both initial creation and subsequent updates.

```python
# Create a plain text prompt
interactiveai.create_prompt(
    name="document-summarizer",
    type="text",
    prompt=(
        "Summarize the following document in {{length}} sentences.\n\n"
        "Document:\n{{document}}\n\n"
        "Summary:"
    ),
    labels=["production"],
)

# Create a JSON (chat) prompt
interactiveai.create_prompt(
    name="customer-support/greeting",
    type="chat",
    prompt=[
        {"role": "system", "content": "You are a helpful customer support agent for {{company_name}}."},
        {"role": "user", "content": "{{customer_message}}"},
    ],
    labels=["staging"],
)
```

For the full Prompts API reference including caching, fallbacks, and deletion, see the [SDK Documentation](/sdk/prompts.md).
{% endtab %}

{% tab title="Via the CLI" %}

```bash
# Create a text prompt
iai prompts create greeting --content "Hello, how can I help you?" --labels production

# Create a chat prompt from a file
iai prompts create greeting --file greeting.json --type chat

# List prompts
iai prompts list

# Get a specific prompt
iai prompts get greeting

# Update a prompt (creates a new version)
iai prompts update greeting --content "Hello! How may I assist you today?" --labels production

# Delete a prompt
iai prompts delete greeting
```

For the full CLI reference, see the [CLI Documentation](/cli/iai_prompts.md).
{% endtab %}
{% endtabs %}

#### Fetching Prompts

Retrieve prompts in your application using `get_prompt()`:

```python
# Get production version (default)
prompt = interactiveai.get_prompt("policy-check")

# Get specific version by number
prompt = interactiveai.get_prompt("policy-check", version=1)

# Get specific label
prompt = interactiveai.get_prompt("policy-check", label="staging")

# Get a chat prompt (must specify type="chat")
prompt = interactiveai.get_prompt("compliance-review-chat", type="chat")
```

When fetching a JSON (chat) prompt, you must specify `type="chat"`. If omitted, the SDK defaults to `type="text"` and returns a `TextPromptClient`.

***

### Shared Features

All context types share a common set of features that work the same way regardless of the type.

#### Versions

Every time you save a change to a context item, InteractiveAI creates a new version. Previous versions are preserved and can still be accessed by version number. You cannot modify an existing version; instead, you create a new one. This gives you a complete audit trail of every change.

<div data-with-frame="true"><figure><img src="/files/PoCXau9k48zxqTu46wsp" alt="" width="318"><figcaption></figcaption></figure></div>

The left panel of the detail view shows all versions with their creation date and author, a search bar and a " + New" button.

#### Labels

Labels control which version your application fetches at runtime. They act as pointers that can be moved between versions without changing your application code.

**Default labels:**

| Label          | Description                                                    |
| -------------- | -------------------------------------------------------------- |
| **production** | The live version fetched by default when no label is specified |
| **latest**     | Automatically assigned to the most recent version              |

You can create **custom labels** for your workflow needs. Common patterns include environment-based labels (`development`, `qa`), feature-based labels (`experiment-a`, `new-tone`), and team-based labels (`review-pending`, `approved`).

Labels can be marked as **Protected Prompt Labels** to prevent accidental changes to critical context.&#x20;

{% hint style="info" %}
To learn more, refer to the [Protected Prompt Labels](/settings/protected-prompt-labels.md) section in Settings.
{% endhint %}

#### Detail View Tabs

When you click any context item to open its detail view, you will find several tabs:

**Context tab** displays the full content of the context item with syntax highlighting for variables and structured formatting appropriate to the type.

**Config tab** shows the arbitrary JSON configuration attached to the context version. Use this for LLM parameters (temperature, max\_tokens), function/tool definitions, or any other custom metadata for your application.

**Linked Generations tab** displays all observations (LLM generations) that used this context item. Linked generations are tracked automatically when your SDK calls reference the context, so use this tab to understand how your context performs in production.

**Use Context tab** provides ready-to-use code snippets for fetching the context item in your application:

```python
from interactiveai import Interactive

# Initialize Interactive client
interactive = Interactive()

# Get production prompt
prompt = interactive.get_prompt("customer-support-agent/node-generate-reply")

# Get by label
# You can use as many labels as you'd like to identify different deployment targets
prompt = interactive.get_prompt("customer-support-agent/node-generate-reply", label="latest")
prompt = interactive.get_prompt("customer-support-agent/node-generate-reply", label="prompt_b")

# Get by version number, usually not recommended as it requires code changes to deploy new prompt versions
interactive.get_prompt("customer-support-agent/node-generate-reply", version=5)

```

**Label History tab** provides a complete audit log of all label changes across versions. You can filter by time range, label, version, and action type. Each entry shows which label was applied, the action taken (Added or Removed), the prompt version it was applied to, who made the change, and the timestamp.

{% hint style="info" %}
All context types provide direct access to the Playground via the Playground button. They can also be commented on using the Comment button. Both buttons are located in the top-right corner of each detailed view.
{% endhint %}

#### Metrics

Click **Metrics** in the top-right corner of any context detail view to see performance data across all versions:

| Metric               | Description                                    |
| -------------------- | ---------------------------------------------- |
| Version              | Version number                                 |
| Labels               | Labels assigned to this version                |
| Median Latency       | Typical response time                          |
| Median Input Tokens  | Typical input token count                      |
| Median Output Tokens | Typical output token count                     |
| Median Cost          | Typical cost per generation                    |
| Generations          | Total number of times this version was used    |
| First Used           | When this version was first used in production |
| Last Used            | Most recent generation timestamp               |

Use this view to compare performance across versions and identify regressions before promoting to production.


---

# Agent Instructions: 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:

```
GET https://docs.interactive.ai/build/context.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
