Context0 Service User Guide

Updated at:

This document describes how to use the six core capabilities of Context0: Memory management, Knowledge Base management, Session management, Context Assembly, Memory Promotion, and Workspace management.

Preparations

Before reading, make sure you have completed the onboarding (seeQuick Start). The following examples use:

export API_KEY="<YOUR_API_KEY>"       # Data Plane USER Key
export HOST="https://<your-endpoint>"
Note

Operations involving the Control Plane (members, Keys, promotion review, etc.) requireOwner Key, marked in examples as$OWNER_KEY.

Memory Management

Memory is the long-term memory capability provided by Context0 for Agents, compatible with the Mem0 protocol.

Memory Hierarchy (L1 Facts / L0 Entities / Rules)

After a conversation is ingested, Context0 progressively distills it into three layers of Memory:

Ingest ──► L2 Raw Conversation ──LLM Extraction──► L1 Atomic Facts ──Entity Recognition──► L0 Entity Profiles
           (Immutable, traceable)        (Single fact, with timeliness)      (Structured entity card)

Level

Content

Description

L2

Raw conversation text

Immutable, used for traceability and real-time recall fallback.

L1

Atomic facts

Single fact, such as "the project uses TypeScript", with subject(topic) and validity(timeliness).

L0

Entity profiles

Structured entity cards, supporting five types: person / project / technology / organization / concept.

  • Timeliness of L1 facts (validity):

    Value

    Meaning

    permanent

    Permanent (e.g., name, core preferences).

    durable

    Persistent (e.g., technology choices).

    temporal

    Time-sensitive (e.g., "focusing on performance optimization this week").

  • Rules (distillation rules): You cancustomize rules for "what to extract from conversations and how to extract it", to control the distillation behavior. Additionally, throughPinyou can fix key memories as high-priority entries that do not decay over time.

Writing Memories (Automatic vs Manual)

  • Automatic write (recommended): Use the ingest endpoint to ingest conversations. The server asynchronously extracts memories without blocking the conversation.

    curl -X POST "$HOST/v1/context/ingest" \
      -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
      -d '{
        "session_id": "sess_789",
        "user_id": "user_001",
        "messages": [
          {"role": "user", "content": "The project prefers TypeScript, with Prisma as the ORM"},
          {"role": "assistant", "content": "Got it, tech stack selection noted"}
        ]
      }'
    Note

    When using the CLI plugin, the plugin calls POST /v3/memories/addby default at the end of each valid turn, and the backend asynchronously distills long-term memories. No manual action is required.

  • Manual write: Call /v1/memories directly to extract atomic facts from a conversation:

    curl -X POST "$HOST/v1/memories" \
      -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
      -d '{
        "messages": [
          {"role": "user", "content": "NextAuth is chosen for authentication"}
        ],
        "user_id": "user_001",
        "metadata": {"source": "manual"}
      }'
  • (Recommended) V3 Memory Add: POST /v3/memories/add is a Box-wrapped memory write endpoint. The request parameters are the same as /v1/memories , and the response includes deduplication information:

    curl -X POST "$HOST/v3/memories/add" \
      -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
      -d '{
        "messages": [{"role": "user", "content": "The project uses Vite for builds"}],
        "user_id": "user_001"
      }'

    Response

    {"code": 0, "msg": "ok", "data": {"memory_id": "mem_1_2_abc", "event_id": 789, "created": true}}

    Field

    Description

    memory_id

    Memory ID

    event_id

    The event ID corresponding to the write (created=false when deduplication matches an existing memory)

    created

    true Created / false Deduplication matched an existing memory

    Note

    The CLI plugin uses this endpoint by default for writing memories.

Search Memories

Search memories by semantic similarity, using a two-way recall of vector kNN + BM25 lexical matching, fused with RRF to return top-k results. Three versions are available with increasing capabilities:

Path

L1 facts

L2 source text

Response format

POST /v1/memories/search

Yes

No

Bare JSON array

POST /v2/memories/search

Yes

Yes (enabled by default)

Bare JSON array

POST /v3/memories/search

Yes

Yes

{"results": [...]} Envelope (Mem0 v1.1 SDK compatible)

Example

Parameter Description

Field

Required

Description

query

Yes

Query text

user_id

No

Restricts to a specific user. USER Key is automatically bound to itself

limit

No

Number of results [1,200], default 10 (alias top_k can also be used)

filters

No

Additional filters, supporting time ranges:{"created_at": {"$gte": "...", "$lte": "..."}}

vector_only

No

true uses only vector recall, disabling BM25

cosine_threshold

No

Similarity threshold [0,1], no filtering by default (alias threshold can also be used)

