Use this file to discover all available pages before exploring further.
Context management enables agents to maintain relevant information, handle long conversations effectively, and optimize performance by balancing comprehensive context with efficient processing.
The Context Management primitive focuses on how agents maintain, organize, and utilize information throughout conversations and workflows. While sessions and states handle persistence, context management addresses the strategic questions of what information to keep active, how to structure it, and when to optimize it.Effective context management is essential for:
Long Conversations: Maintain relevance in extended interactions without performance degradation
Information Prioritization: Keep critical information accessible while managing less relevant details
Memory Optimization: Balance comprehensive context with processing efficiency
Task Continuity: Ensure agents have the right information at the right time
Performance Scaling: Handle complex workflows without overwhelming the context window
Automatic History
All messages automatically preserved in conversation context
Context Windowing
Agents intelligently manage large conversation histories
Strategic Summarization
Condense lengthy contexts while preserving key information
Context flows through agent conversations in several ways:
Message History: All previous messages automatically included in agent context
System Prompts: Persistent instructions and guidelines throughout the session
Tool Results: Outputs from previous tool executions available as context
File State: Created files and their contents accessible in the environment
Explicit Context: Information you provide directly in messages
Automatic Context: Agentbase automatically manages message history. You don’t need to manually include previous messages - they’re always available to the agent.
// Provide important context explicitlyconst result = await agentbase.runAgent({ message: `Analyze this customer feedback and suggest improvements. CONTEXT: - Product: Mobile app for task management - Target users: Small business teams - Current rating: 3.8/5 stars - Main competitors: Asana, Trello, Monday - Recent changes: New collaboration features added last month FEEDBACK: "${customerFeedback}" Focus on actionable improvements that could increase our rating to 4.5+`, system: "You are a product manager specializing in user experience and product strategy."});// Explicit context helps agent provide more relevant analysis
// For very long conversations, periodically summarizeasync function manageConversationContext(sessionId: string, messageCount: number) { if (messageCount > 50) { // Generate summary of conversation so far const summary = await agentbase.runAgent({ message: `Please summarize our conversation so far, highlighting: 1. The main project goal 2. Key decisions made 3. Current progress and status 4. Outstanding tasks or questions 5. Important technical details or constraints`, session: sessionId }); // Store summary for reference await saveSummary({ sessionId, messageCount, summary: summary.message, timestamp: new Date() }); // Optionally start new session with summary const freshSession = await agentbase.runAgent({ message: `Continue project with this context: ${summary.message} Next task: [describe next task]`, system: "Previous conversation summary provided. Continue from this context." }); return freshSession.session; } return sessionId;}
// Inject persistent context via system promptconst sessionContext = { company: "TechCorp Inc.", industry: "B2B SaaS", targetMarket: "Small to medium businesses", keyProducts: ["ProjectHub", "TeamSync", "DataVault"], brandVoice: "Professional, helpful, concise"};const result = await agentbase.runAgent({ message: "Draft a response to a customer asking about our pricing", system: `You are a customer success representative for ${sessionContext.company}. COMPANY CONTEXT: Industry: ${sessionContext.industry} Target Market: ${sessionContext.targetMarket} Products: ${sessionContext.keyProducts.join(', ')} COMMUNICATION GUIDELINES: Brand Voice: ${sessionContext.brandVoice} Always mention relevant products when appropriate Focus on value and ROI for small businesses Be transparent about pricing while highlighting benefits Use this context to inform all your responses.`});// Context persists throughout entire session
async function researchWithContext(topic: string) { // Initialize research session with scope const init = await agentbase.runAgent({ message: `Starting comprehensive research on: ${topic} Research Goals: 1. Understand current state of technology 2. Identify key players and solutions 3. Analyze market trends 4. Assess opportunities and challenges 5. Compile actionable insights`, system: "You are a research analyst. Maintain a running compilation of findings." }); const sessionId = init.session; // Each research phase adds to context await agentbase.runAgent({ message: "Phase 1: Research academic literature and papers", session: sessionId }); await agentbase.runAgent({ message: "Phase 2: Analyze industry reports and market data", session: sessionId // Can reference academic findings from Phase 1 }); await agentbase.runAgent({ message: "Phase 3: Study competitor approaches and solutions", session: sessionId // Can reference both previous phases }); // Final synthesis with full context const report = await agentbase.runAgent({ message: `Create comprehensive research report synthesizing all findings from: - Academic research - Industry reports - Competitor analysis Include executive summary, detailed findings, and recommendations.`, session: sessionId // Agent has full context from all research phases }); return report;}
async function iterativeDevelopment() { // Start with requirements const requirements = await agentbase.runAgent({ message: `Build a REST API for user management with these requirements: - User CRUD operations - Authentication with JWT - Role-based access control - PostgreSQL database - Express.js framework - Comprehensive error handling - API documentation` }); const sessionId = requirements.session; // Design phase - agent remembers requirements await agentbase.runAgent({ message: "Design the database schema and API endpoints", session: sessionId }); // Implementation - agent remembers design await agentbase.runAgent({ message: "Implement user authentication and JWT token generation", session: sessionId }); // Testing - agent knows implementation details await agentbase.runAgent({ message: "Create comprehensive test suite for authentication", session: sessionId }); // Documentation - agent has full project context const docs = await agentbase.runAgent({ message: "Generate API documentation covering all endpoints and examples", session: sessionId // Can document everything because it was involved in building it }); return docs;}
async function multiDocumentAnalysis(documents: string[]) { // Initialize analysis session const init = await agentbase.runAgent({ message: `Analyzing ${documents.length} legal documents for consistency and compliance. Documents to analyze: ${documents.map((d, i) => `${i + 1}. ${d}`).join('\n')} Track common themes, inconsistencies, and compliance issues across all documents.`, system: "You are a legal analyst. Maintain running notes of cross-document findings." }); const sessionId = init.session; // Analyze each document - building context for (const doc of documents) { await agentbase.runAgent({ message: `Analyze document: ${doc} Note any issues, key terms, obligations, and how this relates to previously analyzed documents.`, session: sessionId }); } // Final cross-document analysis with full context const analysis = await agentbase.runAgent({ message: `Create comprehensive cross-document analysis covering: 1. Common themes across all documents 2. Inconsistencies or conflicts between documents 3. Compliance issues 4. Risk assessment 5. Recommendations Reference specific documents in your analysis.`, session: sessionId // Agent has analyzed all documents and can reference them }); return analysis;}
async function debugWithContext() { // Initial bug report const session = await agentbase.runAgent({ message: `Bug Report: - Application: E-commerce checkout - Issue: Payment processing fails intermittently - Error: "Transaction timeout after 30 seconds" - Frequency: ~15% of transactions - Impact: Lost sales, customer frustration Start debugging this issue.`, system: "You are a senior software engineer debugging production issues." }); const sessionId = session.session; // Each debugging step adds to context await agentbase.runAgent({ message: "Analyze error logs from the past week", session: sessionId }); await agentbase.runAgent({ message: "Check payment gateway response times", session: sessionId // Agent can correlate with error logs }); await agentbase.runAgent({ message: "Review recent code changes to checkout flow", session: sessionId // Agent can relate to gateway issues and error patterns }); // Solution with full debugging context const solution = await agentbase.runAgent({ message: `Based on all debugging findings: 1. What is the root cause? 2. What is the recommended fix? 3. How to prevent this in the future? 4. What monitoring should be added?`, session: sessionId // Agent has full context from entire debugging session }); return solution;}
// Good: Structured, scannable contextconst message = `Task: Analyze Q4 sales dataCONTEXT:Business Goals:- Identify top-performing products- Understand seasonal trends- Find underperforming regionsData Available:- sales_q4.csv (100,000 records)- Columns: date, product_id, region, quantity, revenuePrevious Findings:- Q3 showed 15% growth- Mobile category outperformed desktop- West region laggingConstraints:- Focus on actionable insights- Highlight year-over-year comparisons`;// Avoid: Unstructured wall of textconst badMessage = "Analyze Q4 sales data we have about 100k records and Q3 had 15% growth and mobile did better than desktop and west region was behind and we want to find top products and seasonal trends and compare to last year...";
Prioritize Recent Information
// Provide recent context explicitly when importantconst result = await agentbase.runAgent({ message: `RECENT UPDATE (Override previous): The deadline has been moved up to March 15th. Original task: ${originalTask} Please adjust the timeline and resource plan accordingly.`, session: sessionId});// Make critical updates explicit and prominent
Use Reference Points
// Create reference points for long conversationsconst checkpoint = await agentbase.runAgent({ message: "Create a checkpoint: summarize current state, decisions made, and next steps", session: sessionId});// Later, reference the checkpointawait agentbase.runAgent({ message: `Referring to checkpoint from message #47: ${checkpoint.message} Now let's proceed with the next phase...`, session: sessionId});
// When transferring between agents or sessionsconst handoffContext = await agentbase.runAgent({ message: "Prepare handoff summary including all critical information for next agent", session: currentSession});// New agent gets explicit contextconst newAgent = await agentbase.runAgent({ message: `Taking over from previous agent. Context: ${handoffContext.message} Continuing with: ${nextTask}`, system: "You are the specialist taking over this task."});
// State makes context actionableconst result = await agentbase.runAgent({ message: "Create analysis.py with the findings we discussed" // Context: agent remembers what findings were discussed // State: analysis.py is created and persists});
// System prompt = persistent context throughout sessionconst result = await agentbase.runAgent({ message: "Help customer", system: `You are customer support for TechCorp. Company context: [always available] Products: [always available] Policies: [always available]` // This context persists for entire session});
// Context follows conversation through agent transfersconst result = await agentbase.runAgent({ message: "I have a billing question about my order #12345", agents: [ { name: "Billing", description: "Handles billing" } ] // When transferred to Billing agent, they receive full context // including order #12345});
Problem: Agent doesn’t remember earlier conversationSolution: Verify session continuity and explicitly reference important info
// Ensure using same sessionconst result = await agentbase.runAgent({ message: "Continue from earlier", session: sessionId // ✓ Same session});// Explicitly reference important detailsconst explicit = await agentbase.runAgent({ message: "As we discussed earlier about the Q4 deadline...", session: sessionId});
Slow Response Times
Problem: Responses getting slower in long conversationsSolution: Implement summarization
Remember: Context is automatically managed in Agentbase. Focus on providing relevant, well-structured information and implementing summarization for very long conversations to maintain optimal performance.