> ## Documentation Index
> Fetch the complete documentation index at: https://docs.corti.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Context & Memory

> Learn how context and memory work in the Corti Agentic Framework

A **context** in the Corti Agentic Framework makes use of memory from previous text and data in the conversation so far—think of it as a thread that maintains conversation history. Understanding how context works is essential for building effective integrations that maintain continuity across multiple messages.

<Frame>
  <img src="https://mintcdn.com/corti/en_RPjQCFb1qJpbU/images/agent-memory.svg?fit=max&auto=format&n=en_RPjQCFb1qJpbU&q=85&s=12ac969a8c68ef0a1b0dc18a49ea93e2" alt="Diagram showing orchestration flow in the agentic framework" width="773" height="507" data-path="images/agent-memory.svg" />
</Frame>

## What is Context?

A `Context` (identified by a server-generated `contextId`) is a logical grouping of related `Messages`, `Tasks`, and `Artifacts`, providing context across a multi-turn "conversation"". It enables you to associate multiple tasks and agents with a single patient encounter, call, or workflow, ensuring continuity and proper scoping of shared knowledge throughout.

The `contextId` is **always created on the server**. You never generate it client-side. This ensures proper state management and prevents conflicts.

### Data Isolation and Scoping

**Contexts provide strict data isolation**: Data can **NEVER** leak across contexts. Each `contextId` creates a completely isolated conversation scope. Messages, tasks, artifacts, and any data within one context are completely inaccessible to agents working in a different context. This ensures:

* **Privacy and security**: Patient data from one encounter cannot accidentally be exposed to another encounter
* **Data integrity**: Information from different workflows remains properly separated
* **Compliance**: You can confidently scope sensitive data to specific contexts without risk of cross-contamination

When you need to share information across contexts, you must explicitly pass it via `DataPart` objects in your messages—there is no automatic data sharing between contexts.

## Using Context for Automatic Memory Management

The simplest way to use context is to let the framework automatically manage conversation memory:

### Workflow Pattern

1. **First message**: Send your message **without** a `contextId`. The server will create a new context automatically.
2. **Response**: The server's response includes the newly created `contextId`.
3. **Subsequent messages**: Include that `contextId` in your requests. Memory from previous messages in that context is automatically managed and available to the agent.

When you include a `contextId` in your request, the agent has access to all previous messages, artifacts, and state within **that specific context only**. Data from other contexts is completely isolated and inaccessible. This enables natural, continuous conversations without manually passing history, while maintaining strict data boundaries between different encounters or workflows.

### Standalone Requests

If you don't want automatic memory management, always send messages **without** a `contextId`. Each message will then be treated as a standalone request without access to prior conversation history. This is useful for:

* One-off queries that don't depend on prior context
* Testing and debugging individual requests
* Scenarios where you want explicit control over what context is included

## Passing Additional Context with Each Request

In addition to automatic memory management via `contextId`, you can pass additional context in each request by including `DataPart` objects in your message. This is useful when you want to provide specific structured data, summaries, or other context that should be considered for that particular request.

<Accordion title="Example: Passing additional context as DataPart">
  <CodeGroup>
    ```json theme={null}
    {
      "contextId": "ctx_abc123",
      "messages": [
        {
          "role": "user",
          "parts": [
            {
              "type": "text",
              "text": "Generate a summary of this patient encounter"
            },
            {
              "type": "data",
              "data": {
                "patientId": "pat_12345",
                "encounterDate": "2025-12-15",
                "chiefComplaint": "Chest pain",
                "vitalSigns": {
                  "bloodPressure": "120/80",
                  "heartRate": 72,
                  "temperature": 98.6
                }
              }
            }
          ]
        }
      ]
    }
    ```
  </CodeGroup>
</Accordion>

This approach allows you to:

* Provide structured data (patient records, clinical facts, etc.) alongside text
* Include summaries or distilled information from external sources
* Pass metadata or configuration that should be considered for this specific request
* Combine automatic memory (via `contextId`) with explicit context (via `DataPart`)

## How Memory Works

The Corti Agentic Framework uses an intelligent memory system that automatically indexes and stores all content within a context, enabling semantic retrieval when needed.

### Automatic Indexing

Every `TextPart` and `DataPart` you send in messages is automatically indexed and stored in the context's memory. This includes:

* Text content from user and agent messages
* Structured data from `DataPart` objects (patient records, clinical facts, metadata, etc.)
* Artifacts generated by tasks
* Any other content that flows through the context

### Semantic Retrieval

The memory system operates like a RAG (Retrieval Augmented Generation) pipeline. When an agent processes a new message:

1. **Semantic search**: The system performs semantic search across all indexed content in the context's memory
2. **Relevant retrieval**: It retrieves the most semantically relevant information based on the current query or task
3. **Just-in-time injection**: This relevant context is automatically injected into the agent's prompt, ensuring it has access to the right information at the right time

This means you don't need to manually pass all relevant history with each request—the system intelligently retrieves what's needed based on semantic similarity. For example, if you ask "What was the patient's chief complaint?" in a later message, the system will automatically retrieve and include the relevant information from earlier in the conversation, even if it was mentioned many messages ago.

### Benefits

* **Efficient**: Only relevant information is retrieved and used, reducing token usage
* **Automatic**: No need to manually manage what context to include
* **Semantic**: Works based on meaning, not just keyword matching
* **Comprehensive**: All content in the context is searchable and retrievable

## Context vs. Reference Task IDs

The framework provides two mechanisms for linking related work:

* **`contextId`** – Groups multiple related `Messages`, `Tasks`, and `Artifacts` together (think of it as the encounter/call/workflow bucket). This provides automatic memory management and is sufficient for most use cases.

* **`referenceTaskIds`** – An optional list of specific past `Task` IDs within the same context that should be treated as explicit inputs or background. Note that `referenceTaskIds` are scoped to a context—they reference tasks within the same `contextId`.

**In most situations, you can ignore `referenceTaskIds`** since the automatic memory provided by `contextId` is sufficient. Only use `referenceTaskIds` when you need to explicitly direct the agent to pay attention to specific tasks or artifacts within the context, such as in complex multi-step workflows where you want to ensure certain outputs are prioritized.

## Context and Interaction IDs

If you're using contexts alongside Corti's internal interaction representation (for example, when integrating with Corti Assistant or other Corti products that use `interactionId`), note that **these two concepts are currently not linked**.

* **`contextId`** (from the Agentic Framework) and **`interactionId`** (from Corti's internal systems) are separate concepts that you will need to map yourself in your application.
* There is no automatic association between a Corti `interactionId` and an Agentic Framework `contextId`.

**Recommended approach:**

* **Use a fresh context per interaction**: When working with a Corti interaction, create a new `contextId` for that interaction. This keeps data properly scoped and isolated per interaction.
* Store the mapping between your `interactionId` and `contextId`(s) in your own application state or metadata.
* If you need to share data across multiple contexts within the same interaction, explicitly pass it via `DataPart` objects.

We're looking into ways to make the relationship between interactions and contexts more ergonomic if this is relevant to your use case. For now, maintaining your own mapping and using one context per interaction is the recommended pattern.

<Tip>
  For more details on how context relates to other core concepts, see [Core Concepts](/agentic/core-concepts).
</Tip>

<Note>Please [contact us](https://help.corti.app/) if you need more information about context and memory in the Corti Agentic Framework.</Note>