Note
  • V3 search filters map parameter passing(Mem0 v1.1 SDK compatible): In the V3 endpoint POST /v3/memories/search , entity parameters such asuser_id / agent_id / run_id should be placed inside the filters map, for example:{"query": "tech stack", "filters": {"user_id": "user_001"}, "limit": 10}.

  • Top-level parameters with the same names (such as user_idin V1/V2) are still accepted in V3 routes, but using the filters is recommended to align with the Mem0 v1.1 SDK.

Memory Operations (View / Update / Delete / Pin / Invalidate)

Operation

Method and Path

List

GET /v1/memories

Example: optional parameter doc_type Filter by level:L1(atomic facts) / L0_ENTITY_CARD(profile cards) / L2(source text).

curl "$HOST/v1/memories?user_id=user_001&limit=20&offset=0" \
  -H "X-API-Key: $API_KEY"

Details

GET /v1/memories/{id}

Example

curl "$HOST/v1/memories/mem_123" -H "X-API-Key: $API_KEY"

Update

PUT /v1/memories/{id}

Example

curl -X PUT "$HOST/v1/memories/mem_123" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{"data": "The project uses TypeScript + Prisma + Zod validation"}'

Delete

DELETE /v1/memories/{id}

Example:

curl -X DELETE "$HOST/v1/memories/mem_123" -H "X-API-Key: $API_KEY"

Pin / Unpin

POST /v1/memories/{id}/pin / /unpin(Pinned memories get higher recall priority and do not decay over time.)

Example:

curl -X POST "$HOST/v1/memories/mem_123/pin"   -H "X-API-Key: $API_KEY"
curl -X POST "$HOST/v1/memories/mem_123/unpin" -H "X-API-Key: $API_KEY"

Invalidate

POST /v3/memories/{id}/invalidate(Once a memory is outdated, it is excluded from future recall rather than just downweighted.)

Example:

curl -X POST "$HOST/v3/memories/mem_123/invalidate" -H "X-API-Key: $API_KEY"

History

GET /v1/memories/{id}/history

Example

curl "$HOST/v1/memories/mem_123/history" -H "X-API-Key: $API_KEY"

Statistics

GET /v1/memories/stats

Clear (irreversible)

DELETE /v1/memories/clear?confirm=true

Note

Used in reset scenarios, irreversible. Both query and body must includeconfirm: truefor the irreversible batch deletion to execute. If either is missing, a 400 error is returned.

Example

curl -X DELETE "$HOST/v1/memories/clear?confirm=true" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{
    "user_id": "user_001",
    "scope": "all",
    "confirm": true
  }'

Parameter Description

  • scope: all(all) / before_date(before a specified date) / by_session_ids(by session).

  • before_date: scope=before_dateUsed with, ISO-8601 timestamp.

  • session_ids: scope=by_session_idsUsed with, array of session IDs.

  • confirm: must be truein both query parameters and body, otherwise a 400 error is returned

Response Example

{"message": "memories cleared", "deleted": 156, "scope": "all"}

Feedback

POST /v3/memories/{id}/feedback

Note
  • Positive feedback affects the memory's heat score.

  • negative_explicit It also triggers the asynchronous Dream counterfactual pipeline to re-evaluate the memory.

  • Feedback cannot be submitted for invalidated memories. Attempting to do so will return a 400 error. Please submit feedback only for memories in a valid state.

Example

curl -X POST "$HOST/v3/memories/mem_123/feedback" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{
    "signal_type": "negative_explicit",
    "channel": "agent",
    "corrected_content": "Should be Drizzle, not Prisma"
  }'

Parameter Description

  • signal_type: positive_explicit / negative_explicit / positive_implicit / negative_implicit.

  • channel: feedback source, such as agent / user / dashboard.

  • corrected_content: correction content for negative feedback.

  • recall_path: recall path (bm25 / vector / graph), used for adaptive recall weighting.

Response Example

{
  "code": 0,
  "data": {
    "id": 501,
    "memory_id": "mem_123",
    "signal_type": "negative_explicit",
    "created_at": "2026-08-19T11:00:00Z"
  }
}

L2 source text

GET /v1/memories/{id}/source-texts(Traceability)

Returns the original conversation messages (L2 level) that produced this L1 fact, for auditing or debugging purposes.

Example

curl "$HOST/v1/memories/mem_123/source-texts" -H "X-API-Key: $API_KEY"

Response Example

{
  "code": 0,
  "data": [
    {
      "session_id": "sess_789",
      "role": "user",
      "content": "The project prefers TypeScript, with Prisma as the ORM",
      "created_at": "2026-07-15T10:00:00Z"
    }
  ]
}

V3 List

POST /v3/memories

Mem0 v1.1 SDK compatible, with entity filtering via request body and paginated envelope response support.

Example

curl -X POST "$HOST/v3/memories?page=1&page_size=50" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{"user_id": "user_001"}'

Field

Location

Description

user_id / agent_id / run_id

body

Entity filtering; can be placed at the top level or in the filters map

filters

