Common scenarios
This topic provides integration examples, recommended configurations, and expected outcomes for four typical scenarios of Context0. Each scenario is ready to use out of the box. We recommend that you verify the results in a test workspace before deploying to production.
AI coding assistant scenario
Scenario description
Each time a new session is opened in an AI coding assistant such as Claude Code, Qoder, or Codex, the agent has no knowledge of the developer's technical preferences, project architecture, or past decisions. This leads to repetitive questions such as "Which framework? Which ORM?". Context0 provides cross-session experience persistence for coding agents: developer conversations are automatically distilled into a technical profile, and context is restored in seconds when a new session starts.
Interaction flow
Core pipeline:
-
The developer talks to the agent, and the agent writes messages to Context0 by using
ingest. -
The backend asynchronously completes L1 atomic fact extraction and L0 user profile distillation (tech stack, preferences, and project decisions).
-
Before a new session starts, the agent calls
assembleto retrieve context. -
Context0 returns
prompt_blocks(user profile, active decisions, and relevant memories), and the agent injects them into the system prompt.
Complete API examples
In this scenario, user_id="alice" assumes that the USER key in use is bound to the developer alice. The user_id in the request must match the end user bound to that USER key. For cross-user scenarios, use Owner Key.
-
Write a conversation (ingest)
curl -X POST http://<host>:4040/v1/context/ingest \ -H "X-API-Key: ******" -H "Content-Type: application/json" \ -d '{ "session_id": "session-mon-alice", "user_id": "alice", "agent_id": "coding-agent", "messages": [ {"role": "user", "content": "This project uses TypeScript + Prisma, auth with NextAuth, note it down"}, {"role": "assistant", "content": "Noted: project tech stack TypeScript + Prisma + NextAuth"} ] }'Sample response:
{ "code": 0, "data": { "session_id": "session-mon-alice", "session_internal_id": 1, "message_ids": [{"id": 1, "seq": 1}, {"id": 2, "seq": 2}], "event_id": 7 } } -
Assemble context for a new session three days later (assemble)
curl -X POST http://<host>:4040/v1/context/assemble \ -H "X-API-Key: ******" -H "Content-Type: application/json" \ -d '{ "session_id": "session-wed-alice", "user_id": "alice", "query": "add user login endpoint", "token_budget": 6000, "recall": {"top_k": 8} }'Sample response:
{ "code": 0, "data": { "prompt_blocks": [ {"role": "system", "tag": "user_profile", "content": "Alice: TypeScript, Prisma, concise code style, prefers functional patterns", "tokens": 35, "sources": []}, {"role": "system", "tag": "memory_recall", "content": "ORM=Prisma, auth=NextAuth, testing=Vitest", "tokens": 25, "sources": ["mem_101"]}, {"role": "system", "tag": "memory_recall", "content": "Alice confirmed in session-mon: use App Router, place API routes under /app/api/", "tokens": 40, "sources": ["mem_102"]} ], "token_used": 1850, "token_budget": 6000, "trace_id": "a1b2c3d4-..." } }
Recommended configuration
|
Item |
Recommended value |
Description |
|
Strategy preset |
|
Deep recall. Technical decisions are retained permanently. Preference-type memories are not expired. |
|
|
6000~8000 |
The context in coding scenarios is relatively heavy. The budget can be relaxed accordingly. |
|
Code indexing |
Add project documentation and architecture notes to the knowledge base |
Keep the code itself in Git. Only write semantic indexes to Knowledge. |
|
Dream evolution |
Standard |
Summarize recent decision changes at night and merge duplicate preferences. |
Before and after comparison
-- Before integration --
Wednesday (new session)
Alice: "Add a user login endpoint"
Agent: "Which framework? Which auth solution?" <-- repetitive questions
-- After integration --
Wednesday (new session, agent has restored context via assemble)
Alice: "Add a user login endpoint"
Agent: Directly produces TypeScript + Prisma + NextAuth implementation
Uses App Router style, places API routes at /app/api/auth/login/route.ts
(No longer asks "Which framework / ORM?")
Quick integration with CLI
If you use tools that support MCP or plugins, such as Claude Code, Qoder, or Codex, we recommend that you use the CLI for one-click integration. No manual HTTP calls are required:
# Install the CLI (requires Node.js >= 22)
npm install -g @polardbx/ctxdb0
# Bind the coding agent (--agent supports: claude | qoder | codex)
ctxdb0 setup --agent claude \
--api-key sk-user-xxx \
--base-url https://your-context0.example.com
# Verify connectivity
ctxdb0 ping --agent claude # Returns ok if connected
setup automatically configures the MCP Server. After that, just code as usual. Writing and recall are handled automatically by the CLI in the background.
Intelligent customer service and shopping guide scenario
Scenario description
In customer service and shopping guide scenarios, users must re-describe their background and preferences every time they start a conversation. The agent lacks cross-session memory, which causes context loss. When multiple agents are involved in a transfer, users also need to repeat their background information. Context0 builds a persistent profile for each user, including preferences, sentiment tags, and historical interaction summaries, so that the agent has full context as soon as it takes over.
Interaction flow
Core pipeline:
-
The user sends a message to the agent.
-
The agent calls Context0
assemblein parallel to retrieve the user profile and queries the business database for orders and products. -
The agent merges the context and sends it to the LLM to generate a reply.
-
The agent writes the current conversation back to Context0 by using
ingestto asynchronously distill and update the L0 profile (preferences, sentiment, and purchase tendencies).
Complete API examples
In this scenario, user_id="cust_001" assumes that the USER key in use is bound to this end customer. The user_id in the request must match the end customer bound to that USER key. If one agent serves multiple customers, use Owner Key on the server side and explicitly pass user_id.
-
Write a user conversation (ingest)
curl -X POST http://<host>:4040/v1/context/ingest \ -H "X-API-Key: ******" -H "Content-Type: application/json" \ -d '{ "session_id": "sess_789", "user_id": "cust_001", "agent_id": "shopping-agent", "messages": [ {"role": "user", "content": "Looking for a gift for my girlfriend, budget under 500, artsy handcraft style"}, {"role": "assistant", "content": "Recommended: handmade ceramic mug and hand-woven scarf, both artsy handcraft style, budget 300-480"} ], "metadata": { "emotion": "positive", "category": "gift_recommendation" } }'Sample response:
{ "code": 0, "data": { "session_id": "sess_789", "session_internal_id": 2, "message_ids": [{"id": 3, "seq": 1}, {"id": 4, "seq": 2}], "event_id": 12 } } -
Assemble user profile on next contact (assemble)
curl -X POST http://<host>:4040/v1/context/assemble \ -H "X-API-Key: ******" -H "Content-Type: application/json" \ -d '{ "session_id": "sess_790", "user_id": "cust_001", "query": "Does that ceramic mug come in other styles", "token_budget": 4000, "recall": {"top_k": 8} }'Sample response:
{ "code": 0, "data": { "prompt_blocks": [ {"role": "system", "tag": "user_profile", "content": "cust_001: female gift-giving scenario, prefers artsy handcraft style, budget under 500, positive sentiment", "tokens": 40, "sources": []}, {"role": "system", "tag": "memory_recall", "content": "Previously recommended handmade ceramic mug and hand-woven scarf; user was more interested in the ceramic mug", "tokens": 30, "sources": ["mem_201"]}, {"role": "system", "tag": "memory_recall", "content": "sess_789 summary: gift recommendation - artsy handcraft style - budget 500", "tokens": 25, "sources": ["mem_202"]} ], "token_used": 980, "token_budget": 4000, "trace_id": "b2c3d4e5-..." } }
Recommended configuration
|
Item |
Recommended value |
Description |
|
Strategy preset |
|
Fast in and out. Suitable for high-frequency short conversations. Distillation focuses on the user profile. |
|
|
|
Recall by user dimension. User A cannot see the memories of User B. |
|
Dream evolution |
Standard / Premium |
Summarize user preferences at night. The shopping guide recommendation pool is adjusted accordingly. |
|
|
Pass emotion and category as needed |
Facilitates subsequent filtering and summarization by sentiment and category. |
Before and after comparison
-- After integration --
Day 1 (first contact)
User: "Looking for a gift for my girlfriend, budget 500, artsy handcraft style"
Agent: Recommends ceramic mug, hand-woven scarf
Day 3 (new session, agent has retrieved profile via assemble)
User: "Does that mug come in other colors"
Agent: "The one recommended last time was the 'Morning Mist Gray' handmade ceramic mug.
We also have 'Dusk Blue' and 'Sakura Pink',
both priced at CNY 380. Which color does your girlfriend prefer?"
(No longer asks "Which mug are you referring to? What budget?")
Enterprise knowledge base RAG scenario
Scenario description
Enterprise policies, technical documentation, and operation manuals are scattered across platforms such as Feishu, Wiki, and Confluence. Employees have low cross-platform search efficiency, and HR, IT, and administration teams face a large number of repetitive inquiries. The Context0 knowledge base enables "upload and ask" for documents: automatic parsing, dual-layer chunking, and semantic indexing allow employees to get answers by asking questions in natural language.
Interaction flow
Core pipeline:
-
The administrator uploads a document (PDF, Word, Markdown, or other formats).
-
Context0 automatically parses the document and performs dual-layer chunking (small chunks for precise matching and large chunks for context), embedding, and indexing.
-
When a user asks a question, the system retrieves information by using
knowledge/searchorassemble(include=knowledge). -
The system returns the most relevant knowledge snippets and assembles them into a prompt for the LLM to generate an answer.
Complete API examples
In the enterprise knowledge base scenario, user_id="employee_wang" refers to an end-user employee. The user_id in the request must match the end-user employee bound to that USER key. For services that need to initiate searches on behalf of multiple employees, use Owner Key.
-
Create a knowledge base
curl -X POST http://<host>:4040/v1/knowledge/bases \ -H "X-API-Key: ******" -H "Content-Type: application/json" \ -d '{"name": "company-policy-kb", "graph_enabled": false}'Sample response:
{ "code": 0, "data": { "id": 1, "name": "company-policy-kb", "graph_enabled": false, "document_count": 0, "created_at": "2024-12-01T10:00:00Z" } } -
Upload a document
curl -X POST "http://<host>:4040/v1/knowledge/bases/1/documents/upload" \ -H "X-API-Key: ******" \ -F "file=@/path/to/travel-reimbursement-policy.pdf" \ -F "title=Travel Reimbursement Policy v3.2"Sample response:
{ "code": 0, "data": { "document_id": 42, "title": "Travel Reimbursement Policy v3.2", "ingest_status": "pending", "file_size": 1048576 } } -
Search knowledge
curl -X POST http://<host>:4040/v1/knowledge/search \ -H "X-API-Key: ******" -H "Content-Type: application/json" \ -d '{"query": "business travel reimbursement process and standards", "kb_ids": [1], "top_k": 5}'Sample response:
{ "code": 0, "data": [ { "chunk_id": "chunk_42", "document_id": "42", "title": "Travel Reimbursement Policy v3.2", "snippet": "Domestic business travel accommodation standards: tier-1 cities <=CNY 600/night, tier-2 cities <=CNY 400/night; transportation expenses reimbursed upon receipt, pre-approval required for amounts over CNY 500...", "score": 0.92, "position": 1 }, { "chunk_id": "chunk_47", "document_id": "42", "title": "Travel Reimbursement Policy v3.2", "snippet": "Reimbursement process: within 5 business days after the trip, log in to the OA system, fill in the travel reimbursement form, upload scanned receipts, get approval from direct supervisor, then finance review...", "score": 0.88, "position": 2 } ] } -
Unified assembly via assemble (recommended)
curl -X POST http://<host>:4040/v1/context/assemble \ -H "X-API-Key: ******" -H "Content-Type: application/json" \ -d '{ "session_id": "sess_kb_001", "user_id": "employee_wang", "query": "What is the accommodation standard for business travel to Shanghai", "token_budget": 4000, "context_scope": "knowledge_only", "recall": {"top_k": 5} }'Sample response:
{ "code": 0, "data": { "prompt_blocks": [ {"role": "system", "tag": "knowledge", "content": "Domestic business travel accommodation standards: Shanghai is a tier-1 city with a maximum of CNY 600/night. Exceeding the limit requires prior special approval with a department director approval email.", "tokens": 50, "sources": ["runbook.pdf"]}, {"role": "system", "tag": "knowledge", "content": "Hotel bookings must be made through the corporate agreement platform (TravelBao). Self-booked hotels require proof of unavailability from the platform for reimbursement.", "tokens": 45, "sources": ["runbook.pdf"]} ], "token_used": 620, "token_budget": 4000, "trace_id": "c3d4e5f6-..." } }
Recommended configuration
|
Item |
Recommended value |
Description |
|
Strategy preset |
|
Disables memory extraction. Pure knowledge base retrieval mode. |
|
|
|
Recalls only knowledge base content without user profiles. |
|
Dream evolution |
Disabled |
Policy-type knowledge does not require inference-based evolution. The original text is authoritative. |
|
|
As needed |
If documents have relationships (such as organizational structure), enable graph enhancement. |
|
ACL permissions |
|
For example, finance documents are visible only to the finance department. |
Before and after comparison
-- After integration --
Employee: "What is the accommodation standard for business travel to Shanghai?"
QA Bot: "Shanghai is a tier-1 city with a maximum of CNY 600/night.
Exceeding the limit requires prior special approval with
a department director approval email.
Hotels must be booked through TravelBao."
-- Source: Travel Reimbursement Policy v3.2, Chapter 3
Employee: "What if I cannot find an affordable hotel?"
QA Bot: "You may book on your own, but you must provide a screenshot
of the TravelBao unavailability proof for reimbursement."
Quality assurance mechanisms
|
Mechanism |
Purpose |
|
Dual-layer chunking |
After a small chunk is precisely matched, the large chunk is returned to the LLM, balancing granularity and context. |
|
Content review |
Memories must be manually reviewed before being promoted to knowledge, ensuring knowledge quality. |
|
Wiki knowledge distillation |
Automatically discovers high-value memory clusters, synthesizes Markdown knowledge documents, and ingests them after review. |
|
Memory promotion |
Facts distilled from high-frequency Q&A can be promoted to knowledge, allowing the knowledge base to grow automatically with usage. |
|
ACL permission control |
Three-tier document access control: team, private, and public. |
Multi-agent collaboration scenario
Scenario description
In complex business scenarios, multiple specialized agents each handle a segment of the process (reception, technical support, billing, escalation, and so on), presenting a seamless service line to the user. However, in traditional implementations, context cannot be passed during agent transfers, and users must repeatedly provide information they have already shared. Context0 uses a multi-member architecture within the same workspace to let multiple agents share the same user profile and interaction facts.
Interaction flow
Core pipeline:
-
Multiple agents are registered as different members under the same workspace, each with its own API key.
-
The user talks to the reception agent. The reception agent writes facts (including sentiment tags) by using
ingest. -
The request is routed to the technical agent. The technical agent calls
assembleto immediately obtain the reception records and user profile. -
The technical agent writes the investigation conclusion by using
ingest, then routes to the escalation agent. The escalation agent callsassembleto obtain the full pipeline context. -
The L0 user card automatically merges findings from all agents to form a unified profile.
Architecture design
One workspace (customer service system)
+-- Member: reception_agent Reception agent (API Key: ******
+-- Member: tech_agent Technical agent (API Key: ******
+-- Member: billing_agent Billing agent (API Key: ******
+-- Member: escalation_agent Escalation agent (API Key: ******
Memories within the same workspace are visible to all members
-> The technical agent can see the facts and sentiment tags recorded by the reception agent
Key decision: Do two agents need to see each other's recorded content?
-
Yes: use different members in the same workspace.
-
No (independent products with strict data isolation): use different workspaces.
Complete API examples
In a multi-agent collaboration scenario, each agent uses its own USER key (bound to a different member) but serves the same end customer customer_zhang. You need to use Owner Key (or a server-side key that is not bound to any specific end user) to explicitly pass user_id="customer_zhang" in the request. If you mistakenly use a USER key that is already bound to another user, the server returns 403.
-
Reception agent writes a conversation (ingest)
curl -X POST http://<host>:4040/v1/context/ingest \ -H "X-API-Key: $SK_RECEPTION" -H "Content-Type: application/json" \ -d '{ "session_id": "sess_transfer_001", "user_id": "customer_zhang", "agent_id": "reception_agent", "messages": [ {"role": "user", "content": "My order ORD-20241205 has not been shipped for three days, I am very worried"}, {"role": "assistant", "content": "Issue recorded. Transferring you to technical support to check logistics status"} ], "metadata": { "emotion": "anxious", "category": "logistics_delay", "order_id": "ORD-20241205" } }'Sample response:
{ "code": 0, "data": { "session_id": "sess_transfer_001", "session_internal_id": 3, "message_ids": [{"id": 5, "seq": 1}, {"id": 6, "seq": 2}], "event_id": 31 } } -
Technical agent assembles context (assemble)
curl -X POST http://<host>:4040/v1/context/assemble \ -H "X-API-Key: $SK_TECH" -H "Content-Type: application/json" \ -d '{ "session_id": "sess_transfer_002", "user_id": "customer_zhang", "query": "Check logistics status and delay reason", "token_budget": 4000, "recall": {"top_k": 10} }'Sample response:
{ "code": 0, "data": { "prompt_blocks": [ {"role": "system", "tag": "user_profile", "content": "customer_zhang: anxious, concerned about delivery timeliness, VIP customer", "tokens": 30, "sources": []}, {"role": "system", "tag": "memory_recall", "content": "Reception agent recorded: customer reports order ORD-20241205 not shipped for 3 days, anxious, needs logistics status check", "tokens": 45, "sources": ["mem_301"]}, {"role": "system", "tag": "memory_recall", "content": "Order ORD-20241205: placed on Dec 5, status=warehouse picking, expected ship date=Dec 6 (2 days overdue)", "tokens": 40, "sources": ["mem_302"]} ], "token_used": 1320, "token_budget": 4000, "trace_id": "d4e5f6a7-..." } } -
Technical agent writes investigation conclusion (ingest)
curl -X POST http://<host>:4040/v1/context/ingest \ -H "X-API-Key: $SK_TECH" -H "Content-Type: application/json" \ -d '{ "session_id": "sess_transfer_002", "user_id": "customer_zhang", "agent_id": "tech_agent", "messages": [ {"role": "assistant", "content": "After investigation, logistics stalled due to a snowstorm. Shipping is expected to resume tomorrow. Priority shipping and a compensation plan have been applied for."} ], "metadata": { "resolution": "weather_delay", "action": "priority_shipping_applied" } }' -
Escalation agent obtains full pipeline context (assemble)
When the escalation agent calls
assemble, it receives the complete pipeline including reception records, technical investigation conclusions, and the user profile:{ "code": 0, "data": { "prompt_blocks": [ {"role": "system", "tag": "user_profile", "content": "customer_zhang: VIP customer, currently anxious, concerned about delivery timeliness", "tokens": 30, "sources": []}, {"role": "system", "tag": "memory_recall", "content": "Reception record: order ORD-20241205 not shipped for 3 days; technical conclusion: caused by snowstorm, priority shipping applied", "tokens": 45, "sources": ["mem_301", "mem_303"]}, {"role": "system", "tag": "memory_recall", "content": "Resolution progress: priority shipping and compensation plan applied, pending escalation agent to confirm compensation amount", "tokens": 35, "sources": ["mem_304"]} ], "token_used": 1580, "token_budget": 4000, "trace_id": "e5f6a7b8-..." } }
Recommended configuration
|
Item |
Recommended value |
Description |
|
Strategy preset |
|
Deep recall. Suitable for collaboration scenarios that require summarization and reasoning. |
|
|
|
Isolate memories of different end customers. |
|
API key allocation |
One USER key per agent (different |
Facilitates auditing each agent's operations by member. |
|
Entity Card |
Shared across agents |
Each customer has only one profile card, jointly maintained by all agents. |
|
|
Pass emotion, category, and resolution as needed |
Facilitates cross-agent semantic recall and post-incident auditing. |
Before and after comparison
-- After integration --
The customer spoke only 3 rounds but was handled by 3 agents:
Customer -> Reception agent: "Order hasn't shipped for 3 days, I'm in a hurry"
Reception agent: Records sentiment + request -> Routes to technical agent
Customer -> Technical agent: "Can you help me check the reason"
Technical agent: Already has reception record + sentiment tags
-> Finds snowstorm cause -> Routes to escalation agent
Customer -> Escalation agent: "Can I get compensation"
Escalation agent: Already has full history
(reception + technical + sentiment + resolution)
-> Directly provides compensation plan
(Customer never needs to repeat any background)
FAQ
Which platforms are supported?
-
AI coding tools: Tools that support MCP or plugins, such as Claude Code, Qoder, and Codex, can use the
ctxdb0CLI for one-click integration. -
Custom agents and backend services: Any programming language can directly call the data plane REST APIs (
ingest,assemble, memory, and knowledge). -
Mem0 ecosystem: Compatible endpoints such as
/v1/memoriesand/v1/memories/searchare provided. Existing Mem0 clients can connect directly.
Is there a memory limit?
A single ingest call supports up to 100 messages per batch. There is no hard limit on total memory volume. This is the value of the three-layer memory model: raw conversations are progressively distilled into L1 facts and L0 profiles. Token usage remains stable over time and does not grow as more memories accumulate. In real-world usage, after a year of use by a single user, the amount of context recalled for the LLM remains stable and controllable.
Are memories isolated across different API keys?
The core isolation anchor is (workspace_id, member_id), not the API key itself:
-
Cross-workspace: Physical isolation at the index level. Neither side can access the other's data.
-
Different members in the same workspace: Memories are visible by default (this is the foundation of multi-agent collaboration). You can control the recall scope by using
recall.scope. -
Different user_ids in the same workspace: When
recall.scope=user, memories of different end users are invisible to each other.
Independent products that require strict isolation should be assigned to different workspaces.
What are the file format and size limits?
-
Supported formats: PDF, Markdown, Word, Excel, PPT, RTF, EPUB, images, audio, and more.
-
Single file size: The default limit is 50 MB (configurable via the
MAX_FILE_SIZEenvironment variable). The overall request limit is the single-file limit plus 5 MB. -
Inline images in Markdown can be uploaded together by using the
imagesfield. The Vision model automatically generates descriptions for the images.
How much should token_budget be set to?
token_budget ranges from [1, 32000] with a default of 32000. The server guarantees that the budget is never exceeded. Empirical values:
|
Scenario |
Recommended value |
|
Lightweight completion and formatting ( |
1000~2000 |
|
General conversation and customer service |
3000~4000 |
|
Coding assistant (heavy context) |
6000~8000 |
|
Deep RAG and long-document analysis |
8000~16000 |
|
Multi-agent collaboration (full pipeline context) |
4000~6000 |
You can use budget_allocator to fine-tune how the budget is allocated (memory_ratio, knowledge_ratio, history_ratio, and system_ratio). The three proportions are automatically normalized.
How do I delete all memories?
Use DELETE /v1/memories/clear. This is a dangerous operation that requires explicitly adding confirm=true:
Both the query string and request body must include confirm=true for the irreversible batch deletion to execute. If either is missing, 400 is returned.
# Clear all memories for a specific user
curl -X DELETE "http://<host>:4040/v1/memories/clear?confirm=true" \
-H "X-API-Key: ******" -H "Content-Type: application/json" \
-d '{"scope": "all", "user_id": "user_001", "confirm": true}'
scope supports three modes: all (all memories), before_date (before a specific point in time, requires before_date), and by_session_ids (specific sessions, requires session_ids). You can also use DELETE /v1/memories/{id} to delete a single memory.
How about Mem0-compatible migration?
Context0 provides Mem0-compatible endpoints for smooth migration from existing Mem0 applications:
-
POST /v1/memories: Creates a memory (extracts atomic facts from conversations). Behavior is aligned with Mem0. -
POST /v1/memories/search,/v2/memories/search, and/v3/memories/search: Semantic search./v3is compatible with Mem0 v1.1 SDK (entity params use thefiltersmap). -
The
/v1and/v2series return raw JSON directly (without envelope wrapping), compatible with Mem0 SDK parsing.
Migration typically requires only pointing the base URL to the Context0 data plane and switching to a Context0 API key. Compared with native Mem0, you additionally get three-layer memory distillation, hybrid recall, token budget control, and enterprise-grade isolation.
Can multiple scenarios be used together?
Yes. Strategy presets (coding, chat, rag-only, and agent) are per-request parameters. Different requests within the same workspace can use different strategies. Typical practices:
-
The coding agent uses the
codingstrategy for ingest and assemble. -
Knowledge search within the same workspace uses the
rag-onlystrategy for assemble. -
Cross-agent collaboration scenarios use the
agentstrategy for assemble.
The token budget control of Context0 ensures that the output always stays within the budget regardless of which strategy is used.