body

Entity filtering map, accepts snake_case/camelCase keys; unrecognized keys return a 400 error

page

query

Page number (1-indexed), default 1

page_size

query

Page size [1,200], default 100

Response Example(bare JSON, no Box wrapper):

{"count": 156, "next": "/v3/memories/?page=2&page_size=50", "previous": null, "results": [{"id": "mem_1_2_abc123", "memory": "User prefers Vim editor"}]}

L0 Entity Card Editing

POST /v3/entity_cards/{id}/edit

Partially updates an entity profile (only the provided fields are overwritten).

Example

curl -X POST "$HOST/v3/entity_cards/card_1_2_alice/edit" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{"role": "Senior backend engineer", "preferences": ["Java", "Spring Boot"]}'

Field

Description

role

Entity role description

preferences

Preferences list (string array)

attributes

Open attribute map (keys vary by card type:org / repo_url / version / domain etc.)

Custom Distillation Rules

Distillation rules (distill-prompt) control "what to extract from conversations and how to extract it", and can be configured per member without requiring OWNER permissions.

Note

custom_prompt ≤ 8192 characters, defines only what to extract / how to extract, without changing the output JSON structure. OWNERs can use the Control Plane /ops/distill-prompt to set workspace-level default rules or rules for specific members.

  • Priority chain:

    custom_instructions in ingest request > Member-level rules > Workspace default rules > Built-in defaults.

  • Set member-level rules:

    curl -X PUT "$HOST/v1/memories/distill-prompt" \
      -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
      -d '{
        "custom_prompt": "Focus on extracting tech stack selections and architecture decisions, ignore casual chat",
        "enabled": true
      }'
  • Query current rules:

    curl "$HOST/v1/memories/distill-prompt" -H "X-API-Key: $API_KEY"
  • Delete rules(falls back to workspace default or built-in):

    curl -X DELETE "$HOST/v1/memories/distill-prompt" -H "X-API-Key: $API_KEY"

Knowledge Base Management

Knowledge Base supports uploading documents with automatic parsing, chunking, vectorization, and indexing, and provides RAG retrieval with vector + BM25 + rerank fusion.

Create Knowledge Base

The response returns the Knowledge Base id(numeric type), which is used for subsequent uploads and searches.

curl -X POST "$HOST/v1/knowledge/bases" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{
    "name": "Project Documentation Library",
    "description": "Internal technical documentation and policies",
    "visibility": "workspace"
  }'

Field

Required

Description

name

Yes

Name, ≤128 characters.

description

No

Description, ≤1024 characters.

visibility

No

workspace(workspace visible, default) / private(creator only). USER Key is enforced to private.

graph_enabled

No

Whether to enable knowledge graph indexing, default false.

Manage Knowledge Bases

  • List Knowledge Bases:

    curl "$HOST/v1/knowledge/bases?page=0&page_size=20" -H "X-API-Key: $API_KEY"
  • Get a single knowledge base details:

    curl "$HOST/v1/knowledge/bases/1" -H "X-API-Key: $API_KEY"

    Response:

    {
      "code": 0,
      "data": {
        "id": 1,
        "name": "Project Document Library",
        "description": "Internal technical documentation and policies",
        "visibility": "workspace",
        "document_count": 42,
        "graph_enabled": false,
        "created_at": "2026-07-01T00:00:00Z",
        "updated_at": "2026-08-15T12:00:00Z"
      }
    }
  • Delete a knowledge base:

    curl -X DELETE "$HOST/v1/knowledge/bases/1" -H "X-API-Key: $API_KEY"
    Note

    OWNER can delete any knowledge base. USER can only delete private knowledge bases they created. Deletion cascades to all documents and indexes under the knowledge base.

Upload Documents (Formats + Limits + Three Methods)

Supported file formats

  • Documents: PDF, Markdown, Word, Excel, PPT, RTF, EPUB.

  • Images: PNG, JPG, etc. (Vision model automatically generates descriptions).

  • Audio: Common audio formats (automatic transcription).

Limits and mechanisms

  • Processing is asynchronous after upload. The API synchronously returns the document ID and ingest_status, with status transitioning through pending → indexed(failure results in failed + last_error).

  • Idempotent deduplication: Re-uploading the same byte stream returns the existing document ID without duplicate ingestion.

  • After processing completes, chunk_count is updated with the actual chunk count.

Upload methods

Multipart file upload

Knowledge base idis specified in the request path.

curl -X POST "$HOST/v1/knowledge/bases/1/documents/upload" \
  -H "X-API-Key: $API_KEY" \
  -F "file=@/path/to/runbook.pdf" \
  -F "title=Deployment Runbook" \
  -F "external_id=runbook-v2" \
  -F "folder_path=/ops"

When Markdown contains images, upload them together via the images field:

curl -X POST "$HOST/v1/knowledge/bases/1/documents/upload" \
  -H "X-API-Key: $API_KEY" \
  -F "file=@/path/to/guide.md" \
  -F "title=Operations Guide" \
  -F "images=@/path/to/screenshot1.png" \
  -F "images=@/path/to/diagram.jpg"

JSON text content submission

Suitable for programmatic synchronization. Supports chunking by external_id upsert.

curl -X POST "$HOST/v1/knowledge/documents" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{
    "knowledge_base_id": 1,
    "title": "Synced Document",
    "external_id": "feishu-doc-001",
    "content": "# Document Content\n..."
  }'

Console upload

On the Knowledge Base page in the console, select the target knowledge base, drag and drop or select files to upload, and visually monitor ingestion progress.

Manage documents

  • List documents:

    curl "$HOST/v1/knowledge/bases/1/documents?page=0&size=20" -H "X-API-Key: $API_KEY"
  • Get a single document details(including processing status):

    curl "$HOST/v1/knowledge/documents/101" -H "X-API-Key: $API_KEY"

    Response:

    {
      "code": 0,
      "data": {
        "id": 101,
        "knowledge_base_id": 1,
        "title": "Deployment Runbook",
        "external_id": "runbook-v2",
        "ingest_status": "indexed",
        "chunk_count": 24,
        "source_type": "upload",
        "created_at": "2026-08-01T00:00:00Z",
        "updated_at": "2026-08-01T00:05:00Z"
      }
    }
    Note

    ingest_status Possible values:pending → indexed(success) / failed(failure, includes last_error).

  • Delete a document:

    curl -X DELETE "$HOST/v1/knowledge/documents/101" -H "X-API-Key: $API_KEY"
    Note

    Deletion requires editor or higher permissions. Corresponding chunk indexes are cleaned up synchronously.

Knowledge Recall

RAG retrieval: Vector + BM25 hybrid recall with reranking, returning matched chunks.

Example

Parameter Description

Response example (partial)

{
  "code": 0,
  "data": [
    {
      "chunk_id": "chunk_42",
      "document_id": "101",
      "title": "Deployment Runbook",
      "snippet": "Deployment process: 1. Prepare .env ... 2. Run ./deploy.sh ...",
      "score": 0.91,
      "rerank_score": 0.88
    }
  ]
}

Knowledge Review

When quality review is enabled, newly ingested document chunks are automatically scored, and low-scoring chunks enter the manual review queue.

  • Enable review:

    curl -X PUT "$HOST/v1/knowledge/bases/1/settings" \
      -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
      -d '{"review_enabled": true}'
  • View review queue:

    curl "$HOST/v1/knowledge/bases/1/reviews?status=pending_human&page=0&size=20" \
      -H "X-API-Key: $API_KEY"
  • Submit review decision(ACCEPT_ORIGINAL / REJECT / RETRY):

    curl -X POST "$HOST/v1/knowledge/reviews/decision" \
      -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
      -d '{"review_id": 42, "decision": "ACCEPT_ORIGINAL"}'

    Decision

    Description

    ACCEPT_ORIGINAL

    Approve and activate the chunk

    REJECT

    Reject; the chunk remains non-retrievable

    RETRY

    Re-score

    Note

    Review requires deployment-level workers to be enabled and the workspace feature toggle to be turned on; otherwise, it returns FEATURE_DISABLED.

Wiki Knowledge Distillation

Wiki distillation refines knowledge base documents through LLM into structured Wiki pages (entities / concepts / summaries), complementing RAG — RAG returns chunk-level snippets, while Wiki returns page-level structured knowledge.

  • Enable Wiki distillation(Owner Key, Control Plane):

    Note

    Once enabled, newly uploaded documents automatically trigger distillation. Existing documents are not retroactively processed; they can be manually triggered by re-distilling.

    curl -X PUT "$HOST/ops/knowledge/wiki/config?kb_id=1" \
      -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \
      -d '{
        "wiki_enabled": true,
        "wiki_config": "{\"synthesis_model\":\"qwen-max\",\"extraction_granularity\":\"standard\"}"
      }'
  • Read full page content:

    curl "$HOST/v1/knowledge/wiki/pages/42" -H "X-API-Key: $API_KEY"

    Wiki page types:

    Type

    Description

    summary

    Document-level summary (one per document)

    entity

    Entity (person / technology / product, etc.); multiple documents can contribute to the same entity

    concept

    Concept (method / principle / pattern, etc.)

    index

    Wiki home page, automatically maintained by the system

Skill Catalog

The Skill Catalog allows Agents to dynamically discover available Skills at runtime and assemble them into context via the assemble endpoint. Skills support L0/L1/L2 progressive disclosure: L0 metadata → L1 summary → L2 full content.

Note

Typical Agent flow: via search discover relevant Skills → retrieve content → assemble into context for execution. The assemble endpoint can also automatically include matching Skill content.

  • List skills:

    Note

    pagestarts at 0;page_size range [1, 100], default 20.

    curl "$HOST/v1/skills?page=0&page_size=20" -H "X-API-Key: $API_KEY"

    Response example:

    {
      "code": 0,
      "data": {
        "content": [
          {
            "id": 1,
            "name": "deploy-helper",
            "description": "Automated deployment process guide",
            "tags": ["devops", "docker"],
            "updated_at": "2026-08-10T00:00:00Z"
          }
        ],
        "totalElements": 5,
        "totalPages": 1
      }
    }
  • Parameter description:

    Field

    Required

    Description

    query

    Yes

    Query text

    top_k

    No

    Number of results to return. Default 10.

    tags

    No

    Filter by tags

    Response example:

    {
      "code": 0,
      "data": [
        {"id": 1, "name": "deploy-helper", "score": 0.92, "description": "Automated deployment process guide"}
      ]
    }
  • Get full skill content(L2):

    curl "$HOST/v1/skills/1/content" -H "X-API-Key: $API_KEY"

    Response example:

    {
      "code": 0,
      "data": {
        "id": 1,
        "name": "deploy-helper",
        "content": "# Deploy Helper\n\n## When to Use\n...\n## Steps\n..."
      }
    }

Session Management

A session is a container for short-term context. The complete Agent workflow = create session → append messages → assemble → close session. Each message has an auto-incrementing seq sequence number, supporting incremental fetching and reverse pagination.

Session operations quick reference

Operation

Method and Path

Create

POST /v1/sessions

List

GET /v1/sessions?page=0&page_size=20&status=open

Details

GET /v1/sessions/{id}

Update

PATCH /v1/sessions/{id}

Append message

POST /v1/sessions/{id}/messages

Message list

GET /v1/sessions/{id}/messages?since_seq=0&limit=50

Close

PUT /v1/sessions/{id}/close

Delete

DELETE /v1/sessions/{id}

Statistics

GET /v1/sessions/stats

Inheritance chain

GET /v1/sessions/{id}/inheritance

Create a session

Use external_id as the business-side session identifier (idempotent). Under the same user_id , repeated calls with the same external_id return the existing session.

curl -X POST "$HOST/v1/sessions" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{"external_id": "sess-2026-08-19-001", "agent_id": "coding-agent", "title": "Deployment Discussion", "user_id": "user_001"}'

Request parameters

Field

Required

Description

external_id

Yes

External session identifier, ≤128 characters, idempotent under the same user.

agent_id

No

Agent identifier, used to filter sessions by Agent.

title

No

Title, ≤256 characters.

user_id

No

End user identifier; automatically bound for USER Key.

session_key

No

Thread key for cross-session context inheritance.

parent_session_id

No

Parent session external_id, used to explicitly specify the inheritance relationship.

Response Example

Note

created=true indicates a new session. Under the same external_id , repeated calls return the existing session with created=false(idempotent).

{
  "code": 0,
  "data": {
    "session": {
      "id": 42,
      "external_id": "sess-2026-08-19-001",
      "agent_id": "coding-agent",
      "title": "Deployment Discussion",
      "status": "open",
      "user_id": "user_001",
      "message_count": 0,
      "total_tokens": 0,
      "created_at": "2026-08-19T10:00:00Z",
      "updated_at": "2026-08-19T10:00:00Z"
    },
    "created": true
  }
}

List sessions

curl "$HOST/v1/sessions?page=0&page_size=20&status=open" \
  -H "X-API-Key: $API_KEY"

Request parameters

Parameters

Description

page

Page number (0-indexed), default 0.

page_size

Page size [1, 200], default 20.

agent_id

Filter by Agent.

status

Filter by status:open / closed / flushed.

Pagination metadata is returned via response headers:X-Total-Count / X-Page / X-Page-Size / X-Has-More.

Get session details

curl "$HOST/v1/sessions/sess-2026-08-19-001" -H "X-API-Key: $API_KEY"

Path parameter {id} can be the session's external_id or the database id. The response is the same as the create endpoint's session object.

Append messages to a session

curl -X POST "$HOST/v1/sessions/sess-2026-08-19-001/messages" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "How to deploy with Docker?"}, {"role": "assistant", "content": "We recommend using docker compose ..."}]}'

Response Example

{
  "code": 0,
  "data": [
    {"id": 101, "role": "user", "content": "How to deploy with Docker?", "seq": 1, "token_count": 12},
    {"id": 102, "role": "assistant", "content": "We recommend using docker compose ...", "seq": 2, "token_count": 45}
  ]
}
Note

role Supports user / assistant / system / tool, where tool must be accompanied by tool_name.

Get session message list

curl "$HOST/v1/sessions/sess-2026-08-19-001/messages?since_seq=0&limit=50" \
  -H "X-API-Key: $API_KEY"

Request parameters

Parameters

Description

since_seq

Incremental fetch: Returns seq > since_seq 's messages.

before_seq

Reverse fetch: Returns seq < before_seq 's messages.

order

Sort order:asc(default) / desc.

limit

Number of results to return [1, 200], default 50.

Response Example

{
  "code": 0,
  "msg": "ok",
  "data": {
    "items": [
      {"id": 101, "role": "user", "content": "How to deploy with Docker?", "seq": 1, "token_count": 12},
      {"id": 102, "role": "assistant", "content": "We recommend using docker compose ...", "seq": 2, "token_count": 45}
    ],
    "total": 2
  },
  "trace_id": "550e8400-e29b-41d4-a716-446655440000"
}

Close a session

curl -X PUT "$HOST/v1/sessions/sess-2026-08-19-001/close" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{"generate_summary": true}'

Response Example

{
  "code": 0,
  "data": {
    "id": 42,
    "external_id": "sess-2026-08-19-001",
    "status": "closed",
    "closed_at": "2026-08-19T10:30:00Z"
  }
}
Note

generate_summary=true(default) automatically generates a handoff summary for subsequent session inheritance. After closing, messages cannot be appended but remain readable.

Context Assembly

Context assembly is the most frequently called API for Agent invocations: it recalls relevant memories and knowledge based on the query, selects the best content within the token budget, and outputs a structured prompt_blocks, ready to be inserted directly into the system prompt.

Basic usage

curl -X POST "$HOST/v1/context/assemble" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{
    "session_id": "sess_789",
    "user_id": "user_001",
    "query": "How to deploy the application?",
    "token_budget": 4000,
    "recall": {"top_k": 8}
  }'
Note

session_id and user_id must have at least one filled in (otherwise workspace-wide recall is prohibited).query An empty query triggers zero-query cold start.

Recall configuration

Field

Description

token_budget

Output token budget [1, 32000], default 32000. Never exceeds the budget.

recall.top_k

Number of results to recall [1, 50].

recall.cosine_threshold

Minimum similarity threshold [0, 1], default 0.3.

context_scope

Assembly scope:full(default) / minimal / memory_only / knowledge_only.

include_memories / include_knowledge

Boolean to force-enable or disable a single dimension (takes effect after scope).

knowledge_base_ids

List of knowledge base IDs to recall from.

budget_allocator

Budget allocation ratios:memory_ratio / knowledge_ratio / history_ratio / system_ratio.

context_scope Presets:

Value

Included dimensions

Typical scenario

full

System instructions + recent messages + memories + knowledge base.

General conversation

minimal

System instructions + recent messages.

Completion / formatting and other lightweight calls

memory_only

System instructions + recent messages + memory.

Scenario without knowledge base

knowledge_only

System instructions + recent messages + knowledge base.

RAG Q&A

Response structure

Concatenate prompt_blocks 's content into the system prompt in order. The backend selects by importance within the budget and never exceeds it. token_budget.

{
  "code": 0,
  "data": {
    "prompt_blocks": [
      {"role": "system", "tag": "user_profile", "content": "User prefers TypeScript + Prisma", "tokens": 30, "sources": []},
      {"role": "system", "tag": "knowledge", "content": "Deployment process: 1. Prepare .env ...", "tokens": 120, "sources": ["runbook.pdf"]},
      {"role": "user", "tag": "recent_messages", "content": "User: I want to deploy with Docker ...", "tokens": 80, "sources": []}
    ],
    "token_used": 255,
    "token_budget": 4000,
    "trace_id": "550e8400-...",
    "stats": {"recall_total": 12, "recall_kept": 8, "took_ms": 142}
  }
}

Compact Context

Proactively trigger incremental summary compression for long conversations, folding the earliest active messages into leaf summaries to reduce the total message count while preserving semantics.

curl -X POST "$HOST/v1/context/compact" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{
    "session_id": "sess-2026-08-19-001",
    "keep_recent_n": 50,
    "chunk_size": 20
  }'

Parameter Description

Field

Required

Description

session_id

Yes

The external_id of the conversation

keep_recent_n

No

Number of recent active messages to retain. Default: 50, range: [1,500]

chunk_size

No

Number of messages to fold per call. Default: 20, range: [5,200]

Response Example

{
  "code": 0,
  "data": {
    "session_id": "sess-2026-08-19-001",
    "compacted_message_count": 20,
    "summary_token_count": 180,
    "active_message_count": 50
  }
}
Note

Make multiple calls for multi-leaf incremental compression, rather than compressing all old messages into a single summary at once.keep_recent_n Default 50 [1,500],chunk_size Default 20 [5,200].

Flush Context

Persist short-term context as long-term memory after a conversation ends. Flush first performs a compact, then sets the conversation status to flushed, and triggers a memory distillation event.

curl -X POST "$HOST/v1/context/flush" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{
    "session_id": "sess-2026-08-19-001",
    "compact_first": true,
    "keep_recent_n": 20
  }'

Parameter Description

Field

Required

Description

session_id

Yes

The external_id of the conversation

compact_first

No

Whether to compact before flush. Default: true

keep_recent_n

No

Number of recent messages to retain during compact. Default: 20

Response Example

{
  "code": 0,
  "data": {
    "session_id": "sess-2026-08-19-001",
    "status": "flushed",
    "flushed_at": "2026-08-19T10:35:00Z",
    "evolve_event_id": 1001
  }
}
Note
  • compact + flush + assemble are the three core operations of the context lifecycle: assemble reads, compact compresses, and flush persists.

  • Idempotency: flushing an already flushed conversation returns the existing status instead of an error.

Context Lifecycle

POST /v1/context/lifecycle By action drive the conversation state machine:

  • action=start: Create or open a conversation and return the first-screen assembled PromptBlock (equivalent to a combined POST /v1/sessions + POST /v1/context/assemble call).

    -- start -- Create conversation + first-screen assembly
    curl -X POST "$HOST/v1/context/lifecycle" \
      -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
      -d '{
        "action": "start",
        "session": {"external_id": "sess-2026-08-20-001", "user_id": "user_001", "agent_id": "coding-agent"},
        "query": "Continue our previous discussion",
        "token_budget": 4096
      }'
  • action=end: Close the conversation and return closing statistics (equivalent to a PUT /v1/sessions/{id}/close + POST /v1/context/flush call).

    -- end -- Close conversation + flush
    curl -X POST "$HOST/v1/context/lifecycle" \
      -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
      -d '{"action": "end", "session_id": "sess-2026-08-20-001", "user_id": "user_001"}'

Parameter Description

Field

Required

Description

action

Yes

start / end

session

Required for start

New session metadata (external_id required,user_id / agent_id / title / metadata optional)

session_id

Required for end

Session ID

user_id

No

end Optional; used when an OWNER Key closes a specific end-user session

query

No

start Optional, used with token_budget to drive first-screen assembly

token_budget

No

start Optional token budget [1, 32000]

Note

action=start Response structure is the same as assemble, including prompt_blocks / token_used / stats; action=end Returns message_count / total_tokens / event_id.

Dialectic Analysis

POST /v1/context/dialectic Perform multi-perspective dialectic analysis on context recall results, outputting structured evidence and judgments. Requires session_id or user_id , at least one must be provided.

Example

curl -X POST "$HOST/v1/context/dialectic" \
  -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
  -d '{
    "query": "What are the pros and cons of Rust's ownership model?",
    "user_id": "user_001",
    "depth": "standard",
    "top_k": 5
  }'

Parameter Description

Field

Required

Description

query

Yes

Query text

session_id

Condition

and user_id At least one is required

user_id

Condition

and session_id At least one is required

depth

No

Analysis depth:fast / standard(default) / deep / highest

top_k

No

Return top-k [1,20], default 5

Note

In the response, prompt_blocks has the same structure as assemble, with additional hits_count(recall hit count) and latency_ms(elapsed time).

Memory Promotion

Memory Promotion bridges the memory system and the knowledge base system: it automatically discovers high-value memory clusters, has an Agent synthesize Markdown knowledge documents, routes them through human review, and ingests them as knowledge base documents, forming a closed-loop evolution from "memory to knowledge."

Feature description

The state transitions of a Promotion:

generate (manual) / auto-nomination
        |
        v
   generating --synthesis success--> pending_review --approve--> approved (ingested)
        |                        |
   synthesis failed            reject
        v                        v
 generation_failed            rejected

Status

Meaning

generating

Enqueued; the Agent is retrieving evidence and synthesizing the document.

pending_review

Synthesis complete; awaiting human review.

approved

Successfully ingested; knowledge base document created.

rejected

Review rejected.

generation_failed

Synthesis failed.

Note

Must be enabled on the deployment side context.promotion.enabled=true(disabled by default). When enabled, the system periodically auto-discovers hot memory clusters and creates promotion tickets; it can also be initiated manually.

Procedure

The following examples use theOwner Key. The Data Plane (initiate / query) also supports USER Keys (operating on own members only).

  1. Manually initiate a promotion (async enqueue):

    curl -X POST "$HOST/ops/promotion/generate" \
      -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \
      -d '{"topic": "Project deployment process", "target_member_id": 10}'
  2. Poll the list and wait for the status to change to pending_review:

    curl "$HOST/ops/promotion/list?status=pending_review&page=0&pageSize=20" \
      -H "X-API-Key: $OWNER_KEY"
  3. View details to confirm the content and doubts:

    curl "$HOST/ops/promotion/detail?promotionId=101" -H "X-API-Key: $OWNER_KEY"
  4. (Optional) Resolve doubts: If the Agent encounters conflicting evidence during synthesis, it lists pending doubts in the doubts field. Providing resolutions triggers re-synthesis:

    curl -X POST "$HOST/ops/promotion/resolve-doubts" \
      -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \
      -d '{
        "promotion_id": 101,
        "resolutions": [{"doubt_title": "Deployment environment", "chosen_value": "prod"}]
      }'
  5. Approve and write to the knowledge base:

    curl -X POST "$HOST/ops/promotion/approve" \
      -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \
      -d '{"promotion_id": 101, "knowledge_base_id": 5}'

    orReject:

    curl -X POST "$HOST/ops/promotion/reject" \
      -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \
      -d '{"promotion_id": 101, "reason": "Content duplicates existing knowledge base entries"}'
Note

After approval, a Markdown document is created in the target knowledge base (source=memory_promotion). The above review operations can also be completed visually on the Memory Promotion page in the console.

Workspace management

Workspace management operations use theOwner Keyand can be completed visually in the console or via API calls.

Note

Owner Key vs Admin Key's Control Plane responsibilities:

  • Owner KeyHandles single-Workspace-level management (member management, Key management, Wiki configuration, promotion review, and other /ops/... endpoints)

  • Admin KeyHandles platform-level global management (creating Workspaces, issuing/revokingOwner Keyand other global endpoints). Do not mix them.

Members and permissions

  • List members:

    curl "$HOST/ops/workspaces/members?workspaceId=1" -H "X-API-Key: $OWNER_KEY"
  • Create a member:

    curl -X POST "$HOST/ops/workspaces/members" \
      -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \
      -d '{"workspace_id": 1, "user_id": "agent_tech", "name": "Tech Agent", "role": "member"}'
    Note

    Role enum values (lowercase):owner, admin, viewer, member.owner has full workspace permissions;member can only access own memory.

  • Other APIs:

    • Update:PATCH /ops/workspaces/members

    • Delete:DELETE /ops/workspaces/members

API Key management

  • Issue a USER Key for a member:

    curl -X POST "$HOST/ops/workspaces/members/keys" \
      -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \
      -d '{"workspace_id": 1, "member_id": 10, "key_type": "USER"}'

    Response example:

    Warning

    plain_key is returned only once; save it immediately. You can revoke it at any time if suspicious activity is detected, and a stolen Key becomes invalid immediately.

    {"id": 42, "key_prefix": "ctx_9f3a", "key_type": "USER", "plain_key": "ctx_user_xxx..."}
  • List Keys (excluding plaintext values):

    curl "$HOST/ops/workspaces/members/keys?workspaceId=1" -H "X-API-Key: $OWNER_KEY"
  • Revoke a Key(revoked Keys become invalid cluster-wide within 30 seconds):

    curl -X POST "$HOST/ops/workspaces/members/keys/revoke" \
      -H "X-API-Key: $OWNER_KEY" -H "Content-Type: application/json" \
      -d '{"workspace_id": 1, "id": 42}'

Usage monitoring

  • Memory statistics:

      curl "$HOST/v1/memories/stats?user_id=user_001" -H "X-API-Key: $API_KEY"
  • Workspace overview(Owner Key):

    curl "$HOST/ops/overview/summary" -H "X-API-Key: $OWNER_KEY"

    Response Example

    {
      "memory_total": 12800,
      "active_sessions": 42,
      "queue_depth": 3,
      "token_saved_estimate": 1250000
    }
  • Token usage and quotas:

    # Monthly usage snapshot
    curl "$HOST/ops/quota/usage" -H "X-API-Key: $OWNER_KEY"
    
    # Current quota (dimension: workspace / member)
    curl "$HOST/ops/quota/current?dimension=workspace" -H "X-API-Key: $OWNER_KEY"
    Note

    Usage, token economics, and API call trends can also be viewed as charts on the Usage page in the console.

Audit logs

Every API call records workspace_id + member_id + action + path + result, retained for 30 days by default.

  • Retrieve audit logs:

    curl "$HOST/v1/audit/logs?action=MEMORY_ADD&result=success&from=2026-07-01T00:00:00Z&size=20" \
      -H "X-API-Key: $OWNER_KEY"

    Response example (partial):

    {
      "id": 9001,
      "workspace_id": 1,
      "action": "MEMORY_ADD",
      "subject_type": "user",
      "subject_id": "10",
      "result": "success",
      "path": "/v1/memories",
      "created_at": "2026-07-01T10:01:00Z"
    }
  • Statistics by dimension:

    curl "$HOST/v1/audit/stats?group_by=action" -H "X-API-Key: $OWNER_KEY"
    Note

    Use the following to get single-record details: GET /v1/audit/logs/{id}. Audit logs can also be searched on the Audit page in the console by action / result / time range.

Related documentation