# Overview Source: https://docs.agentbase.sh/build/overview Learn how to build production-grade AI agents with Agentbase Build production-ready AI agents with simple APIs. Agentbase handles infrastructure so you can focus on what your agents do. We designed Agentbase to make creating AI agents stupidly easy. You can start with the bootstrap commands or SDK, and begin by giving your agent a system prompt and a set of rules. Each agent comes with built-in primitives, so you don't need to set up a new environment. It already runs on a persistent computer with browser access, web search, MCP, and other capabilities. ## What You Can Build People build both internal agents (for automating internal workflows) and external agents (for customer-facing applications). Agentbase agents can handle a wide variety of tasks with built-in capabilities: **Built-in capabilities:** * Write, test, and debug code in Python, Node.js, and more * Install packages and manage dependencies * Run tests and validate outputs * Work with files and Git repositories **Example tasks:** * "Create a REST API with authentication" * "Write unit tests for my Python module" * "Debug this error and fix the code" **Built-in capabilities:** * Search the web for real-time information * Crawl and scrape websites * Process and analyze data * Synthesize insights from multiple sources **Example tasks:** * "Research our top 3 competitors and their pricing" * "Analyze this dataset and create visualizations" * "Find the latest AI research papers on this topic" **Built-in capabilities:** * Navigate websites and fill forms * Extract data from web pages * Test web applications * Automate repetitive browser tasks **Example tasks:** * "Fill out this form submission" * "Test the checkout flow on our website" * "Monitor competitor pricing daily" **Built-in capabilities:** * Read and write various file formats * Transform and clean data * Generate reports and summaries * Work with APIs and integrations **Example tasks:** * "Convert these CSV files to JSON" * "Process customer feedback and categorize by sentiment" * "Generate a weekly report from our analytics" Most developers start by defining their agent's behavior with a **system prompt** that sets personality and expertise, then add **rules** for constraints and compliance. Each agent automatically gets access to built-in **primitives** like web browsing, file systems, and tools - no setup required. Instead of configuring and setting up your own infrastructure, you can utilize ours as a managed service. As they build, they'll create custom tools and functions, use primitives like data stores and MCP, and evaluate agents with traces. ## Core Concepts | Concept | Description | Link | | -------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------- | | **Agent Primitives** | Understand the building blocks: environments, tools, states, sessions, and more | [Learn more →](/primitives/overview) | | **Agent Modes** | Choose between Flash, Base, and Max modes based on task complexity | [Learn more →](/getting-started/agent-modes) | | **System Prompts** | Guide how agents approach tasks and make decisions | [Learn more →](/build/system-prompts) | | **Custom Tools** | Extend agent capabilities with your own tools and APIs | [Learn more →](/primitives/essentials/custom-tools) | ## Architecture Agentbase handles all the complex infrastructure so you don't have to: ```mermaid theme={null} graph TB A[Your Application] --> B[Agentbase API] B --> C[Agent Runtime] C --> D[Sandboxed Environment] C --> E[Tool Execution] C --> F[State Management] D --> G[File System] D --> H[Browser] D --> I[Shell Access] E --> J[Built-in Tools] E --> K[Custom Tools] F --> L[Session Persistence] F --> M[Context Management] ``` **What Agentbase manages for you:** * Agent orchestration and reasoning * Sandboxed execution environments * Tool selection and execution * State and session persistence * Scaling and load balancing * Security and compliance ## Agent Primitives Build sophisticated agents using Agentbase primitives - the building blocks that power agent functionality: **Sandbox, File System, Computer, Browser** Execution environments where agents operate with full isolation and security **Prompts, Tools, Sessions, States** Core capabilities every agent needs for interaction and memory **Memory, RAG, Workflows, Voice** Advanced features for specialized use cases and complex workflows See all 35+ primitives and learn how they work together → # Rules Source: https://docs.agentbase.sh/build/rules Set specific constraints and requirements for agent behavior > Rules provide specific constraints and requirements that agents must follow. Rules work alongside system prompts to enforce boundaries and compliance requirements. ## Basic Usage ```javascript theme={null} const response = await agentbase.runAgent({ message: "Help with customer refund request", system: "You are a customer service specialist", rules: [ "Never approve refunds over $500 without manager approval", "Always verify customer identity before processing requests", "Document all refund decisions with clear reasoning" ] }); ``` ## Combining Rules with System Prompts ```javascript theme={null} const response = await agentbase.runAgent({ message: "Help customer with billing dispute", system: "You are an empathetic customer service specialist focused on resolution", rules: [ "Maximum refund authorization without approval: $200", "Always verify account ownership before discussing billing", "Document all billing adjustments with detailed reasoning", "Escalate disputes over $500 to billing supervisor" ] }); ``` # System Prompt Source: https://docs.agentbase.sh/build/system-prompts Guide agent behavior and expertise with custom system prompts > System prompts define your agent's personality, expertise, and behavioral guidelines. System prompts are often used to define: * **Role** - What the agent is and its expertise * **Behavior** - How the agent should act and respond * **Tool definitions** - Specific tools and capabilities to use * **Process workflow** - Steps and procedures to follow ## Customer Support Agent ```javascript theme={null} // Reusable pattern for different support tiers const createSupportAgent = (productName, tier) => { return agentbase.runAgent({ message: userQuestion, system: `You are a ${tier} support agent for ${productName}. Role: Resolve customer issues and provide product guidance Behavior: Professional, empathetic, solution-focused Tools: Access knowledge base, create tickets, escalate when needed Process: 1. Understand the issue completely 2. Check knowledge base for solutions 3. Provide step-by-step guidance 4. ${tier === 'L1' ? 'Escalate complex technical issues' : 'Handle technical deep-dives'}`, rules: [ "Never share internal system details", "Always verify user identity for account changes", "Keep responses under 200 words unless technical explanation needed" ] }); }; ``` ## Website Change Detection Agent ```javascript theme={null} // Monitor competitor websites for changes const detectWebsiteChanges = async (websiteUrl, companyName) => { const sessionId = `monitor_${companyName.toLowerCase().replace(/\s+/g, '_')}`; return await agentbase.runAgent({ message: `Monitor ${websiteUrl} for changes since last check and generate change report`, system: `You are a website change detection specialist monitoring ${companyName}'s online presence. Role: Detect and analyze website changes for competitive intelligence Behavior: Methodical, detail-oriented, comprehensive in change detection Tools: Browser automation, memory storage, content analysis, screenshot capture Process: 1. Open browser and navigate to ${websiteUrl} 2. Retrieve previous snapshot from memory (key: 'website_snapshot_${companyName}') 3. Capture current website structure, navigation, and key content areas 4. Generate sitemap of all discoverable pages 5. Compare against previous snapshot to identify changes 6. Save new snapshot to memory as structured markdown 7. Create detailed change report with before/after analysis Output Format: - Executive Summary: High-level changes - New Content: Pages, sections, features added - Modified Content: Updated text, images, layouts - Removed Content: Deleted pages or sections - Technical Changes: New tools, frameworks, performance updates`, mode: "base", session: sessionId, rules: [ "Always capture screenshots of significant changes for evidence", "Store all snapshots in memory with timestamp metadata", "Focus on user-facing changes, not technical implementation details", "Respect robots.txt and rate limiting while crawling" ] }); }; ``` # Tools Source: https://docs.agentbase.sh/build/tools Available tools and capabilities for Agentbase agents > Agents automatically select and use tools based on your task. No configuration required. ## How Tools Work Agents automatically choose tools when needed: ```javascript theme={null} // Agent will automatically use web browsing tools const research = await agentbase.runAgent({ message: "Find the latest pricing for our competitors", }); // Agent will automatically create computer environment and use bash/file tools const development = await agentbase.runAgent({ message: "Create a Python script that processes CSV data", }); ``` ## Built-in Tools Here are the built-in tools that Agentbase agents have access to: | Category | Tool | Description | | --------------------------- | -------------------- | --------------------------------------------------------------------------- | | **File System** | `str_replace_editor` | Create, edit, view, and manage files with persistent state across sessions | | | `bash` | Run shell commands with internet access and package management capabilities | | | `glob` | Find files using glob patterns (e.g., `*.js`, `**/*.ts`) | | | `grep` | Search for text patterns in files with regex support | | **Web Tools** | `web` (search) | Search the web for real-time information and current data | | | `web` (crawl) | Extract content from specific URLs and websites | | **Computer Environment** | `computer` | Create/resume Linux computer instances for development tasks | | **Thinking & Planning** | `think` | Private scratchpad for complex reasoning, planning, and maintaining context | | **Development Environment** | Python 3.11.2 | Execute Python code and scripts | | | Node.js 18.20.4 | JavaScript runtime environment | | | Package management | apt (Debian), pip (Python), npm (Node.js) | ## Example Tool Event Flow When agents use tools, the API streams real-time events showing tool execution: ```json theme={null} // Tool execution starts {"type": "agent_tool_use", "content": "{\"tool\":\"web\",\"input\":\"{\\\"command\\\":\\\"search\\\",\\\"query\\\":\\\"AI developments 2025\\\"}\"}"} // Tool returns results {"type": "agent_tool_response", "content": "{\n \"tool\": \"web\",\n \"response\": [\n {\n \"url\": \"https://example.com/ai-news\",\n \"title\": \"Latest AI Developments\"\n }\n ]\n}"} // Cost tracking {"type": "agent_cost", "session": "abc123", "cost": "0.0095", "balance": 47.45} // Step completion {"type": "agent_step", "session": "abc123", "stepNumber": 1} ``` ## Custom Tools You can write custom code tools with environment variables in the Agentbase app's Tools section: Custom tools interface showing code editor with environment variables ```typescript theme={null} // Example custom tool usage const result = await agentbase.runAgent({ message: "Get customer data for user ID 12345", tools: ["get_customer_data"], // deployed tool name on the agentbase app }); ``` ## Key Points * Tools are selected automatically based on your task * No manual configuration or tool specification required * Computer environments created when needed for stateful operations * All tools work together seamlessly in workflows # Contact Support Source: https://docs.agentbase.sh/contact-support Get help and connect with our community ## Get Help Join for real-time support and discussions Or reach out to us on Twitter, LinkedIn, through our website, or contact the founders directly. ## Connect With Us Main website and resources Latest updates and features Updates and insights Company updates and news # Clear Messages Source: https://docs.agentbase.sh/deploy/api/clear-messages POST https://api.agentbase.sh/clear-messages Clear all messages from the current agent session. ### Query Parameters The session ID to clear messages from. This identifies the specific agent session. ### Response Returns confirmation of the clear messages operation. ```json theme={null} { "success": true, "message": "Messages cleared" } ``` # Create Datastore Source: https://docs.agentbase.sh/deploy/api/create-datastore POST https://api.agentbase.sh/create-datastore Create a new datastore to organize your documents or databases. ### Body Parameters The name of the datastore. This helps you identify and organize your data. The type of datastore to create. Supported values: - `database` - For structured database content - `documents` - For document files The metadata for the datastore. This is only required for `database` type datastores. Set the connection string for the database. ```json theme={null} { "metadata": { "connectionString": "postgresql://username:password@host:port/database" } } ``` ### Response Returns the created datastore information including the datastore ID. ```json theme={null} { "datastore_id": "ds_1234567890abcdef", "name": "My Documents", "type": "documents", "created_at": "2025-10-01T12:00:00Z" } ``` ### Response Fields The unique identifier for the created datastore. Use this ID when indexing documents. The name of the datastore The type of datastore (`database` or `documents`) Timestamp of when the datastore was created # API Examples Source: https://docs.agentbase.sh/deploy/api/example Complete examples for different use cases and integration patterns. ## Basic Usage Examples ### Simple Text Generation ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"message": "Write a Python function to calculate fibonacci numbers"}' ``` ### Code Generation ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"message": "Create a JSON schema for a user profile with name, email, and preferences"}' ``` ### Web Search and Research ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"message": "Search for the latest developments in AI and summarize the key findings"}' ``` ### Complex Automation ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"message": "Plan a project roadmap for building a mobile app with user authentication, including technical requirements and timeline"}' ``` ## Agent Modes ### Base Mode (Balanced Performance) ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": "Generate code examples", "mode": "base" }' ``` ### Flash Mode (See Agent Thinking) ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": "Plan a marketing strategy", "mode": "flash" }' ``` ### Max Mode (Complex Reasoning) ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": "Design a complete system architecture", "mode": "max" }' ``` ## Streaming Control ### Non-Streaming (Complete Blocks) ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": "Write a product description", "streaming": false }' ``` ### Streaming Enabled (Token-by-Token) ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Accept: text/event-stream" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": "Analyze this website and suggest improvements", "streaming": true }' ``` ## Session Management ### Continue Conversations ```bash theme={null} # First message - creates a new session curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"message": "Help me plan a marketing campaign for a SaaS product"}' # Save the session ID from the response, then continue the conversation curl -X POST "https://api.agentbase.sh?session=SESSION_ID" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{"message": "Now create social media content for this campaign"}' ``` **Session Management:** * **Auto-Creation**: If you don't specify a session ID, a new one is automatically created * **Continue Conversations**: Append `?session=[SESSION_ID]` to the URL for follow-up messages * **Persistent Context**: The agent remembers previous messages within the same session ## Advanced Features ### Custom Tools and Rules ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": "Optimize this SQL query for better performance", "mode": "max", "system": "You are a database optimization expert", "rules": ["Always explain your reasoning", "Provide before/after comparisons"], "mcpServers": [ { "serverName": "database-tools", "serverUrl": "https://your-mcp-server.com/mcp" } ] }' ``` ### Built-in Capabilities #### File Processing ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"message": "Analyze this spreadsheet and create visualizations of the key trends"}' ``` #### Web Automation ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"message": "Monitor competitor pricing on their website and compile a comparison report"}' ``` #### Multi-step Planning ```bash theme={null} curl -X POST "https://api.agentbase.sh" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{"message": "Create a complete deployment strategy for a new microservice, including CI/CD pipeline, monitoring, and rollback procedures"}' ``` ## Programming Language Integration ### JavaScript/Node.js with Error Handling ```javascript theme={null} async function callAgent(message) { try { const response = await fetch('https://api.agentbase.sh', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_API_KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ message: message, mode: 'base' }) }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error('Agent request failed:', error); throw error; } } ``` ### Python with Session Management ```python theme={null} import requests class AgentbaseClient: def __init__(self, api_key): self.api_key = api_key self.session_id = None self.base_url = 'https://api.agentbase.sh' def send_message(self, message, mode='base'): url = self.base_url if self.session_id: url += f'?session={self.session_id}' response = requests.post( url, headers={ 'Authorization': f'Bearer {self.api_key}', 'Content-Type': 'application/json' }, json={ 'message': message, 'mode': mode } ) data = response.json() # Save session ID for future requests if 'session' in data: self.session_id = data['session'] return data # Usage client = AgentbaseClient('YOUR_API_KEY') response1 = client.send_message('Plan a marketing campaign') response2 = client.send_message('Create social media content for this campaign') ``` ## Troubleshooting ### Common Issues and Solutions #### Streaming Problems ```bash theme={null} # If your stream is choppy, disable streaming for complete blocks curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": "Write documentation", "streaming": false }' ``` #### See Agent Reasoning ```bash theme={null} # Use flash mode to see the agent's thinking process curl -X POST "https://api.agentbase.sh" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "message": "Solve this complex problem step by step", "mode": "flash" }' ``` ## Example Streaming Response ```text theme={null} data: {"type":"agent_started","session":"[SESSION_ID]"} data: {"type":"agent_thinking_start","session":"[SESSION_ID]"} data: {"type":"agent_thinking","session":"[SESSION_ID]","content":"The user is asking me to introduce myself."} data: {"type":"agent_response_start","session":"[SESSION_ID]"} data: {"type":"agent_response","session":"[SESSION_ID]","content":"Hello! I'm agentbase, a general-purpose AI agent designed to help you…"} data: {"type":"agent_tool_use_start","session":"[SESSION_ID]"} data: {"type":"agent_tool_use","session":"[SESSION_ID]","content":"{\"tool\":\"computer\",\"input\":\"\"}"} data: {"type":"agent_tool_response","session":"[SESSION_ID]","content":"{\"tool\":\"computer\",\"content\":\"success\"}"} data: {"type":"agent_step","session":"[SESSION_ID]","step":"1"} data: {"type":"agent_cost","session":"[SESSION_ID]","cost":"0.0934"} data: {"type":"agent_completed","session":"[SESSION_ID]"} ``` For an explanation of every `type` value, see [Streaming Message Types](/api/message-events). # Get Messages Source: https://docs.agentbase.sh/deploy/api/get-messages POST https://api.agentbase.sh/get-messages Retrieve the messages from the current agent session. ### Query Parameters The session ID to retrieve messages from. This identifies the specific agent session. ### Response Returns the entire message history for the specified agent session as an array of message objects. ```json theme={null} [ { "type": "user_message", "content": "Can you launch a computer instance?" }, { "type": "agent_thinking", "content": "The user is asking me to launch a computer instance. I can see that I have a \"computer\" function available that creates a new computer instance for the current user session." }, { "type": "agent_response", "content": "I'll launch a computer instance for you right away." }, { "type": "agent_tool_use", "content": "{\"tool\":\"computer\",\"input\":\"\"}" }, { "type": "agent_response", "content": "Great! I've successfully launched a computer instance for you." } ] ``` ### Message Types Messages sent by the user to the agent Internal agent reasoning and thought processes Agent responses visible to the user Records of tools used by the agent, including input parameters # Index Document Source: https://docs.agentbase.sh/deploy/api/index-document POST https://api.agentbase.sh/index-document Upload and index a document to an Agentbase datastore. ### Body Parameters The document file to upload and index. Supported formats include PDF, TXT, PNG, JPG, and more. The ID of the datastore where the document will be indexed. You can get this ID from the Create Datastore endpoint. ### Example Request ```bash theme={null} curl -X POST https://api.agentbase.sh/index-document \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: multipart/form-data" \ -F "file=@./Trends_Artificial_Intelligence.pdf" \ -F "datastore_id=ds_1234567890abcdef" ``` ### Response Returns information about the indexed document. ```json theme={null} { "document_id": "doc_abcdef1234567890", "datastore_id": "ds_1234567890abcdef", "filename": "Trends_Artificial_Intelligence.pdf", "status": "indexed", "indexed_at": "2025-10-01T12:00:00Z" } ``` ### Response Fields The unique identifier for the indexed document The ID of the datastore containing the document The name of the uploaded file The indexing status of the document (e.g., `indexed`, `processing`) Timestamp of when the document was successfully indexed # Message Events Source: https://docs.agentbase.sh/deploy/api/message-events | Type | Description | | ---------------------- | --------------------------------------------------------- | | `agent_started` | Agent session started | | `agent_thinking_start` | Agent started thinking (only when streaming is enabled) | | `agent_thinking` | Agent thinking with content | | `agent_response_start` | Agent started responding (only when streaming is enabled) | | `agent_response` | Agent response with content | | `agent_tool_use_start` | Tool call started (only when streaming is enabled) | | `agent_tool_use` | Tool call with tool name and input | | `agent_tool_response` | Tool result with tool name and result | | `agent_cost` | Agent step cost info | | `agent_step` | Step completed with step number | | `agent_completed` | Agent session finished | | `agent_error` | Agent error | # Run Agent Source: https://docs.agentbase.sh/deploy/api/run-agent POST https://api.agentbase.sh Run an agent with a message and receive a streaming agent response. ### Query Parameters The session ID to continue the agent session conversation. If not provided, a new agent session will be created. ### Request Body The task or message to run the agent with. A system prompt to provide system information to the agent. The Agents API defaults to the Agentbase default system prompt. The mode of the agent. Can be `flash`, `base` or `max`. Flash mode is great for simple, one-off tasks. Base mode is much faster and cheaper, with comparable performance to `max` mode. The Agents API defaults to `base`. A set of declarative workflows for the agent to execute. Each workflow is a DAG (Directed Acyclic Graph) of steps that the agent interprets and executes dynamically. The agent decides how to implement each step based on its description, making this a truly AI-native workflow system rather than a deterministic workflow builder. ```json theme={null} { "workflows": [ { "id": "customer_onboarding", "name": "onboard_new_customer", "description": "Onboard new customers by collecting information and setting up their account", "steps": [ { "id": "step_1", "name": "collect_customer_info", "description": "Gather customer name, email, and company details from the conversation", "depends_on": [] }, { "id": "step_2", "name": "validate_email", "description": "Verify the email address is valid and not already registered in the system", "depends_on": ["step_1"] }, { "id": "step_3", "name": "create_account", "description": "Create a new user account with the collected and validated information", "depends_on": ["step_2"] }, { "id": "step_4", "name": "send_welcome_email", "description": "Send a welcome email with account details and next steps", "depends_on": ["step_3"] } ] } ] } ``` **Workflow Schema:** * `id` (string, required): Unique identifier for the workflow * `name` (string, required): Name of the workflow * `description` (string, required): What the workflow accomplishes * `steps` (array, required): Array of step objects **Step Schema:** * `id` (string, required): Unique identifier for the step * `name` (string, required): Name of the step * `description` (string, required): What the step should accomplish - the agent interprets this to decide HOW to execute * `depends_on` (string\[], required): Array of step IDs that must complete before this step runs. Empty array means the step can run immediately. Steps with no dependencies run in parallel. **Advanced Step Options:** ```json theme={null} { "steps": [ { "id": "step_1", "name": "optional_verification", "description": "Attempt to verify user identity through third-party service", "depends_on": [], "optional": true, "retry_policy": { "max_attempts": 3, "backoff": "exponential" }, "output_schema": { "type": "object", "properties": { "verified": { "type": "boolean" }, "confidence_score": { "type": "number" } } } } ] } ``` * `optional` (boolean, optional): Whether the step can be skipped if it fails * `retry_policy` (object, optional): Retry configuration for the step * `output_schema` (object, optional): JSON schema for expected output validation A set of rules to provide to the agent. Rules are a set of constraints that the agent must follow. Defaults to no rules. A set of agent configurations that enables the agent to transfer conversations to other specialized agents. When provided, the main agent will have access to seamless handoffs between agents based on the conversation context. ```json theme={null} { "agents": [ { "name": "Support Agent", "description": "Handles customer support inquiries and technical issues" }, { "name": "Sales Agent", "description": "Handles sales questions and product inquiries" } ] } ``` This enables multi-agent workflows where specialized agents handle specific types of requests. A set of MCP servers to provide to the agent. MCP servers configs are not stored within the agent, so each request must include the MCP servers configs, and you can modify them each time. You need to provide both `serverName` and `serverUrl`. Optionally include `auth` for authentication. We have backward compatibility with the old `/sse` endpoint. ```json theme={null} { "mcp_servers": [ { "serverName": "mcp-server-authless", "serverUrl": "https://mcp-server-authless.com/mcp" }, { "serverName": "mcp-server-bearer", "serverUrl": "https://mcp-server-bearer.com/mcp", "auth": { "type": "bearer", "token": "your-bearer-token" } }, { "serverName": "mcp-server-oauth", "serverUrl": "https://mcp-server-oauth.com/mcp", "auth": { "type": "oauth", "oauth": { "accessToken": "your-oauth-access-token" } } } ] } ``` Whether to run the agent asynchronously on the server. When set to `true`, the agent runs in the background and you can use the `callback` parameter to receive agent message events. Defaults to `false`. A callback endpoint configuration to send agent message events back to. Use this with `background: true` to receive events at your specified endpoint. ```json theme={null} { "callback": { "url": "https://your-server.com/webhook", "headers": { "Authorization": "Bearer your-token" } } } ``` A set of datastores to provide to the agent. Datastores are a set of data sources that the agent can utilize. Datastores are either databases or documents as the knowledge base. ```json theme={null} { "datastores": [ { "id": "ds_1234567890abcdef", "name": "my-datastore"} ] } ``` A set of custom actions based on datastore (database) queries. Allows you to quickly define actions that the agent can use to query your datastores. ```json theme={null} { "queries": [ { "name": "getUserById", "description": "Fetch user details by their ID", "query": "SELECT * FROM users WHERE id = ?" }, { "name": "listActiveRecords", "description": "Get all active records from the database", "query": "SELECT * FROM records WHERE status = 'active'" } ] } ``` Whether to stream the agent messages token by token. Defaults to `false`. A set of scheduled tasks to run the agent with messages at specific times or intervals. Each schedule can be defined using: * A number (seconds from now): `10` runs in 10 seconds * A Date string: `"2025-01-01"` runs at that specific date/time * A cron expression: `"*/10 * * * *"` runs every 10 minutes ```json theme={null} { "schedules": [ { "schedule": 10, "message": "Run a task in 10 seconds" }, { "schedule": "2025-01-01", "message": "Run a task on New Year's Day" }, { "schedule": "*/10 * * * *", "message": "Run a recurring task every 10 minutes" }, { "schedule": "*/10 * * * 1", "message": "Run a task every 10 minutes on Mondays" } ] } ``` Each scheduled task will trigger the agent with the specified message at the scheduled time. Returns task IDs that can be used to cancel schedules later. Configuration for an extra final output event that processes the entire agent message thread and produces a structured output based on the provided JSON schema. ```json theme={null} { "final_output": { "name": "task_summary", "strict": true, "schema": { "type": "object", "properties": { "summary": { "type": "string" }, "outcome": { "type": "string", "enum": ["success", "partial_success", "failure"] }, "next_steps": { "type": "array", "items": { "type": "string" }, "description": "Recommended next steps or follow-up actions", "minItems": 3, "maxItems": 3 } }, "required": ["summary", "outcome", "next_steps"], "additionalProperties": false } } } ``` See [Streaming Message Types](/api/message-events) for event details. # Authentication Source: https://docs.agentbase.sh/deploy/authentication Secure your Agentbase API integration with API keys ## API Key Authentication Agentbase uses API keys to authenticate requests. All API requests must include a valid API key in the `Authorization` header. ## Getting Your API Key Create an account at [base.agentbase.sh/sign-up](https://base.agentbase.sh/sign-up) Use your work email to get free credits automatically! Log in to your dashboard at [base.agentbase.sh](https://base.agentbase.sh) Find your API key in the dashboard under **Settings** or **API Keys** ## Using Your API Key Include your API key in the `Authorization` header: ```bash theme={null} curl -X POST https://api.agentbase.sh/run-agent \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Hello, world!", "mode": "base" }' ``` Pass your API key when creating the client: ```typescript theme={null} import Agentbase from "@agentbase/sdk"; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); ``` Pass your API key when creating the client: ```python theme={null} from agentbase import Agentbase client = Agentbase( api_key=os.environ.get("AGENTBASE_API_KEY") ) ``` ## Security Best Practices **Don't do this:** ```typescript theme={null} // ❌ Bad: API key in code const agentbase = new Agentbase({ apiKey: "agb_1234567890abcdef" }); ``` **Do this instead:** ```typescript theme={null} // ✅ Good: API key in environment variable const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); ``` **Why:** Committing API keys to version control exposes them to anyone with repository access. Store API keys in environment variables: ```bash theme={null} # .env file AGENTBASE_API_KEY=agb_1234567890abcdef ``` ```typescript theme={null} // Load from .env import dotenv from 'dotenv'; dotenv.config(); const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); ``` **Note:** Add `.env` to your `.gitignore` file. Rotate your API keys periodically: Generate a new API key in the dashboard Update all applications to use the new key Verify all integrations work with the new key Once confirmed, revoke the old API key **Recommended schedule:** Every 90 days or when team members leave **Never expose API keys in client-side code:** ```javascript theme={null} // ❌ Bad: API key in browser const agentbase = new Agentbase({ apiKey: "agb_1234567890abcdef" // Visible to users! }); ``` **Instead, proxy through your backend:** ```typescript theme={null} // ✅ Good: API key on server // Frontend const response = await fetch('/api/agent', { method: 'POST', body: JSON.stringify({ message: 'Hello' }) }); // Backend app.post('/api/agent', async (req, res) => { const result = await agentbase.runAgent({ message: req.body.message, mode: "base" }); res.json(result); }); ``` Regularly review API usage in your dashboard: * Check for unexpected spikes * Monitor cost trends * Review active sessions * Identify anomalies **Set up alerts** for unusual activity: * Sudden usage increases * Cost threshold exceeded * Failed authentication attempts ## Error Handling Handle authentication errors gracefully: ```typescript theme={null} try { const result = await agentbase.runAgent({ message: "Hello", mode: "base" }); } catch (error) { if (error.status === 401) { console.error('Invalid API key'); // Notify team, check configuration } else if (error.status === 403) { console.error('API key lacks permissions'); // Check account status } } ``` ```python theme={null} try: result = client.run_agent( message="Hello", mode="base" ) except AgentbaseError as e: if e.status_code == 401: print("Invalid API key") # Notify team, check configuration elif e.status_code == 403: print("API key lacks permissions") # Check account status ``` ## Common Errors | Error Code | Meaning | Solution | | ----------------------- | -------------------------- | ---------------------------------------------------- | | `401 Unauthorized` | Invalid or missing API key | Check your API key is correct and properly formatted | | `403 Forbidden` | API key lacks permissions | Verify your account is active and has credits | | `429 Too Many Requests` | Rate limit exceeded | Implement backoff and retry logic | ## Rate Limiting Agentbase implements rate limiting to ensure fair usage: * **Rate limits** are applied per account * **Limits vary** by account tier * **Headers** include rate limit information: ``` X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1640000000 ``` **Handling rate limits:** ```typescript theme={null} async function runAgentWithRetry(message: string, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await agentbase.runAgent({ message, mode: "base" }); } catch (error) { if (error.status === 429) { const retryAfter = error.headers["retry-after"] || Math.pow(2, i); await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000)); continue; } throw error; } } throw new Error("Max retries exceeded"); } ``` # Cost Tracking Source: https://docs.agentbase.sh/deploy/cost-tracking Monitor agent usage costs in real-time > Every API response includes detailed cost information for real-time tracking. **Looking for pricing information?** See our [Pricing Overview](/deploy/pricing) for cost ranges and monthly projections. ## Cost Event Structure Every API response includes an `agent_cost` event: ```json theme={null} { "type": "agent_cost", "session": "sess_abc123", "cost": "0.0091", "balance": 49.99, "deductionSuccess": true, "lowBalance": false } ``` ## What's Next? Understand cost ranges and monthly projections Complete API documentation with cost parameters Optimize agent behavior to control costs # Overview Source: https://docs.agentbase.sh/deploy/overview Deploy AI agents to production with Agentbase ## Production-Ready Agent Deployment Agentbase makes deploying AI agents to production simple and reliable. No infrastructure to manage, no scaling concerns, and no maintenance overhead. Same API you tested locally works in production - no code changes needed Automatically scales from 1 to 1000s of concurrent agents based on demand Enterprise-grade reliability with built-in redundancy and failover Pay per action, not per token - predictable costs that scale with usage ## Deployment Options ### Direct API Integration The simplest way to deploy agents - call the API directly from any language or platform. ```bash theme={null} curl -X POST https://api.agentbase.sh/run-agent \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Analyze this data and create a report", "mode": "base" }' ``` **Best for:** * Simple integrations * Any programming language * Webhook-based workflows * Serverless functions See complete API documentation and examples ### TypeScript/JavaScript Integration Use the official TypeScript SDK for type-safe agent integration. ```typescript theme={null} import Agentbase from "@agentbase/sdk"; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); const result = await agentbase.runAgent({ message: "Analyze this data and create a report", mode: "base" }); ``` **Best for:** * Node.js applications * Next.js backends * Express/Fastify APIs * React applications See TypeScript SDK documentation ### Python Integration Use the official Python SDK for seamless integration with Python applications. ```python theme={null} from agentbase import Agentbase client = Agentbase(api_key="YOUR_API_KEY") result = client.run_agent( message="Analyze this data and create a report", mode="base" ) ``` **Best for:** * Flask/Django applications * Data science workflows * ML/AI pipelines * Automation scripts See Python SDK documentation ## Production Checklist Sign up at [base.agentbase.sh](https://base.agentbase.sh/sign-up) and get your API key from the dashboard. Use work email to get free credits automatically! Store API keys in environment variables, never in code: ```bash theme={null} # .env file AGENTBASE_API_KEY=your_api_key_here ``` ```typescript theme={null} // Use environment variables const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); ``` Handle errors gracefully in production: ```typescript theme={null} try { const result = await agentbase.runAgent({ message: userInput, mode: "base" }); } catch (error) { if (error.status === 429) { // Handle rate limiting } else if (error.status === 500) { // Handle server errors } // Log error and notify team } ``` Track costs and usage in your [dashboard](https://base.agentbase.sh): * Real-time cost tracking * Session monitoring * Performance metrics * Usage analytics Use sessions for multi-turn conversations: ```typescript theme={null} // First message creates a session const result1 = await agentbase.runAgent({ message: "Create a Python script" }); // Continue in the same session const result2 = await agentbase.runAgent({ message: "Now add error handling", session: result1.session }); ``` ## Architecture Patterns **Use case:** One-off tasks, simple queries, independent operations ```typescript theme={null} // Each request is independent app.post('/api/analyze', async (req, res) => { const result = await agentbase.runAgent({ message: `Analyze: ${req.body.data}`, mode: "base" }); res.json(result); }); ``` **Pros:** * Simple to implement * No session management * Easy to scale **Cons:** * No conversation history * Can't build on previous context **Use case:** Chat applications, multi-turn conversations, iterative tasks ```typescript theme={null} // Store session per user app.post('/api/chat', async (req, res) => { const userId = req.user.id; const session = await getUserSession(userId); const result = await agentbase.runAgent({ message: req.body.message, session: session, mode: "base" }); await saveUserSession(userId, result.session); res.json(result); }); ``` **Pros:** * Maintains conversation context * Builds on previous interactions * Natural chat experience **Cons:** * Requires session storage * More complex state management **Use case:** Long-running tasks, async workflows, scheduled jobs ```typescript theme={null} // Queue job for background processing app.post('/api/process', async (req, res) => { const jobId = generateJobId(); // Return immediately res.json({ jobId, status: 'processing' }); // Process in background processInBackground(async () => { const result = await agentbase.runAgent({ message: req.body.task, mode: "max" }); await saveResult(jobId, result); await notifyUser(jobId); }); }); ``` **Pros:** * Non-blocking operations * Handle long tasks gracefully * Better user experience **Cons:** * More complex architecture * Requires job queue **Use case:** Real-time updates, chat UIs, progress tracking ```typescript theme={null} // Stream agent responses app.get('/api/stream', async (req, res) => { res.setHeader('Content-Type', 'text/event-stream'); const stream = await agentbase.runAgent({ message: req.query.message, mode: "base", stream: true }); for await (const event of stream) { res.write(`data: ${JSON.stringify(event)}\n\n`); } res.end(); }); ``` **Pros:** * Real-time feedback * Better UX for long tasks * See agent thinking process **Cons:** * Requires SSE/WebSocket support * More complex client code ## Security Best Practices * Never commit API keys to version control * Use environment variables * Rotate keys regularly * Use separate keys for dev/staging/prod * Validate and sanitize user inputs * Set message length limits * Filter sensitive information * Implement rate limiting * Authenticate users before agent access * Implement role-based permissions * Log all agent interactions * Monitor for abuse * Don't send PII to agents unnecessarily * Implement data retention policies * Clear sensitive sessions * Comply with GDPR/CCPA ## Monitoring & Observability Track your agents in production: **Agentbase Dashboard** ([base.agentbase.sh](https://base.agentbase.sh)) * Real-time cost tracking * Session monitoring * Usage analytics * Performance metrics **Stream agent events** for real-time monitoring: ```typescript theme={null} const stream = await agentbase.runAgent({ message: "Process this data", stream: true }); for await (const event of stream) { switch (event.type) { case 'agent_tool_use': console.log('Tool:', event.content); break; case 'agent_cost': console.log('Cost:', event.cost); break; case 'agent_step': console.log('Step:', event.stepNumber); break; } } ``` **Implement comprehensive logging:** ```typescript theme={null} const logger = createLogger(); try { logger.info('Agent request started', { userId, message: truncate(message), mode }); const result = await agentbase.runAgent({ message, mode }); logger.info('Agent request completed', { userId, session: result.session, cost: result.cost }); return result; } catch (error) { logger.error('Agent request failed', { userId, error: error.message, stack: error.stack }); throw error; } ``` ## Scaling Considerations Agentbase automatically handles scaling, but consider these patterns: Reuse SDK instances across requests for better performance Cache common agent responses to reduce costs and latency Implement rate limits to prevent abuse and control costs Distribute requests across multiple API keys if needed ## Next Steps Complete API documentation and examples TypeScript SDK guide and reference Python SDK guide and reference Learn how to track and optimize costs # Pricing Source: https://docs.agentbase.sh/getting-started/pricing Simple, fixed cost-per-step pricing for agent execution **Unified pricing**, you only pay for per agent step, resources like computers, datastore, etc are free. > Pay per action, not per token. Simple pricing that scales with value delivered. ## Fixed Cost-per-Step Pricing *Currency: USD (\$)* | Mode | Cost per Step | Best For | Major Models | | :---- | :------------ | :------------------------------------- | :--------------------------- | | Flash | \$0.0075 | Simple tasks, quick responses | GPT-5-mini, Claude-4.5-Haiku | | Base | \$0.025 | Most tasks, balanced performance | Agentbase Base Model | | Max | \$0.05 | Most complex tasks, advanced reasoning | GPT-5, Claude-4.5-Sonnet | Agentbase offers three distinct agent modes that optimize performance and cost through intelligent model selection. Rather than using a single model, each mode employs a **mixture of models** including custom models specifically designed to reduce agent execution steps and overall costs. ## Example cost calculation For example, using the Base mode for a 10 step task: * 10 steps \* 0.025 = \$0.25 * Computer / Browser / Datastore usage: \$0.00 * Total cost: \$0.25 **Beta Phase**: During our beta phase, all other resources like computers, datastore, etc are free. You only pay for agent steps. ## Subscription Plans For different usage scenarios, we offer flexible options: * **Pay-as-you-go**: Perfect for getting started and small projects * **Enterprise**: Custom pricing with volume discounts and priority support. Email us at [team@agentbase.sh](mailto:team@agentbase.sh) Heavy usage users can add top-up credits for seamless scaling without service interruption. Sign up with your work email to get **free credits automatically** and explore subscription options in your dashboard. # Quickstart Source: https://docs.agentbase.sh/getting-started/quickstart Get started with Agentbase AI agents in 2 minutes Get your first AI agent running locally in 2 minutes. **Start in the app:** Visit the [overview page](https://base.agentbase.sh/overview) for a guided quickstart that walks you through: 1. **Choose your SDK** - TypeScript, Python, or cURL 2. **Get your API key** - Secure authentication setup 3. **Copy the bootstrap command** - One-click setup 4. **Select your agent mode** - Flash, Base, or Max 5. **Configure add-ons** - Optional integrations The guided setup generates a ready-to-use code snippet you can paste directly into your IDE. Agentbase overview page showing guided quickstart ## Before you begin * [Agentbase account](https://base.agentbase.sh/sign-up) with credits * Node.js 18+ installed Sign up with your work email to get free credits automatically! ## Step 1: Install and run ```bash theme={null} # Create your agent project npm create agentbase@latest # Select to create a Next.js agent chat app or a terminal chat app 📦 Select a template: 1. agent-chat-nextjs (Next.js app) 2. terminal-chat (Terminal agent chat) ✔ Choose template (1 or 2) (1): # Navigate and start cd my-agent npm run dev ``` You'll be prompted to add your API key on first use. You can get your API key from the [overview page](https://base.agentbase.sh/overview). ## Step 2: Test capabilities Try these prompts in the CLI to understand what agents can do: ``` > What can you do? > Write and run a Python function to calculate fibonacci numbers > Search for the latest AI news and summarize it > Create a React component for a user profile card ``` ## Step 3: Understand agent modes Change the mode in your `index.ts` file: ```typescript theme={null} const params = { message: message, mode: "base", // "base", "flash", or "max" }; ``` **Mode differences:** * **Flash**: Shows agent thinking process and steps * **Base**: Balanced performance (recommended) * **Max**: Advanced reasoning for complex tasks You can also test your agents in the [Agentbase playground](https://base.agentbase.sh/playground). ## Need help? * Join our [Discord](https://discord.com/invite/KFtqf7j9fs) for support * Monitor usage at [base.agentbase.sh](https://base.agentbase.sh) * Check [API examples](/api/example) for more patterns # Traces Source: https://docs.agentbase.sh/improve/traces Debug and understand agent behavior with execution traces Traces provide detailed execution logs of your agent's behavior, helping you debug issues, optimize performance, and understand how your agent processes requests. Traces Dashboard ## What are Traces? Traces are comprehensive execution logs that capture every step of your agent's workflow, including: * **Agent Initialization**: When the agent starts processing a request * **Agent Steps**: Each reasoning step the agent takes * **Tool Usage**: When and how the agent uses tools * **Tool Responses**: Results returned from tool executions * **Agent Responses**: Final responses generated by the agent Each event in the trace includes: * Timestamp of when it occurred * Duration of execution * Detailed information about inputs and outputs * Status (completed, in progress, failed) ## Accessing Traces Navigate to the **Traces** page in your Agentbase dashboard under the **Improve** section. Here you'll find: 1. **Sessions**: A list of all agent execution sessions with unique session IDs 2. **Traces**: Individual agent runs within each session 3. **Timeline**: A chronological view of all events in a trace ## Using Traces for Debugging Traces are invaluable for: * **Performance Optimization**: Identify slow steps or tool calls by examining execution durations * **Error Diagnosis**: Pinpoint where failures occur in your agent's workflow * **Behavior Analysis**: Understand the reasoning path your agent takes * **Tool Usage Monitoring**: See which tools are being called and how often * **Response Quality**: Review agent responses and the context that led to them ## Trace Events ### Agent Initialization Records when the agent begins processing a request, including the initial prompt and configuration. ### Agent Steps Each step represents a discrete reasoning action by the agent. Steps are numbered sequentially (Step 0, Step 1, etc.) and show: * The agent's thought process * Decisions about which tools to use * Planning for next actions ### Tool Events Tool usage is captured in two events: * **Tool: \[name]** - When a tool is invoked, showing the tool name and parameters * **Tool Response: \[name]** - The result returned by the tool execution ### Agent Response The final response generated by the agent after completing all necessary steps. ## Best Practices Use traces during development to validate that your agent is using tools correctly and following expected reasoning patterns. * **Regular Monitoring**: Review traces periodically to catch issues early * **Performance Tracking**: Compare execution times across different agent modes * **Error Patterns**: Look for recurring failures to identify systemic issues * **Tool Optimization**: Analyze tool usage patterns to optimize your tool implementations Traces are automatically captured for all agent runs. You can search and filter traces by session ID, time range, or status to find specific executions. # Browser Source: https://docs.agentbase.sh/primitives/environment/browser Web browser automation for scraping, testing, and web interaction > Agentbase provides agents with full Chrome browser capabilities for navigating websites, interacting with web applications, extracting data, and automating web workflows. ## Overview The Browser primitive gives agents access to a full Google Chrome browser running within their execution environment. This enables sophisticated web automation, data extraction, and testing capabilities without any additional setup: * **Web Navigation**: Visit any website and navigate through pages * **Element Interaction**: Click buttons, fill forms, submit data * **Data Extraction**: Scrape content, tables, images, and structured data * **JavaScript Execution**: Run custom JavaScript in the browser context * **Screenshots**: Capture full pages or specific elements * **Session Management**: Handle cookies, authentication, and multi-page workflows Google Chrome 140.0.7339.127 with complete rendering and JavaScript support Run browser invisibly for automation or with display for debugging Built-in support for Selenium, Playwright, and Puppeteer Full access to the web with cookies, sessions, and authentication ## How Browser Automation Works Agents use browser capabilities automatically when you request web-based tasks: ```typescript theme={null} // Agent automatically uses browser tools const result = await agentbase.runAgent({ message: "Navigate to example.com and extract the main heading" }); // Browser is launched, page is loaded, data is extracted ``` ### Browser Lifecycle 1. **Launch**: Browser starts when needed (headless by default) 2. **Navigate**: Open URLs and wait for page load 3. **Interact**: Click, type, scroll, execute JavaScript 4. **Extract**: Scrape data, take screenshots, save content 5. **Close**: Browser closes automatically after task completion ## Browser Specifications ### Software Details * **Browser**: Google Chrome 140.0.7339.127 (Official Build) (64-bit) * **ChromeDriver**: Compatible version for Selenium automation * **Rendering Engine**: Chromium Blink * **JavaScript**: V8 engine with full ES6+ support * **Modes**: Headless (default) and GUI available ### Capabilities * Load any URL * Follow links and redirects * Handle single-page applications (SPAs) * Wait for dynamic content * Navigate browser history (back/forward) ```typescript theme={null} const nav = await agentbase.runAgent({ message: "Visit github.com/trending and extract top repositories" }); ``` * Click buttons and links * Fill input fields and text areas * Select dropdown options * Check/uncheck checkboxes * Submit forms * Hover over elements ```typescript theme={null} const interact = await agentbase.runAgent({ message: "Go to the search page, enter 'AI tools', and submit the search" }); ``` * Extract text content * Parse HTML structure * Extract links and images * Scrape tables and lists * Get element attributes * Access page metadata ```typescript theme={null} const scrape = await agentbase.runAgent({ message: "Extract all product names and prices from the e-commerce page" }); ``` * Run custom JavaScript * Inject scripts into pages * Access window and document objects * Interact with page JavaScript * Return values from executed scripts ```typescript theme={null} const js = await agentbase.runAgent({ message: "Execute JavaScript to scroll to the bottom of the page" }); ``` * Capture full page screenshots * Screenshot specific elements * Save as PNG or JPEG * Different viewport sizes * Mobile and desktop views ```typescript theme={null} const screenshot = await agentbase.runAgent({ message: "Take a screenshot of the homepage and save it" }); ``` * Handle cookies * Maintain authentication * Session persistence * Local storage access * Cache management ```typescript theme={null} const session = await agentbase.runAgent({ message: "Login to the website and navigate to the dashboard" }); ``` ## Code Examples ### Basic Web Navigation ```typescript TypeScript theme={null} // Simple page visit const visit = await agentbase.runAgent({ message: "Navigate to https://example.com and show the page title" }); // Navigate and extract const extract = await agentbase.runAgent({ message: "Go to news.ycombinator.com and extract the top 5 story titles" }); // Follow links const follow = await agentbase.runAgent({ message: "Visit the homepage, click on the About link, and show the content" }); ``` ```python Python theme={null} # Simple page visit visit = agentbase.run_agent( message="Navigate to https://example.com and show the page title" ) # Navigate and extract extract = agentbase.run_agent( message="Go to news.ycombinator.com and extract the top 5 story titles" ) # Follow links follow = agentbase.run_agent( message="Visit the homepage, click on the About link, and show the content" ) ``` ### Web Scraping ```typescript TypeScript theme={null} // Scrape structured data const scrape = await agentbase.runAgent({ message: `Visit https://example-store.com/products and extract: - Product names - Prices - Availability status Save the data as products.json` }); // Multi-page scraping const multiPage = await agentbase.runAgent({ message: `Scrape the first 3 pages of search results: 1. Visit the search page 2. Extract results from page 1 3. Click next and scrape page 2 4. Click next and scrape page 3 5. Combine all results into a CSV file` }); // Table extraction const table = await agentbase.runAgent({ message: "Extract the data table from the page and convert to CSV" }); ``` ```python Python theme={null} # Scrape structured data scrape = agentbase.run_agent( message="""Visit https://example-store.com/products and extract: - Product names - Prices - Availability status Save the data as products.json""" ) # Multi-page scraping multi_page = agentbase.run_agent( message="""Scrape the first 3 pages of search results: 1. Visit the search page 2. Extract results from page 1 3. Click next and scrape page 2 4. Click next and scrape page 3 5. Combine all results into a CSV file""" ) # Table extraction table = agentbase.run_agent( message="Extract the data table from the page and convert to CSV" ) ``` ### Form Interaction ```typescript TypeScript theme={null} // Fill and submit form const form = await agentbase.runAgent({ message: `Fill out the contact form: - Name: John Doe - Email: john@example.com - Message: Hello, I have a question Then submit the form and confirm submission` }); // Login workflow const login = await agentbase.runAgent({ message: `Login to the website: 1. Navigate to /login 2. Enter username: testuser 3. Enter password: testpass 4. Click submit 5. Verify successful login` }); // Search and filter const search = await agentbase.runAgent({ message: `Use the search and filter: 1. Enter "laptops" in search box 2. Select "Price: Low to High" from dropdown 3. Check "In Stock Only" checkbox 4. Click Search 5. Extract the results` }); ``` ```python Python theme={null} # Fill and submit form form = agentbase.run_agent( message="""Fill out the contact form: - Name: John Doe - Email: john@example.com - Message: Hello, I have a question Then submit the form and confirm submission""" ) # Login workflow login = agentbase.run_agent( message="""Login to the website: 1. Navigate to /login 2. Enter username: testuser 3. Enter password: testpass 4. Click submit 5. Verify successful login""" ) # Search and filter search = agentbase.run_agent( message="""Use the search and filter: 1. Enter "laptops" in search box 2. Select "Price: Low to High" from dropdown 3. Check "In Stock Only" checkbox 4. Click Search 5. Extract the results""" ) ``` ### Screenshots and Visual Testing ```typescript TypeScript theme={null} // Full page screenshot const screenshot = await agentbase.runAgent({ message: "Navigate to homepage and take a full page screenshot" }); // Element screenshot const element = await agentbase.runAgent({ message: "Take a screenshot of just the navigation menu" }); // Multiple screenshots const comparison = await agentbase.runAgent({ message: `Take screenshots for visual testing: 1. Desktop view (1920x1080) 2. Tablet view (768x1024) 3. Mobile view (375x667) Save all three screenshots` }); // Before/after comparison const changes = await agentbase.runAgent({ message: `Compare page changes: 1. Take screenshot of current state 2. Click "Show More" button 3. Take screenshot of new state 4. Highlight differences` }); ``` ```python Python theme={null} # Full page screenshot screenshot = agentbase.run_agent( message="Navigate to homepage and take a full page screenshot" ) # Element screenshot element = agentbase.run_agent( message="Take a screenshot of just the navigation menu" ) # Multiple screenshots comparison = agentbase.run_agent( message="""Take screenshots for visual testing: 1. Desktop view (1920x1080) 2. Tablet view (768x1024) 3. Mobile view (375x667) Save all three screenshots""" ) # Before/after comparison changes = agentbase.run_agent( message="""Compare page changes: 1. Take screenshot of current state 2. Click "Show More" button 3. Take screenshot of new state 4. Highlight differences""" ) ``` ### JavaScript Execution ```typescript TypeScript theme={null} // Execute custom JavaScript const executeJS = await agentbase.runAgent({ message: "Run JavaScript to get the page's scroll height" }); // Interact with page JavaScript const interact = await agentbase.runAgent({ message: "Execute JavaScript to trigger the page's custom modal" }); // Extract dynamic data const dynamic = await agentbase.runAgent({ message: `Use JavaScript to: 1. Wait for data to load via AJAX 2. Extract the dynamically loaded content 3. Return as JSON` }); // Modify page content const modify = await agentbase.runAgent({ message: "Execute JavaScript to highlight all external links on the page" }); ``` ```python Python theme={null} # Execute custom JavaScript execute_js = agentbase.run_agent( message="Run JavaScript to get the page's scroll height" ) # Interact with page JavaScript interact = agentbase.run_agent( message="Execute JavaScript to trigger the page's custom modal" ) # Extract dynamic data dynamic = agentbase.run_agent( message="""Use JavaScript to: 1. Wait for data to load via AJAX 2. Extract the dynamically loaded content 3. Return as JSON""" ) # Modify page content modify = agentbase.run_agent( message="Execute JavaScript to highlight all external links on the page" ) ``` ## Use Cases ### 1. Competitive Intelligence Monitor competitor websites: ```typescript theme={null} const competitive = await agentbase.runAgent({ message: `Competitor analysis: 1. Visit competitor website 2. Extract current pricing for all products 3. Screenshot their homepage 4. Extract featured products 5. Save all data to competitor_data.json 6. Compare with our pricing` }); ``` ### 2. Web Testing Automated UI and functionality testing: ```typescript theme={null} const testing = await agentbase.runAgent({ message: `Test user registration flow: 1. Navigate to /signup 2. Fill registration form with test data 3. Submit form 4. Verify email confirmation page 5. Take screenshot of confirmation 6. Check for any errors or issues 7. Generate test report` }); ``` ### 3. Data Collection Gather data from multiple sources: ```typescript theme={null} const collection = await agentbase.runAgent({ message: `Collect real estate listings: 1. Visit property listing site 2. Search for "apartments in San Francisco" 3. Extract all listings (address, price, bedrooms, etc.) 4. Visit each listing for detailed info 5. Save all data to properties.csv 6. Create summary statistics` }); ``` ### 4. Research and Monitoring Track information over time: ```typescript theme={null} const research = await agentbase.runAgent({ message: `Research trending topics: 1. Visit top tech news sites 2. Extract today's headlines 3. Identify trending topics 4. Visit each article and extract summary 5. Create a consolidated report 6. Save as research_report.md` }); ``` ### 5. Form Automation Automate repetitive form submissions: ```typescript theme={null} const automation = await agentbase.runAgent({ message: `Submit bulk job applications: 1. Read applicant_data.csv 2. For each application: - Navigate to application form - Fill in all fields from CSV - Upload resume.pdf - Submit form - Save confirmation number 3. Generate submission report` }); ``` ### 6. Content Verification Verify website content and links: ```typescript theme={null} const verification = await agentbase.runAgent({ message: `Website health check: 1. Visit all pages listed in sitemap.xml 2. Check for broken links 3. Verify images load correctly 4. Check page load times 5. Screenshot any error pages 6. Generate health report` }); ``` ## Best Practices ### Reliable Web Scraping ```typescript theme={null} // Good: Wait for dynamic content const good = await agentbase.runAgent({ message: `Visit the page and wait for the products to load before extracting data` }); // Avoid: Extracting before content loads const bad = await agentbase.runAgent({ message: "Quickly visit page and extract data" }); ``` ```typescript theme={null} // Good: Navigate through all pages const good = await agentbase.runAgent({ message: `Scrape all pages: - Extract data from current page - Click next button - Repeat until no more pages - Combine all results` }); ``` ```typescript theme={null} // Good: Specific instructions const good = await agentbase.runAgent({ message: "Extract prices from elements with class 'product-price'" }); // Avoid: Vague instructions const bad = await agentbase.runAgent({ message: "Get all the prices" }); ``` ### Error Handling **Graceful Failures**: Instruct agents to handle common web issues like timeouts, missing elements, and navigation errors. ```typescript theme={null} // Robust error handling const robust = await agentbase.runAgent({ message: `Scrape data with error handling: - If page doesn't load, retry up to 3 times - If element not found, log and continue - If data format unexpected, note in output - Generate report of successful and failed extractions` }); ``` ### Performance Optimization Extract all needed data in one visit when possible Headless is faster - use GUI only for debugging Scrape multiple pages concurrently when appropriate Save scraped data to avoid re-scraping ```typescript theme={null} // Efficient: Extract all data at once const efficient = await agentbase.runAgent({ message: `Visit the page and extract: - All product names - All prices - All descriptions - All images In a single visit` }); // Inefficient: Multiple visits const inefficient = await agentbase.runAgent({ message: "Visit page, get names, then visit again for prices..." }); ``` ### Ethical Considerations **Respect Robots.txt**: Always respect website terms of service and robots.txt. Be mindful of scraping frequency and server load. ```typescript theme={null} // Responsible scraping const responsible = await agentbase.runAgent({ message: `Scrape responsibly: - Check robots.txt first - Add delays between requests - Respect rate limits - Don't overload the server` }); ``` ## Integration with Other Primitives ### With File System Save scraped data to files: ```typescript theme={null} const combined = await agentbase.runAgent({ message: `Scrape product data and save: 1. Extract data from website 2. Save as products.json 3. Also create products.csv 4. Generate summary report as report.md` }); ``` Learn more: [File System Primitive](/primitives/environment/file-system) ### With Computer Use programming tools with browser automation: ```typescript theme={null} const automation = await agentbase.runAgent({ message: `Create web scraping script: 1. Install selenium and beautifulsoup4 2. Write Python script for scraping 3. Run the script 4. Save results to database` }); ``` Learn more: [Computer Primitive](/primitives/environment/computer) ### With Web Search Combine search with browsing: ```typescript theme={null} const research = await agentbase.runAgent({ message: `Research topic: 1. Search web for "topic" 2. Visit top 5 results 3. Extract key information from each 4. Create comprehensive summary` }); ``` Learn more: [Web Search Extension](/primitives/extensions/web-search) ### With Sessions Maintain browser state across requests: ```typescript theme={null} // Login persists across requests const login = await agentbase.runAgent({ message: "Login to the website" }); const authenticated = await agentbase.runAgent({ message: "Navigate to account dashboard and extract data", session: login.session // Maintains login state }); ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ## Performance Considerations ### Browser Startup * **Cold Start**: First browser launch \~2-3 seconds * **Warm Start**: Subsequent pages in same session are faster * **Headless Mode**: 20-30% faster than GUI mode ### Page Load Times * **Simple Pages**: 1-3 seconds * **Complex SPAs**: 3-10 seconds * **Heavy Content**: 10+ seconds ### Optimization Tips ```typescript theme={null} // Fast: Headless mode (default) const base = await agentbase.runAgent({ message: "Scrape data quickly in headless mode" }); // Slow: GUI mode (only when needed) const slow = await agentbase.runAgent({ message: "Open browser with display for debugging" }); ``` ### Resource Usage * **Memory**: 200-500MB per browser instance * **CPU**: Varies with page complexity * **Network**: Depends on page size and requests ## Advanced Techniques ### Handling Dynamic Content ```typescript theme={null} const dynamic = await agentbase.runAgent({ message: `Handle dynamic content: 1. Wait for AJAX calls to complete 2. Scroll to trigger lazy loading 3. Wait for animations to finish 4. Extract the fully loaded content` }); ``` ### Cookie and Session Management ```typescript theme={null} const session = await agentbase.runAgent({ message: `Manage sessions: 1. Login and save cookies 2. Navigate to protected pages using saved session 3. Extract user-specific data 4. Logout when done` }); ``` ### Handling Popups and Alerts ```typescript theme={null} const popups = await agentbase.runAgent({ message: `Handle popups: 1. Navigate to page 2. If popup appears, close it 3. If alert shows, accept it 4. Continue with main task` }); ``` ### Mobile Emulation ```typescript theme={null} const mobile = await agentbase.runAgent({ message: `Test mobile view: 1. Set viewport to mobile size (375x667) 2. Set mobile user agent 3. Navigate to website 4. Take screenshots 5. Extract mobile-specific content` }); ``` ### Proxy and Network Control ```typescript theme={null} const network = await agentbase.runAgent({ message: `Monitor network: 1. Start network monitoring 2. Navigate to page 3. Capture all API requests 4. Extract request/response data 5. Save network log` }); ``` ## Troubleshooting **Problem**: Browser cannot load the page **Solutions**: * Check URL is correct and accessible * Wait longer for page load * Check for JavaScript errors * Try different user agent ```typescript theme={null} const fix = await agentbase.runAgent({ message: `If page doesn't load: - Wait up to 30 seconds - Check for error messages - Try loading a different page to test connection` }); ``` **Problem**: Cannot find element to interact with **Solutions**: * Wait for element to appear * Check selector is correct * Verify element is visible * Check if it's in an iframe ```typescript theme={null} const fix = await agentbase.runAgent({ message: `Find element with retry: - Wait for element to appear (up to 10s) - If not found, check page source - List available elements for debugging` }); ``` **Problem**: Page JavaScript errors affect functionality **Solutions**: * Check browser console for errors * Try different approach * Use direct JavaScript execution ```typescript theme={null} const fix = await agentbase.runAgent({ message: "Check console for JavaScript errors and try alternative approach" }); ``` **Problem**: Operations timing out **Solutions**: * Increase wait time * Check network connection * Simplify task ```typescript theme={null} const fix = await agentbase.runAgent({ message: "If timeout occurs, wait longer and retry with simpler approach" }); ``` **Problem**: Website blocking automation **Solutions**: * Add delays between requests * Use realistic user agent * Respect rate limits * Consider alternative data sources ```typescript theme={null} const respectful = await agentbase.runAgent({ message: `Scrape respectfully: - Add 2-3 second delays between requests - Use standard browser user agent - Limit to reasonable number of pages` }); ``` ## Browser vs Web Search When to use Browser vs Web Search extension: * Need to interact with page elements * Extracting structured data from specific sites * Filling forms or logging in * Taking screenshots * Testing web applications * Navigating multi-step workflows * Finding information across the web * Need current events or recent data * Quick fact-checking * Discovering relevant URLs * Broad research topics * Multiple source aggregation ## Related Primitives Isolated environment hosting the browser Install browser automation tools Save scraped data and screenshots Search web for information ## Additional Resources Browser tools documentation Complete API documentation **Remember**: Browser capabilities are available automatically when you describe web-based tasks. Agents handle browser management, navigation, and data extraction for you. # Computer Source: https://docs.agentbase.sh/primitives/environment/computer Full Linux environment with shell access, development tools, and runtime environments > Agentbase provides agents with complete Linux computer environments featuring shell access, multiple programming runtimes, package managers, and development tools for complex workflows. ## Overview The Computer primitive represents the full Linux operating system environment that agents can access for executing code, running commands, installing packages, and performing system-level operations. Unlike simple code execution, the computer environment provides: * **Shell Access**: Full bash shell for running any command * **Multiple Runtimes**: Python, Node.js, and more pre-installed * **Package Management**: apt, pip, npm for installing dependencies * **Development Tools**: git, curl, wget, vim, and standard Unix utilities * **Internet Access**: Download packages, make API calls, clone repositories * **Persistent State**: Installed packages and files persist across requests Debian GNU/Linux 12 (bookworm) with kernel 6.1.134 x86\_64 Python 3.11.2, Node.js 18.20.4, and essential development tools apt for system packages, pip for Python, npm for Node.js Full outbound internet access for downloads and API calls ## When Computer Environments Are Created Computer environments are created automatically when agents need to perform tasks that require: Python, Node.js, or other language execution, package installation, testing, and debugging Creating, reading, writing, or processing files, data transformation, and file system management Web scraping, browser automation, form submission, and website testing Shell commands, system configuration, process management, and tool installation **Automatic Creation**: You don't need to explicitly request a computer - agents create them automatically when tasks require persistent state or system access. ## System Specifications ### Operating System ```bash theme={null} # System details OS: Debian GNU/Linux 12 (bookworm) Kernel: 6.1.134 x86_64 Architecture: x86_64 Working Directory: /home/pointer ``` ### Pre-installed Software * **Python 3.11.2**: Full Python runtime with pip package manager * **Node.js 18.20.4**: JavaScript runtime with npm * **Bash 5.2.15**: Shell scripting and command execution ```bash theme={null} python --version # Python 3.11.2 node --version # v18.20.4 npm --version # 9.5.0 ``` * **git**: Version control system * **curl/wget**: HTTP clients for downloading files * **vim/nano**: Text editors * **grep/sed/awk**: Text processing utilities * **tar/gzip**: Archive and compression tools * **gcc/make**: Compilation tools (available via apt) ```bash theme={null} git --version # git version 2.39.2 curl --version # curl 7.88.1 ``` * **apt**: Debian package manager for system packages * **pip**: Python package installer * **npm**: Node.js package manager ```bash theme={null} apt --version # apt 2.6.1 pip --version # pip 23.0.1 npm --version # 9.5.0 ``` * **Google Chrome 140.0.7339.127**: Full browser for web automation * Headless and GUI modes supported * ChromeDriver included for Selenium automation ```bash theme={null} google-chrome --version # 140.0.7339.127 ``` * **ps/top**: Process monitoring * **df/du**: Disk usage * **netstat/ss**: Network statistics * **chmod/chown**: File permissions * **find/locate**: File search * **cat/less/more**: File viewing ### Resource Allocation * **CPU**: Shared allocation based on agent mode * **Memory**: 2GB for flash/base modes, 4GB for max mode * **Disk**: 10GB persistent storage per session * **Network**: Unlimited bandwidth with rate limiting * **File Descriptors**: Standard Linux limits ## Code Examples ### Running Shell Commands ```typescript TypeScript theme={null} // Simple command execution const result = await agentbase.runAgent({ message: "Run 'ls -la' to list all files" }); // Command with pipes const pipeline = await agentbase.runAgent({ message: "List all Python files and count them" }); // Multiple commands const multi = await agentbase.runAgent({ message: "Create a directory, navigate to it, and create a file" }); ``` ```python Python theme={null} # Simple command execution result = agentbase.run_agent( message="Run 'ls -la' to list all files" ) # Command with pipes pipeline = agentbase.run_agent( message="List all Python files and count them" ) # Multiple commands multi = agentbase.run_agent( message="Create a directory, navigate to it, and create a file" ) ``` ```bash cURL theme={null} # Shell commands via API curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Check disk usage with df -h" }' ``` ### Installing and Using Packages ```typescript TypeScript theme={null} // Install Python packages const installPython = await agentbase.runAgent({ message: "Install pandas, numpy, and matplotlib using pip" }); // Install Node.js packages const installNode = await agentbase.runAgent({ message: "Install express and axios using npm" }); // Install system packages const installSystem = await agentbase.runAgent({ message: "Install imagemagick using apt" }); // Use installed packages (same session) const usePackage = await agentbase.runAgent({ message: "Use pandas to read a CSV file and create a summary", session: installPython.session }); ``` ```python Python theme={null} # Install Python packages install_python = agentbase.run_agent( message="Install pandas, numpy, and matplotlib using pip" ) # Install Node.js packages install_node = agentbase.run_agent( message="Install express and axios using npm" ) # Install system packages install_system = agentbase.run_agent( message="Install imagemagick using apt" ) # Use installed packages (same session) use_package = agentbase.run_agent( message="Use pandas to read a CSV file and create a summary", session=install_python.session ) ``` ### Running Scripts ```typescript TypeScript theme={null} // Run Python script const python = await agentbase.runAgent({ message: "Create and run a Python script that analyzes data.csv" }); // Run Node.js script const node = await agentbase.runAgent({ message: "Create a Node.js script to fetch data from an API and save it" }); // Run bash script const bash = await agentbase.runAgent({ message: "Create a bash script to backup all .txt files" }); ``` ```python Python theme={null} # Run Python script python = agentbase.run_agent( message="Create and run a Python script that analyzes data.csv" ) # Run Node.js script node = agentbase.run_agent( message="Create a Node.js script to fetch data from an API and save it" ) # Run bash script bash = agentbase.run_agent( message="Create a bash script to backup all .txt files" ) ``` ### Git Operations ```typescript TypeScript theme={null} // Clone repository const clone = await agentbase.runAgent({ message: "Clone the repository from https://github.com/user/repo.git" }); // Work with git (same session) const gitOps = await agentbase.runAgent({ message: "Navigate to the cloned repo, check the branches, and list recent commits", session: clone.session }); // Make changes const changes = await agentbase.runAgent({ message: "Create a new file in the repo and show git status", session: clone.session }); ``` ```python Python theme={null} # Clone repository clone = agentbase.run_agent( message="Clone the repository from https://github.com/user/repo.git" ) # Work with git (same session) git_ops = agentbase.run_agent( message="Navigate to the cloned repo, check the branches, and list recent commits", session=clone.session ) # Make changes changes = agentbase.run_agent( message="Create a new file in the repo and show git status", session=clone.session ) ``` ### System Monitoring ```typescript TypeScript theme={null} // Check disk usage const disk = await agentbase.runAgent({ message: "Show disk usage with df -h" }); // Monitor processes const processes = await agentbase.runAgent({ message: "Show running Python processes" }); // Check memory const memory = await agentbase.runAgent({ message: "Display memory usage with free -h" }); // Network information const network = await agentbase.runAgent({ message: "Show network connections and listening ports" }); ``` ```python Python theme={null} # Check disk usage disk = agentbase.run_agent( message="Show disk usage with df -h" ) # Monitor processes processes = agentbase.run_agent( message="Show running Python processes" ) # Check memory memory = agentbase.run_agent( message="Display memory usage with free -h" ) # Network information network = agentbase.run_agent( message="Show network connections and listening ports" ) ``` ## Use Cases ### 1. Software Development Complete development workflows: ```typescript theme={null} const development = await agentbase.runAgent({ message: `Create a Python web scraper project: 1. Create project structure (src/, tests/, requirements.txt) 2. Install beautifulsoup4 and requests 3. Create scraper.py with basic scraping logic 4. Create tests for the scraper 5. Run the tests to verify everything works` }); ``` ### 2. Data Analysis Process and analyze data files: ```typescript theme={null} const analysis = await agentbase.runAgent({ message: `Analyze sales data: 1. Install pandas and matplotlib 2. Read sales.csv 3. Calculate monthly totals and trends 4. Create visualization charts 5. Generate a summary report as PDF` }); ``` ### 3. System Administration Automate system tasks: ```typescript theme={null} const sysadmin = await agentbase.runAgent({ message: `System maintenance tasks: 1. Check disk usage and identify large files 2. Clean up temporary files older than 7 days 3. Check for available system updates 4. Generate a system health report` }); ``` ### 4. CI/CD Workflows Build and test pipelines: ```typescript theme={null} const cicd = await agentbase.runAgent({ message: `Run CI/CD pipeline: 1. Clone the repository 2. Install dependencies 3. Run linting and code quality checks 4. Execute test suite 5. Build the application 6. Generate coverage report` }); ``` ### 5. Web Scraping and Automation Extract data from websites: ```typescript theme={null} const scraping = await agentbase.runAgent({ message: `Scrape product data: 1. Install selenium and beautifulsoup4 2. Navigate to product listing pages 3. Extract product names, prices, and reviews 4. Save data to products.json 5. Create a CSV summary` }); ``` ### 6. Machine Learning Train and evaluate models: ```typescript theme={null} const ml = await agentbase.runAgent({ message: `Build ML model: 1. Install scikit-learn and tensorflow 2. Load and preprocess training data 3. Train a classification model 4. Evaluate model performance 5. Save the trained model 6. Create prediction script` }); ``` ## Core Capabilities & Tools The computer environment provides comprehensive built-in capabilities: **Bash access**: Full shell command execution for system operations, package installation, and process management. **Use cases**: Installing dependencies, running scripts, system configuration, file operations ```typescript theme={null} const shell = await agentbase.runAgent({ message: "Use bash to find all log files and compress them" }); ``` **Complete file access**: Read, write, create, and manage files across the entire Linux filesystem. **Use cases**: Code development, data processing, configuration management, artifact storage ```typescript theme={null} const files = await agentbase.runAgent({ message: "Create a project with multiple files and organize them" }); ``` **Full browser capabilities**: Navigate websites, interact with web applications, and extract data from web pages. **Use cases**: Web scraping, testing web applications, research, form automation ```typescript theme={null} const browser = await agentbase.runAgent({ message: "Open Chrome, navigate to a website, and extract data" }); ``` **Screen capture**: Take screenshots of the desktop, applications, or specific regions for visual debugging. **Use cases**: UI testing, visual verification, debugging graphical applications ```typescript theme={null} const screenshot = await agentbase.runAgent({ message: "Take a screenshot of the website homepage" }); ``` **Internet access**: Make HTTP requests, download files, clone repositories, access APIs. **Use cases**: API integration, data fetching, package downloads, repository cloning ```typescript theme={null} const network = await agentbase.runAgent({ message: "Download data from API and save to file" }); ``` **Process control**: Start, stop, monitor processes and background jobs. **Use cases**: Running servers, background tasks, monitoring applications ```typescript theme={null} const process = await agentbase.runAgent({ message: "Start a development server in the background" }); ``` ## Best Practices ### Package Management ```typescript theme={null} // Good: Install once, use across multiple requests const setup = await agentbase.runAgent({ message: "Install pandas, numpy, scikit-learn" }); // Reuse session for subsequent operations const analyze = await agentbase.runAgent({ message: "Use pandas to analyze data.csv", session: setup.session }); // Packages still installed const visualize = await agentbase.runAgent({ message: "Use matplotlib to create charts", session: setup.session }); ``` ```typescript theme={null} // Good: Use requirements.txt for Python dependencies const setup = await agentbase.runAgent({ message: `Create requirements.txt with: pandas==2.0.0 numpy==1.24.0 Then install with pip install -r requirements.txt` }); ``` ```typescript theme={null} // Good: Pin versions for reproducibility const install = await agentbase.runAgent({ message: "Install tensorflow==2.13.0 numpy==1.24.0" }); // Avoid: Unpinned versions may cause issues const install = await agentbase.runAgent({ message: "Install tensorflow numpy" }); ``` ### Command Execution **Error Handling**: Always check command exit codes and handle errors appropriately. Agents do this automatically but you can be explicit in your instructions. ```typescript theme={null} // Explicit error handling in instructions const result = await agentbase.runAgent({ message: `Run the test suite. If tests fail, show the error details and suggest fixes. If they pass, show the coverage report.` }); ``` ### Resource Management Monitor resource usage to avoid limits: ```typescript theme={null} // Check resources before heavy operations const check = await agentbase.runAgent({ message: "Check available disk space and memory before processing large files" }); // Clean up after operations const cleanup = await agentbase.runAgent({ message: "Remove temporary files and cached data after processing", session: check.session }); ``` ### Security Considerations **Sensitive Data**: Be cautious with secrets and credentials. While the environment is isolated, avoid hardcoding sensitive information in files. ```typescript theme={null} // Good: Use environment variables or secure parameters const secure = await agentbase.runAgent({ message: "Connect to database using environment variable DATABASE_URL", system: `Environment: DATABASE_URL=${process.env.DATABASE_URL}` }); // Avoid: Hardcoding secrets const insecure = await agentbase.runAgent({ message: "Create config.json with password: secret123" }); ``` ## Integration with Other Primitives ### With Sandbox The computer environment runs within a sandbox: ```typescript theme={null} // Each session has its own computer environment const session1 = await agentbase.runAgent({ message: "Install package and run script" }); const session2 = await agentbase.runAgent({ message: "Install different package and run different script" }); // Completely isolated computer environments ``` Learn more: [Sandbox Primitive](/primitives/environment/sandbox) ### With File System Shell commands interact with the file system: ```typescript theme={null} const combined = await agentbase.runAgent({ message: "Create files, organize them into directories, and run a script on them" }); ``` Learn more: [File System Primitive](/primitives/environment/file-system) ### With Browser Use shell to control browser automation: ```typescript theme={null} const webAutomation = await agentbase.runAgent({ message: "Install selenium, write a script to scrape data, and run it" }); ``` Learn more: [Browser Primitive](/primitives/environment/browser) ### With Custom Tools Combine system commands with custom tools: ```typescript theme={null} const integration = await agentbase.runAgent({ message: "Use bash to download data, then use custom tool to process it" }); ``` Learn more: [Custom Tools](/primitives/essentials/custom-tools) ## Performance Considerations ### Execution Speed * **Command execution**: Milliseconds for simple commands * **Package installation**: Varies (30s - 5min depending on package) * **Script execution**: Depends on script complexity * **File operations**: Near-instant for files under 10MB ### Optimization Strategies Install packages once per session and reuse Use background processes for concurrent tasks Optimize scripts for speed and resource usage Only install required packages, not full suites ### Performance Example ```typescript theme={null} // Efficient: Parallel installation const efficient = await agentbase.runAgent({ message: "Install multiple packages in parallel using & and wait" }); // Efficient: Reuse session const step1 = await agentbase.runAgent({ message: "Install dependencies" }); const step2 = await agentbase.runAgent({ message: "Run analysis", session: step1.session // Dependencies already installed }); ``` ## Advanced Usage ### Working Directory Default working directory is `/home/pointer`: ```typescript theme={null} // Check current directory const pwd = await agentbase.runAgent({ message: "Show current working directory with pwd" }); // Navigate directories const navigate = await agentbase.runAgent({ message: "Create projects folder, navigate to it, and create files there" }); ``` ### Environment Variables Set and use environment variables: ```typescript theme={null} const env = await agentbase.runAgent({ message: "Set environment variable API_KEY=xyz and use it in a script" }); ``` ### Background Processes Run processes in the background: ```typescript theme={null} const background = await agentbase.runAgent({ message: "Start a development server in the background and show logs" }); ``` ### Cron Jobs and Scheduling While cron isn't directly supported, use sessions for scheduled tasks: ```typescript theme={null} // Not recommended (cron not persistent) // Instead, use Agentbase scheduling: const scheduled = await agentbase.runAgent({ message: "Run this analysis task", schedules: [{ schedule: "0 0 * * *", // Daily at midnight message: "Run daily analysis" }] }); ``` ## Troubleshooting **Problem**: Command or package not available **Solution**: Install the package first ```typescript theme={null} const fix = await agentbase.runAgent({ message: "Install the missing package using apt, pip, or npm" }); ``` **Problem**: Insufficient permissions for operation **Solution**: Use sudo or adjust file permissions ```typescript theme={null} const fix = await agentbase.runAgent({ message: "Use sudo for system-level operations or chmod for file permissions" }); ``` **Problem**: Process exceeds memory limits **Solution**: Optimize script or use max mode ```typescript theme={null} const optimized = await agentbase.runAgent({ message: "Process data in chunks to reduce memory usage", mode: "max" // More memory available }); ``` **Problem**: pip or npm installation errors **Solution**: Check error messages and dependencies ```typescript theme={null} const debug = await agentbase.runAgent({ message: "Show detailed error from package installation and suggest fixes" }); ``` **Problem**: Running out of storage **Solution**: Clean up unnecessary files ```typescript theme={null} const cleanup = await agentbase.runAgent({ message: "Find and remove large temporary files and caches" }); ``` ## Related Primitives Isolated execution environment hosting the computer Persistent file storage and operations Web automation and interaction Maintain computer state across requests ## Additional Resources All available tools and commands How computer state persists Complete API documentation **Remember**: Computer environments are created automatically when tasks require them. Simply describe your goal - agents will handle provisioning, tool selection, and environment management. # File System Source: https://docs.agentbase.sh/primitives/environment/file-system Persistent file storage and management for agent workflows > Agent file systems provide persistent, isolated storage that survives across sessions, enabling complex workflows with data persistence and file management. ## Overview The File System primitive gives agents the ability to create, read, write, and manage files within their execution environment. Each agent session has access to a complete Linux file system with persistent storage, allowing agents to: * **Store Data**: Save files, datasets, configurations, and artifacts * **Process Files**: Read, modify, and transform file contents * **Organize Content**: Create directory structures and manage file hierarchies * **Persist State**: Maintain files across multiple requests in the same session * **Generate Outputs**: Create reports, code files, images, and other deliverables Complete file system operations - create, read, update, delete files and directories Each session gets 10GB of persistent disk space Files remain available across all requests in the same session Agents handle file operations automatically based on your instructions ## How File Systems Work Agents use specialized tools to interact with the file system: ### Core File Tools The primary tool for file operations. Provides: * **Create**: Create new files with content * **View**: Read file contents * **Edit**: Modify files using find-and-replace * **Insert**: Add content at specific locations * **Undo**: Revert recent changes ```typescript theme={null} // Agent automatically uses str_replace_editor const result = await agentbase.runAgent({ message: "Create a file called config.json with database settings" }); ``` Shell commands for file manipulation: * **Copy**: `cp source dest` * **Move**: `mv source dest` * **Delete**: `rm file` * **List**: `ls -la` * **Permissions**: `chmod`, `chown` ```typescript theme={null} const result = await agentbase.runAgent({ message: "Copy all .txt files to the backup folder" }); ``` Find files matching patterns: * Pattern matching: `*.js`, `**/*.ts` * Recursive search: `**/test/*.py` * Multiple patterns: `{*.json,*.yaml}` ```typescript theme={null} const result = await agentbase.runAgent({ message: "Find all Python files in the project" }); ``` Search for text within files: * Regex patterns: `grep "pattern" file` * Recursive search: `grep -r "pattern" .` * Case-insensitive: `grep -i "pattern"` ```typescript theme={null} const result = await agentbase.runAgent({ message: "Find all TODO comments in the codebase" }); ``` ## File System Architecture ### Directory Structure The default working directory is `/home/pointer`: ``` /home/pointer/ # Default working directory ├── .cache/ # Cache directory ├── .config/ # Configuration files ├── .local/ # User-local data └── [your files] # Created by agent ``` ### Storage Hierarchy ```mermaid theme={null} graph TB A[Session] --> B["File System"] B --> C["/home/pointer"] C --> D["User Files"] C --> E["Installed Packages"] C --> F["Generated Outputs"] D --> G["Persistent Storage"] E --> G F --> G G --> H["10GB Limit"] ``` ## Code Examples ### Creating Files ```typescript TypeScript theme={null} // Create a single file const result = await agentbase.runAgent({ message: "Create a file called hello.py with a simple hello world program" }); // Create multiple files const multi = await agentbase.runAgent({ message: "Create a React project structure with App.js, index.js, and package.json" }); // Create file with specific content const config = await agentbase.runAgent({ message: `Create config.json with this content: { "apiKey": "xxx", "endpoint": "https://api.example.com" }` }); ``` ```python Python theme={null} # Create a single file result = agentbase.run_agent( message="Create a file called hello.py with a simple hello world program" ) # Create multiple files multi = agentbase.run_agent( message="Create a React project structure with App.js, index.js, and package.json" ) # Create file with specific content config = agentbase.run_agent( message="""Create config.json with this content: { "apiKey": "xxx", "endpoint": "https://api.example.com" }""" ) ``` ### Reading Files ```typescript TypeScript theme={null} // Read file contents const read = await agentbase.runAgent({ message: "Read the contents of data.csv and summarize it" }); // Read multiple files const readMulti = await agentbase.runAgent({ message: "Read all .md files in the docs folder and create a table of contents" }); // Read and process const process = await agentbase.runAgent({ message: "Read config.json and validate all required fields are present" }); ``` ```python Python theme={null} # Read file contents read = agentbase.run_agent( message="Read the contents of data.csv and summarize it" ) # Read multiple files read_multi = agentbase.run_agent( message="Read all .md files in the docs folder and create a table of contents" ) # Read and process process = agentbase.run_agent( message="Read config.json and validate all required fields are present" ) ``` ### Modifying Files ```typescript TypeScript theme={null} // Edit existing file const edit = await agentbase.runAgent({ message: "Update the version number in package.json to 2.0.0", session: existingSession }); // Find and replace const replace = await agentbase.runAgent({ message: "Replace all instances of 'oldFunction' with 'newFunction' in src/utils.js", session: existingSession }); // Append to file const append = await agentbase.runAgent({ message: "Add a new route to routes.js for the profile page", session: existingSession }); ``` ```python Python theme={null} # Edit existing file edit = agentbase.run_agent( message="Update the version number in package.json to 2.0.0", session=existing_session ) # Find and replace replace = agentbase.run_agent( message="Replace all instances of 'oldFunction' with 'newFunction' in src/utils.js", session=existing_session ) # Append to file append = agentbase.run_agent( message="Add a new route to routes.js for the profile page", session=existing_session ) ``` ### File Organization ```typescript TypeScript theme={null} // Create directory structure const structure = await agentbase.runAgent({ message: "Create folders for src, tests, and docs" }); // Move files const organize = await agentbase.runAgent({ message: "Move all .js files to the src folder", session: structure.session }); // Copy with organization const backup = await agentbase.runAgent({ message: "Create a backup folder and copy all important files there", session: structure.session }); ``` ```python Python theme={null} # Create directory structure structure = agentbase.run_agent( message="Create folders for src, tests, and docs" ) # Move files organize = agentbase.run_agent( message="Move all .js files to the src folder", session=structure.session ) # Copy with organization backup = agentbase.run_agent( message="Create a backup folder and copy all important files there", session=structure.session ) ``` ### Searching Files ```typescript TypeScript theme={null} // Find files by pattern const find = await agentbase.runAgent({ message: "Find all TypeScript files in the project" }); // Search content const search = await agentbase.runAgent({ message: "Search for all files containing 'API_KEY'" }); // Complex search const complexSearch = await agentbase.runAgent({ message: "Find all Python test files that import the requests library" }); ``` ```python Python theme={null} # Find files by pattern find = agentbase.run_agent( message="Find all TypeScript files in the project" ) # Search content search = agentbase.run_agent( message="Search for all files containing 'API_KEY'" ) # Complex search complex_search = agentbase.run_agent( message="Find all Python test files that import the requests library" ) ``` ## Use Cases ### 1. Code Generation and Management Generate complete projects with proper file organization: ```typescript theme={null} const project = await agentbase.runAgent({ message: `Create a FastAPI project with: - main.py with basic setup - requirements.txt with dependencies - .env.example for configuration - README.md with setup instructions - tests/test_main.py with sample tests` }); // All files persist in the session ``` ### 2. Data Processing Workflows Process data files and generate reports: ```typescript theme={null} // Step 1: Upload data (in practice, you'd create the file) const upload = await agentbase.runAgent({ message: "Create a sample sales_data.csv with 100 rows of sales data" }); // Step 2: Process const process = await agentbase.runAgent({ message: "Analyze sales_data.csv and create a summary report as report.md", session: upload.session }); // Step 3: Visualize const viz = await agentbase.runAgent({ message: "Create a Python script to visualize the data and save charts as images", session: upload.session }); // All files (CSV, report, scripts, charts) persist ``` ### 3. Configuration Management Manage configuration files across environments: ```typescript theme={null} const config = await agentbase.runAgent({ message: `Create configuration files for dev, staging, and prod environments: - config/dev.json - config/staging.json - config/prod.json Each should have appropriate API endpoints and settings` }); // Later, update configs const update = await agentbase.runAgent({ message: "Update the prod config to use the new API endpoint", session: config.session }); ``` ### 4. Documentation Generation Generate and maintain documentation: ```typescript theme={null} const docs = await agentbase.runAgent({ message: `Read all Python files in src/ and generate API documentation: - docs/api.md with function signatures - docs/examples.md with usage examples - docs/index.md as main entry point` }); ``` ### 5. File Transformations Convert between file formats: ```typescript theme={null} const transform = await agentbase.runAgent({ message: "Convert data.json to CSV format and save as data.csv" }); const convert = await agentbase.runAgent({ message: "Read all markdown files and convert them to HTML", session: transform.session }); ``` ## Best Practices ### File Naming and Organization ```typescript theme={null} // Good: Clear, descriptive names const result = await agentbase.runAgent({ message: "Create customer_analysis_report.md" }); // Avoid: Generic or unclear names const result = await agentbase.runAgent({ message: "Create file1.txt" }); ``` ```typescript theme={null} // Good: Organized structure const result = await agentbase.runAgent({ message: `Create organized structure: - src/ for source code - tests/ for test files - docs/ for documentation - data/ for data files` }); // Avoid: Everything in root const result = await agentbase.runAgent({ message: "Create 20 files in the main folder" }); ``` ```typescript theme={null} // Good: Follow standard conventions const result = await agentbase.runAgent({ message: `Create Python project: - __init__.py - setup.py - requirements.txt - README.md` }); ``` ### Session Management **Persist Files Across Requests**: Always use the same session ID when working with files that need to persist across multiple agent requests. ```typescript theme={null} // Create files in first request const create = await agentbase.runAgent({ message: "Create data.json and processor.py" }); // Access files in subsequent requests const process = await agentbase.runAgent({ message: "Run processor.py on data.json", session: create.session // Critical! }); ``` ### Storage Management Monitor and manage your 10GB storage limit: ```typescript theme={null} // Check disk usage const check = await agentbase.runAgent({ message: "Check disk usage and list the largest files" }); // Clean up when needed const cleanup = await agentbase.runAgent({ message: "Delete temporary files and cache folders", session: check.session }); ``` ### Error Handling Handle file-related errors gracefully: ```typescript theme={null} const result = await agentbase.runAgent({ message: `Read config.json. If it doesn't exist, create a default one with: { "apiKey": "", "endpoint": "https://api.example.com" }` }); ``` ## Integration with Other Primitives ### With Sandbox Files exist within the sandbox environment: ```typescript theme={null} // Files are isolated per sandbox/session const session1 = await agentbase.runAgent({ message: "Create secret.txt with password" }); const session2 = await agentbase.runAgent({ message: "Create secret.txt with different password" }); // Each session has its own secret.txt ``` Learn more: [Sandbox Primitive](/primitives/environment/sandbox) ### With Computer Use bash commands for advanced file operations: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Use bash to find all files larger than 1MB and compress them" }); ``` Learn more: [Computer Primitive](/primitives/environment/computer) ### With Browser Save web content to files: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Navigate to example.com, extract the data, and save it to data.json" }); ``` Learn more: [Browser Primitive](/primitives/environment/browser) ### With Custom Tools Create files as tool outputs: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Use the weather API to get forecasts and save to forecast.json" }); ``` Learn more: [Custom Tools](/primitives/essentials/custom-tools) ## Performance Considerations ### File Size Limits * **Individual Files**: No strict limit, but large files consume storage quota * **Total Storage**: 10GB per session * **Read Performance**: Files under 10MB read instantly * **Write Performance**: Optimized for files under 100MB ### Optimization Tips Group file operations together to reduce overhead Process large files in chunks rather than loading entirely Remove temp files after processing to free space Compress large datasets to save storage ### Performance Example ```typescript theme={null} // Efficient: Process large file in chunks const efficient = await agentbase.runAgent({ message: "Read large_data.csv in chunks of 1000 rows and process each chunk" }); // Inefficient: Loading entire large file const inefficient = await agentbase.runAgent({ message: "Load all of large_data.csv into memory and process" }); ``` ## Common File Operations ### Working with Different File Types ```typescript theme={null} // Create JSON const create = await agentbase.runAgent({ message: 'Create data.json with {"users": [], "settings": {}}' }); // Read and modify JSON const modify = await agentbase.runAgent({ message: "Add a new user to data.json", session: create.session }); // Validate JSON const validate = await agentbase.runAgent({ message: "Validate that data.json is valid JSON", session: create.session }); ``` ```typescript theme={null} // Create CSV const csv = await agentbase.runAgent({ message: "Create sales.csv with columns: date, product, amount" }); // Process CSV const process = await agentbase.runAgent({ message: "Read sales.csv and calculate total sales by product", session: csv.session }); // Convert CSV const convert = await agentbase.runAgent({ message: "Convert sales.csv to JSON format", session: csv.session }); ``` ```typescript theme={null} // Create and write const write = await agentbase.runAgent({ message: "Create notes.txt with a list of tasks" }); // Read and search const search = await agentbase.runAgent({ message: "Search notes.txt for tasks containing 'urgent'", session: write.session }); // Append const append = await agentbase.runAgent({ message: "Add a new task to notes.txt", session: write.session }); ``` ```typescript theme={null} // Create source files const code = await agentbase.runAgent({ message: "Create a Python module utils.py with helper functions" }); // Modify code const modify = await agentbase.runAgent({ message: "Add error handling to all functions in utils.py", session: code.session }); // Test code const test = await agentbase.runAgent({ message: "Create test_utils.py to test the functions", session: code.session }); ``` ```typescript theme={null} // Download and save const download = await agentbase.runAgent({ message: "Download image from URL and save as logo.png" }); // Process binary const process = await agentbase.runAgent({ message: "Resize logo.png to 200x200 pixels", session: download.session }); ``` ## Advanced Patterns ### Multi-File Workflows ```typescript theme={null} // Complex project setup const project = await agentbase.runAgent({ message: `Create a full-stack project: Backend (backend/): - app.py with Flask setup - requirements.txt - config.py - models/user.py - routes/api.py Frontend (frontend/): - index.html - style.css - app.js - package.json Root: - README.md - .gitignore - docker-compose.yml` }); ``` ### Incremental File Building ```typescript theme={null} // Start with base const base = await agentbase.runAgent({ message: "Create base.py with common utilities" }); // Add features incrementally const feature1 = await agentbase.runAgent({ message: "Add logging functionality to base.py", session: base.session }); const feature2 = await agentbase.runAgent({ message: "Add configuration loading to base.py", session: base.session }); const feature3 = await agentbase.runAgent({ message: "Add error handling decorators to base.py", session: base.session }); ``` ### File-Based State Management ```typescript theme={null} // Use files to track state const init = await agentbase.runAgent({ message: "Create state.json to track workflow progress: {step: 1, completed: []}" }); // Update state after each step const step2 = await agentbase.runAgent({ message: "Complete step 1, update state.json to step 2", session: init.session }); const step3 = await agentbase.runAgent({ message: "Complete step 2, update state.json to step 3", session: init.session }); ``` ## Troubleshooting **Problem**: Agent cannot find a file **Solutions**: * Verify you're using the correct session ID * Check file path and name (Linux is case-sensitive) * List directory contents to confirm file exists ```typescript theme={null} const check = await agentbase.runAgent({ message: "List all files in the current directory and show their paths", session: yourSession }); ``` **Problem**: Cannot read or write file **Solution**: Files should be in `/home/pointer` directory with proper permissions ```typescript theme={null} const fix = await agentbase.runAgent({ message: "Check file permissions and fix any permission issues" }); ``` **Problem**: Reached 10GB storage limit **Solutions**: * Clean up temporary files * Compress large files * Start a new session if needed ```typescript theme={null} const cleanup = await agentbase.runAgent({ message: "Show disk usage, identify large files, and remove unnecessary ones" }); ``` **Problem**: File contents appear corrupted **Solution**: Verify file encoding and format ```typescript theme={null} const verify = await agentbase.runAgent({ message: "Check the encoding and format of data.json and repair if needed" }); ``` ## Related Primitives Isolated execution environment for files Shell access for advanced file operations Session persistence for file continuity Understanding data persistence ## Additional Resources Complete tool documentation File operation examples Production file management **File Persistence**: Files persist within a session until the session expires or is deleted. For long-term storage, consider downloading files or using external storage solutions. # Sandbox Source: https://docs.agentbase.sh/primitives/environment/sandbox Isolated, secure execution environments for agent workloads > Each agent session runs in its own isolated sandbox environment, providing security, resource isolation, and clean state management. ## Overview The Sandbox primitive is the foundation of Agentbase's execution model. Every agent session operates within its own isolated sandbox - a lightweight, secure container that provides a clean execution environment. This isolation ensures that: * **Security**: Agent operations are contained and cannot affect other sessions or the host system * **Resource Isolation**: Each sandbox has dedicated CPU, memory, and disk resources * **Clean State**: Every new session starts with a fresh environment * **Predictable Execution**: Consistent runtime conditions across all sessions Sandboxes are created automatically when you run an agent - no manual setup required Each sandbox is tied to a session ID and can be reused across multiple requests Automatic resource allocation and cleanup based on workload requirements Full internet access for API calls, package downloads, and web interactions ## How Sandboxes Work When you make an agent request, Agentbase automatically: 1. **Creates** a new isolated sandbox environment (or resumes an existing one) 2. **Provisions** the sandbox with necessary runtime tools and capabilities 3. **Executes** your agent's tasks within the isolated environment 4. **Persists** the sandbox state for future requests in the same session 5. **Pauses** the sandbox after 5 minutes of inactivity to save resources 6. **Cleans up** the sandbox automatically when no longer needed **Session Continuity**: Use the same session ID to reuse a sandbox and maintain state across multiple agent requests. ## Sandbox Architecture ### Isolation Layers Agentbase sandboxes use multiple layers of isolation: ```mermaid theme={null} graph TB A[Agent Request] --> B[Session Manager] B --> C[Sandbox Container] C --> D[File System Layer] C --> E[Network Layer] C --> F[Process Layer] D --> G[Persistent Storage] E --> H[Internet Access] F --> I[Runtime Environment] I --> J[Python 3.11.2] I --> K[Node.js 18.20.4] I --> L[Chrome Browser] ``` ### Security Boundaries Each sandbox provides: * **Process Isolation**: Separate process namespaces prevent cross-contamination * **File System Isolation**: Dedicated filesystem with controlled access * **Network Isolation**: Outbound internet access with security policies * **Resource Limits**: CPU, memory, and disk quotas to prevent resource exhaustion ## Code Examples ### Basic Sandbox Usage ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Sandbox is created automatically const result = await agentbase.runAgent({ message: "Create a Python script to analyze data.csv" }); console.log('Session ID:', result.session); // Output: Session ID: agent_session_abc123... ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Sandbox is created automatically result = agentbase.run_agent( message="Create a Python script to analyze data.csv" ) print(f"Session ID: {result.session}") # Output: Session ID: agent_session_abc123... ``` ```bash cURL theme={null} curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Create a Python script to analyze data.csv" }' # Response includes session ID for sandbox reuse ``` ### Reusing a Sandbox Maintain state across multiple requests by reusing the same session: ```typescript TypeScript theme={null} // First request - creates sandbox const result1 = await agentbase.runAgent({ message: "Install pandas and create a sample CSV file" }); // Second request - reuses the same sandbox const result2 = await agentbase.runAgent({ message: "Now read that CSV file and show the contents", session: result1.session }); // The CSV file and pandas installation persist ``` ```python Python theme={null} # First request - creates sandbox result1 = agentbase.run_agent( message="Install pandas and create a sample CSV file" ) # Second request - reuses the same sandbox result2 = agentbase.run_agent( message="Now read that CSV file and show the contents", session=result1.session ) # The CSV file and pandas installation persist ``` ### Sandbox with Custom Modes Different modes affect sandbox resource allocation: ```typescript TypeScript theme={null} // Flash mode - lightweight sandbox const flash = await agentbase.runAgent({ message: "Quick calculation: 123 * 456", mode: "flash" }); // Base mode - standard sandbox (default) const base = await agentbase.runAgent({ message: "Analyze this data and create a chart", mode: "base" }); // Max mode - enhanced sandbox resources const max = await agentbase.runAgent({ message: "Process large dataset and train ML model", mode: "max" }); ``` ```python Python theme={null} # Flash mode - lightweight sandbox flash = agentbase.run_agent( message="Quick calculation: 123 * 456", mode="flash" ) # Base mode - standard sandbox (default) base = agentbase.run_agent( message="Analyze this data and create a chart", mode="base" ) # Max mode - enhanced sandbox resources max = agentbase.run_agent( message="Process large dataset and train ML model", mode="max" ) ``` ## Sandbox Lifecycle ### Creation Sandboxes are created automatically on the first request: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Hello, create a file called test.txt" }); // Sandbox created: agent_session_xyz789 // File test.txt exists in sandbox ``` ### Persistence Sandboxes remain active and persist state: ```typescript theme={null} // File from previous request still exists const result2 = await agentbase.runAgent({ message: "Read the contents of test.txt", session: result.session }); // Successfully reads the file ``` ### Auto-Pause After 5 minutes of inactivity, sandboxes automatically pause: * **Files preserved**: All files and data remain intact * **Packages preserved**: Installed packages stay installed * **Resume on next request**: Automatic resume when session is reused ### Cleanup Sandboxes are automatically cleaned up after extended inactivity or when explicitly terminated. ## Use Cases ### 1. Development Workflows Create and test code in an isolated environment: ```typescript theme={null} const dev = await agentbase.runAgent({ message: "Create a React component with TypeScript, install dependencies, and test it" }); // Sandbox provides Node.js, npm, and isolated workspace ``` ### 2. Data Processing Process sensitive data in isolated environments: ```typescript theme={null} const analysis = await agentbase.runAgent({ message: "Download this CSV, analyze it, and create visualizations" }); // Each analysis runs in its own sandbox - no data leakage ``` ### 3. Multi-Step Tasks Maintain state across multiple steps: ```typescript theme={null} // Step 1: Setup const setup = await agentbase.runAgent({ message: "Install required packages for web scraping" }); // Step 2: Execute (reuses sandbox) const scrape = await agentbase.runAgent({ message: "Now scrape data from these 5 websites", session: setup.session }); // Step 3: Process (reuses sandbox) const process = await agentbase.runAgent({ message: "Process the scraped data and create a report", session: setup.session }); ``` ### 4. Testing and Experimentation Safe environment for testing code: ```typescript theme={null} const test = await agentbase.runAgent({ message: "Test this algorithm with different inputs and show results" }); // Sandbox isolation prevents any side effects ``` ## Best Practices ### Session Management ```typescript theme={null} // Good: Reuse session for related work const session = result1.session; const result2 = await agentbase.runAgent({ message: "Continue from previous step", session }); // Avoid: Creating new sandbox for each step const result2 = await agentbase.runAgent({ message: "Continue from previous step" // No session ID - creates new sandbox }); ``` ```typescript theme={null} // Good: New session for independent task const taskA = await agentbase.runAgent({ message: "Process customer data" }); const taskB = await agentbase.runAgent({ message: "Generate marketing report" // Different task - don't reuse session }); ``` ```typescript theme={null} // Store session ID in database await db.workflows.update({ id: workflowId, sessionId: result.session }); // Resume later const workflow = await db.workflows.get(workflowId); const continued = await agentbase.runAgent({ message: "Continue the workflow", session: workflow.sessionId }); ``` ### Resource Optimization **Mode Selection**: Use `flash` mode for simple tasks, `base` for standard workloads, and `max` only when you need advanced reasoning capabilities. This optimizes both cost and performance. ```typescript theme={null} // Optimize by choosing the right mode const modes = { simple: "flash", // Quick calculations, simple queries standard: "base", // Most development and analysis tasks complex: "max" // Advanced reasoning, complex workflows }; const result = await agentbase.runAgent({ message: "Your task here", mode: modes.standard }); ``` ### Error Handling Handle sandbox-related errors gracefully: ```typescript theme={null} try { const result = await agentbase.runAgent({ message: "Process this task", session: existingSessionId }); } catch (error) { if (error.code === 'SANDBOX_NOT_FOUND') { // Session expired, start fresh const result = await agentbase.runAgent({ message: "Process this task" // Creates new sandbox }); } else { throw error; } } ``` ## Integration with Other Primitives ### With File System Sandboxes provide the execution environment for file operations: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Create multiple files and organize them into folders" }); // Sandbox provides the file system where files are created ``` Learn more: [File System Primitive](/primitives/environment/file-system) ### With Computer Sandboxes host the full Linux computer environment: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Install packages and run shell commands" }); // Sandbox contains the Linux environment ``` Learn more: [Computer Primitive](/primitives/environment/computer) ### With Browser Browser automation runs within the sandbox: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Navigate to website and extract data" }); // Chrome browser runs inside the sandbox ``` Learn more: [Browser Primitive](/primitives/environment/browser) ### With Sessions Sessions manage sandbox lifecycle and persistence: ```typescript theme={null} // Session primitive controls sandbox reuse const result = await agentbase.runAgent({ message: "Start a task", session: previousSession // Reuses sandbox }); ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ## Performance Considerations ### Startup Time * **Cold Start**: First request creates sandbox (\~2-5 seconds overhead) * **Warm Start**: Subsequent requests in same session are instant * **Resume from Pause**: Paused sandboxes resume quickly (\~1-2 seconds) ```typescript theme={null} // First request - cold start const start = Date.now(); const result1 = await agentbase.runAgent({ message: "Hello" }); console.log(`Cold start: ${Date.now() - start}ms`); // Second request - warm start const start2 = Date.now(); const result2 = await agentbase.runAgent({ message: "Hello again", session: result1.session }); console.log(`Warm start: ${Date.now() - start2}ms`); ``` ### Resource Limits Each sandbox has resource quotas: * **CPU**: Shared allocation based on mode * **Memory**: 2GB for flash/base, 4GB for max mode * **Disk**: 10GB persistent storage per session * **Network**: Unlimited bandwidth with rate limiting ### Optimization Tips Group related operations in a single session to minimize sandbox creation overhead Install packages once and reuse the session for multiple tasks Remove large temporary files to stay within disk limits Complete work within 5 minutes to avoid auto-pause overhead ## Security Features ### Isolation Guarantees Sandboxes provide strong isolation: * **No Cross-Session Access**: Sandboxes cannot access files or processes from other sessions * **Network Security**: Outbound connections only, no inbound access * **Process Isolation**: Separate kernel namespaces for each sandbox * **Resource Protection**: Quotas prevent resource exhaustion attacks ### Data Privacy ```typescript theme={null} // Each user's data is isolated const userA = await agentbase.runAgent({ message: "Process confidential data" }); const userB = await agentbase.runAgent({ message: "Process different confidential data" }); // userA and userB run in completely separate sandboxes ``` ### Security Best Practices **Sensitive Data**: While sandboxes provide isolation, avoid storing long-term sensitive credentials in sandbox files. Use environment variables or secure parameter passing instead. ```typescript theme={null} // Good: Pass credentials securely const result = await agentbase.runAgent({ message: "Connect to database using the provided credentials", system: `Database credentials: ${secureCredentials}` }); // Avoid: Writing credentials to files const result = await agentbase.runAgent({ message: "Write these credentials to config.json: ..." }); ``` ## Troubleshooting ### Common Issues **Problem**: Session expired or invalid **Solution**: Create a new session or verify session ID ```typescript theme={null} // Check if session is valid const result = await agentbase.runAgent({ message: "test", session: maybeInvalidSession }).catch(() => { // Session invalid, start fresh return agentbase.runAgent({ message: "test" }); }); ``` **Problem**: Sandbox reached 10GB storage limit **Solution**: Clean up large files or start new session ```typescript theme={null} const cleanup = await agentbase.runAgent({ message: "Delete large temporary files and downloads", session: existingSession }); ``` **Problem**: Sandbox running slow **Solution**: Check mode selection and resource usage ```typescript theme={null} // Use appropriate mode for task complexity const result = await agentbase.runAgent({ message: "Simple task", mode: "flash" // Don't use "max" for simple tasks }); ``` ## Related Primitives Persistent storage within sandboxes Full Linux environment inside sandboxes Web automation within sandboxes Session management and persistence ## Additional Resources Complete API documentation Understanding state management Production deployment patterns **Remember**: Sandboxes are created automatically and managed transparently. Focus on your agent's tasks, and Agentbase handles the infrastructure. # Background Tasks Source: https://docs.agentbase.sh/primitives/essentials/background Execute long-running agent tasks asynchronously with status tracking and result retrieval > Background Tasks enable agents to execute long-running operations asynchronously, allowing your application to remain responsive while complex work continues in the background. ## Overview The Background Tasks primitive allows agents to perform time-intensive operations without blocking your application. Instead of waiting for completion, you can initiate a background task, receive a task ID, and check status or retrieve results later. Background tasks are essential for: * **Long-Running Operations**: Multi-hour data processing, analysis, or generation tasks * **Async Workflows**: Decouple request initiation from result consumption * **Batch Processing**: Process large datasets without timeout constraints * **Scheduled Jobs**: Execute recurring agent tasks on a schedule * **Resource-Intensive Tasks**: Complex computations without blocking other operations Initiate tasks and continue without waiting for completion Monitor progress, check status, and receive notifications when complete Tasks continue running even if client disconnects or crashes Fetch results when ready, with full session context preserved ## How Background Tasks Work ### Task Lifecycle Background tasks follow a well-defined lifecycle: 1. **Initiation**: Submit task request with `background: true` parameter 2. **Task Creation**: System creates background job and returns task ID immediately 3. **Execution**: Agent processes task asynchronously in background 4. **Progress Updates**: Task status updates as execution proceeds 5. **Completion**: Task finishes with success or error state 6. **Result Retrieval**: Results remain available for retrieval 7. **Cleanup**: Completed tasks eventually expire and clean up ### Task States Tasks transition through these states: * **`queued`**: Task accepted, waiting to start * **`running`**: Task currently executing * **`completed`**: Task finished successfully * **`failed`**: Task encountered error and stopped * **`cancelled`**: Task was manually cancelled **Persistent Execution**: Background tasks continue running even if your application disconnects. Results remain available until you retrieve them. ## Code Examples ### Basic Background Task ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Start long-running task in background const task = await agentbase.runAgent({ message: "Analyze all customer feedback from the past year and create comprehensive report", background: true // Run asynchronously }); console.log('Task ID:', task.taskId); console.log('Status:', task.status); // 'queued' or 'running' // Continue with other work... // Task executes in background // Later, check status const status = await agentbase.getTaskStatus(task.taskId); console.log('Current status:', status.state); console.log('Progress:', status.progress); // When complete, get results if (status.state === 'completed') { const result = await agentbase.getTaskResult(task.taskId); console.log('Result:', result.message); } ``` ```python Python theme={null} from agentbase import Agentbase import time agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Start long-running task in background task = agentbase.run_agent( message="Analyze all customer feedback from the past year and create comprehensive report", background=True # Run asynchronously ) print(f"Task ID: {task.task_id}") print(f"Status: {task.status}") # 'queued' or 'running' # Continue with other work... # Task executes in background # Later, check status status = agentbase.get_task_status(task.task_id) print(f"Current status: {status.state}") print(f"Progress: {status.progress}") # When complete, get results if status.state == 'completed': result = agentbase.get_task_result(task.task_id) print(f"Result: {result.message}") ``` ```bash cURL theme={null} # Start background task curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Analyze all customer feedback from the past year", "background": true }' # Response: { "taskId": "task_abc123", "status": "queued" } # Check status curl https://api.agentbase.sh/tasks/task_abc123 \ -H "Authorization: Bearer $AGENTBASE_API_KEY" # Get results when complete curl https://api.agentbase.sh/tasks/task_abc123/result \ -H "Authorization: Bearer $AGENTBASE_API_KEY" ``` ### Polling for Completion ```typescript TypeScript theme={null} // Poll until task completes async function waitForTask(taskId: string): Promise { while (true) { const status = await agentbase.getTaskStatus(taskId); console.log(`Status: ${status.state} - Progress: ${status.progress}%`); if (status.state === 'completed') { return await agentbase.getTaskResult(taskId); } if (status.state === 'failed') { throw new Error(`Task failed: ${status.error}`); } // Wait before next check await new Promise(resolve => setTimeout(resolve, 5000)); // 5 seconds } } // Usage const task = await agentbase.runAgent({ message: "Generate 100 product descriptions", background: true }); const result = await waitForTask(task.taskId); console.log('All descriptions:', result.message); ``` ```python Python theme={null} import time # Poll until task completes async def wait_for_task(task_id: str): while True: status = agentbase.get_task_status(task_id) print(f"Status: {status.state} - Progress: {status.progress}%") if status.state == 'completed': return agentbase.get_task_result(task_id) if status.state == 'failed': raise Exception(f"Task failed: {status.error}") # Wait before next check time.sleep(5) # 5 seconds # Usage task = agentbase.run_agent( message="Generate 100 product descriptions", background=True ) result = await wait_for_task(task.task_id) print(f"All descriptions: {result.message}") ``` ### Webhook Notifications ```typescript TypeScript theme={null} // Get notified when task completes const task = await agentbase.runAgent({ message: "Process large dataset", background: true, webhook: { url: "https://api.yourapp.com/webhooks/task-complete", events: ["completed", "failed"] } }); // Your webhook endpoint receives: // POST https://api.yourapp.com/webhooks/task-complete // { // "taskId": "task_abc123", // "status": "completed", // "timestamp": "2025-01-08T10:30:00Z" // } // Webhook handler app.post('/webhooks/task-complete', async (req, res) => { const { taskId, status } = req.body; if (status === 'completed') { const result = await agentbase.getTaskResult(taskId); await processResult(result); } res.sendStatus(200); }); ``` ```python Python theme={null} from flask import Flask, request app = Flask(__name__) # Get notified when task completes task = agentbase.run_agent( message="Process large dataset", background=True, webhook={ 'url': 'https://api.yourapp.com/webhooks/task-complete', 'events': ['completed', 'failed'] } ) # Your webhook endpoint receives: # POST https://api.yourapp.com/webhooks/task-complete # { # "taskId": "task_abc123", # "status": "completed", # "timestamp": "2025-01-08T10:30:00Z" # } # Webhook handler @app.route('/webhooks/task-complete', methods=['POST']) async def task_complete(): data = request.json task_id = data['taskId'] status = data['status'] if status == 'completed': result = agentbase.get_task_result(task_id) await process_result(result) return '', 200 ``` ### Batch Background Processing ```typescript TypeScript theme={null} // Process multiple items in background async function batchProcess(items: string[]): Promise { // Start all tasks const tasks = await Promise.all( items.map(item => agentbase.runAgent({ message: `Process item: ${item}`, background: true }) ) ); console.log(`Started ${tasks.length} background tasks`); // Collect results as they complete const results = []; for (const task of tasks) { const result = await waitForTask(task.taskId); results.push(result); console.log(`Completed ${results.length}/${tasks.length}`); } return results; } // Process 100 items in parallel const items = Array.from({ length: 100 }, (_, i) => `item-${i}`); const results = await batchProcess(items); ``` ```python Python theme={null} # Process multiple items in background async def batch_process(items: list) -> list: # Start all tasks tasks = await asyncio.gather(*[ agentbase.run_agent( message=f"Process item: {item}", background=True ) for item in items ]) print(f"Started {len(tasks)} background tasks") # Collect results as they complete results = [] for task in tasks: result = await wait_for_task(task.task_id) results.append(result) print(f"Completed {len(results)}/{len(tasks)}") return results # Process 100 items in parallel items = [f"item-{i}" for i in range(100)] results = await batch_process(items) ``` ## Use Cases ### 1. Large-Scale Data Analysis Process massive datasets without timeout constraints: ```typescript theme={null} async function analyzeAllCustomers() { const task = await agentbase.runAgent({ message: ` Analyze all customer data: 1. Load customer database (2M+ records) 2. Segment customers by behavior patterns 3. Calculate lifetime value for each segment 4. Identify churn risk factors 5. Generate actionable insights 6. Create detailed report with visualizations This will take 2-3 hours to complete. `, background: true, webhook: { url: 'https://api.company.com/webhooks/analysis-complete', events: ['completed'] } }); // Store task for monitoring await db.tasks.create({ taskId: task.taskId, type: 'customer-analysis', startedAt: new Date() }); return task.taskId; } ``` ```typescript theme={null} async function runFinancialSimulations() { const task = await agentbase.runAgent({ message: ` Run Monte Carlo simulations: - 10,000 simulation iterations - Model portfolio performance over 30 years - Test various market scenarios - Calculate risk metrics and confidence intervals - Generate comprehensive investment report Estimated time: 4-6 hours `, background: true }); // Check progress periodically setInterval(async () => { const status = await agentbase.getTaskStatus(task.taskId); console.log(`Progress: ${status.progress}% - ${status.currentStep}`); }, 60000); // Every minute return task.taskId; } ``` ### 2. Content Generation at Scale Generate large volumes of content asynchronously: ```typescript theme={null} async function generateProductContent(productIds: string[]) { const task = await agentbase.runAgent({ message: ` Generate content for ${productIds.length} products: - Product descriptions (200-300 words each) - SEO meta descriptions - Social media posts (3 per product) - Email marketing copy Products: ${productIds.join(', ')} Estimated time: 2-3 hours for ${productIds.length} products `, background: true, webhook: { url: 'https://api.company.com/webhooks/content-ready', events: ['completed', 'failed'] } }); // Update products database await db.products.updateMany( { id: { $in: productIds } }, { contentGenerationTask: task.taskId, status: 'generating' } ); return task.taskId; } ``` ### 3. Scheduled Reports Generate periodic reports in background: ```typescript theme={null} // Daily report generation async function generateDailyReport() { const task = await agentbase.runAgent({ message: ` Generate comprehensive daily report: 1. Collect data from all sources 2. Analyze sales, traffic, conversions 3. Compare to previous day and week 4. Identify trends and anomalies 5. Create executive summary 6. Generate detailed charts and tables 7. Export to PDF and send to stakeholders `, background: true, session: await getReportingSession() // Maintains historical context }); // Store for tracking await db.reports.create({ date: new Date(), taskId: task.taskId, type: 'daily', status: 'generating' }); } // Schedule with cron cron.schedule('0 6 * * *', generateDailyReport); // Daily at 6 AM ``` ### 4. ETL Pipelines Run complex data pipelines asynchronously: ```typescript theme={null} async function runETLPipeline() { const task = await agentbase.runAgent({ message: ` Execute ETL pipeline: EXTRACT: - Download data from 15 different APIs - Fetch files from S3 buckets - Query production database snapshots TRANSFORM: - Clean and normalize data - Apply business logic transformations - Merge data from different sources - Calculate derived metrics LOAD: - Validate transformed data - Load into data warehouse - Update materialized views - Trigger downstream processes Handle errors gracefully and create detailed log. `, background: true, webhook: { url: 'https://api.company.com/webhooks/etl-complete', events: ['completed', 'failed'] } }); return task.taskId; } ``` ### 5. Machine Learning Training Train models in background: ```typescript theme={null} async function trainMLModel(datasetId: string) { const task = await agentbase.runAgent({ message: ` Train machine learning model: 1. Load dataset ${datasetId} 2. Split into train/validation/test sets 3. Train multiple model architectures 4. Perform hyperparameter tuning 5. Evaluate on test set 6. Select best performing model 7. Save model artifacts 8. Generate performance report Expected training time: 6-12 hours `, background: true }); // Monitor training progress const monitor = setInterval(async () => { const status = await agentbase.getTaskStatus(task.taskId); await db.mlTraining.update(datasetId, { status: status.state, progress: status.progress, currentEpoch: status.metadata?.currentEpoch, bestAccuracy: status.metadata?.bestAccuracy }); if (status.state === 'completed' || status.state === 'failed') { clearInterval(monitor); } }, 30000); // Every 30 seconds return task.taskId; } ``` ### 6. Web Scraping Jobs Large-scale web scraping operations: ```typescript theme={null} async function scrapeCompetitorData(urls: string[]) { const task = await agentbase.runAgent({ message: ` Scrape competitor websites: - URLs: ${urls.join(', ')} - Extract: pricing, products, features - Handle rate limits and retries - Respect robots.txt - Parse and structure data - Store in database ${urls.length} sites to scrape, estimated 3-4 hours `, background: true, webhook: { url: 'https://api.company.com/webhooks/scraping-complete', events: ['completed'] } }); return task.taskId; } ``` ## Best Practices ### Task Design ```typescript theme={null} // Good: Complete instructions with all context const task = await agentbase.runAgent({ message: ` Process dataset located at: s3://bucket/data.csv Credentials: Use IAM role arn:aws:iam::123:role/processor Output: Save results to s3://bucket/results/ Notification: Email team@company.com when complete `, background: true }); // Avoid: Incomplete instructions requiring interaction const bad = await agentbase.runAgent({ message: "Process the dataset", // Which dataset? Where? background: true }); ``` ```typescript theme={null} // Configure appropriate timeout for task duration const task = await agentbase.runAgent({ message: "Long-running analysis (expected: 4-6 hours)", background: true, timeout: 8 * 60 * 60 * 1000 // 8 hours in milliseconds }); ``` ```typescript theme={null} // Design tasks with progress reporting const task = await agentbase.runAgent({ message: ` Process 10,000 records. Report progress after every 1,000 records: - Log completion count - Update progress percentage - Report any errors encountered - Estimate time remaining `, background: true }); ``` ```typescript theme={null} // Design for resilience const task = await agentbase.runAgent({ message: ` Process all files in directory. Error handling: - If file fails, log error and continue - Save progress after each file - If total errors exceed 10%, stop and report - Create summary of successful and failed files `, background: true }); ``` ### Monitoring and Management ```typescript theme={null} // Comprehensive task management class BackgroundTaskManager { async submitTask(message: string, options = {}) { const task = await agentbase.runAgent({ message, background: true, ...options }); // Store task metadata await db.tasks.create({ taskId: task.taskId, message, status: 'queued', createdAt: new Date(), ...options }); // Start monitoring this.monitorTask(task.taskId); return task.taskId; } async monitorTask(taskId: string) { const interval = setInterval(async () => { const status = await agentbase.getTaskStatus(taskId); // Update database await db.tasks.update(taskId, { status: status.state, progress: status.progress, updatedAt: new Date() }); // Handle completion if (status.state === 'completed') { clearInterval(interval); await this.handleCompletion(taskId); } // Handle failure if (status.state === 'failed') { clearInterval(interval); await this.handleFailure(taskId, status.error); } }, 10000); // Check every 10 seconds } async handleCompletion(taskId: string) { const result = await agentbase.getTaskResult(taskId); await db.tasks.update(taskId, { status: 'completed', result: result.message, completedAt: new Date() }); // Notify stakeholders await notifyCompletion(taskId); } async handleFailure(taskId: string, error: string) { await db.tasks.update(taskId, { status: 'failed', error, failedAt: new Date() }); // Alert team await alertFailure(taskId, error); } async cancelTask(taskId: string) { await agentbase.cancelTask(taskId); await db.tasks.update(taskId, { status: 'cancelled', cancelledAt: new Date() }); } async listActiveTasks() { return await db.tasks.find({ status: { $in: ['queued', 'running'] } }); } } ``` ### Resource Management ```typescript theme={null} // Limit concurrent background tasks class TaskQueue { private maxConcurrent = 10; private active = 0; private queue: Array<() => Promise> = []; async submit(message: string): Promise { return new Promise((resolve, reject) => { const taskFn = async () => { try { this.active++; const task = await agentbase.runAgent({ message, background: true }); resolve(task.taskId); } catch (error) { reject(error); } finally { this.active--; this.processQueue(); } }; if (this.active < this.maxConcurrent) { taskFn(); } else { this.queue.push(taskFn); } }); } private processQueue() { while (this.active < this.maxConcurrent && this.queue.length > 0) { const taskFn = this.queue.shift(); if (taskFn) taskFn(); } } } ``` ## Integration with Other Primitives ### With Persistence Background tasks maintain session state: ```typescript theme={null} // Use persistent session for background work const reportingSession = await getReportingSession(); const task = await agentbase.runAgent({ message: "Generate monthly report using historical data", session: reportingSession, // Access to all previous reports background: true }); ``` Learn more: [Persistence Primitive](/primitives/essentials/persistence) ### With Hooks Execute callbacks during background task lifecycle: ```typescript theme={null} const task = await agentbase.runAgent({ message: "Long-running task", background: true, hooks: { onStart: async () => { await metrics.increment('tasks.started'); }, onProgress: async (progress) => { await updateUI(progress); }, onComplete: async (result) => { await processResult(result); await metrics.increment('tasks.completed'); }, onError: async (error) => { await logger.error('Task failed', { error }); await metrics.increment('tasks.failed'); } } }); ``` Learn more: [Hooks Primitive](/primitives/essentials/hooks) ### With Traces Monitor background task execution: ```typescript theme={null} // Stream trace events from background task const task = await agentbase.runAgent({ message: "Background analysis", background: true, stream: true // Stream events even for background task }); // Receive real-time updates for await (const event of task.events) { console.log(`[${event.type}]`, event); if (event.type === 'agent_progress') { console.log(`Progress: ${event.progress}%`); } } ``` Learn more: [Traces Primitive](/primitives/essentials/traces) ## Performance Considerations ### Task Overhead * **Submission**: \< 100ms to queue task * **Status Check**: \< 50ms to check task status * **Result Retrieval**: 100-500ms depending on result size ### Concurrency Limits * **Default Limit**: 50 concurrent background tasks per account * **Enterprise Limit**: Configurable based on needs * **Queue Depth**: Unlimited queued tasks ### Resource Optimization ```typescript theme={null} // Optimize background task resource usage const task = await agentbase.runAgent({ message: "Process data efficiently", background: true, resources: { priority: "low", // Use lower priority for background work memory: "medium", // Request appropriate memory cpu: "low", // Most background tasks don't need high CPU timeout: 12 * 60 * 60 // 12 hour timeout } }); ``` ## Troubleshooting **Problem**: Task not starting execution **Solutions**: * Check concurrent task limits * Verify account has available resources * Review task priority settings ```typescript theme={null} // Check active tasks const active = await agentbase.listTasks({ status: 'running' }); console.log(`Active tasks: ${active.length}`); // Increase priority if needed await agentbase.updateTask(taskId, { priority: 'high' }); ``` **Problem**: Results not available after completion **Solutions**: * Verify task actually completed successfully * Check result retention period (typically 7 days) * Ensure using correct task ID ```typescript theme={null} const status = await agentbase.getTaskStatus(taskId); console.log('Status:', status); if (status.state === 'completed') { try { const result = await agentbase.getTaskResult(taskId); } catch (error) { console.error('Result no longer available:', error); } } ``` **Problem**: Task fails with timeout error **Solutions**: * Increase timeout setting * Break into smaller subtasks * Optimize task execution ```typescript theme={null} // Longer timeout const task = await agentbase.runAgent({ message: "Very long task", background: true, timeout: 24 * 60 * 60 * 1000 // 24 hours }); // Or break into smaller tasks const subtasks = await Promise.all([ agentbase.runAgent({ message: "Part 1", background: true }), agentbase.runAgent({ message: "Part 2", background: true }), agentbase.runAgent({ message: "Part 3", background: true }) ]); ``` ## Related Primitives Session state for background tasks Lifecycle callbacks for tasks Monitor background execution Automatic error recovery in tasks ## Additional Resources Background task parameters Configure webhook notifications Background task examples **Remember**: Background tasks are perfect for operations that take more than a few seconds. Use webhooks for notifications and implement proper monitoring for production workloads. # Context Management Source: https://docs.agentbase.sh/primitives/essentials/context-management Optimize agent performance by managing conversation context, memory, and information flow > Context management enables agents to maintain relevant information, handle long conversations effectively, and optimize performance by balancing comprehensive context with efficient processing. ## Overview 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 All messages automatically preserved in conversation context Agents intelligently manage large conversation histories Condense lengthy contexts while preserving key information Highlight critical details for agent attention ## How Context Management Works Context flows through agent conversations in several ways: 1. **Message History**: All previous messages automatically included in agent context 2. **System Prompts**: Persistent instructions and guidelines throughout the session 3. **Tool Results**: Outputs from previous tool executions available as context 4. **File State**: Created files and their contents accessible in the environment 5. **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. ## Code Examples ### Basic Context Flow ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Turn 1: Establish context const turn1 = await agentbase.runAgent({ message: "I'm working on a Python data analysis project. The dataset is sales.csv with columns: date, product, quantity, revenue." }); const sessionId = turn1.session; // Turn 2: Agent remembers project context const turn2 = await agentbase.runAgent({ message: "Create a script to calculate monthly totals", session: sessionId // Agent knows: Python project, sales.csv, column names }); // Turn 3: Agent remembers previous work const turn3 = await agentbase.runAgent({ message: "Now add a function to find top products", session: sessionId // Agent knows: the script from turn2, can build on it }); // All context automatically maintained ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Turn 1: Establish context turn1 = agentbase.run_agent( message="I'm working on a Python data analysis project. The dataset is sales.csv with columns: date, product, quantity, revenue." ) session_id = turn1.session # Turn 2: Agent remembers project context turn2 = agentbase.run_agent( message="Create a script to calculate monthly totals", session=session_id # Agent knows: Python project, sales.csv, column names ) # Turn 3: Agent remembers previous work turn3 = agentbase.run_agent( message="Now add a function to find top products", session=session_id # Agent knows: the script from turn2, can build on it ) # All context automatically maintained ``` ### Explicit Context Provision ```typescript TypeScript theme={null} // Provide important context explicitly const 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 ``` ```python Python theme={null} # Provide important context explicitly result = agentbase.run_agent( message=f"""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: "{customer_feedback}" 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 ``` ### Context Summarization ```typescript TypeScript theme={null} // For very long conversations, periodically summarize async 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; } ``` ```python Python theme={null} # For very long conversations, periodically summarize async def manage_conversation_context(session_id: str, message_count: int): if message_count > 50: # Generate summary of conversation so far summary = await agentbase.run_agent_async( 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=session_id ) # Store summary for reference await save_summary({ 'session_id': session_id, 'message_count': message_count, 'summary': summary.message, 'timestamp': datetime.now() }) # Optionally start new session with summary fresh_session = await agentbase.run_agent_async( message=f"""Continue project with this context: {summary.message} Next task: [describe next task]""", system="Previous conversation summary provided. Continue from this context." ) return fresh_session.session return session_id ``` ### Structured Context ```typescript TypeScript theme={null} // Use structured context for complex information interface ProjectContext { projectName: string; objectives: string[]; stakeholders: string[]; constraints: string[]; timeline: { start: string; deadline: string; milestones: Array<{ date: string; description: string }>; }; technicalStack: string[]; currentPhase: string; } async function runWithStructuredContext( context: ProjectContext, task: string ) { const result = await agentbase.runAgent({ message: `${task} PROJECT CONTEXT: ${JSON.stringify(context, null, 2)}`, system: `You are a project manager. Use the provided project context to inform your decisions and recommendations.` }); return result; } // Use with rich context const projectContext: ProjectContext = { projectName: "Customer Portal Redesign", objectives: [ "Improve user experience", "Reduce support tickets by 30%", "Increase customer satisfaction to 4.5/5" ], stakeholders: ["Product Team", "Engineering", "Customer Success", "Marketing"], constraints: [ "Budget: $150k", "Must maintain backward compatibility", "Cannot require user data migration" ], timeline: { start: "2024-01-01", deadline: "2024-06-30", milestones: [ { date: "2024-02-15", description: "Design approval" }, { date: "2024-04-30", description: "MVP complete" }, { date: "2024-06-15", description: "Beta testing" } ] }, technicalStack: ["React", "Node.js", "PostgreSQL", "AWS"], currentPhase: "Development" }; const result = await runWithStructuredContext( projectContext, "Create a risk assessment for the current project timeline" ); ``` ### Context Injection via System Prompt ```typescript TypeScript theme={null} // Inject persistent context via system prompt const 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 ``` ```python Python theme={null} # Inject persistent context via system prompt session_context = { 'company': 'TechCorp Inc.', 'industry': 'B2B SaaS', 'target_market': 'Small to medium businesses', 'key_products': ['ProjectHub', 'TeamSync', 'DataVault'], 'brand_voice': 'Professional, helpful, concise' } result = agentbase.run_agent( message="Draft a response to a customer asking about our pricing", system=f"""You are a customer success representative for {session_context['company']}. COMPANY CONTEXT: Industry: {session_context['industry']} Target Market: {session_context['target_market']} Products: {', '.join(session_context['key_products'])} COMMUNICATION GUIDELINES: Brand Voice: {session_context['brand_voice']} 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 ``` ## Use Cases ### 1. Long-Running Project Management Maintain context across weeks or months: ```typescript theme={null} class ProjectManager { private sessionId: string; private messageCount: number = 0; private summaries: Array<{ count: number; summary: string }> = []; async initialize(projectDetails: any) { const init = await agentbase.runAgent({ message: `Initialize project management for: ${JSON.stringify(projectDetails, null, 2)}`, system: "You are a project manager tracking a long-term software project." }); this.sessionId = init.session; return this.sessionId; } async addUpdate(update: string) { this.messageCount++; // Provide recent summary as context if available const recentSummary = this.summaries[this.summaries.length - 1]; const contextMessage = recentSummary ? `Previous summary (from message ${recentSummary.count}): ${recentSummary.summary} New update: ${update}` : update; const result = await agentbase.runAgent({ message: contextMessage, session: this.sessionId }); // Summarize every 25 messages if (this.messageCount % 25 === 0) { await this.createSummary(); } return result; } private async createSummary() { const summary = await agentbase.runAgent({ message: "Create a comprehensive project status summary", session: this.sessionId }); this.summaries.push({ count: this.messageCount, summary: summary.message }); } async getStatus() { return await agentbase.runAgent({ message: "Provide current project status, recent progress, and next steps", session: this.sessionId }); } } ``` ### 2. Customer Conversation Management Handle extended customer interactions: ```typescript theme={null} async function customerSupportWithContext(customerId: string) { // Load customer context const customer = await getCustomerData(customerId); // Create context-rich session const session = await agentbase.runAgent({ message: "Customer initiated support request", system: `You are a customer support agent. CUSTOMER CONTEXT: Name: ${customer.name} Account Type: ${customer.accountType} Member Since: ${customer.memberSince} Lifetime Value: $${customer.lifetimeValue} Support History: ${customer.supportTickets} previous tickets Recent Activity: ${customer.recentActivity} Current Issues: ${customer.openIssues.join(', ')} Provide personalized support based on their history and value. Reference their account type and previous interactions when relevant.` }); return { sessionId: session.session, handleMessage: async (message: string) => { return await agentbase.runAgent({ message, session: session.session // All customer context automatically maintained }); } }; } ``` ### 3. Research Compilation Accumulate research findings with context: ```typescript theme={null} 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; } ``` ### 4. Iterative Development with Context Maintain development context across iterations: ```typescript theme={null} 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; } ``` ### 5. Multi-Document Analysis Analyze multiple documents with shared context: ```typescript theme={null} 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; } ``` ### 6. Contextual Debugging Debug with full session context: ```typescript theme={null} 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; } ``` ## Best Practices ### Context Organization ```typescript theme={null} // Good: Structured, scannable context const message = `Task: Analyze Q4 sales data CONTEXT: Business Goals: - Identify top-performing products - Understand seasonal trends - Find underperforming regions Data Available: - sales_q4.csv (100,000 records) - Columns: date, product_id, region, quantity, revenue Previous Findings: - Q3 showed 15% growth - Mobile category outperformed desktop - West region lagging Constraints: - Focus on actionable insights - Highlight year-over-year comparisons`; // Avoid: Unstructured wall of text const 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..."; ``` ```typescript theme={null} // Provide recent context explicitly when important const 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 ``` ```typescript theme={null} // Create reference points for long conversations const checkpoint = await agentbase.runAgent({ message: "Create a checkpoint: summarize current state, decisions made, and next steps", session: sessionId }); // Later, reference the checkpoint await agentbase.runAgent({ message: `Referring to checkpoint from message #47: ${checkpoint.message} Now let's proceed with the next phase...`, session: sessionId }); ``` ### Context Optimization **Periodic Summarization**: For conversations exceeding 40-50 messages, consider creating summaries to maintain performance while preserving key information. ```typescript theme={null} // Instead of including entire documents const verboseContext = ` Full document text: [10,000 words]... `; // Provide extracted key points const optimizedContext = ` Document Summary: - Key Finding 1: Revenue increased 25% - Key Finding 2: Customer retention improved - Key Finding 3: New market opportunities in APAC - Recommendation: Expand sales team by Q2 - Risk: Supply chain constraints `; const result = await agentbase.runAgent({ message: `Based on this summary: ${optimizedContext} Create action plan...` }); ``` ```typescript theme={null} // Start fresh session when context becomes irrelevant if (contextNoLongerRelevant) { // Save important information const summary = await agentbase.runAgent({ message: "Summarize key decisions and outcomes", session: oldSessionId }); // Start fresh with just relevant context const newSession = await agentbase.runAgent({ message: `Starting new phase. Relevant context from previous phase: ${summary.message} Now focusing on: ${newTask}` }); return newSession.session; } ``` ### Context Handoff ```typescript theme={null} // When transferring between agents or sessions const handoffContext = await agentbase.runAgent({ message: "Prepare handoff summary including all critical information for next agent", session: currentSession }); // New agent gets explicit context const 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." }); ``` ## Integration with Other Primitives ### With Sessions Sessions are the container for context: ```typescript theme={null} // All context lives within a session const session1 = await agentbase.runAgent({ message: "Context A" }); // Session 1 has context A const session2 = await agentbase.runAgent({ message: "Context B" }); // Session 2 has completely separate context B // Context doesn't leak between sessions ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ### With States State persistence enables context continuity: ```typescript theme={null} // State makes context actionable const 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 }); ``` Learn more: [States Primitive](/primitives/essentials/states) ### With Prompts System prompts provide persistent context: ```typescript theme={null} // System prompt = persistent context throughout session const 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 }); ``` Learn more: [Prompts Primitive](/primitives/essentials/prompts) ### With Multi-Agent Context transfers between agents: ```typescript theme={null} // Context follows conversation through agent transfers const 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 }); ``` Learn more: [Multi-Agent Primitive](/primitives/essentials/multi-agents) ## Performance Considerations ### Context Window Size * **Small contexts** (\<10 messages): Optimal performance * **Medium contexts** (10-50 messages): Good performance * **Large contexts** (50-100 messages): Consider summarization * **Very large contexts** (100+ messages): Implement context optimization ### Optimization Strategies ```typescript theme={null} // Monitor conversation length class ContextMonitor { private messageCount = 0; async sendMessage(message: string, session: string) { this.messageCount++; // Warn at thresholds if (this.messageCount === 50) { console.warn('Consider summarizing conversation'); } if (this.messageCount >= 75) { // Auto-summarize return await this.summarizeAndContinue(session, message); } return await agentbase.runAgent({ message, session }); } private async summarizeAndContinue(session: string, newMessage: string) { const summary = await agentbase.runAgent({ message: "Concise summary of our conversation", session }); // Start fresh with summary const fresh = await agentbase.runAgent({ message: `Context: ${summary.message} New message: ${newMessage}` }); this.messageCount = 1; return fresh; } } ``` ### Memory vs. Performance Trade-offs Pros: Agent has all information Cons: Slower, higher costs Pros: Faster, lower costs Cons: May lose some detail ## Troubleshooting **Problem**: Agent doesn't remember earlier conversation **Solution**: Verify session continuity and explicitly reference important info ```typescript theme={null} // Ensure using same session const result = await agentbase.runAgent({ message: "Continue from earlier", session: sessionId // ✓ Same session }); // Explicitly reference important details const explicit = await agentbase.runAgent({ message: "As we discussed earlier about the Q4 deadline...", session: sessionId }); ``` **Problem**: Responses getting slower in long conversations **Solution**: Implement summarization ```typescript theme={null} if (messageCount > 50) { const summary = await agentbase.runAgent({ message: "Brief summary of key points", session: longSession }); // Start fresh session with summary const newSession = await agentbase.runAgent({ message: `Context: ${summary.message} Continuing with: ${nextTask}` }); } ``` **Problem**: Agent mixing up different topics or tasks **Solution**: Use structured context and clear delineation ```typescript theme={null} // Clear structure const result = await agentbase.runAgent({ message: `TOPIC: Customer Onboarding (not billing) SPECIFIC TASK: Create welcome email template CONTEXT: - Target audience: New enterprise customers - Tone: Professional, welcoming - Must include: Login link, support contact, video tutorial`, session: sessionId }); ``` ## Related Primitives Container for all conversation context Persistent state that forms part of context Persistent context via system prompts Context transfer between agents ## Additional Resources Retrieve conversation history Production patterns **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. # Custom Tools Source: https://docs.agentbase.sh/primitives/essentials/custom-tools Extend agent capabilities with custom tools via Model Context Protocol (MCP) > Custom tools allow agents to interact with your APIs, databases, and services seamlessly through the Model Context Protocol (MCP), enabling domain-specific capabilities beyond built-in tools. ## Overview The Custom Tools primitive extends agent capabilities by connecting external services, APIs, and databases through the Model Context Protocol (MCP). While agents come with powerful built-in tools for file operations, web browsing, and code execution, custom tools enable domain-specific functionality unique to your business needs. Custom tools are essential for: * **API Integration**: Connect agents to your internal and external APIs * **Database Access**: Query and manipulate data in your databases * **Business Logic**: Expose company-specific operations and workflows * **Third-Party Services**: Integrate with CRM, payment processors, analytics platforms * **Legacy Systems**: Bridge modern AI agents with existing infrastructure Built on the open Model Context Protocol standard for maximum compatibility and flexibility Agents automatically discover and use available tools based on task requirements Strongly-typed tool definitions ensure reliable agent-tool interactions Configure tools per-request for multi-tenant applications with different capabilities ## How Custom Tools Work When you provide MCP server configurations to an agent: 1. **Registration**: Agent connects to specified MCP servers and discovers available tools 2. **Tool Discovery**: Each MCP server exposes its tool catalog with descriptions and parameters 3. **Automatic Selection**: Agent evaluates available tools and selects appropriate ones for the task 4. **Execution**: Agent calls tools with proper parameters and receives structured responses 5. **Integration**: Tool results are incorporated into the agent's reasoning and response 6. **Error Handling**: Failed tool calls are handled gracefully with retry logic **Protocol Standard**: Agentbase implements the full Model Context Protocol specification. Learn more at [modelcontextprotocol.io](https://modelcontextprotocol.io) ## MCP Server Architecture ### Basic MCP Server Structure An MCP server exposes tools through HTTP endpoints: ```mermaid theme={null} graph LR A[Agent] -->|Tool Discovery| B[MCP Server] A -->|Tool Execution| B B -->|Available Tools| A B -->|Tool Results| A B -->|Query/Execute| C[Your API/Database] C -->|Results| B ``` ### MCP Server Requirements Your MCP server must provide: * **Tool Listing Endpoint**: Return available tools with descriptions and schemas * **Tool Execution Endpoint**: Execute specific tools with provided parameters * **Authentication Handling**: Support bearer tokens or OAuth for security * **Error Responses**: Return structured error messages for failed operations * **Type Definitions**: JSON Schema for parameters and return values ## Code Examples ### Basic Custom Tool Integration ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Connect to custom MCP server const result = await agentbase.runAgent({ message: "Get customer data for user ID 12345", mcpServers: [ { serverName: "customer-api", serverUrl: "https://api.yourcompany.com/mcp" } ] }); // Agent automatically discovers and uses available tools ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Connect to custom MCP server result = agentbase.run_agent( message="Get customer data for user ID 12345", mcp_servers=[ { "serverName": "customer-api", "serverUrl": "https://api.yourcompany.com/mcp" } ] ) # Agent automatically discovers and uses available tools ``` ```bash cURL theme={null} curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Get customer data for user ID 12345", "mcp_servers": [ { "serverName": "customer-api", "serverUrl": "https://api.yourcompany.com/mcp" } ] }' ``` ### Authentication with MCP Servers ```typescript TypeScript theme={null} // Bearer token authentication const resultBearer = await agentbase.runAgent({ message: "Fetch sales data", mcpServers: [ { serverName: "sales-api", serverUrl: "https://api.yourcompany.com/mcp", auth: { type: "bearer", token: process.env.API_TOKEN } } ] }); // OAuth authentication const resultOAuth = await agentbase.runAgent({ message: "Access user profile", mcpServers: [ { serverName: "user-service", serverUrl: "https://users.yourcompany.com/mcp", auth: { type: "oauth", oauth: { accessToken: process.env.OAUTH_ACCESS_TOKEN } } } ] }); ``` ```python Python theme={null} # Bearer token authentication result_bearer = agentbase.run_agent( message="Fetch sales data", mcp_servers=[ { "serverName": "sales-api", "serverUrl": "https://api.yourcompany.com/mcp", "auth": { "type": "bearer", "token": os.environ['API_TOKEN'] } } ] ) # OAuth authentication result_oauth = agentbase.run_agent( message="Access user profile", mcp_servers=[ { "serverName": "user-service", "serverUrl": "https://users.yourcompany.com/mcp", "auth": { "type": "oauth", "oauth": { "accessToken": os.environ['OAUTH_ACCESS_TOKEN'] } } } ] ) ``` ### Multiple MCP Servers ```typescript TypeScript theme={null} // Use multiple custom tools from different sources const result = await agentbase.runAgent({ message: "Create a customer order and charge their card", mcpServers: [ { serverName: "crm-tools", serverUrl: "https://crm.yourcompany.com/mcp", auth: { type: "bearer", token: process.env.CRM_TOKEN } }, { serverName: "payment-gateway", serverUrl: "https://payments.yourcompany.com/mcp", auth: { type: "bearer", token: process.env.PAYMENT_TOKEN } }, { serverName: "inventory-system", serverUrl: "https://inventory.yourcompany.com/mcp" } ] }); // Agent coordinates across multiple systems automatically ``` ```python Python theme={null} # Use multiple custom tools from different sources result = agentbase.run_agent( message="Create a customer order and charge their card", mcp_servers=[ { "serverName": "crm-tools", "serverUrl": "https://crm.yourcompany.com/mcp", "auth": { "type": "bearer", "token": os.environ['CRM_TOKEN'] } }, { "serverName": "payment-gateway", "serverUrl": "https://payments.yourcompany.com/mcp", "auth": { "type": "bearer", "token": os.environ['PAYMENT_TOKEN'] } }, { "serverName": "inventory-system", "serverUrl": "https://inventory.yourcompany.com/mcp" } ] ) # Agent coordinates across multiple systems automatically ``` ### Database Query Tools ```typescript TypeScript theme={null} // Predefined database queries as tools const result = await agentbase.runAgent({ message: "Show me all active users from California", datastores: [ { id: "ds_1234567890abcdef", name: "production-db" } ], queries: [ { name: "getUsersByState", description: "Fetch users filtered by state", query: "SELECT * FROM users WHERE state = ? AND status = 'active'" }, { name: "getUserById", description: "Fetch user details by their ID", query: "SELECT * FROM users WHERE id = ?" }, { name: "getOrderHistory", description: "Get order history for a specific user", query: "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC" } ] }); ``` ```python Python theme={null} # Predefined database queries as tools result = agentbase.run_agent( message="Show me all active users from California", datastores=[ { "id": "ds_1234567890abcdef", "name": "production-db" } ], queries=[ { "name": "getUsersByState", "description": "Fetch users filtered by state", "query": "SELECT * FROM users WHERE state = ? AND status = 'active'" }, { "name": "getUserById", "description": "Fetch user details by their ID", "query": "SELECT * FROM users WHERE id = ?" }, { "name": "getOrderHistory", "description": "Get order history for a specific user", "query": "SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC" } ] ) ``` ## Building an MCP Server ### MCP Server Implementation Here's a complete example of an MCP server implementation: ```typescript TypeScript (Express) theme={null} import express from 'express'; import { z } from 'zod'; const app = express(); app.use(express.json()); // Tool definitions const tools = [ { name: 'get_customer', description: 'Retrieve customer information by customer ID', inputSchema: { type: 'object', properties: { customer_id: { type: 'string', description: 'The unique customer identifier' } }, required: ['customer_id'] } }, { name: 'create_order', description: 'Create a new order for a customer', inputSchema: { type: 'object', properties: { customer_id: { type: 'string' }, items: { type: 'array', items: { type: 'object', properties: { product_id: { type: 'string' }, quantity: { type: 'number' } } } }, total_amount: { type: 'number' } }, required: ['customer_id', 'items', 'total_amount'] } } ]; // List available tools app.post('/mcp/tools/list', (req, res) => { res.json({ tools }); }); // Execute tool app.post('/mcp/tools/call', async (req, res) => { const { name, arguments: args } = req.body; try { switch (name) { case 'get_customer': const customer = await getCustomerFromDB(args.customer_id); res.json({ content: [{ type: 'text', text: JSON.stringify(customer) }] }); break; case 'create_order': const order = await createOrderInDB(args); res.json({ content: [{ type: 'text', text: JSON.stringify(order) }] }); break; default: res.status(404).json({ error: 'Tool not found' }); } } catch (error) { res.status(500).json({ error: error.message }); } }); // Authentication middleware app.use((req, res, next) => { const authHeader = req.headers.authorization; if (!authHeader || !authHeader.startsWith('Bearer ')) { return res.status(401).json({ error: 'Unauthorized' }); } // Verify token next(); }); app.listen(3000, () => { console.log('MCP server running on port 3000'); }); ``` ```python Python (FastAPI) theme={null} from fastapi import FastAPI, HTTPException, Header from pydantic import BaseModel from typing import List, Dict, Any app = FastAPI() # Tool definitions tools = [ { "name": "get_customer", "description": "Retrieve customer information by customer ID", "inputSchema": { "type": "object", "properties": { "customer_id": { "type": "string", "description": "The unique customer identifier" } }, "required": ["customer_id"] } }, { "name": "create_order", "description": "Create a new order for a customer", "inputSchema": { "type": "object", "properties": { "customer_id": {"type": "string"}, "items": { "type": "array", "items": { "type": "object", "properties": { "product_id": {"type": "string"}, "quantity": {"type": "number"} } } }, "total_amount": {"type": "number"} }, "required": ["customer_id", "items", "total_amount"] } } ] class ToolCallRequest(BaseModel): name: str arguments: Dict[str, Any] # List available tools @app.post("/mcp/tools/list") async def list_tools(): return {"tools": tools} # Execute tool @app.post("/mcp/tools/call") async def call_tool(request: ToolCallRequest, authorization: str = Header(None)): if not authorization or not authorization.startswith("Bearer "): raise HTTPException(status_code=401, detail="Unauthorized") try: if request.name == "get_customer": customer = await get_customer_from_db(request.arguments["customer_id"]) return {"content": [{"type": "text", "text": str(customer)}]} elif request.name == "create_order": order = await create_order_in_db(request.arguments) return {"content": [{"type": "text", "text": str(order)}]} else: raise HTTPException(status_code=404, detail="Tool not found") except Exception as e: raise HTTPException(status_code=500, detail=str(e)) ``` ### Tool Schema Best Practices ```json theme={null} { "name": "search_products", "description": "Search the product catalog with filters. Returns products matching all specified criteria including name, category, price range, and availability status.", "inputSchema": { "type": "object", "properties": { "query": { "type": "string", "description": "Search terms to match against product names and descriptions" }, "category": { "type": "string", "description": "Product category to filter by (e.g., 'electronics', 'clothing')" }, "max_price": { "type": "number", "description": "Maximum price in USD" } } } } ``` ```json theme={null} { "name": "create_user", "inputSchema": { "type": "object", "properties": { "email": { "type": "string", "format": "email", "description": "User's email address (must be valid email format)" }, "age": { "type": "integer", "minimum": 18, "maximum": 120, "description": "User's age (must be 18 or older)" }, "role": { "type": "string", "enum": ["admin", "user", "guest"], "description": "User role in the system" } }, "required": ["email", "role"] } } ``` ```json theme={null} { "name": "calculate_shipping", "description": "Calculate shipping cost and estimated delivery date", "inputSchema": { /* ... */ }, "outputSchema": { "type": "object", "properties": { "cost": { "type": "number", "description": "Shipping cost in USD" }, "currency": { "type": "string", "description": "Currency code (always USD)" }, "estimated_days": { "type": "integer", "description": "Estimated delivery time in business days" }, "carrier": { "type": "string", "description": "Shipping carrier name" } } } } ``` ## Use Cases ### 1. CRM Integration Connect agents to customer relationship management systems: ```typescript theme={null} const crmTools = await agentbase.runAgent({ message: "Find all high-value customers who haven't been contacted in 30 days", mcpServers: [ { serverName: "salesforce-mcp", serverUrl: "https://mcp.yourcompany.com/salesforce", auth: { type: "oauth", oauth: { accessToken: salesforceToken } } } ], system: "You are a sales assistant. Use CRM tools to find and prioritize customer outreach opportunities." }); // Agent uses tools like: // - search_customers(filters) // - get_customer_interactions(customer_id) // - get_customer_value(customer_id) // - create_task(customer_id, description) ``` ### 2. E-Commerce Operations Automate order processing and inventory management: ```typescript theme={null} const ecommerce = await agentbase.runAgent({ message: "Process pending orders and update inventory", mcpServers: [ { serverName: "shopify-integration", serverUrl: "https://mcp.yourcompany.com/shopify" }, { serverName: "inventory-system", serverUrl: "https://mcp.yourcompany.com/inventory" } ] }); // Available tools: // - get_pending_orders() // - process_order(order_id) // - check_inventory(product_id) // - update_stock(product_id, quantity) // - send_shipping_notification(order_id) ``` ### 3. Financial Analysis Query financial databases and perform calculations: ```typescript theme={null} const financial = await agentbase.runAgent({ message: "Calculate Q4 revenue by region and compare to last year", datastores: [ { id: "ds_financial_db", name: "financial-data" } ], queries: [ { name: "getRevenueByRegion", description: "Get total revenue for a specific region and time period", query: `SELECT region, SUM(amount) as total_revenue FROM transactions WHERE date BETWEEN ? AND ? AND region = ? GROUP BY region` }, { name: "getYearOverYearGrowth", description: "Calculate year-over-year revenue growth", query: `SELECT current.region, current.revenue as current_revenue, previous.revenue as previous_revenue, ((current.revenue - previous.revenue) / previous.revenue * 100) as growth_pct FROM revenue_summary current JOIN revenue_summary previous ON current.region = previous.region WHERE current.year = ? AND previous.year = ?` } ] }); ``` ### 4. DevOps Automation Integrate with infrastructure and deployment tools: ```typescript theme={null} const devops = await agentbase.runAgent({ message: "Check production health and scale if needed", mcpServers: [ { serverName: "kubernetes-api", serverUrl: "https://mcp.yourcompany.com/k8s", auth: { type: "bearer", token: k8sToken } }, { serverName: "monitoring-tools", serverUrl: "https://mcp.yourcompany.com/monitoring" } ] }); // Tools available: // - get_pod_metrics(namespace, pod_name) // - scale_deployment(deployment, replicas) // - get_alerts(severity) // - check_service_health(service_name) // - restart_pod(pod_name) ``` ### 5. Support Ticket Management Automate customer support workflows: ```typescript theme={null} const support = await agentbase.runAgent({ message: "Analyze open support tickets and prioritize urgent issues", mcpServers: [ { serverName: "zendesk-integration", serverUrl: "https://mcp.yourcompany.com/zendesk" }, { serverName: "customer-db", serverUrl: "https://mcp.yourcompany.com/customers" } ] }); // Available tools: // - get_open_tickets(status, priority) // - get_ticket_details(ticket_id) // - update_ticket(ticket_id, fields) // - get_customer_tier(customer_id) // - create_internal_note(ticket_id, note) // - escalate_ticket(ticket_id, reason) ``` ### 6. Content Management Integrate with CMS and publishing platforms: ```typescript theme={null} const cms = await agentbase.runAgent({ message: "Publish the blog post draft and schedule social media posts", mcpServers: [ { serverName: "wordpress-api", serverUrl: "https://mcp.yourcompany.com/wordpress" }, { serverName: "social-media", serverUrl: "https://mcp.yourcompany.com/social" } ] }); // Tools: // - create_post(title, content, category) // - upload_media(file, alt_text) // - schedule_post(post_id, publish_date) // - create_social_post(platform, content, schedule) ``` ## Best Practices ### Tool Design ```json theme={null} // Good: Focused, single-purpose tools { "name": "get_customer", "description": "Retrieve customer details by ID" } { "name": "update_customer_email", "description": "Update a customer's email address" } // Avoid: Kitchen-sink tools doing too much { "name": "manage_customer", "description": "Get, create, update, or delete customers" } ``` ```json theme={null} // Good: Clear, descriptive names "get_order_by_id" "calculate_shipping_cost" "send_password_reset_email" // Avoid: Vague or unclear names "fetch_data" "do_calculation" "send_email" ``` ```typescript theme={null} // Design tools to be safely repeatable { name: "create_or_update_user", description: "Create user if not exists, update if exists (idempotent)", // Uses upsert pattern } // Or provide clear state-checking tools { name: "user_exists", description: "Check if user exists" } { name: "create_user", description: "Create new user (fails if exists)" } ``` ```typescript theme={null} // Return structured errors { "error": { "code": "CUSTOMER_NOT_FOUND", "message": "No customer found with ID: 12345", "details": { "customer_id": "12345", "suggestion": "Verify the customer ID and try again" } } } // Not just generic errors { "error": "An error occurred" } ``` ### Security **Authentication Required**: Always implement authentication on MCP servers. Never expose tools publicly without proper security measures. ```typescript theme={null} // Good: Per-user authentication with scoped access const result = await agentbase.runAgent({ message: "Get my account details", mcpServers: [ { serverName: "user-api", serverUrl: "https://api.yourcompany.com/mcp", auth: { type: "bearer", token: userSpecificToken // User-scoped token } } ] }); // Server validates token and returns only user's data ``` ```typescript theme={null} // Always validate and sanitize inputs app.post('/mcp/tools/call', async (req, res) => { const { name, arguments: args } = req.body; // Validate input if (name === 'get_customer') { if (!args.customer_id || typeof args.customer_id !== 'string') { return res.status(400).json({ error: 'Invalid customer_id parameter' }); } // Sanitize input to prevent SQL injection const customerId = sanitize(args.customer_id); const customer = await db.query( 'SELECT * FROM customers WHERE id = ?', [customerId] // Parameterized query ); res.json({ content: [{ type: 'text', text: JSON.stringify(customer) }] }); } }); ``` ```typescript theme={null} import rateLimit from 'express-rate-limit'; // Implement rate limiting on MCP endpoints const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, // Limit each token to 100 requests per windowMs message: 'Too many requests, please try again later' }); app.use('/mcp', limiter); ``` ```typescript theme={null} // Log all tool executions for audit trail app.post('/mcp/tools/call', async (req, res) => { const { name, arguments: args } = req.body; const userId = extractUserFromToken(req.headers.authorization); // Log the request await auditLog.create({ userId, toolName: name, parameters: args, timestamp: new Date(), ipAddress: req.ip }); // Execute tool... }); ``` ### Performance Cache frequently accessed data to reduce load on backend systems Return paginated results for large datasets instead of everything at once Use async patterns for long-running operations with status checking Reuse database connections instead of creating new ones per request ```typescript theme={null} // Implement caching for expensive operations import NodeCache from 'node-cache'; const cache = new NodeCache({ stdTTL: 300 }); // 5 minute TTL app.post('/mcp/tools/call', async (req, res) => { const { name, arguments: args } = req.body; if (name === 'get_product_catalog') { // Check cache first const cacheKey = `catalog_${args.category}`; const cached = cache.get(cacheKey); if (cached) { return res.json({ content: [{ type: 'text', text: cached }] }); } // Fetch from database const catalog = await getProductCatalog(args.category); // Store in cache cache.set(cacheKey, JSON.stringify(catalog)); res.json({ content: [{ type: 'text', text: JSON.stringify(catalog) }] }); } }); ``` ## Integration with Other Primitives ### With Prompts Guide agents on when and how to use custom tools: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Help customer with order status", system: `You are a customer support agent. When helping with orders: 1. Use get_order_status tool to check current status 2. Use get_tracking_info if order is shipped 3. Use estimate_delivery for pending orders 4. Always provide tracking numbers when available`, mcpServers: [ { serverName: "order-tools", serverUrl: "https://api.yourcompany.com/mcp" } ] }); ``` Learn more: [Prompts Primitive](/primitives/essentials/prompts) ### With Rules Enforce constraints on tool usage: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Update customer record", mcpServers: [ { serverName: "customer-api", serverUrl: "https://api.yourcompany.com/mcp" } ], rules: [ "Always verify customer identity before accessing account data", "Never update payment information without explicit customer confirmation", "Log all customer data access for audit purposes" ] }); ``` Learn more: [Rules](/build/rules) ### With Multi-Agent Systems Different agents with different tool access: ```typescript theme={null} const result = await agentbase.runAgent({ message: "I need help", system: "You are a routing agent. Transfer to appropriate specialist.", agents: [ { name: "Order Support", description: "Handles order-related questions", // Order support agent gets order tools }, { name: "Technical Support", description: "Handles technical issues", // Technical support gets different tools } ] }); ``` Learn more: [Multi-Agent Primitive](/primitives/essentials/multi-agents) ### With Datastores Combine database access with custom business logic: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Generate sales report and email to team", datastores: [ { id: "ds_sales_db", name: "sales-data" } ], queries: [ { name: "getSalesData", description: "Get sales for date range", query: "SELECT * FROM sales WHERE date BETWEEN ? AND ?" } ], mcpServers: [ { serverName: "email-service", serverUrl: "https://api.yourcompany.com/email" } ] }); // Agent can query database AND send emails ``` ## Performance Considerations ### Tool Discovery Overhead * **First Request**: Agent discovers all available tools (\~100-500ms) * **Subsequent Requests**: Tool catalog cached within session * **Optimization**: Minimize number of MCP servers when possible ```typescript theme={null} // Efficient: One MCP server with all related tools mcpServers: [ { serverName: "crm-suite", serverUrl: "https://api.company.com/mcp" // Contains: customer tools, order tools, analytics tools } ] // Less efficient: Multiple servers for related functionality mcpServers: [ { serverName: "customers", serverUrl: "https://api.company.com/customers" }, { serverName: "orders", serverUrl: "https://api.company.com/orders" }, { serverName: "analytics", serverUrl: "https://api.company.com/analytics" } ] ``` ### Tool Execution Time Monitor and optimize tool response times: ```typescript theme={null} // Add timeout handling app.post('/mcp/tools/call', async (req, res) => { const timeout = setTimeout(() => { res.status(408).json({ error: 'Tool execution timeout', message: 'Operation took longer than 30 seconds' }); }, 30000); try { const result = await executeTool(req.body); clearTimeout(timeout); res.json(result); } catch (error) { clearTimeout(timeout); res.status(500).json({ error: error.message }); } }); ``` ### Network Latency **Co-location**: Deploy MCP servers in the same region as Agentbase for lowest latency. Cross-region calls can add 50-200ms per tool execution. ## Troubleshooting **Problem**: Agent doesn't call your custom tools **Solutions**: * Improve tool descriptions to be more specific * Add guidance in system prompt about when to use tools * Verify MCP server is accessible and returning tool list * Check authentication is configured correctly * Ensure tool parameters match task requirements ```typescript theme={null} // Add explicit guidance system: `You are a customer service agent. Available tools: - get_customer(id): Always use this to fetch customer details - get_order(id): Use this to check order status - create_ticket(details): Use this to escalate issues Always retrieve customer information before helping them.` ``` **Problem**: Tools returning 401/403 errors **Solutions**: * Verify auth token is valid and not expired * Check token has required permissions * Ensure auth type matches server expectations * Test authentication with direct API call ```typescript theme={null} // Debug authentication const result = await agentbase.runAgent({ message: "Test connection", mcpServers: [ { serverName: "test", serverUrl: "https://api.company.com/mcp", auth: { type: "bearer", token: testToken } } ] }); // Check agent_tool_response events for auth errors ``` **Problem**: Tools taking too long to execute **Solutions**: * Add caching for frequently accessed data * Optimize database queries * Implement pagination for large datasets * Use connection pooling * Consider async operations for long tasks ```typescript theme={null} // Monitor tool performance app.post('/mcp/tools/call', async (req, res) => { const start = Date.now(); const result = await executeTool(req.body); const duration = Date.now() - start; console.log(`Tool ${req.body.name} executed in ${duration}ms`); if (duration > 5000) { console.warn('Slow tool execution detected'); } res.json(result); }); ``` **Problem**: Agent gets confused by tool errors **Solutions**: * Return structured error messages * Include helpful error codes * Provide suggested fixes in error response * Document error scenarios in tool description ```typescript theme={null} // Return helpful errors if (!customer) { return res.json({ content: [{ type: 'text', text: JSON.stringify({ error: { code: 'CUSTOMER_NOT_FOUND', message: `No customer found with ID: ${customerId}`, suggestion: 'Verify the customer ID or search by email instead', available_actions: ['search_customer_by_email', 'list_recent_customers'] } }) }] }); } ``` ## Related Primitives Guide agents on when and how to use tools Enforce constraints on tool usage Give different agents different tool access Database integration for custom queries ## Additional Resources Official Model Context Protocol documentation Complete MCP server configuration options Learn about Agentbase's built-in tools **Remember**: Custom tools are most powerful when they expose domain-specific operations that agents can't accomplish with built-in tools alone. Focus on business logic unique to your application. # Hooks Source: https://docs.agentbase.sh/primitives/essentials/hooks Lifecycle callbacks and event handlers for agent execution monitoring and custom logic > Hooks provide lifecycle callbacks that let you execute custom logic at key points during agent execution, enabling monitoring, logging, validation, and integration with external systems. ## Overview The Hooks primitive allows you to attach custom code to specific events in the agent lifecycle. Like React hooks or Git hooks, agent hooks let you intercept execution at critical moments to add custom behavior, logging, validation, or integration logic. Hooks are essential for: * **Execution Monitoring**: Track agent activity in real-time * **Custom Logging**: Send execution data to your logging infrastructure * **Validation**: Verify inputs and outputs meet your requirements * **Error Handling**: Implement custom error recovery logic * **Metrics Collection**: Track performance and usage metrics * **External Integration**: Sync agent activity with other systems Hook into all major agent lifecycle events from start to completion Hooks can execute async operations without blocking agent execution Hook failures don't crash agent execution - they're logged and isolated Integrate with any logging, monitoring, or analytics platform ## How Hooks Work ### Available Hooks Hooks are triggered at specific points in the agent lifecycle: 1. **`onStart`**: Agent execution begins 2. **`onThinking`**: Agent is reasoning about the task 3. **`onToolUse`**: Agent calls a tool 4. **`onToolResponse`**: Tool returns a response 5. **`onProgress`**: Progress update (background tasks) 6. **`onStep`**: Agent completes a step 7. **`onComplete`**: Agent execution completes successfully 8. **`onError`**: Error occurs during execution 9. **`onCancel`**: Execution is cancelled ### Hook Execution Hooks execute asynchronously: 1. **Event Occurs**: Agent lifecycle event happens 2. **Hook Triggered**: Registered hook function is called 3. **Async Execution**: Hook executes (can be async) 4. **Error Handling**: Hook errors are caught and logged 5. **Continuation**: Agent execution continues regardless of hook result **Non-Blocking**: Hooks execute asynchronously and don't block agent execution. Hook failures are logged but don't stop the agent. ## Code Examples ### Basic Hooks ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Define hooks const result = await agentbase.runAgent({ message: "Analyze sales data", hooks: { onStart: async (event) => { console.log('Agent started:', event.timestamp); await logToDatabase('agent_start', event); }, onToolUse: async (event) => { console.log(`Tool called: ${event.tool}`); console.log('Input:', event.input); }, onToolResponse: async (event) => { console.log(`Tool response: ${event.tool}`); console.log('Output:', event.response); }, onComplete: async (event) => { console.log('Agent completed:', event.message); await sendNotification('Task complete', event.message); }, onError: async (event) => { console.error('Error occurred:', event.error); await sendAlert('Agent error', event.error); } } }); ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Define hooks async def on_start(event): print(f"Agent started: {event.timestamp}") await log_to_database('agent_start', event) async def on_tool_use(event): print(f"Tool called: {event.tool}") print(f"Input: {event.input}") async def on_tool_response(event): print(f"Tool response: {event.tool}") print(f"Output: {event.response}") async def on_complete(event): print(f"Agent completed: {event.message}") await send_notification('Task complete', event.message) async def on_error(event): print(f"Error occurred: {event.error}") await send_alert('Agent error', event.error) # Use hooks result = agentbase.run_agent( message="Analyze sales data", hooks={ 'on_start': on_start, 'on_tool_use': on_tool_use, 'on_tool_response': on_tool_response, 'on_complete': on_complete, 'on_error': on_error } ) ``` ### Logging Hook ```typescript TypeScript theme={null} // Comprehensive logging hook class AgentLogger { private sessionId: string; private startTime: number; constructor(sessionId: string) { this.sessionId = sessionId; this.startTime = Date.now(); } createHooks() { return { onStart: async (event: any) => { await this.log('start', { message: event.message, mode: event.mode, timestamp: event.timestamp }); }, onThinking: async (event: any) => { await this.log('thinking', { content: event.content, duration: Date.now() - this.startTime }); }, onToolUse: async (event: any) => { await this.log('tool_use', { tool: event.tool, input: event.input, timestamp: event.timestamp }); }, onToolResponse: async (event: any) => { await this.log('tool_response', { tool: event.tool, response: event.response, duration: event.duration }); }, onStep: async (event: any) => { await this.log('step_complete', { stepNumber: event.stepNumber, totalTime: Date.now() - this.startTime }); }, onComplete: async (event: any) => { await this.log('complete', { message: event.message, totalDuration: Date.now() - this.startTime, success: true }); }, onError: async (event: any) => { await this.log('error', { error: event.error, step: event.step, severity: 'high' }); } }; } async log(eventType: string, data: any) { await sendToLoggingService({ sessionId: this.sessionId, eventType, data, timestamp: new Date() }); } } // Usage const logger = new AgentLogger(sessionId); const result = await agentbase.runAgent({ message: "Process customer data", session: sessionId, hooks: logger.createHooks() }); ``` ```python Python theme={null} # Comprehensive logging hook class AgentLogger: def __init__(self, session_id: str): self.session_id = session_id self.start_time = time.time() def create_hooks(self): return { 'on_start': self.on_start, 'on_thinking': self.on_thinking, 'on_tool_use': self.on_tool_use, 'on_tool_response': self.on_tool_response, 'on_step': self.on_step, 'on_complete': self.on_complete, 'on_error': self.on_error } async def on_start(self, event): await self.log('start', { 'message': event.message, 'mode': event.mode, 'timestamp': event.timestamp }) async def on_thinking(self, event): await self.log('thinking', { 'content': event.content, 'duration': time.time() - self.start_time }) async def on_tool_use(self, event): await self.log('tool_use', { 'tool': event.tool, 'input': event.input, 'timestamp': event.timestamp }) async def on_tool_response(self, event): await self.log('tool_response', { 'tool': event.tool, 'response': event.response, 'duration': event.duration }) async def on_step(self, event): await self.log('step_complete', { 'step_number': event.step_number, 'total_time': time.time() - self.start_time }) async def on_complete(self, event): await self.log('complete', { 'message': event.message, 'total_duration': time.time() - self.start_time, 'success': True }) async def on_error(self, event): await self.log('error', { 'error': event.error, 'step': event.step, 'severity': 'high' }) async def log(self, event_type: str, data: dict): await send_to_logging_service({ 'session_id': self.session_id, 'event_type': event_type, 'data': data, 'timestamp': datetime.now() }) # Usage logger = AgentLogger(session_id) result = agentbase.run_agent( message="Process customer data", session=session_id, hooks=logger.create_hooks() ) ``` ### Metrics Collection Hook ```typescript TypeScript theme={null} // Collect and send metrics class MetricsCollector { private metrics: Map = new Map(); createHooks() { return { onStart: async () => { this.metrics.set('startTime', Date.now()); await this.increment('agent.executions'); }, onToolUse: async (event: any) => { await this.increment(`tools.${event.tool}.calls`); }, onToolResponse: async (event: any) => { await this.timing(`tools.${event.tool}.duration`, event.duration); }, onStep: async (event: any) => { await this.increment('agent.steps'); const currentStep = this.metrics.get('stepCount') || 0; this.metrics.set('stepCount', currentStep + 1); }, onComplete: async (event: any) => { const startTime = this.metrics.get('startTime'); const duration = Date.now() - startTime; await this.timing('agent.execution.duration', duration); await this.increment('agent.executions.success'); await this.gauge('agent.steps.total', this.metrics.get('stepCount')); }, onError: async (event: any) => { await this.increment('agent.executions.error'); await this.increment(`agent.errors.${event.errorType}`); } }; } async increment(metric: string, value: number = 1) { await sendMetric({ type: 'increment', metric, value }); } async timing(metric: string, value: number) { await sendMetric({ type: 'timing', metric, value }); } async gauge(metric: string, value: number) { await sendMetric({ type: 'gauge', metric, value }); } } // Usage const metrics = new MetricsCollector(); const result = await agentbase.runAgent({ message: "Generate report", hooks: metrics.createHooks() }); ``` ### Validation Hook ```typescript TypeScript theme={null} // Validate inputs and outputs const validationHooks = { onStart: async (event: any) => { // Validate input message if (!event.message || event.message.length < 10) { throw new Error('Message too short'); } // Check for prohibited content const prohibited = ['password', 'secret', 'api_key']; if (prohibited.some(word => event.message.toLowerCase().includes(word))) { throw new Error('Message contains prohibited content'); } }, onToolUse: async (event: any) => { // Validate tool parameters if (event.tool === 'database_query') { if (!event.input.query) { throw new Error('Database query missing'); } // Check for dangerous SQL const dangerous = ['DROP', 'DELETE', 'TRUNCATE']; if (dangerous.some(cmd => event.input.query.includes(cmd))) { throw new Error('Dangerous SQL operation detected'); } } }, onComplete: async (event: any) => { // Validate output if (!event.message || event.message.length === 0) { console.warn('Empty response generated'); } // Check output length if (event.message.length > 10000) { console.warn('Response exceeds recommended length'); } } }; const result = await agentbase.runAgent({ message: "Query user database", hooks: validationHooks }); ``` ### External Integration Hook ```typescript TypeScript theme={null} // Integrate with external systems class ExternalIntegration { createHooks() { return { onStart: async (event: any) => { // Create ticket in project management system const ticket = await createJiraTicket({ title: `Agent Task: ${event.message}`, status: 'in_progress', assignee: 'agent-system' }); // Store ticket ID for later updates this.ticketId = ticket.id; }, onProgress: async (event: any) => { // Update ticket with progress await updateJiraTicket(this.ticketId, { progress: event.progress, comment: `Progress: ${event.progress}%` }); }, onComplete: async (event: any) => { // Mark ticket as complete await updateJiraTicket(this.ticketId, { status: 'done', resolution: event.message }); // Send to Slack await sendSlackMessage({ channel: '#agent-completions', text: `Task completed: ${event.message.substring(0, 100)}...` }); // Update CRM await updateCRM({ activityType: 'agent_task', outcome: 'success', details: event.message }); }, onError: async (event: any) => { // Update ticket with error await updateJiraTicket(this.ticketId, { status: 'failed', error: event.error }); // Alert in Slack await sendSlackMessage({ channel: '#agent-errors', text: `⚠️ Agent task failed: ${event.error}`, priority: 'high' }); // Create PagerDuty incident await createPagerDutyIncident({ title: 'Agent Task Failure', description: event.error, severity: 'high' }); } }; } } ``` ## Use Cases ### 1. Production Monitoring Monitor agent health and performance: ```typescript theme={null} // Stream metrics to monitoring dashboard const monitoringHooks = { onStart: async (event) => { await metrics.increment('agent.starts'); await dashboard.updateStatus('running'); }, onThinking: async (event) => { await dashboard.updateActivity('thinking', event.content); }, onToolUse: async (event) => { await dashboard.addToolCall(event.tool, event.input); await metrics.increment(`tools.${event.tool}`); }, onStep: async (event) => { await dashboard.updateProgress(event.stepNumber); }, onComplete: async (event) => { await metrics.increment('agent.completions'); await dashboard.updateStatus('complete'); await dashboard.setResult(event.message); }, onError: async (event) => { await metrics.increment('agent.errors'); await dashboard.updateStatus('error', event.error); await alerting.sendAlert('Agent error', event); } }; const result = await agentbase.runAgent({ message: userRequest, hooks: monitoringHooks }); ``` ```typescript theme={null} // Track detailed performance metrics class PerformanceTracker { private timings: Map = new Map(); createHooks() { return { onStart: () => { this.timings.set('start', Date.now()); }, onToolUse: (event) => { this.timings.set(`tool_${event.tool}_start`, Date.now()); }, onToolResponse: (event) => { const startKey = `tool_${event.tool}_start`; const start = this.timings.get(startKey); const duration = Date.now() - start; analytics.trackToolPerformance({ tool: event.tool, duration, success: !event.error }); }, onComplete: (event) => { const totalDuration = Date.now() - this.timings.get('start'); analytics.trackExecution({ duration: totalDuration, steps: event.stepCount, success: true, averageStepDuration: totalDuration / event.stepCount }); } }; } } ``` ### 2. Audit Logging Maintain detailed audit trails: ```typescript theme={null} // Comprehensive audit logging class AuditLogger { async createHooks(userId: string, requestId: string) { return { onStart: async (event) => { await auditLog.record({ requestId, userId, action: 'agent_start', message: event.message, timestamp: new Date(), ip: event.ip, userAgent: event.userAgent }); }, onToolUse: async (event) => { await auditLog.record({ requestId, userId, action: 'tool_call', tool: event.tool, input: sanitize(event.input), // Remove sensitive data timestamp: new Date() }); }, onComplete: async (event) => { await auditLog.record({ requestId, userId, action: 'agent_complete', result: truncate(event.message, 1000), duration: event.duration, timestamp: new Date() }); }, onError: async (event) => { await auditLog.record({ requestId, userId, action: 'agent_error', error: event.error, severity: 'error', timestamp: new Date() }); } }; } } ``` ### 3. Cost Tracking Track and control costs: ```typescript theme={null} // Monitor and limit costs class CostController { private totalCost: number = 0; private costLimit: number; constructor(costLimit: number) { this.costLimit = costLimit; } createHooks() { return { onToolUse: async (event) => { // Estimate tool cost const estimatedCost = this.estimateToolCost(event.tool, event.input); if (this.totalCost + estimatedCost > this.costLimit) { throw new Error(`Cost limit exceeded: ${this.costLimit}`); } }, onStep: async (event) => { // Track actual cost if (event.cost) { this.totalCost += event.cost; await costTracking.record({ step: event.stepNumber, cost: event.cost, cumulative: this.totalCost }); if (this.totalCost > this.costLimit * 0.9) { await alerting.warn(`Approaching cost limit: ${this.totalCost}/${this.costLimit}`); } } }, onComplete: async (event) => { await costTracking.recordTotal({ requestId: event.requestId, totalCost: this.totalCost, steps: event.stepCount, avgCostPerStep: this.totalCost / event.stepCount }); } }; } estimateToolCost(tool: string, input: any): number { // Estimate based on tool and input size const baseCosts = { 'web_search': 0.01, 'database_query': 0.005, 'api_call': 0.002 }; return baseCosts[tool] || 0.001; } } ``` ### 4. Security and Compliance Enforce security policies: ```typescript theme={null} // Security monitoring and enforcement const securityHooks = { onStart: async (event) => { // Check user permissions const hasPermission = await checkPermission(event.userId, 'use_agent'); if (!hasPermission) { throw new Error('Unauthorized'); } // Log access await securityLog.record({ userId: event.userId, action: 'agent_access', resource: event.agentId, timestamp: new Date() }); }, onToolUse: async (event) => { // Check tool permissions const canUseTool = await checkToolPermission(event.userId, event.tool); if (!canUseTool) { throw new Error(`Unauthorized to use tool: ${event.tool}`); } // Scan for sensitive data if (containsPII(event.input)) { await securityLog.warn({ userId: event.userId, issue: 'PII detected in tool input', tool: event.tool, timestamp: new Date() }); } }, onComplete: async (event) => { // Scan output for sensitive data const sensitiveData = scanForSensitiveData(event.message); if (sensitiveData.length > 0) { await securityLog.alert({ issue: 'Sensitive data in output', types: sensitiveData, redact: true }); // Redact sensitive data event.message = redactSensitiveData(event.message, sensitiveData); } } }; ``` ### 5. User Experience Enhancement Improve user experience with real-time updates: ```typescript theme={null} // Real-time UI updates class UIUpdateHooks { constructor(private websocket: WebSocket) {} createHooks() { return { onStart: async () => { this.websocket.send(JSON.stringify({ type: 'status', status: 'processing', message: 'Agent is working on your request...' })); }, onThinking: async (event) => { this.websocket.send(JSON.stringify({ type: 'thinking', content: event.content, showToUser: true })); }, onToolUse: async (event) => { this.websocket.send(JSON.stringify({ type: 'activity', message: `Using ${event.tool}...`, icon: getToolIcon(event.tool) })); }, onProgress: async (event) => { this.websocket.send(JSON.stringify({ type: 'progress', progress: event.progress, message: `${event.progress}% complete` })); }, onStep: async (event) => { this.websocket.send(JSON.stringify({ type: 'step', stepNumber: event.stepNumber, message: `Completed step ${event.stepNumber}` })); }, onComplete: async (event) => { this.websocket.send(JSON.stringify({ type: 'complete', message: event.message, success: true })); }, onError: async (event) => { this.websocket.send(JSON.stringify({ type: 'error', error: event.error, userMessage: 'Something went wrong. Please try again.' })); } }; } } ``` ## Best Practices ### Hook Design ```typescript theme={null} // Good: Quick logging, async operations const hooks = { onToolUse: async (event) => { // Fire and forget - don't await sendToLoggingService(event).catch(console.error); } }; // Avoid: Slow synchronous operations const slowHooks = { onToolUse: async (event) => { // Bad: Blocks execution await heavyProcessing(event); } }; ``` ```typescript theme={null} // Robust error handling in hooks const hooks = { onComplete: async (event) => { try { await sendNotification(event); } catch (error) { // Log but don't throw - hook failures shouldn't break agent console.error('Notification failed:', error); await logHookError('onComplete', error); } } }; ``` ```typescript theme={null} // Good: Read-only hooks const hooks = { onToolUse: async (event) => { // Just observe, don't modify await logToolUsage(event); } }; // Avoid: Modifying event data const badHooks = { onToolUse: async (event) => { // Don't do this - can cause unexpected behavior event.input = modifyInput(event.input); } }; ``` ### Performance Optimization ```typescript theme={null} // Optimize hook performance class OptimizedHooks { private buffer: any[] = []; private flushInterval: NodeJS.Timeout; constructor() { // Batch logging for efficiency this.flushInterval = setInterval(() => { this.flush(); }, 5000); // Flush every 5 seconds } createHooks() { return { onToolUse: (event) => { // Buffer events instead of sending immediately this.buffer.push({ type: 'tool_use', data: event, timestamp: Date.now() }); // Flush if buffer gets too large if (this.buffer.length >= 100) { this.flush(); } } }; } async flush() { if (this.buffer.length === 0) return; const events = [...this.buffer]; this.buffer = []; // Send batch await sendBatchToLogging(events).catch(console.error); } cleanup() { clearInterval(this.flushInterval); this.flush(); } } ``` ## Integration with Other Primitives ### With Traces Hooks complement traces by adding custom logic: ```typescript theme={null} // Combine hooks with traces const result = await agentbase.runAgent({ message: "Process data", stream: true, // Get trace events hooks: { onToolUse: async (event) => { // Custom logic triggered by trace events await customToolAnalysis(event); } } }); // Process both streams for await (const event of result) { // Trace events flow through here // Hooks are called automatically } ``` Learn more: [Traces Primitive](/primitives/essentials/traces) ### With Background Tasks Monitor long-running background tasks: ```typescript theme={null} const task = await agentbase.runAgent({ message: "Long-running analysis", background: true, hooks: { onProgress: async (event) => { // Update UI with progress await updateTaskProgress(taskId, event.progress); }, onComplete: async (event) => { // Notify when complete await sendEmail('Task complete', event.message); } } }); ``` Learn more: [Background Tasks Primitive](/primitives/essentials/background) ### With Evals Add custom validation in evals: ```typescript theme={null} // Validation hooks for evals await runEvals({ testCases, hooks: { onComplete: async (event) => { // Custom validation logic const valid = await customValidation(event.message); if (!valid) { throw new Error('Custom validation failed'); } } } }); ``` Learn more: [Evals Primitive](/primitives/essentials/evals) ## Performance Considerations ### Hook Overhead * **Hook Registration**: \< 1ms per hook * **Hook Execution**: Depends on hook logic (should be \< 100ms) * **Async Hooks**: Don't block agent execution * **Error Handling**: Failed hooks are logged but don't stop execution ### Optimization ```typescript theme={null} // Minimize hook overhead const efficientHooks = { onToolUse: async (event) => { // 1. Quick validation if (!shouldLog(event.tool)) return; // 2. Fire and forget logAsync(event).catch(console.error); } }; ``` ## Troubleshooting **Problem**: Hook function not being called **Solutions**: * Verify hook name is spelled correctly * Check hook is passed in hooks object * Ensure event actually occurs during execution ```typescript theme={null} // Debug hooks const debugHooks = { onStart: (event) => console.log('START triggered'), onToolUse: (event) => console.log('TOOL USE triggered:', event.tool), onComplete: (event) => console.log('COMPLETE triggered') }; ``` **Problem**: Hook failures stopping agent **Solutions**: * Wrap hook logic in try-catch * Log errors instead of throwing * Use error boundaries ```typescript theme={null} const safeHooks = { onToolUse: async (event) => { try { await riskyOperation(event); } catch (error) { console.error('Hook error:', error); // Don't throw - let execution continue } } }; ``` ## Related Primitives Event streaming and execution monitoring Async task lifecycle events Testing with custom validation hooks Version lifecycle callbacks ## Additional Resources Hook parameters and events Complete event reference Hook implementation patterns **Remember**: Hooks are for observing and reacting to agent execution, not for modifying it. Keep hooks fast, handle errors gracefully, and use async operations wisely. # Multi-Agent Source: https://docs.agentbase.sh/primitives/essentials/multi-agents Coordinate multiple specialized agents for complex workflows and seamless conversation handoffs > Multi-agent systems enable sophisticated workflows where specialized agents collaborate, transfer conversations, and handle different aspects of complex tasks. ## Overview The Multi-Agent primitive allows you to orchestrate multiple specialized agents within a single workflow or conversation. Instead of one generalist agent handling everything, you can deploy domain experts that collaborate, transfer work between each other, and provide specialized capabilities for different parts of your application. Multi-agent systems are essential for: * **Specialized Expertise**: Different agents with deep knowledge in specific domains * **Conversation Routing**: Intelligent transfer between support, sales, technical agents * **Complex Workflows**: Breaking down large tasks across multiple specialized agents * **Parallel Processing**: Multiple agents working simultaneously on different subtasks * **Scalable Architecture**: Add new agent specialists without modifying existing ones Agents can transfer conversations to other specialists while maintaining full context Each agent can have specialized knowledge, tools, and behavioral patterns Main agent intelligently determines which specialist should handle each request All agents in a session share conversation history and can build on each other's work ## How Multi-Agent Works When you configure multiple agents: 1. **Main Agent**: Acts as coordinator, receives initial requests 2. **Agent Discovery**: Main agent knows about available specialists and their capabilities 3. **Intelligent Routing**: Determines which specialist is best suited for the current task 4. **Transfer**: Hands off conversation to specialist while preserving full context 5. **Specialist Handling**: Specialist agent takes over and handles the request 6. **Return or Continue**: Specialist can return control to main agent or continue handling **Context Preservation**: When agents transfer conversations, the entire message history and context is preserved. The specialist agent has full visibility into everything that was discussed before. ## Code Examples ### Basic Multi-Agent Setup ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Configure multiple specialized agents const result = await agentbase.runAgent({ message: "I need help with my order", system: "You are a customer service coordinator. Analyze the request and transfer to the appropriate specialist.", agents: [ { name: "Order Support", description: "Handles order status, tracking, shipping, and delivery questions" }, { name: "Billing Support", description: "Handles payment issues, refunds, invoices, and billing questions" }, { name: "Technical Support", description: "Handles technical issues, bugs, and product functionality questions" } ] }); // Main agent analyzes request and transfers to Order Support ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Configure multiple specialized agents result = agentbase.run_agent( message="I need help with my order", system="You are a customer service coordinator. Analyze the request and transfer to the appropriate specialist.", agents=[ { "name": "Order Support", "description": "Handles order status, tracking, shipping, and delivery questions" }, { "name": "Billing Support", "description": "Handles payment issues, refunds, invoices, and billing questions" }, { "name": "Technical Support", "description": "Handles technical issues, bugs, and product functionality questions" } ] ) # Main agent analyzes request and transfers to Order Support ``` ```bash cURL theme={null} curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "I need help with my order", "system": "You are a customer service coordinator. Analyze the request and transfer to the appropriate specialist.", "agents": [ { "name": "Order Support", "description": "Handles order status, tracking, shipping, and delivery questions" }, { "name": "Billing Support", "description": "Handles payment issues, refunds, invoices, and billing questions" }, { "name": "Technical Support", "description": "Handles technical issues, bugs, and product functionality questions" } ] }' ``` ### Sales and Support Routing ```typescript TypeScript theme={null} // Configure sales and support agents const result = await agentbase.runAgent({ message: "What are your pricing plans?", system: `You are a helpful assistant. Route customers to: - Sales Agent for pricing, demos, and product information - Support Agent for existing customer issues and technical help`, agents: [ { name: "Sales Agent", description: "Handles product inquiries, pricing questions, demos, and new customer onboarding" }, { name: "Support Agent", description: "Handles existing customer support, technical issues, and account management" } ] }); // Main agent transfers to Sales Agent for pricing inquiry ``` ```python Python theme={null} # Configure sales and support agents result = agentbase.run_agent( message="What are your pricing plans?", system="""You are a helpful assistant. Route customers to: - Sales Agent for pricing, demos, and product information - Support Agent for existing customer issues and technical help""", agents=[ { "name": "Sales Agent", "description": "Handles product inquiries, pricing questions, demos, and new customer onboarding" }, { "name": "Support Agent", "description": "Handles existing customer support, technical issues, and account management" } ] ) # Main agent transfers to Sales Agent for pricing inquiry ``` ### Multi-Agent with Custom Tools ```typescript TypeScript theme={null} // Different agents with different tool access const result = await agentbase.runAgent({ message: "Process this customer order", system: "You are an order coordinator. Route to appropriate specialist.", agents: [ { name: "Order Processor", description: "Processes new orders, checks inventory, creates order records" }, { name: "Payment Handler", description: "Handles payment processing, refunds, and billing" }, { name: "Shipping Coordinator", description: "Manages shipping, tracking, and delivery logistics" } ], mcpServers: [ { serverName: "order-system", serverUrl: "https://api.company.com/orders" }, { serverName: "payment-gateway", serverUrl: "https://api.company.com/payments" }, { serverName: "shipping-api", serverUrl: "https://api.company.com/shipping" } ] }); // Each specialist agent uses relevant tools for their domain ``` ```python Python theme={null} # Different agents with different tool access result = agentbase.run_agent( message="Process this customer order", system="You are an order coordinator. Route to appropriate specialist.", agents=[ { "name": "Order Processor", "description": "Processes new orders, checks inventory, creates order records" }, { "name": "Payment Handler", "description": "Handles payment processing, refunds, and billing" }, { "name": "Shipping Coordinator", "description": "Manages shipping, tracking, and delivery logistics" } ], mcp_servers=[ { "serverName": "order-system", "serverUrl": "https://api.company.com/orders" }, { "serverName": "payment-gateway", "serverUrl": "https://api.company.com/payments" }, { "serverName": "shipping-api", "serverUrl": "https://api.company.com/shipping" } ] ) # Each specialist agent uses relevant tools for their domain ``` ### Continuing Multi-Agent Conversations ```typescript TypeScript theme={null} // Initial request with multi-agent setup const initial = await agentbase.runAgent({ message: "I have a billing question", system: "Route to appropriate specialist", agents: [ { name: "Billing Specialist", description: "Handles all billing and payment questions" }, { name: "Technical Specialist", description: "Handles technical issues" } ] }); // Main agent transfers to Billing Specialist const sessionId = initial.session; // Continue conversation with same session const followUp = await agentbase.runAgent({ message: "I need a copy of my invoice", session: sessionId // Billing Specialist still handling, has full context }); // Another follow-up const finalResponse = await agentbase.runAgent({ message: "Can you explain this charge?", session: sessionId // Still with Billing Specialist, remembers everything }); ``` ```python Python theme={null} # Initial request with multi-agent setup initial = agentbase.run_agent( message="I have a billing question", system="Route to appropriate specialist", agents=[ { "name": "Billing Specialist", "description": "Handles all billing and payment questions" }, { "name": "Technical Specialist", "description": "Handles technical issues" } ] ) # Main agent transfers to Billing Specialist session_id = initial.session # Continue conversation with same session follow_up = agentbase.run_agent( message="I need a copy of my invoice", session=session_id # Billing Specialist still handling, has full context ) # Another follow-up final_response = agentbase.run_agent( message="Can you explain this charge?", session=session_id # Still with Billing Specialist, remembers everything ) ``` ## Use Cases ### 1. Customer Service Hub Multi-tier support with specialized agents: ```typescript theme={null} async function customerServiceHub() { const config = { system: `You are a customer service coordinator for TechCorp. Analyze each customer request and route to the appropriate specialist: - Order Support: order status, shipping, delivery - Billing Support: payments, refunds, invoices - Technical Support: product issues, bugs, troubleshooting - Account Support: account settings, password resets, user management Always greet customers warmly and let them know you're transferring them to a specialist.`, agents: [ { name: "Order Support", description: "Expert in order management, shipping, tracking, and delivery. Has access to order database and shipping APIs." }, { name: "Billing Support", description: "Expert in payments, refunds, invoices, and billing issues. Has access to payment systems and accounting tools." }, { name: "Technical Support", description: "Expert in product functionality, troubleshooting, and bug reporting. Has access to technical documentation and bug tracking system." }, { name: "Account Support", description: "Expert in account management, user settings, and authentication. Has access to user management system." } ], mcpServers: [ { serverName: "customer-systems", serverUrl: "https://api.company.com/mcp" } ] }; return config; } // Use in application const result = await agentbase.runAgent({ message: "I can't access my account", ...await customerServiceHub() }); ``` ### 2. Sales Pipeline Route through sales stages with specialized agents: ```typescript theme={null} const salesPipeline = await agentbase.runAgent({ message: "I'm interested in your enterprise plan", system: `You manage the sales pipeline. Route prospects through: - Discovery Agent: initial contact, qualification - Demo Agent: product demonstrations, feature explanations - Pricing Agent: pricing discussions, proposals - Closing Agent: contract negotiation, final steps`, agents: [ { name: "Discovery Agent", description: "Qualifies leads, understands customer needs, identifies pain points, and determines fit" }, { name: "Demo Agent", description: "Showcases product features, provides demonstrations, explains use cases, answers product questions" }, { name: "Pricing Agent", description: "Discusses pricing options, creates proposals, explains ROI, handles budget conversations" }, { name: "Closing Agent", description: "Finalizes contracts, addresses final concerns, coordinates onboarding, completes sale" } ] }); ``` ### 3. Content Production Workflow Coordinate content creation across specialists: ```typescript theme={null} const contentWorkflow = await agentbase.runAgent({ message: "Create a comprehensive blog post about AI in healthcare", system: "You coordinate content production. Route through specialists for best results.", agents: [ { name: "Research Agent", description: "Conducts research, gathers sources, verifies facts, finds statistics and case studies" }, { name: "Writing Agent", description: "Creates compelling content, ensures proper structure, maintains tone and voice" }, { name: "SEO Agent", description: "Optimizes for search engines, adds meta descriptions, suggests keywords, improves discoverability" }, { name: "Editing Agent", description: "Reviews for grammar, clarity, consistency, fact-checks, and overall quality" } ] }); // Research Agent gathers information // Writing Agent creates draft // SEO Agent optimizes // Editing Agent reviews and polishes ``` ### 4. Development Team Simulation Specialized development agents: ```typescript theme={null} const devTeam = await agentbase.runAgent({ message: "Build a REST API for user management", system: "You are a tech lead coordinating development specialists.", agents: [ { name: "Backend Developer", description: "Designs and implements server-side logic, APIs, database schemas, and business logic" }, { name: "Database Architect", description: "Designs database schemas, optimizes queries, ensures data integrity and performance" }, { name: "DevOps Engineer", description: "Sets up deployment pipelines, manages infrastructure, handles containerization and orchestration" }, { name: "QA Engineer", description: "Creates test plans, writes tests, performs quality assurance, validates functionality" }, { name: "Security Specialist", description: "Reviews for security vulnerabilities, implements authentication, ensures compliance" } ] }); // Each specialist contributes their expertise to the project ``` ### 5. Healthcare Triage System Medical domain specialists: ```typescript theme={null} const healthcareTriage = await agentbase.runAgent({ message: "Patient experiencing chest pain and shortness of breath", system: `You are a medical triage coordinator. IMPORTANT: This is for informational purposes only. Always advise patients to seek immediate medical attention for serious symptoms. Route to appropriate specialist based on symptoms and severity.`, agents: [ { name: "Emergency Triage", description: "Handles urgent symptoms requiring immediate medical attention. Advises calling 911 or going to ER." }, { name: "Primary Care Advisor", description: "Handles general health questions, non-urgent symptoms, provides health information and guidance" }, { name: "Specialist Referral", description: "Recommends appropriate medical specialists based on symptoms, provides information about specialists" }, { name: "Appointment Scheduler", description: "Helps schedule appointments with appropriate providers, checks availability" } ] }); // Emergency Triage would handle this serious symptom ``` ### 6. Financial Advisory Service Financial domain specialists: ```typescript theme={null} const financialAdvisory = await agentbase.runAgent({ message: "Help me plan for retirement", system: `You coordinate financial advisory services. IMPORTANT: Remind users that agents provide educational information only and to consult licensed financial advisors for personalized advice.`, agents: [ { name: "Retirement Planner", description: "Provides retirement planning information, 401k guidance, pension advice, retirement age calculations" }, { name: "Investment Advisor", description: "Educates about investment options, portfolio strategies, risk assessment, asset allocation" }, { name: "Tax Specialist", description: "Provides tax-related information, deduction guidance, tax-advantaged account education" }, { name: "Estate Planner", description: "Educates about estate planning, wills, trusts, inheritance considerations" } ] }); ``` ## Best Practices ### Agent Design ```typescript theme={null} // Good: Clear, distinct specializations agents: [ { name: "Technical Support", description: "Handles technical issues: bugs, errors, performance problems, integration issues" }, { name: "Product Support", description: "Handles product usage: features, best practices, workflows, how-to questions" } ] // Avoid: Overlapping or vague descriptions agents: [ { name: "Support Agent 1", description: "Helps with various issues" }, { name: "Support Agent 2", description: "Also helps with issues" } ] ``` ```typescript theme={null} // Good: Descriptive, role-based names agents: [ { name: "Order Fulfillment Specialist", description: "Processes orders, manages inventory, coordinates shipping" }, { name: "Returns and Refunds Specialist", description: "Handles return requests, processes refunds, manages exchanges" } ] // Avoid: Generic or numbered names agents: [ { name: "Agent 1", description: "Handles some tasks" }, { name: "Agent 2", description: "Handles other tasks" } ] ``` ```typescript theme={null} // Good: Comprehensive descriptions agents: [ { name: "Billing Specialist", description: `Expert in all billing matters including: - Payment processing and methods - Invoice generation and history - Refund and chargeback handling - Subscription management - Pricing and plan changes - Payment failure resolution Has access to payment gateway and billing systems.` } ] // Avoid: Minimal descriptions agents: [ { name: "Billing Specialist", description: "Handles billing" } ] ``` ### Routing Strategy **Main Agent Guidance**: Give your main/coordinator agent clear instructions on when to route to each specialist and how to handle edge cases. ```typescript theme={null} const result = await agentbase.runAgent({ message: customerMessage, system: `You are a customer service coordinator. ROUTING RULES: 1. Order questions (status, tracking, delivery) → Order Support 2. Payment questions (charges, refunds, invoices) → Billing Support 3. Technical problems (errors, bugs, not working) → Technical Support 4. Account questions (login, settings, profile) → Account Support EDGE CASES: - If unclear, ask clarifying questions before routing - If spans multiple areas, route to primary concern - If urgent (data loss, security), route to Technical Support immediately Always: - Greet customer warmly - Briefly acknowledge their issue - Explain which specialist will help them - Transfer seamlessly`, agents: [ // ... agent definitions ] }); ``` ### Performance Optimization Use 3-5 specialized agents per workflow for optimal performance Design clear routing criteria to minimize unnecessary transfers Keep multi-agent sessions alive for related conversations Give each agent access only to tools they need ### Error Handling ```typescript theme={null} system: `You are a coordinator. If the customer's request is ambiguous: 1. DON'T transfer immediately 2. Ask 1-2 clarifying questions 3. Once clear, route to appropriate specialist Example: Customer: "I have a problem" You: "I'd be happy to help! Could you tell me a bit more about the problem you're experiencing? Is it related to an order, billing, technical issue, or something else?" Then route based on clarification.` ``` ```typescript theme={null} agents: [ { name: "Order Support", description: "Handles order-related questions" }, { name: "Billing Support", description: "Handles billing questions" }, { name: "General Support", description: "Fallback agent for questions that don't fit other categories or need general assistance" } ] // Main agent can route to General Support for edge cases ``` ## Integration with Other Primitives ### With Prompts Each agent can have specialized system prompts: ```typescript theme={null} // Main agent has routing prompt // Specialist agents get specialized prompts when they take over const result = await agentbase.runAgent({ message: "Technical issue", system: "You are a coordinator. Route technical issues to Technical Support.", agents: [ { name: "Technical Support", description: "Handles technical issues" // When this agent takes over, it gets technical support expertise } ] }); ``` Learn more: [Prompts Primitive](/primitives/essentials/prompts) ### With Custom Tools Different agents can access different tools: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Process order and payment", agents: [ { name: "Order Agent", description: "Processes orders (has access to order-system tools)" }, { name: "Payment Agent", description: "Handles payments (has access to payment-gateway tools)" } ], mcpServers: [ { serverName: "order-system", serverUrl: "https://api.company.com/orders" }, { serverName: "payment-gateway", serverUrl: "https://api.company.com/payments" } ] }); // Each agent intelligently uses tools relevant to their domain ``` Learn more: [Custom Tools Primitive](/primitives/essentials/custom-tools) ### With Sessions All agents in a session share context: ```typescript theme={null} // Start multi-agent session const initial = await agentbase.runAgent({ message: "I need help", agents: [ { name: "Agent A", description: "Handles A" }, { name: "Agent B", description: "Handles B" } ] }); // Continue - agents share full conversation history const continued = await agentbase.runAgent({ message: "Follow-up question", session: initial.session // Current agent has full context from previous agents }); ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ### With Parallelization Run multiple agents in parallel: ```typescript theme={null} // Parallel multi-agent execution const results = await Promise.all([ agentbase.runAgent({ message: "Research topic A", agents: [{ name: "Research A", description: "Expert in A" }] }), agentbase.runAgent({ message: "Research topic B", agents: [{ name: "Research B", description: "Expert in B" }] }), agentbase.runAgent({ message: "Research topic C", agents: [{ name: "Research C", description: "Expert in C" }] }) ]); // Each runs independently with specialized agent ``` Learn more: [Parallelization Primitive](/primitives/essentials/parallelization) ## Performance Considerations ### Agent Count Impact * **2-3 Agents**: Optimal performance, clear routing * **4-6 Agents**: Good performance, more specialization * **7+ Agents**: Consider if all are necessary, may slow routing decisions ```typescript theme={null} // Optimize by grouping related capabilities // Instead of 10 narrow specialists: agents: [ { name: "Spec1", description: "Does X" }, { name: "Spec2", description: "Does Y" }, // ... 8 more ] // Use 4-5 broader specialists: agents: [ { name: "Order & Shipping", description: "Handles all order-related tasks including shipping" }, { name: "Billing & Payments", description: "Handles all financial transactions" }, { name: "Technical Support", description: "Handles all technical issues" }, { name: "Account Management", description: "Handles user accounts and settings" } ] ``` ### Routing Efficiency Clear routing reduces transfer overhead: ```typescript theme={null} // Efficient: Clear routing criteria system: `Route based on keywords: - "order", "shipping", "delivery" → Order Support - "payment", "charge", "refund" → Billing Support - "error", "bug", "not working" → Technical Support` // Less efficient: Vague routing system: "Figure out which agent should handle this" ``` ### Tool Access Optimization Only provide tools relevant to each agent: ```typescript theme={null} // Configure tools that all agents might need at the main level mcpServers: [ { serverName: "customer-data", // All agents can access serverUrl: "https://api.company.com/customers" } ] // Specialist agents automatically use domain-specific tools wisely ``` ## Troubleshooting **Problem**: Main agent not routing to specialists **Solutions**: * Make agent descriptions more specific * Add explicit routing guidance in system prompt * Ensure agent names clearly indicate their purpose ```typescript theme={null} // Add explicit routing guidance system: `IMPORTANT: You must transfer to specialists. When you receive a request: 1. Identify the primary topic 2. Match to specialist description 3. Transfer immediately with warm introduction Examples: - "Track my order" → Transfer to Order Support - "Refund question" → Transfer to Billing Support DO NOT try to handle specialist topics yourself.` ``` **Problem**: Requests routed to incorrect specialist **Solutions**: * Improve agent descriptions to be more distinct * Add routing examples in system prompt * Use clear, non-overlapping specializations ```typescript theme={null} // Make descriptions mutually exclusive agents: [ { name: "Pre-Sales", description: "ONLY for prospects and leads who haven't purchased yet. Handles product questions, demos, pricing for new customers." }, { name: "Post-Sales", description: "ONLY for existing customers who have already purchased. Handles support, issues, account management." } ] ``` **Problem**: Specialist doesn't seem to have previous context **Solution**: This shouldn't happen - verify you're using same session ```typescript theme={null} // Ensure session continuity const initial = await agentbase.runAgent({ message: "My order #12345 is late", agents: [ /* ... */ ] }); // Use same session for follow-ups const followUp = await agentbase.runAgent({ message: "Did you check the tracking?", session: initial.session // ✓ Context preserved }); ``` **Problem**: Request bounces between multiple agents **Solutions**: * Design clear, non-overlapping specializations * Give guidance on edge cases * Use a generalist fallback agent ```typescript theme={null} system: `Route requests clearly: - If request fits ONE specialist perfectly → transfer immediately - If request spans MULTIPLE areas → route to primary concern - If request is UNCLEAR → ask clarifying question first - If request is GENERAL → handle yourself or route to General Support Never transfer more than once per request.` ``` ## Related Primitives Specialized system prompts for each agent Shared context across all agents Domain-specific tools for specialists Run multiple agents concurrently ## Additional Resources Agents parameter documentation Multi-agent implementation examples **Remember**: Design agents as specialists with clear, non-overlapping domains. Let the main agent handle routing, and give each specialist deep expertise in their area. # Parallelization Source: https://docs.agentbase.sh/primitives/essentials/parallelization Execute multiple agent tasks concurrently for improved performance and scalability > Parallelization enables concurrent execution of multiple agent tasks, dramatically improving performance for independent operations and complex workflows. ## Overview The Parallelization primitive allows you to run multiple agent requests simultaneously rather than sequentially. By executing independent tasks in parallel, you can significantly reduce total execution time, improve resource utilization, and build more responsive applications. Parallelization is essential for: * **Performance Optimization**: Reduce total execution time by running tasks concurrently * **Scalable Workflows**: Handle high-throughput scenarios with parallel processing * **Independent Operations**: Execute unrelated tasks simultaneously * **Data Processing**: Process multiple data items or files in parallel * **Multi-Source Aggregation**: Gather information from multiple sources simultaneously Run multiple agent requests at the same time instead of waiting for each to complete Each parallel task runs in its own isolated session with independent state Combine parallel execution with sequential workflows for complex patterns Collect and combine results from all parallel tasks ## How Parallelization Works When you execute multiple agent requests in parallel: 1. **Dispatch**: All requests are sent simultaneously 2. **Parallel Execution**: Each agent task runs independently in its own session 3. **Isolation**: Tasks don't share state or interfere with each other 4. **Completion**: Tasks complete at their own pace based on complexity 5. **Aggregation**: Results are collected and can be combined as needed **Independence Requirement**: Parallelized tasks should be independent - they shouldn't depend on each other's results. For dependent tasks, use sequential execution or workflows. ## Code Examples ### Basic Parallel Execution ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Execute multiple independent tasks in parallel const results = await Promise.all([ agentbase.runAgent({ message: "Research artificial intelligence trends in 2024" }), agentbase.runAgent({ message: "Research machine learning applications in healthcare" }), agentbase.runAgent({ message: "Research natural language processing advances" }) ]); // All three research tasks run simultaneously console.log('Task 1:', results[0].message); console.log('Task 2:', results[1].message); console.log('Task 3:', results[2].message); // Time saved: ~3x faster than sequential execution ``` ```python Python theme={null} import asyncio from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Execute multiple independent tasks in parallel async def parallel_research(): results = await asyncio.gather( agentbase.run_agent_async( message="Research artificial intelligence trends in 2024" ), agentbase.run_agent_async( message="Research machine learning applications in healthcare" ), agentbase.run_agent_async( message="Research natural language processing advances" ) ) # All three research tasks run simultaneously print('Task 1:', results[0].message) print('Task 2:', results[1].message) print('Task 3:', results[2].message) # Run the parallel tasks asyncio.run(parallel_research()) ``` ### Parallel Data Processing ```typescript TypeScript theme={null} // Process multiple files in parallel const files = [ 'sales_q1.csv', 'sales_q2.csv', 'sales_q3.csv', 'sales_q4.csv' ]; const analyses = await Promise.all( files.map(file => agentbase.runAgent({ message: `Analyze ${file} and generate summary statistics` }) ) ); // All files processed simultaneously console.log('All quarterly analyses completed'); console.log(analyses.map((a, i) => `${files[i]}: ${a.message}`)); ``` ```python Python theme={null} # Process multiple files in parallel files = [ 'sales_q1.csv', 'sales_q2.csv', 'sales_q3.csv', 'sales_q4.csv' ] async def process_files(): analyses = await asyncio.gather( *[agentbase.run_agent_async( message=f"Analyze {file} and generate summary statistics" ) for file in files] ) # All files processed simultaneously print('All quarterly analyses completed') for i, analysis in enumerate(analyses): print(f'{files[i]}: {analysis.message}') asyncio.run(process_files()) ``` ### Parallel Web Scraping ```typescript TypeScript theme={null} // Scrape multiple websites in parallel const websites = [ 'https://example.com/products', 'https://competitor.com/catalog', 'https://market.com/listings' ]; const scrapedData = await Promise.all( websites.map(url => agentbase.runAgent({ message: `Navigate to ${url} and extract all product names and prices` }) ) ); // Combine results const allProducts = scrapedData.flatMap((result, i) => ({ source: websites[i], data: result.message })); ``` ```python Python theme={null} # Scrape multiple websites in parallel websites = [ 'https://example.com/products', 'https://competitor.com/catalog', 'https://market.com/listings' ] async def scrape_websites(): scraped_data = await asyncio.gather( *[agentbase.run_agent_async( message=f"Navigate to {url} and extract all product names and prices" ) for url in websites] ) # Combine results all_products = [] for i, result in enumerate(scraped_data): all_products.append({ 'source': websites[i], 'data': result.message }) return all_products asyncio.run(scrape_websites()) ``` ### Parallel with Different Modes ```typescript TypeScript theme={null} // Use different modes for different task complexities const results = await Promise.all([ // Simple calculation - flash mode agentbase.runAgent({ message: "Calculate 15% of 2000", mode: "flash" }), // Standard analysis - base mode agentbase.runAgent({ message: "Analyze this dataset and find trends", mode: "base" }), // Complex reasoning - max mode agentbase.runAgent({ message: "Design a comprehensive system architecture", mode: "max" }) ]); // Each uses appropriate resources for the task ``` ```python Python theme={null} # Use different modes for different task complexities async def mixed_mode_parallel(): results = await asyncio.gather( # Simple calculation - flash mode agentbase.run_agent_async( message="Calculate 15% of 2000", mode="flash" ), # Standard analysis - base mode agentbase.run_agent_async( message="Analyze this dataset and find trends", mode="base" ), # Complex reasoning - max mode agentbase.run_agent_async( message="Design a comprehensive system architecture", mode="max" ) ) return results asyncio.run(mixed_mode_parallel()) ``` ### Result Aggregation ```typescript TypeScript theme={null} // Parallel tasks with result aggregation const cities = ['New York', 'London', 'Tokyo', 'Sydney']; const weatherData = await Promise.all( cities.map(city => agentbase.runAgent({ message: `Get current weather for ${city}` }) ) ); // Aggregate results const summary = await agentbase.runAgent({ message: `Here is weather data from multiple cities: ${weatherData.map((w, i) => `${cities[i]}: ${w.message}`).join('\n')} Create a summary report comparing weather across all cities.` }); console.log('Global weather summary:', summary.message); ``` ```python Python theme={null} # Parallel tasks with result aggregation cities = ['New York', 'London', 'Tokyo', 'Sydney'] async def aggregate_weather(): weather_data = await asyncio.gather( *[agentbase.run_agent_async( message=f"Get current weather for {city}" ) for city in cities] ) # Aggregate results weather_summary = '\n'.join([ f"{cities[i]}: {w.message}" for i, w in enumerate(weather_data) ]) summary = await agentbase.run_agent_async( message=f"""Here is weather data from multiple cities: {weather_summary} Create a summary report comparing weather across all cities.""" ) print('Global weather summary:', summary.message) asyncio.run(aggregate_weather()) ``` ## Use Cases ### 1. Batch Data Processing Process large datasets by splitting them across parallel agents: ```typescript theme={null} async function batchDataProcessing(records: any[]) { const batchSize = 100; const batches = []; // Split into batches for (let i = 0; i < records.length; i += batchSize) { batches.push(records.slice(i, i + batchSize)); } // Process all batches in parallel const results = await Promise.all( batches.map((batch, index) => agentbase.runAgent({ message: `Process this batch of ${batch.length} records: ${JSON.stringify(batch)} For each record: 1. Validate data format 2. Enrich with additional info 3. Calculate derived fields 4. Return processed results`, system: `You are a data processing agent handling batch ${index + 1}` }) ) ); // Combine results const allProcessedRecords = results.flatMap(r => JSON.parse(r.message) ); return allProcessedRecords; } // Process 1000 records in 10 parallel batches const processed = await batchDataProcessing(largeDataset); ``` ### 2. Multi-Source Research Gather information from multiple sources simultaneously: ```typescript theme={null} async function comprehensiveResearch(topic: string) { // Research different aspects in parallel const [ academicResearch, industryTrends, competitorAnalysis, marketData, technicalSpecs ] = await Promise.all([ agentbase.runAgent({ message: `Research academic papers and studies about ${topic}`, system: "You are an academic research specialist" }), agentbase.runAgent({ message: `Research industry trends and developments in ${topic}`, system: "You are an industry analyst" }), agentbase.runAgent({ message: `Analyze competitors and their approaches to ${topic}`, system: "You are a competitive intelligence analyst" }), agentbase.runAgent({ message: `Gather market size, growth rates, and forecasts for ${topic}`, system: "You are a market research analyst" }), agentbase.runAgent({ message: `Research technical specifications and requirements for ${topic}`, system: "You are a technical analyst" }) ]); // Synthesize all research const synthesis = await agentbase.runAgent({ message: `Synthesize comprehensive research report from multiple sources: Academic Research: ${academicResearch.message} Industry Trends: ${industryTrends.message} Competitor Analysis: ${competitorAnalysis.message} Market Data: ${marketData.message} Technical Specifications: ${technicalSpecs.message} Create an executive summary highlighting key insights from all sources.`, system: "You are a research synthesis specialist" }); return synthesis; } ``` ### 3. Content Generation at Scale Generate multiple content pieces in parallel: ```typescript theme={null} async function contentCampaign(products: string[]) { // Generate content for all products simultaneously const contentPieces = await Promise.all( products.map(product => Promise.all([ // Product description agentbase.runAgent({ message: `Write a compelling product description for ${product}`, system: "You are a product copywriter" }), // SEO metadata agentbase.runAgent({ message: `Generate SEO-optimized title, meta description, and keywords for ${product}`, system: "You are an SEO specialist" }), // Social media posts agentbase.runAgent({ message: `Create 3 social media posts promoting ${product} for Twitter, LinkedIn, and Instagram`, system: "You are a social media content creator" }), // Email campaign agentbase.runAgent({ message: `Write a promotional email for ${product}`, system: "You are an email marketing specialist" }) ]) ) ); // Organize results by product const campaign = products.map((product, i) => ({ product, description: contentPieces[i][0].message, seo: contentPieces[i][1].message, social: contentPieces[i][2].message, email: contentPieces[i][3].message })); return campaign; } // Generate complete marketing campaign for 10 products const campaign = await contentCampaign(productList); ``` ### 4. Testing and Validation Run parallel test scenarios: ```typescript theme={null} async function parallelTesting(apiEndpoint: string) { const testScenarios = [ { name: 'Happy Path', data: validData }, { name: 'Missing Fields', data: incompleteData }, { name: 'Invalid Format', data: malformedData }, { name: 'Boundary Values', data: edgeCaseData }, { name: 'Large Payload', data: largeData }, { name: 'Special Characters', data: specialCharsData } ]; // Run all test scenarios in parallel const results = await Promise.all( testScenarios.map(scenario => agentbase.runAgent({ message: `Test the API endpoint ${apiEndpoint} with this scenario: Scenario: ${scenario.name} Data: ${JSON.stringify(scenario.data)} 1. Send request to endpoint 2. Capture response 3. Validate response format 4. Check status code 5. Verify data integrity 6. Report results`, system: "You are an API testing specialist" }) ) ); // Summarize test results const summary = await agentbase.runAgent({ message: `Test Results Summary: ${results.map((r, i) => ` ${testScenarios[i].name}: ${r.message} `).join('\n')} Create a comprehensive test report with pass/fail status for each scenario.` }); return summary; } ``` ### 5. Multi-Language Translation Translate content to multiple languages simultaneously: ```typescript theme={null} async function multiLanguageTranslation(content: string) { const languages = [ 'Spanish', 'French', 'German', 'Italian', 'Portuguese', 'Japanese', 'Chinese', 'Korean', 'Arabic', 'Russian' ]; // Translate to all languages in parallel const translations = await Promise.all( languages.map(language => agentbase.runAgent({ message: `Translate the following content to ${language}: ${content} Ensure: - Natural, fluent translation - Cultural appropriateness - Maintain tone and style - Preserve formatting`, system: `You are a professional ${language} translator` }) ) ); // Return translations return languages.reduce((acc, lang, i) => { acc[lang] = translations[i].message; return acc; }, {} as Record); } // Translate to 10 languages simultaneously const allTranslations = await multiLanguageTranslation(originalContent); ``` ### 6. Distributed Analysis Analyze different dimensions of data in parallel: ```typescript theme={null} async function distributedAnalysis(dataset: any) { // Analyze different aspects in parallel const [ statistical, temporal, categorical, correlational, outliers, trends ] = await Promise.all([ agentbase.runAgent({ message: `Perform statistical analysis: mean, median, mode, std dev, quartiles`, system: "You are a statistical analyst" }), agentbase.runAgent({ message: `Analyze temporal patterns: seasonality, cycles, time-based trends`, system: "You are a time series analyst" }), agentbase.runAgent({ message: `Analyze categorical distributions and frequencies`, system: "You are a categorical data analyst" }), agentbase.runAgent({ message: `Identify correlations between variables`, system: "You are a correlation analyst" }), agentbase.runAgent({ message: `Detect outliers and anomalies`, system: "You are an anomaly detection specialist" }), agentbase.runAgent({ message: `Identify long-term trends and patterns`, system: "You are a trend analysis specialist" }) ]); // Compile comprehensive report const report = await agentbase.runAgent({ message: `Compile comprehensive data analysis report from: Statistical Analysis: ${statistical.message} Temporal Patterns: ${temporal.message} Categorical Analysis: ${categorical.message} Correlations: ${correlational.message} Outliers: ${outliers.message} Trends: ${trends.message} Create executive summary with key findings and recommendations.` }); return report; } ``` ## Best Practices ### Task Independence ```typescript theme={null} // Good: Independent tasks that can run in parallel const results = await Promise.all([ agentbase.runAgent({ message: "Analyze dataset A" }), agentbase.runAgent({ message: "Analyze dataset B" }), agentbase.runAgent({ message: "Analyze dataset C" }) ]); // Each analysis is independent // Avoid: Dependent tasks in parallel const badResults = await Promise.all([ agentbase.runAgent({ message: "Download file" }), agentbase.runAgent({ message: "Process the downloaded file" }) // Second task needs first to complete! ]); // Instead, run dependent tasks sequentially const step1 = await agentbase.runAgent({ message: "Download file" }); const step2 = await agentbase.runAgent({ message: "Process the file", session: step1.session }); ``` ```typescript theme={null} // Good: Batch similar operations for parallel execution const urls = [/* list of 100 URLs */]; const results = await Promise.all( urls.map(url => agentbase.runAgent({ message: `Scrape ${url} and extract key data` }) ) ); // Each URL scraped in parallel // Avoid: Processing one at a time for (const url of urls) { await agentbase.runAgent({ message: `Scrape ${url}` }); // Sequential = slow! } ``` ### Resource Management **Concurrency Limits**: While Agentbase can handle many parallel requests, consider implementing concurrency limits for very large batches to avoid overwhelming your application. ```typescript theme={null} // Implement concurrency control for large batches async function parallelWithConcurrencyLimit( items: T[], limit: number, handler: (item: T) => Promise ): Promise { const results: any[] = []; const executing: Promise[] = []; for (const item of items) { const promise = handler(item).then(result => { results.push(result); executing.splice(executing.indexOf(promise), 1); }); executing.push(promise); if (executing.length >= limit) { await Promise.race(executing); } } await Promise.all(executing); return results; } // Process 1000 items with max 10 concurrent const results = await parallelWithConcurrencyLimit( items, 10, item => agentbase.runAgent({ message: `Process ${item}` }) ); ``` ### Error Handling ```typescript theme={null} // Use Promise.allSettled for graceful failure handling const results = await Promise.allSettled([ agentbase.runAgent({ message: "Task 1" }), agentbase.runAgent({ message: "Task 2" }), agentbase.runAgent({ message: "Task 3" }) ]); // Process results and failures separately const successful = results .filter(r => r.status === 'fulfilled') .map(r => r.value); const failed = results .filter(r => r.status === 'rejected') .map(r => r.reason); console.log(`${successful.length} tasks succeeded`); console.log(`${failed.length} tasks failed`); // Continue with successful results ``` ```typescript theme={null} async function retryableParallel( tasks: (() => Promise)[], maxRetries: number = 3 ): Promise { const results = await Promise.allSettled(tasks.map(t => t())); // Retry failed tasks const retries: Promise[] = []; const finalResults: T[] = []; for (let i = 0; i < results.length; i++) { if (results[i].status === 'fulfilled') { finalResults[i] = (results[i] as PromiseFulfilledResult).value; } else { // Retry failed tasks retries.push( retryWithBackoff(tasks[i], maxRetries) .then(result => { finalResults[i] = result; }) ); } } await Promise.all(retries); return finalResults; } async function retryWithBackoff( fn: () => Promise, maxRetries: number ): Promise { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (i === maxRetries - 1) throw error; await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); } } throw new Error('Max retries exceeded'); } ``` ### Performance Optimization Group tasks into reasonable batch sizes (10-50 per batch) Match agent mode to task complexity for optimal resource use Track performance metrics to optimize batch sizes Cancel remaining tasks if you have enough results ```typescript theme={null} // Implement early termination async function findFirstValid(items: string[]) { const controller = new AbortController(); const promises = items.map(item => agentbase.runAgent({ message: `Validate ${item}`, signal: controller.signal }) ); try { // Race for first valid result const result = await Promise.race(promises); // Cancel remaining requests controller.abort(); return result; } catch (error) { controller.abort(); throw error; } } ``` ## Integration with Other Primitives ### With Multi-Agent Parallelize across different agent specialists: ```typescript theme={null} const results = await Promise.all([ agentbase.runAgent({ message: "Research topic A", agents: [{ name: "Research Specialist A", description: "Expert in A" }] }), agentbase.runAgent({ message: "Research topic B", agents: [{ name: "Research Specialist B", description: "Expert in B" }] }) ]); // Different specialists working in parallel ``` Learn more: [Multi-Agent Primitive](/primitives/essentials/multi-agents) ### With Custom Tools Parallel tool execution: ```typescript theme={null} const results = await Promise.all([ agentbase.runAgent({ message: "Fetch customer data", mcpServers: [{ serverName: "crm", serverUrl: "..." }] }), agentbase.runAgent({ message: "Fetch order data", mcpServers: [{ serverName: "orders", serverUrl: "..." }] }), agentbase.runAgent({ message: "Fetch analytics data", mcpServers: [{ serverName: "analytics", serverUrl: "..." }] }) ]); // Multiple data sources accessed in parallel ``` Learn more: [Custom Tools Primitive](/primitives/essentials/custom-tools) ### With Sessions Each parallel task gets its own session: ```typescript theme={null} // Parallel tasks with independent sessions const tasks = await Promise.all([ agentbase.runAgent({ message: "Task 1" }), agentbase.runAgent({ message: "Task 2" }), agentbase.runAgent({ message: "Task 3" }) ]); // Each has unique session ID console.log('Session IDs:', tasks.map(t => t.session)); // Can continue each independently await agentbase.runAgent({ message: "Continue task 1", session: tasks[0].session }); ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ## Performance Considerations ### Speedup Calculation Theoretical speedup with parallel execution: ``` Sequential Time: T1 + T2 + T3 + ... + Tn Parallel Time: max(T1, T2, T3, ..., Tn) Speedup: (T1 + T2 + ... + Tn) / max(T1, T2, ..., Tn) ``` Example: ```typescript theme={null} // Sequential: 30 seconds total await task1(); // 10s await task2(); // 10s await task3(); // 10s // Parallel: 10 seconds total (limited by longest task) await Promise.all([ task1(), // 10s task2(), // 10s task3() // 10s ]); // Speedup: 30s / 10s = 3x faster ``` ### Optimal Batch Sizing Find the sweet spot for your use case: * **Too Small** (1-5 tasks): Underutilizes parallelization * **Optimal** (10-50 tasks): Good balance of throughput and manageability * **Too Large** (100+ tasks): May overwhelm system, consider batching ```typescript theme={null} // Test different batch sizes async function findOptimalBatchSize(items: any[]) { const batchSizes = [10, 25, 50, 100]; for (const size of batchSizes) { const start = Date.now(); const batches = []; for (let i = 0; i < items.length; i += size) { batches.push(items.slice(i, i + size)); } await Promise.all( batches.map(batch => agentbase.runAgent({ message: `Process batch of ${batch.length} items` }) ) ); const duration = Date.now() - start; console.log(`Batch size ${size}: ${duration}ms`); } } ``` ### Memory Considerations Monitor memory usage with large parallel operations: ```typescript theme={null} // Streaming results instead of collecting all in memory async function* parallelStream(items: any[]) { const batchSize = 10; for (let i = 0; i < items.length; i += batchSize) { const batch = items.slice(i, i + batchSize); const results = await Promise.all( batch.map(item => agentbase.runAgent({ message: `Process ${item}` }) ) ); for (const result of results) { yield result; } } } // Process results as they come for await (const result of parallelStream(largeDataset)) { // Process result immediately await saveToDatabase(result); // Don't keep all results in memory } ``` ## Troubleshooting **Problem**: Some parallel tasks fail while others succeed **Solution**: Use Promise.allSettled and handle failures gracefully ```typescript theme={null} const results = await Promise.allSettled(tasks); const successful = results .filter(r => r.status === 'fulfilled') .map(r => r.value); const failed = results .filter(r => r.status === 'rejected') .map((r, i) => ({ index: i, error: r.reason })); // Retry failed tasks const retried = await Promise.all( failed.map(f => tasks[f.index]()) ); return [...successful, ...retried]; ``` **Problem**: Parallel execution not as fast as expected **Possible Causes**: * Tasks aren't actually independent * Too many tasks overwhelming system * One slow task bottlenecking others **Solutions**: * Verify task independence * Implement concurrency limits * Identify and optimize slow tasks * Consider different batch sizes **Problem**: Running out of memory with large parallel batches **Solution**: Implement streaming or chunked processing ```typescript theme={null} // Process in chunks async function chunkedParallel(items: any[], chunkSize: number = 50) { const results = []; for (let i = 0; i < items.length; i += chunkSize) { const chunk = items.slice(i, i + chunkSize); const chunkResults = await Promise.all( chunk.map(item => agentbase.runAgent({ message: `Process ${item}` }) ) ); results.push(...chunkResults); // Optionally process results immediately await processResults(chunkResults); } return results; } ``` **Problem**: Task depends on results from another parallel task **Solution**: Use sequential execution or workflow patterns ```typescript theme={null} // Wrong: Parallel execution of dependent tasks const [data, processed] = await Promise.all([ agentbase.runAgent({ message: "Fetch data" }), agentbase.runAgent({ message: "Process data" }) // Can't process before fetching! ]); // Correct: Sequential for dependencies const data = await agentbase.runAgent({ message: "Fetch data" }); const processed = await agentbase.runAgent({ message: "Process data", session: data.session }); // Or: Use workflows for complex dependencies const result = await agentbase.runAgent({ message: "Complete workflow", workflows: [{ id: "data-workflow", steps: [ { id: "fetch", description: "Fetch data", depends_on: [] }, { id: "process", description: "Process data", depends_on: ["fetch"] } ] }] }); ``` ## Related Primitives Structured DAGs for complex task dependencies Coordinate multiple specialized agents Each parallel task gets its own session Parallel tool execution across tasks ## Additional Resources Complete API documentation Optimization best practices Parallel execution examples **Remember**: Parallelization is most effective for independent tasks of similar complexity. Use it to dramatically reduce execution time for batch operations, multi-source data gathering, and scalable processing. # Persistence Source: https://docs.agentbase.sh/primitives/essentials/persistence Maintain state, context, and computational environments across agent sessions > Persistence ensures your agent workflows maintain continuity by preserving conversation history, computational state, and environmental configurations across requests and sessions. ## Overview The Persistence primitive is a foundational capability that enables agents to maintain state across multiple interactions. Unlike stateless systems that forget everything between requests, Agentbase's persistence model allows agents to build on previous work, remember context, and preserve computational environments. Persistence operates at two distinct tiers: * **Chat & Message History**: Automatic, zero-cost persistence of all conversation messages * **Computational Environment**: On-demand persistence of files, packages, and system state All messages persist automatically with no storage fees or configuration required Computational resources auto-pause when idle and resume instantly when needed Isolated persistence scopes per session for security and multi-tenancy Maintain workflows over hours, days, or weeks with automatic state preservation ## How Persistence Works ### Two-Tier Model Agentbase implements a sophisticated two-tier persistence model optimized for both cost and performance: **Tier 1: Message History** (Always Active) * Automatically persists all messages and responses * Zero storage cost * Instantly available for context * No configuration required * Unlimited retention **Tier 2: Computational Environment** (On-Demand) * Created when agents need code execution, file operations, or web browsing * Persists files, installed packages, and system state * Auto-pauses after 5 minutes of inactivity * Resumes in 1-2 seconds when accessed again * Full environment preservation across sessions **Cost Optimization**: Message history is completely free. Computational environments are only created when needed and automatically pause to minimize costs. ### Session-Scoped Persistence Each session maintains its own isolated persistence scope: 1. **Session Creation**: New session starts with empty state 2. **State Accumulation**: Messages, files, and environment changes persist within session 3. **Cross-Request Continuity**: State remains available across all requests in the session 4. **Automatic Cleanup**: Sessions eventually expire after extended inactivity 5. **Isolation**: Complete separation between different sessions ## Code Examples ### Basic Persistence Pattern ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Request 1: Agent creates files const step1 = await agentbase.runAgent({ message: "Create a file called data.json with sample user data" }); const sessionId = step1.session; console.log('Session ID:', sessionId); // Request 2: Agent accesses previous work (same session) const step2 = await agentbase.runAgent({ message: "Read data.json and count the number of users", session: sessionId // Reuse session - files persist }); // Files created in step1 are still available in step2 ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Request 1: Agent creates files step1 = agentbase.run_agent( message="Create a file called data.json with sample user data" ) session_id = step1.session print(f"Session ID: {session_id}") # Request 2: Agent accesses previous work (same session) step2 = agentbase.run_agent( message="Read data.json and count the number of users", session=session_id # Reuse session - files persist ) # Files created in step1 are still available in step2 ``` ```bash cURL theme={null} # Request 1: Create files curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Create a file called data.json with sample user data" }' # Response includes session ID # { "session": "agent_session_abc123...", ... } # Request 2: Access previous work curl -X POST "https://api.agentbase.sh?session=agent_session_abc123" \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Read data.json and count the number of users" }' ``` ### Long-Running Project Persistence ```typescript TypeScript theme={null} // Day 1: Initialize project const init = await agentbase.runAgent({ message: "Create a Python web scraper project with proper structure" }); const projectSession = init.session; // Store session ID for later use await db.projects.create({ name: 'web-scraper', sessionId: projectSession, createdAt: new Date() }); // Day 2: Continue development (hours or days later) const savedProject = await db.projects.findOne({ name: 'web-scraper' }); const day2 = await agentbase.runAgent({ message: "Add error handling and retry logic to the scraper", session: savedProject.sessionId }); // Day 3: Test and refine const day3 = await agentbase.runAgent({ message: "Run the scraper and fix any errors", session: savedProject.sessionId }); // All previous work persists across days ``` ```python Python theme={null} # Day 1: Initialize project init = agentbase.run_agent( message="Create a Python web scraper project with proper structure" ) project_session = init.session # Store session ID for later use db.projects.create({ 'name': 'web-scraper', 'session_id': project_session, 'created_at': datetime.now() }) # Day 2: Continue development (hours or days later) saved_project = db.projects.find_one({'name': 'web-scraper'}) day2 = agentbase.run_agent( message="Add error handling and retry logic to the scraper", session=saved_project.session_id ) # Day 3: Test and refine day3 = agentbase.run_agent( message="Run the scraper and fix any errors", session=saved_project.session_id ) # All previous work persists across days ``` ### Multi-Step Workflow with Persistence ```typescript TypeScript theme={null} async function dataAnalysisWorkflow(dataUrl: string) { // Step 1: Download data const download = await agentbase.runAgent({ message: `Download dataset from ${dataUrl} and save as data.csv` }); const session = download.session; // Step 2: Clean data (uses downloaded file) const clean = await agentbase.runAgent({ message: "Clean data.csv: remove duplicates, handle missing values", session }); // Step 3: Analyze (uses cleaned data) const analyze = await agentbase.runAgent({ message: "Perform statistical analysis and create visualizations", session }); // Step 4: Generate report (uses all previous work) const report = await agentbase.runAgent({ message: "Generate comprehensive analysis report with charts", session }); return { sessionId: session, report: report.message }; } // All intermediate files and results persist throughout workflow ``` ```python Python theme={null} async def data_analysis_workflow(data_url: str): # Step 1: Download data download = agentbase.run_agent( message=f"Download dataset from {data_url} and save as data.csv" ) session = download.session # Step 2: Clean data (uses downloaded file) clean = agentbase.run_agent( message="Clean data.csv: remove duplicates, handle missing values", session=session ) # Step 3: Analyze (uses cleaned data) analyze = agentbase.run_agent( message="Perform statistical analysis and create visualizations", session=session ) # Step 4: Generate report (uses all previous work) report = agentbase.run_agent( message="Generate comprehensive analysis report with charts", session=session ) return { 'session_id': session, 'report': report.message } # All intermediate files and results persist throughout workflow ``` ## What Persists ### Message History Everything in the conversation persists automatically: * **User Messages**: All requests sent to the agent * **Agent Responses**: Complete responses including reasoning * **Tool Calls**: Record of all tools used and their inputs * **Tool Results**: Outputs from tool executions * **Timestamps**: When each interaction occurred * **Metadata**: Session information, modes used, cost tracking ### Computational Environment When a computational environment is created, these persist: * **Files**: All files created, modified, or downloaded * **Installed Packages**: npm, pip, apt packages remain installed * **Environment Variables**: Custom environment configurations * **Working Directory**: Current directory state and structure * **Process State**: Background processes and their status * **System Modifications**: Configuration changes and system state ### What Doesn't Persist Some ephemeral state is intentionally not persisted: * **Memory State**: RAM contents are cleared on pause * **Network Connections**: Active connections are closed * **Temporary Files**: /tmp contents may be cleaned up * **Running Processes**: Processes terminate on pause (but can be restarted) **Important**: While files and packages persist, active processes stop when the environment pauses. Design workflows to handle process restarts gracefully. ## Use Cases ### 1. Iterative Development Projects Build software projects across multiple sessions: ```typescript theme={null} // Session 1: Project setup const setup = await agentbase.runAgent({ message: "Create a Next.js project with TypeScript and Tailwind" }); const devSession = setup.session; // Session 2: Add features await agentbase.runAgent({ message: "Add authentication with NextAuth.js", session: devSession }); // Session 3: Database integration await agentbase.runAgent({ message: "Set up Prisma with PostgreSQL", session: devSession }); // Session 4: Testing await agentbase.runAgent({ message: "Add unit tests with Jest", session: devSession }); // All code, dependencies, and configurations persist ``` ```typescript theme={null} // Build complex data pipeline over multiple sessions const pipeline = await agentbase.runAgent({ message: "Set up Python environment with pandas, numpy, scikit-learn" }); const pipelineSession = pipeline.session; // Add data processing steps await agentbase.runAgent({ message: "Create data preprocessing module with validation", session: pipelineSession }); // Add ML model await agentbase.runAgent({ message: "Implement random forest classifier with cross-validation", session: pipelineSession }); // All datasets, models, and code remain available ``` ### 2. Customer Support Conversations Maintain context throughout support interactions: ```typescript theme={null} async function handleSupportTicket(customerId: string, initialMessage: string) { // Create support session const initial = await agentbase.runAgent({ message: `Customer ${customerId}: ${initialMessage}`, system: "You are a customer support specialist.", mcpServers: [{ serverName: 'customer-api', serverUrl: 'https://api.company.com/mcp' }] }); const supportSession = initial.session; // Store session with ticket await db.tickets.create({ customerId, sessionId: supportSession, status: 'open', createdAt: new Date() }); return supportSession; } // Hours later, customer responds async function continueSupport(ticketId: string, message: string) { const ticket = await db.tickets.findById(ticketId); // Continue in same session - agent remembers everything return await agentbase.runAgent({ message: `Customer: ${message}`, session: ticket.sessionId }); } ``` ### 3. Research and Analysis Accumulate research over extended periods: ```typescript theme={null} async function researchProject(topic: string) { // Week 1: Initial research const research = await agentbase.runAgent({ message: `Research ${topic} and create initial notes document` }); const researchSession = research.session; // Week 2: Deep dive into specific areas await agentbase.runAgent({ message: "Expand section on recent developments with citations", session: researchSession }); // Week 3: Add case studies await agentbase.runAgent({ message: "Find and document 5 real-world case studies", session: researchSession }); // Week 4: Compile final report await agentbase.runAgent({ message: "Compile all research into comprehensive report", session: researchSession }); // All notes, sources, and documents accumulated over weeks } ``` ### 4. Scheduled Jobs and Automation Maintain state across scheduled executions: ```typescript theme={null} // Daily report generation with historical context async function generateDailyReport() { const reportConfig = await db.config.findOne({ name: 'daily-report' }); let sessionId = reportConfig?.sessionId; if (!sessionId) { // First run: initialize const init = await agentbase.runAgent({ message: "Initialize daily reporting system, create templates" }); sessionId = init.session; await db.config.create({ name: 'daily-report', sessionId }); } // Generate today's report with access to all previous reports const report = await agentbase.runAgent({ message: "Generate today's report and compare to previous days", session: sessionId }); return report; } // Each day's report has context of all previous reports ``` ## Best Practices ### Session Management ```typescript theme={null} // Good: Store in database with proper access control interface WorkflowRecord { id: string; userId: string; sessionId: string; workflowType: string; createdAt: Date; lastAccess: Date; } async function createWorkflow(userId: string, type: string) { const result = await agentbase.runAgent({ message: `Initialize ${type} workflow` }); await db.workflows.create({ id: generateId(), userId, sessionId: result.session, workflowType: type, createdAt: new Date(), lastAccess: new Date() }); } // Avoid: Storing in client-side storage without encryption ``` ```typescript theme={null} async function updateSessionActivity(sessionId: string) { await db.workflows.updateOne( { sessionId }, { $set: { lastAccess: new Date() }, $inc: { requestCount: 1 } } ); } // Monitor for stale sessions async function cleanupStaleSessions() { const threshold = new Date(); threshold.setDate(threshold.getDate() - 30); const staleSessions = await db.workflows.find({ lastAccess: { $lt: threshold } }); for (const session of staleSessions) { await archiveAndDelete(session); } } ``` ```typescript theme={null} // Tag sessions with meaningful metadata await db.sessions.create({ sessionId: result.session, tags: ['data-analysis', 'customer-insights', 'q1-2025'], description: 'Customer behavior analysis for Q1 2025', owner: userId, team: 'analytics' }); // Easy retrieval and organization const analyticsSessions = await db.sessions.find({ tags: { $in: ['data-analysis'] }, team: 'analytics' }); ``` ### Performance Optimization Make requests within 5 minutes to avoid auto-pause overhead Use different sessions for unrelated work to keep context focused Remove unnecessary files to reduce storage and improve performance Save important state externally for critical long-running workflows ### Data Management ```typescript theme={null} // Periodically export important artifacts async function exportWorkflowArtifacts(sessionId: string) { const export_request = await agentbase.runAgent({ message: "Create a zip file of all important project files", session: sessionId }); // Download and store externally const artifacts = await downloadArtifacts(export_request); await s3.upload(`backups/${sessionId}.zip`, artifacts); } // Clear temporary data to optimize performance async function cleanupSession(sessionId: string) { await agentbase.runAgent({ message: "Delete all files in /tmp and clear build caches", session: sessionId }); } ``` ## Integration with Other Primitives ### With Sessions Persistence is session-scoped - each session maintains its own state: ```typescript theme={null} // Session A: Isolated persistence const sessionA = await agentbase.runAgent({ message: "Create project A files" }); // Session B: Separate isolated persistence const sessionB = await agentbase.runAgent({ message: "Create project B files" }); // Each session has completely separate file systems and state ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ### With States States represent the current snapshot of persisted data: ```typescript theme={null} // State evolves as persistence accumulates const initial = await agentbase.runAgent({ message: "Create config.json" }); // State: config.json exists const updated = await agentbase.runAgent({ message: "Add database settings to config.json", session: initial.session }); // State: config.json exists with database settings ``` Learn more: [States Primitive](/primitives/essentials/states) ### With Versioning Combine persistence with versioning for rollback capabilities: ```typescript theme={null} // Create versioned checkpoints await agentbase.runAgent({ message: "Create git repository and commit current state as v1.0", session: projectSession }); // Later, rollback if needed await agentbase.runAgent({ message: "Revert to v1.0", session: projectSession }); ``` Learn more: [Versioning Primitive](/primitives/essentials/versioning) ## Performance Considerations ### Environment Startup Times * **New Environment**: 2-5 seconds to create from scratch * **Warm Environment**: Instant access if active (\< 5 min since last request) * **Resume from Pause**: 1-2 seconds to wake up paused environment ### Storage Impact Message history is free and unlimited. For computational environments: * **Small Projects** (\< 100 MB): Negligible impact * **Medium Projects** (100 MB - 1 GB): Normal performance * **Large Projects** (> 1 GB): Consider periodic cleanup ### Optimization Strategies ```typescript theme={null} // Keep sessions warm for interactive workflows setInterval(async () => { await agentbase.runAgent({ message: "status", session: activeSessionId }); }, 4 * 60 * 1000); // Every 4 minutes // Lazy load for batch workflows async function batchProcess(items: string[]) { let sessionId: string | undefined; for (const item of items) { const result = await agentbase.runAgent({ message: `Process ${item}`, session: sessionId }); sessionId = result.session; // Reuse session for efficiency } } ``` ## Troubleshooting **Problem**: Files created in one request don't appear in the next **Solutions**: * Verify you're passing the same session ID * Check that files are created in persistent directories (not /tmp) * Ensure session hasn't expired ```typescript theme={null} // Verify session continuity const step1 = await agentbase.runAgent({ message: "Create file.txt" }); console.log('Session:', step1.session); const step2 = await agentbase.runAgent({ message: "Read file.txt", session: step1.session // Must match! }); ``` **Problem**: Error when trying to use a session ID **Solutions**: * Session may have expired after extended inactivity * Session ID may be incorrect or corrupted * Start a new session and restore state if needed ```typescript theme={null} try { await agentbase.runAgent({ message: "Continue work", session: maybeExpiredSession }); } catch (error) { if (error.code === 'SESSION_NOT_FOUND') { // Start new session const fresh = await agentbase.runAgent({ message: "Restore project from backup" }); await updateStoredSession(fresh.session); } } ``` **Problem**: Noticeable delay when resuming paused environment **Solutions**: * This is expected behavior (1-2 second resume time) * Keep environment warm with periodic requests if low latency is critical * Consider if you really need environment persistence for simple tasks ```typescript theme={null} // For latency-critical workflows, keep warm const keepWarm = setInterval(async () => { await agentbase.runAgent({ message: "ping", session: criticalSession }); }, 4 * 60 * 1000); // Stop when done clearInterval(keepWarm); ``` ## Related Primitives Session containers that enable persistence Current snapshot of persisted data Version control for persisted state Long-running tasks with persistence ## Additional Resources Session and persistence parameters Environment capabilities and tools Real-world persistence patterns **Remember**: Chat history persists automatically and free, while computational environments are created only when needed and persist for ongoing work. Always pass session IDs to maintain continuity. # Prompts Source: https://docs.agentbase.sh/primitives/essentials/prompts Guide agent behavior, expertise, and personality with custom system prompts > System prompts are the foundation of agent customization, defining your agent's expertise, personality, behavioral guidelines, and approach to tasks. ## Overview The Prompts primitive allows you to shape how your agent thinks, communicates, and approaches problems. Unlike user messages that describe specific tasks, system prompts establish the agent's core identity, expertise domain, and operational framework. They act as the agent's professional background and personality blueprint. System prompts are essential for: * **Role Definition**: Establish the agent as a domain expert (e.g., data analyst, DevOps engineer, customer support specialist) * **Behavioral Guidance**: Define communication style, tone, and interaction patterns * **Expertise Scoping**: Focus the agent's knowledge and approach on specific domains * **Constraint Setting**: Establish boundaries, preferences, and operational rules * **Context Injection**: Provide company-specific knowledge, policies, or frameworks Define agents as domain experts with specific expertise, communication styles, and behavioral patterns Inject company knowledge, policies, and domain-specific frameworks directly into agent behavior System prompts persist throughout the entire session, guiding every agent response Combine with rules, tools, and other primitives for sophisticated agent behavior ## How System Prompts Work System prompts are processed before any user messages and establish the agent's operational context. When you provide a system prompt: 1. **Initialization**: The prompt is loaded into the agent's context at session start 2. **Persistence**: It remains active throughout the entire session 3. **Influence**: Every agent response is shaped by the system prompt's guidance 4. **Integration**: The prompt works seamlessly with tools, rules, and other primitives 5. **Override**: New sessions can use different prompts for different use cases **Session Scope**: System prompts are set per session. Different sessions can have different prompts, enabling multi-tenant applications with specialized agents. ## Code Examples ### Basic Role Definition ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Define agent as data analyst const result = await agentbase.runAgent({ message: "Analyze this sales data and identify trends", system: "You are a senior data analyst with expertise in retail analytics and business intelligence." }); ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Define agent as data analyst result = agentbase.run_agent( message="Analyze this sales data and identify trends", system="You are a senior data analyst with expertise in retail analytics and business intelligence." ) ``` ```bash cURL theme={null} curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Analyze this sales data and identify trends", "system": "You are a senior data analyst with expertise in retail analytics and business intelligence." }' ``` ### Prompt with Behavioral Guidelines ```typescript TypeScript theme={null} // Technical writing assistant with style guidelines const result = await agentbase.runAgent({ message: "Document this API endpoint", system: `You are a technical writing assistant specializing in API documentation. Follow these guidelines: - Use clear, concise language - Write in active voice - Include practical code examples - Explain both what and why - Highlight potential pitfalls - Focus on developer experience` }); ``` ```python Python theme={null} # Technical writing assistant with style guidelines result = agentbase.run_agent( message="Document this API endpoint", system="""You are a technical writing assistant specializing in API documentation. Follow these guidelines: - Use clear, concise language - Write in active voice - Include practical code examples - Explain both what and why - Highlight potential pitfalls - Focus on developer experience""" ) ``` ### Prompt with Domain Context ```typescript TypeScript theme={null} // Customer support with company context const result = await agentbase.runAgent({ message: "Help customer with billing question", system: `You are a customer success specialist for TechCorp, a B2B SaaS company. Company Context: - Target customers: Small to medium businesses - Product: Project management platform - Pricing: Tiered subscription model - Support hours: 24/7 for premium tier Approach: - Be empathetic and solution-focused - Prioritize customer satisfaction - Escalate complex issues to human support - Always verify account details before making changes` }); ``` ```python Python theme={null} # Customer support with company context result = agentbase.run_agent( message="Help customer with billing question", system="""You are a customer success specialist for TechCorp, a B2B SaaS company. Company Context: - Target customers: Small to medium businesses - Product: Project management platform - Pricing: Tiered subscription model - Support hours: 24/7 for premium tier Approach: - Be empathetic and solution-focused - Prioritize customer satisfaction - Escalate complex issues to human support - Always verify account details before making changes""" ) ``` ### Multi-Line Prompt with Structure ```typescript TypeScript theme={null} // DevOps engineer with comprehensive guidance const systemPrompt = `You are a senior DevOps engineer specializing in cloud infrastructure and CI/CD. EXPERTISE: - Cloud platforms: AWS, GCP, Azure - Infrastructure as Code: Terraform, CloudFormation - Container orchestration: Kubernetes, Docker - CI/CD: GitHub Actions, GitLab CI, Jenkins - Monitoring: Prometheus, Grafana, Datadog RESPONSIBILITIES: 1. Design scalable, reliable infrastructure 2. Optimize for cost and performance 3. Implement security best practices 4. Ensure high availability and disaster recovery 5. Document all infrastructure decisions COMMUNICATION STYLE: - Explain technical concepts clearly - Provide step-by-step implementation guides - Include relevant code examples - Highlight potential risks and trade-offs - Suggest monitoring and alerting strategies CONSTRAINTS: - Always follow the principle of least privilege - Prefer managed services over self-hosted when appropriate - Implement infrastructure as code (no manual changes) - Include automated testing for infrastructure changes`; const result = await agentbase.runAgent({ message: "Design a highly available web application infrastructure on AWS", system: systemPrompt }); ``` ```python Python theme={null} # DevOps engineer with comprehensive guidance system_prompt = """You are a senior DevOps engineer specializing in cloud infrastructure and CI/CD. EXPERTISE: - Cloud platforms: AWS, GCP, Azure - Infrastructure as Code: Terraform, CloudFormation - Container orchestration: Kubernetes, Docker - CI/CD: GitHub Actions, GitLab CI, Jenkins - Monitoring: Prometheus, Grafana, Datadog RESPONSIBILITIES: 1. Design scalable, reliable infrastructure 2. Optimize for cost and performance 3. Implement security best practices 4. Ensure high availability and disaster recovery 5. Document all infrastructure decisions COMMUNICATION STYLE: - Explain technical concepts clearly - Provide step-by-step implementation guides - Include relevant code examples - Highlight potential risks and trade-offs - Suggest monitoring and alerting strategies CONSTRAINTS: - Always follow the principle of least privilege - Prefer managed services over self-hosted when appropriate - Implement infrastructure as code (no manual changes) - Include automated testing for infrastructure changes""" result = agentbase.run_agent( message="Design a highly available web application infrastructure on AWS", system=system_prompt ) ``` ## Use Cases and Patterns ### 1. Domain Expert Agents Create specialized agents for specific domains: ```typescript theme={null} const dataScientist = { system: `You are a data scientist specializing in machine learning and statistical analysis. Expertise: Python (pandas, scikit-learn, tensorflow), R, SQL, statistical modeling Approach: - Start with exploratory data analysis - Validate assumptions and check data quality - Choose appropriate models for the problem - Explain model performance metrics clearly - Provide actionable insights from data` }; const result = await agentbase.runAgent({ message: "Build a customer churn prediction model", system: dataScientist.system }); ``` ```typescript theme={null} const legalAdvisor = { system: `You are a legal compliance specialist focusing on data privacy and GDPR. Expertise: GDPR, CCPA, data protection, privacy policies, compliance auditing Approach: - Cite relevant regulations and articles - Explain legal implications clearly - Provide practical compliance steps - Highlight risks and liabilities - Recommend documentation practices Important: Remind users to consult qualified legal counsel for specific legal advice.` }; const result = await agentbase.runAgent({ message: "Review our data retention policy for GDPR compliance", system: legalAdvisor.system }); ``` ```typescript theme={null} const financialAnalyst = { system: `You are a financial analyst with expertise in corporate finance and investment analysis. Expertise: Financial modeling, valuation, risk assessment, portfolio analysis Methodology: - Use established financial frameworks (DCF, comparable analysis) - Show calculations and assumptions clearly - Consider market conditions and trends - Assess risks and sensitivities - Provide actionable recommendations Standards: Follow GAAP/IFRS accounting principles` }; const result = await agentbase.runAgent({ message: "Perform a DCF valuation for this company", system: financialAnalyst.system }); ``` ```typescript theme={null} const architect = { system: `You are a software architect specializing in distributed systems and microservices. Expertise: System design, scalability, microservices, event-driven architecture, API design Design Principles: - SOLID principles and clean architecture - Separation of concerns - Scalability and performance optimization - Security by design - Observability and monitoring Deliverables: - High-level architecture diagrams - Component interaction flows - Technology stack recommendations - Scalability and performance considerations - Security and compliance requirements` }; const result = await agentbase.runAgent({ message: "Design a microservices architecture for an e-commerce platform", system: architect.system }); ``` ### 2. Customer-Facing Agents Customize communication style for end users: ```typescript theme={null} // Friendly customer support const supportAgent = await agentbase.runAgent({ message: "Customer can't log in to their account", system: `You are a friendly and empathetic customer support specialist. Tone: Warm, patient, and reassuring Goal: Solve problems quickly while maintaining positive customer experience Always: - Acknowledge customer frustration - Provide clear, step-by-step solutions - Verify understanding before escalating - End with confirmation that issue is resolved - Thank customers for their patience` }); // Professional sales assistant const salesAgent = await agentbase.runAgent({ message: "Customer asking about enterprise pricing", system: `You are a professional B2B sales consultant. Approach: Consultative, value-focused, professional Goal: Understand needs and match them to appropriate solutions Process: 1. Ask qualifying questions about their business 2. Listen actively to pain points 3. Present relevant solutions with ROI focus 4. Address concerns with data and case studies 5. Provide clear next steps and timeline` }); ``` ### 3. Internal Tools & Automation Agents for internal workflows and processes: ```typescript theme={null} // Code review assistant const codeReviewer = await agentbase.runAgent({ message: "Review this pull request", system: `You are a senior software engineer performing code review. Focus Areas: - Code quality and maintainability - Performance and scalability - Security vulnerabilities - Test coverage - Documentation completeness - Best practices adherence Review Style: - Be constructive and educational - Explain the "why" behind suggestions - Prioritize feedback (critical, recommended, nitpick) - Acknowledge good patterns and improvements - Provide code examples for suggestions` }); // Database administrator const dbaAgent = await agentbase.runAgent({ message: "Optimize this slow query", system: `You are a database administrator specializing in query optimization. Expertise: PostgreSQL, MySQL, query optimization, indexing, performance tuning Methodology: 1. Analyze query execution plan 2. Identify bottlenecks (table scans, missing indexes, join order) 3. Suggest specific optimizations (indexes, query rewrites, schema changes) 4. Estimate performance improvements 5. Consider trade-offs (write performance, storage, maintenance) 6. Provide monitoring recommendations` }); ``` ### 4. Educational & Training Agents Agents designed to teach and mentor: ```typescript theme={null} // Programming tutor const programmingTutor = await agentbase.runAgent({ message: "Explain async/await in JavaScript", system: `You are a patient and encouraging programming instructor. Teaching Philosophy: - Build on existing knowledge - Use clear analogies and examples - Provide hands-on practice exercises - Explain common pitfalls - Encourage experimentation - Adapt to learner's pace Instruction Style: - Start with conceptual understanding - Show practical code examples - Explain what's happening step-by-step - Provide exercises to practice - Review common mistakes - Offer additional resources` }); // Math tutor const mathTutor = await agentbase.runAgent({ message: "Help me understand calculus derivatives", system: `You are a mathematics tutor specializing in making complex concepts accessible. Approach: - Start with intuitive explanations - Use visual aids and real-world examples - Break complex problems into steps - Check understanding before moving forward - Connect new concepts to prior knowledge - Provide practice problems with detailed solutions Remember: Every student learns differently - adapt to their pace and style.` }); ``` ## Best Practices ### Crafting Effective Prompts ```typescript theme={null} // Good: Specific role with clear expertise system: `You are a React developer specializing in performance optimization and modern hooks patterns. You have 5+ years of experience with production React applications.` // Avoid: Vague or generic system: "You are a developer." ``` ```typescript theme={null} // Good: Clear behavioral guidelines system: `You are a technical writer. Guidelines: - Use active voice - Keep sentences under 20 words - Include code examples for every concept - Explain the "why" not just the "what" - Highlight common mistakes` // Avoid: No guidance on how to approach tasks system: "You are a technical writer." ``` ```typescript theme={null} // Good: Relevant company/domain context system: `You are customer support for HealthTech Pro, a HIPAA-compliant healthcare platform serving hospitals and clinics. Context: - Customers are healthcare professionals - All data is protected health information (PHI) - Compliance with HIPAA is critical - Downtime directly impacts patient care` // Avoid: Missing critical context system: "You are customer support for a healthcare app." ``` ```typescript theme={null} // Good: Clear constraints system: `You are a financial advisor assistant. Constraints: - Never provide specific investment recommendations - Always include risk disclaimers - Recommend consulting a licensed financial advisor for personalized advice - Focus on general education and information - Cite sources for financial data` // Avoid: Missing important constraints system: "You are a financial advisor." ``` ```typescript theme={null} // Good: Well-structured with sections system: `You are a DevOps engineer. EXPERTISE: - Kubernetes, Docker, Terraform - AWS, GCP, Azure - CI/CD pipelines RESPONSIBILITIES: 1. Design infrastructure 2. Optimize for cost and performance 3. Ensure security best practices COMMUNICATION: - Explain technical concepts clearly - Provide step-by-step guides - Include relevant examples CONSTRAINTS: - Follow principle of least privilege - Prefer infrastructure as code - Document all decisions` // Avoid: Wall of unstructured text system: "You are a DevOps engineer who knows Kubernetes Docker..." ``` ### Common Patterns **Template Pattern**: Create reusable prompt templates for common agent roles in your organization. Store them as constants or configuration files. ```typescript theme={null} // Prompt templates library const AGENT_PROMPTS = { dataAnalyst: `You are a senior data analyst with expertise in {domain}. Focus Areas: {focus_areas} Tools: {tools} Approach: {approach}`, customerSupport: `You are a {tone} customer support specialist for {company}. Product: {product} Guidelines: {guidelines} Escalation: {escalation_criteria}`, developer: `You are a {seniority} {language} developer. Expertise: {expertise} Standards: {standards} Style: {style_guide}` }; // Use with variable substitution const prompt = AGENT_PROMPTS.dataAnalyst .replace('{domain}', 'retail analytics') .replace('{focus_areas}', 'sales trends, customer segmentation') .replace('{tools}', 'Python, SQL, Tableau') .replace('{approach}', 'data-driven insights with actionable recommendations'); ``` ### Dos and Don'ts * Define clear role and expertise * Provide relevant context * Set behavioral guidelines * Include constraints and boundaries * Structure complex prompts with sections * Test prompts with sample tasks * Iterate based on agent performance * Use vague or generic descriptions * Overload with unnecessary details * Contradict yourself in the prompt * Assume implicit knowledge * Ignore domain-specific requirements * Forget to set ethical boundaries * Write unstructured walls of text ## Integration with Other Primitives ### With Rules Combine prompts with rules for fine-grained control: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Generate a product description", system: "You are a product marketing copywriter specializing in e-commerce.", rules: [ "Keep descriptions under 150 words", "Include at least 3 key features", "Use an enthusiastic but professional tone", "End with a clear call-to-action" ] }); ``` Learn more: [Rules Primitive](/build/rules) ### With Custom Tools Guide how agents use custom tools: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Analyze customer feedback", system: `You are a customer insights analyst. When analyzing feedback: 1. Use the sentiment_analysis tool for each review 2. Use the categorize_feedback tool to group by theme 3. Use the priority_calculator tool to identify urgent issues 4. Summarize findings with actionable recommendations`, mcpServers: [{ serverName: "analytics-tools", serverUrl: "https://api.company.com/mcp" }] }); ``` Learn more: [Custom Tools Primitive](/primitives/essentials/custom-tools) ### With Multi-Agent Systems Define specialized agents for different roles: ```typescript theme={null} const result = await agentbase.runAgent({ message: "I need help with my order", system: "You are the main routing agent. Analyze requests and transfer to appropriate specialist.", agents: [ { name: "Order Support", description: "Handles order status, tracking, and delivery questions" }, { name: "Billing Support", description: "Handles payment, refunds, and billing questions" } ] }); ``` Learn more: [Multi-Agent Primitive](/primitives/essentials/multi-agents) ### With Sessions Different prompts for different session contexts: ```typescript theme={null} // Session 1: Data analysis agent const analysis = await agentbase.runAgent({ message: "Analyze sales data", system: "You are a data analyst." }); // Session 2: Content writing agent (different session, different role) const content = await agentbase.runAgent({ message: "Write a blog post", system: "You are a content marketing specialist." }); ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ## Performance Considerations ### Prompt Length and Latency * **Short prompts** (\< 100 tokens): Negligible impact on response time * **Medium prompts** (100-500 tokens): Minimal impact (\~100ms) * **Long prompts** (500+ tokens): Moderate impact (\~200-500ms) * **Very long prompts** (1000+ tokens): Consider if all details are necessary **Optimization**: Keep prompts concise and focused. Move lengthy reference material to context documents or custom tools when possible. ### Token Usage System prompts consume tokens with every request in a session: ```typescript theme={null} // System prompt: ~150 tokens // Over 100 requests: 15,000 tokens const result = await agentbase.runAgent({ message: "Simple task", system: `[Your 150-token prompt here]` }); // Optimization: Balance detail with token efficiency ``` ### Caching and Reusability ```typescript theme={null} // Store prompts as constants const DATA_ANALYST_PROMPT = "You are a data analyst..."; // Reuse across multiple sessions const session1 = await agentbase.runAgent({ message: "Task 1", system: DATA_ANALYST_PROMPT }); const session2 = await agentbase.runAgent({ message: "Task 2", system: DATA_ANALYST_PROMPT }); ``` ```typescript theme={null} // Generate prompts based on context function generatePrompt(role: string, context: object): string { return `You are a ${role}. Context: ${JSON.stringify(context)} [Additional guidelines...]`; } const prompt = generatePrompt('customer support', { company: 'TechCorp', product: 'SaaS Platform' }); const result = await agentbase.runAgent({ message: "Help customer", system: prompt }); ``` ## Advanced Techniques ### Dynamic Prompt Injection Inject user or session-specific context: ```typescript theme={null} async function runPersonalizedAgent(userId: string, message: string) { // Fetch user context const user = await getUserContext(userId); // Build personalized system prompt const systemPrompt = `You are a personal assistant for ${user.name}. User Preferences: - Communication style: ${user.preferences.tone} - Expertise level: ${user.expertise} - Focus areas: ${user.interests.join(', ')} Context: - Account tier: ${user.tier} - Previous interactions: ${user.history.length} - Key goals: ${user.goals.join(', ')}`; return await agentbase.runAgent({ message, system: systemPrompt }); } ``` ### Prompt Versioning Track and manage prompt versions: ```typescript theme={null} const PROMPT_VERSIONS = { 'v1.0': 'You are a basic customer support agent.', 'v1.1': 'You are a customer support agent. Be friendly and helpful.', 'v2.0': `You are a customer support specialist. Approach: - Be empathetic and solution-focused - Provide step-by-step guidance - Escalate complex issues Constraints: - Verify identity before sharing account info - Follow company policies - Document all interactions` }; // Use specific version const result = await agentbase.runAgent({ message: "Customer inquiry", system: PROMPT_VERSIONS['v2.0'] }); // A/B test different versions const versionToUse = Math.random() > 0.5 ? 'v2.0' : 'v1.1'; ``` ### Conditional Prompt Selection Choose prompts based on request type: ```typescript theme={null} function selectPrompt(requestType: string): string { const prompts = { technical: "You are a senior software engineer...", business: "You are a business analyst...", support: "You are a customer support specialist...", sales: "You are a sales consultant..." }; return prompts[requestType] || prompts.support; } const result = await agentbase.runAgent({ message: userMessage, system: selectPrompt(detectRequestType(userMessage)) }); ``` ## Troubleshooting **Problem**: Agent responses don't align with system prompt instructions **Solutions**: * Make guidelines more explicit and specific * Use imperative language ("Always...", "Never...", "Must...") * Add examples of desired behavior in the prompt * Check for conflicting instructions * Combine with rules for stricter enforcement ```typescript theme={null} // More explicit guidance system: `You are a customer support agent. ALWAYS: - Start with a friendly greeting - Acknowledge the customer's issue - Provide step-by-step solutions - Confirm issue resolution - Thank the customer NEVER: - Make promises you can't keep - Share confidential information - Argue with customers - Skip verification steps` ``` **Problem**: System prompt is becoming unwieldy **Solutions**: * Extract reference material to custom tools or documents * Focus on core role and critical guidelines * Use concise, structured formatting * Move detailed examples to separate documentation ```typescript theme={null} // Concise version system: `You are a data analyst (retail, 5+ years experience). Approach: EDA → validation → modeling → insights Tools: Python (pandas, sklearn), SQL Output: Clear visualizations + actionable recommendations Constraints: Cite sources, explain assumptions, highlight limitations` ``` **Problem**: Agent behaves differently across similar requests **Solutions**: * Make prompts more deterministic with clear procedures * Add structured decision-making frameworks * Include examples of edge cases * Use rules for critical constraints ```typescript theme={null} system: `You are a content moderator. Decision Framework: 1. Check against policy list (hate speech, spam, etc.) 2. If policy violation → flag and explain which policy 3. If unclear → mark for human review 4. If acceptable → approve Always provide specific policy citation for flags.` ``` **Problem**: Agent seems to forget system prompt guidance in long conversations **Solutions**: * Reinforce critical points in user messages * Create new sessions for distinct conversation phases * Use rules to enforce critical constraints * Periodically remind agent of role in conversation ```typescript theme={null} // Reinforce in message for critical tasks const result = await agentbase.runAgent({ message: "Remember your role as a compliance officer. Review this contract...", session: existingSession, system: complianceOfficerPrompt }); ``` ## Testing and Validation ### Testing Prompt Effectiveness ```typescript TypeScript theme={null} // Test prompt with various inputs async function testPrompt(systemPrompt: string, testCases: string[]) { const results = []; for (const testCase of testCases) { const result = await agentbase.runAgent({ message: testCase, system: systemPrompt }); results.push({ input: testCase, output: result.message, followsGuidelines: validateResponse(result.message) }); } return results; } // Validate response quality function validateResponse(response: string): boolean { // Check for required elements based on prompt const hasGreeting = response.includes('Hello') || response.includes('Hi'); const hasSteps = response.split('\n').length > 3; const hasConclusion = response.includes('Let me know') || response.includes('help'); return hasGreeting && hasSteps && hasConclusion; } ``` ```python Python theme={null} # Test prompt with various inputs async def test_prompt(system_prompt: str, test_cases: list): results = [] for test_case in test_cases: result = agentbase.run_agent( message=test_case, system=system_prompt ) results.append({ 'input': test_case, 'output': result.message, 'follows_guidelines': validate_response(result.message) }) return results # Validate response quality def validate_response(response: str) -> bool: # Check for required elements based on prompt has_greeting = 'Hello' in response or 'Hi' in response has_steps = len(response.split('\n')) > 3 has_conclusion = 'Let me know' in response or 'help' in response return has_greeting and has_steps and has_conclusion ``` ## Related Primitives Add strict constraints and requirements to agent behavior Extend agent capabilities with domain-specific tools Create specialized agents for different roles Maintain prompt context across conversations ## Additional Resources Complete system prompt parameters Combine prompts with rules Example agent implementations **Remember**: Great system prompts are specific, structured, and tested. Start simple, iterate based on results, and refine as you understand your use case better. # Sessions Source: https://docs.agentbase.sh/primitives/essentials/sessions Persistent conversation containers that maintain context, state, and memory across requests > Sessions are the foundational container for agent conversations, providing persistent context, state management, and continuity across multiple requests. ## Overview The Sessions primitive represents a persistent conversation thread between you and an agent. Each session is a unique, isolated container that maintains: * **Conversation History**: All messages and responses in chronological order * **Computational State**: Files, installed packages, and environment configuration * **Context Memory**: Agent's understanding of ongoing tasks and user preferences * **Tool State**: Results from previous tool executions and data gathered * **Session Identity**: Unique identifier for tracking and resuming conversations Sessions enable sophisticated multi-turn interactions where agents can remember context, build on previous work, and maintain continuity across hours, days, or even weeks. Every agent request creates a new session or continues an existing one Message history and state persist automatically at no extra cost Each session is completely isolated from others for security and privacy Sessions can span multiple requests over extended time periods ## How Sessions Work When you make an agent request: 1. **No Session ID**: Agentbase creates a new session with fresh state 2. **With Session ID**: Agentbase resumes the existing session with all previous context 3. **Auto-Pause**: After 5 minutes of inactivity, the computational environment pauses 4. **Auto-Resume**: Next request automatically resumes the paused environment 5. **Expiration**: After extended inactivity, sessions eventually expire and clean up **Session Reuse**: Pass the same `session` parameter to maintain continuity. Each response includes the session ID for use in subsequent requests. ## Code Examples ### Creating a New Session ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Omit session parameter to create new session const result = await agentbase.runAgent({ message: "Hello, I'm starting a new project" }); console.log('Session ID:', result.session); // Output: Session ID: agent_session_abc123xyz789... // Save this session ID for continuing the conversation const sessionId = result.session; ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Omit session parameter to create new session result = agentbase.run_agent( message="Hello, I'm starting a new project" ) print(f"Session ID: {result.session}") # Output: Session ID: agent_session_abc123xyz789... # Save this session ID for continuing the conversation session_id = result.session ``` ```bash cURL theme={null} # Create new session (no session query parameter) curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Hello, I am starting a new project" }' # Response includes session ID in the response # Save the session ID for subsequent requests ``` ### Continuing a Session ```typescript TypeScript theme={null} // Continue existing session const continuation = await agentbase.runAgent({ message: "Let's continue working on that project", session: sessionId // Reuse the session ID from above }); // Agent has full context from previous conversation // All files, packages, and state are preserved ``` ```python Python theme={null} # Continue existing session continuation = agentbase.run_agent( message="Let's continue working on that project", session=session_id # Reuse the session ID from above ) # Agent has full context from previous conversation # All files, packages, and state are preserved ``` ```bash cURL theme={null} # Continue session via query parameter curl -X POST "https://api.agentbase.sh?session=agent_session_abc123xyz789" \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Let'\''s continue working on that project" }' ``` ### Multi-Turn Conversation ```typescript TypeScript theme={null} // Turn 1: Start conversation const turn1 = await agentbase.runAgent({ message: "My name is Alice and I need help building a website" }); const sessionId = turn1.session; // Turn 2: Agent remembers your name const turn2 = await agentbase.runAgent({ message: "What technologies should I use?", session: sessionId }); // Agent response will reference Alice and the website project // Turn 3: Continue with context const turn3 = await agentbase.runAgent({ message: "Can you create the project structure?", session: sessionId }); // Agent knows what project we're talking about // Turn 4: Build on previous work const turn4 = await agentbase.runAgent({ message: "Add a homepage and contact form", session: sessionId }); // Project structure from turn 3 still exists ``` ```python Python theme={null} # Turn 1: Start conversation turn1 = agentbase.run_agent( message="My name is Alice and I need help building a website" ) session_id = turn1.session # Turn 2: Agent remembers your name turn2 = agentbase.run_agent( message="What technologies should I use?", session=session_id ) # Agent response will reference Alice and the website project # Turn 3: Continue with context turn3 = agentbase.run_agent( message="Can you create the project structure?", session=session_id ) # Agent knows what project we're talking about # Turn 4: Build on previous work turn4 = agentbase.run_agent( message="Add a homepage and contact form", session=session_id ) # Project structure from turn 3 still exists ``` ### Session Management Pattern ```typescript TypeScript theme={null} interface WorkflowSession { id: string; userId: string; type: string; sessionId: string; status: 'active' | 'paused' | 'completed'; createdAt: Date; lastActivity: Date; } class SessionManager { async createWorkflow(userId: string, type: string): Promise { // Start new agent session const result = await agentbase.runAgent({ message: `Initialize ${type} workflow`, system: `You are assisting with a ${type} workflow.` }); // Store session in database const workflow = await db.workflows.create({ id: generateId(), userId, type, sessionId: result.session, status: 'active', createdAt: new Date(), lastActivity: new Date() }); return workflow.id; } async continueWorkflow(workflowId: string, message: string) { // Retrieve session const workflow = await db.workflows.findById(workflowId); if (!workflow) { throw new Error('Workflow not found'); } // Continue agent session const result = await agentbase.runAgent({ message, session: workflow.sessionId }); // Update last activity await db.workflows.update(workflowId, { lastActivity: new Date() }); return result; } async getWorkflowHistory(workflowId: string) { const workflow = await db.workflows.findById(workflowId); // Get message history for session const messages = await agentbase.getMessages(workflow.sessionId); return messages; } async completeWorkflow(workflowId: string) { await db.workflows.update(workflowId, { status: 'completed', completedAt: new Date() }); } } ``` ```python Python theme={null} from datetime import datetime from typing import Literal class WorkflowSession: def __init__(self, id: str, user_id: str, type: str, session_id: str, status: str, created_at: datetime, last_activity: datetime): self.id = id self.user_id = user_id self.type = type self.session_id = session_id self.status = status self.created_at = created_at self.last_activity = last_activity class SessionManager: async def create_workflow(self, user_id: str, workflow_type: str) -> str: # Start new agent session result = agentbase.run_agent( message=f"Initialize {workflow_type} workflow", system=f"You are assisting with a {workflow_type} workflow." ) # Store session in database workflow = await db.workflows.create({ 'id': generate_id(), 'user_id': user_id, 'type': workflow_type, 'session_id': result.session, 'status': 'active', 'created_at': datetime.now(), 'last_activity': datetime.now() }) return workflow.id async def continue_workflow(self, workflow_id: str, message: str): # Retrieve session workflow = await db.workflows.find_by_id(workflow_id) if not workflow: raise ValueError('Workflow not found') # Continue agent session result = agentbase.run_agent( message=message, session=workflow.session_id ) # Update last activity await db.workflows.update(workflow_id, { 'last_activity': datetime.now() }) return result async def get_workflow_history(self, workflow_id: str): workflow = await db.workflows.find_by_id(workflow_id) # Get message history for session messages = agentbase.get_messages(workflow.session_id) return messages async def complete_workflow(self, workflow_id: str): await db.workflows.update(workflow_id, { 'status': 'completed', 'completed_at': datetime.now() }) ``` ## Session Lifecycle ### Creation New sessions are created automatically: ```typescript theme={null} // No session parameter = new session created const newSession = await agentbase.runAgent({ message: "Start fresh" }); // Session characteristics: // - Unique session ID // - Empty message history // - Clean environment (no files, packages) // - Fresh computational state ``` ### Active Phase Session is actively being used: ```typescript theme={null} // Active session characteristics: // - Computational environment running // - Instant response times // - All state immediately accessible const active = await agentbase.runAgent({ message: "Continue working", session: activeSessionId }); ``` ### Pause Phase After 5 minutes of inactivity: ```typescript theme={null} // Session pauses automatically // - Computational environment suspended // - All state preserved (files, packages) // - Message history intact // - Next request will auto-resume (~1-2 seconds) // After 10 minutes of no activity... const resumed = await agentbase.runAgent({ message: "Resume work", session: pausedSessionId }); // Automatically resumes, all state intact ``` ### Expiration After extended inactivity: ```typescript theme={null} // Eventually sessions expire // Attempting to use expired session: try { const result = await agentbase.runAgent({ message: "Use old session", session: expiredSessionId }); } catch (error) { if (error.code === 'SESSION_NOT_FOUND') { // Session no longer exists // Start new session or restore from backup } } ``` ## Use Cases ### 1. Interactive Development Multi-session development workflow: ```typescript theme={null} async function interactiveDevelopment() { // Day 1: Start project const day1 = await agentbase.runAgent({ message: "Create a React app with TypeScript" }); const projectSession = day1.session; // Day 1: Setup continues await agentbase.runAgent({ message: "Add React Router and set up routing", session: projectSession }); // Store session ID overnight await saveSessionToDatabase({ projectName: 'my-react-app', sessionId: projectSession, lastActivity: new Date() }); // Day 2: Resume work const savedSession = await loadSessionFromDatabase('my-react-app'); await agentbase.runAgent({ message: "Add authentication flow", session: savedSession.sessionId }); // All previous work still available } ``` ### 2. Customer Support Conversations Maintain context throughout support interactions: ```typescript theme={null} async function customerSupport(customerId: string) { // Customer initiates conversation const initial = await agentbase.runAgent({ message: "Customer: I can't log into my account", system: `You are a customer support agent for TechCorp. Customer ID: ${customerId}`, mcpServers: [{ serverName: 'customer-api', serverUrl: 'https://api.company.com/mcp' }] }); const supportSession = initial.session; // Store session for this customer interaction await db.supportTickets.create({ customerId, sessionId: supportSession, status: 'open', issue: 'login problem' }); // 10 minutes later, customer responds await agentbase.runAgent({ message: "Customer: I tried resetting my password but didn't get the email", session: supportSession // Agent remembers the original issue and all previous context }); // 1 hour later, issue resolved const resolution = await agentbase.runAgent({ message: "Customer: It's working now, thank you!", session: supportSession }); // Update ticket status await db.supportTickets.update({ sessionId: supportSession, status: 'resolved', resolution: resolution.message }); } ``` ### 3. Long-Running Research Projects Accumulate research over multiple sessions: ```typescript theme={null} async function researchProject(topic: string) { // Week 1: Initial research const week1 = await agentbase.runAgent({ message: `Research ${topic} and create a document with key findings` }); const researchSession = week1.session; // Week 2: Expand research await agentbase.runAgent({ message: "Add recent developments and industry trends", session: researchSession }); // Week 3: Add case studies await agentbase.runAgent({ message: "Find and document 5 real-world case studies", session: researchSession }); // Week 4: Finalize const final = await agentbase.runAgent({ message: "Organize all research into a comprehensive report with executive summary", session: researchSession }); return final; } ``` ### 4. Multi-User Collaboration Separate sessions per user: ```typescript theme={null} async function collaborativeProject(projectId: string, userId: string) { // Each user gets their own session for the same project const userSession = await getUserSession(projectId, userId); if (!userSession) { // Create new session for this user const result = await agentbase.runAgent({ message: `Load project ${projectId} for user ${userId}`, system: "You are assisting with a collaborative project." }); await saveUserSession({ projectId, userId, sessionId: result.session, role: 'contributor' }); return result.session; } // User continues their work in their session return userSession.sessionId; } // User A works in their session const userA = await collaborativeProject('proj_123', 'user_alice'); await agentbase.runAgent({ message: "Work on feature A", session: userA }); // User B works in separate session const userB = await collaborativeProject('proj_123', 'user_bob'); await agentbase.runAgent({ message: "Work on feature B", session: userB }); // Sessions are isolated but can be coordinated ``` ### 5. Testing and Iteration Separate sessions for different test scenarios: ```typescript theme={null} async function testingWorkflow() { // Create test scenarios in separate sessions const scenarios = [ 'test happy path with valid data', 'test error handling with invalid data', 'test edge cases with boundary values' ]; const sessions = await Promise.all( scenarios.map(async (scenario) => { const result = await agentbase.runAgent({ message: `Set up test environment and ${scenario}`, system: "You are a QA engineer running test scenarios." }); return { scenario, sessionId: result.session, result: result.message }; }) ); // Each test runs in isolated session // Continue specific tests as needed await agentbase.runAgent({ message: "Run additional edge case tests", session: sessions[2].sessionId // Edge case session }); } ``` ### 6. Scheduled Workflows Sessions for recurring tasks: ```typescript theme={null} async function scheduledReport(reportType: string) { // Check if session exists for this report type const existing = await db.scheduledReports.findByType(reportType); let sessionId: string; if (existing && existing.sessionId) { // Reuse session for continuity sessionId = existing.sessionId; } else { // Create new session const init = await agentbase.runAgent({ message: `Initialize ${reportType} reporting workflow`, system: `You maintain a recurring ${reportType} report.` }); sessionId = init.session; await db.scheduledReports.create({ reportType, sessionId, schedule: 'weekly' }); } // Generate this week's report const report = await agentbase.runAgent({ message: "Generate report for this week and compare to previous weeks", session: sessionId // Historical context from previous reports available }); return report; } ``` ## Best Practices ### Session Organization ```typescript theme={null} // Good: Dedicated session per workflow const dataAnalysis = await agentbase.runAgent({ message: "Analyze customer data" }); const contentGen = await agentbase.runAgent({ message: "Generate marketing content" }); // Each workflow has clean, focused context // Avoid: Mixing unrelated workflows const mixed = await agentbase.runAgent({ message: "Analyze data" }); await agentbase.runAgent({ message: "Now write marketing content", session: mixed.session // Confusing context with unrelated previous work }); ``` ```typescript theme={null} interface SessionMetadata { sessionId: string; userId: string; workflowType: string; status: 'active' | 'paused' | 'completed'; createdAt: Date; lastActivity: Date; description: string; tags: string[]; } async function createTrackedSession(metadata: Omit) { const result = await agentbase.runAgent({ message: `Start ${metadata.workflowType} workflow` }); await db.sessions.create({ ...metadata, sessionId: result.session, createdAt: new Date(), lastActivity: new Date() }); return result.session; } ``` ```typescript theme={null} async function cleanupCompletedSessions() { // Archive or delete completed workflows const completedSessions = await db.sessions.find({ status: 'completed', completedAt: { $lt: thirtyDaysAgo() } }); for (const session of completedSessions) { // Export important data const history = await agentbase.getMessages(session.sessionId); await archiveSession({ sessionId: session.sessionId, history, metadata: session }); // Remove from active tracking await db.sessions.delete(session.sessionId); } } ``` ### Performance Optimization Keep sessions alive for related tasks to avoid cold start overhead Use different sessions for unrelated work to keep context clean Track session creation time and plan for eventual expiration Group related requests in same session to leverage warm state ### Error Handling ```typescript theme={null} async function robustSessionRequest( sessionId: string | undefined, message: string, fallbackStrategy: 'create' | 'restore' ) { try { return await agentbase.runAgent({ message, session: sessionId }); } catch (error) { if (error.code === 'SESSION_NOT_FOUND') { if (fallbackStrategy === 'create') { // Start fresh return await agentbase.runAgent({ message }); } else { // Restore from checkpoint const checkpoint = await loadCheckpoint(sessionId); const restored = await agentbase.runAgent({ message: `Restore session: ${checkpoint.description}`, system: checkpoint.context }); // Update session ID await updateStoredSession(sessionId, restored.session); return restored; } } throw error; } } ``` ```typescript theme={null} async function validateSession(sessionId: string): Promise { try { // Test if session is still valid await agentbase.runAgent({ message: "ping", session: sessionId }); return true; } catch (error) { if (error.code === 'SESSION_NOT_FOUND') { return false; } throw error; } } // Use in workflow if (!(await validateSession(storedSessionId))) { console.warn('Session expired, creating new one'); storedSessionId = await createNewSession(); } ``` ### Security and Isolation **Session Isolation**: Each session is completely isolated. Never share session IDs between different users or security contexts. ```typescript theme={null} // Good: User-specific sessions async function getUserSession(userId: string, workflowId: string) { const session = await db.sessions.findOne({ userId, workflowId }); if (!session) { throw new Error('Session not found or unauthorized'); } // Verify user owns this session if (session.userId !== userId) { throw new Error('Unauthorized access to session'); } return session.sessionId; } // Avoid: Sharing sessions between users const sharedSession = 'agent_session_123'; // Don't do this! ``` ## Integration with Other Primitives ### With States Sessions contain states: ```typescript theme={null} // Session = container // State = contents (messages, files, environment) const session = await agentbase.runAgent({ message: "Create project files" }); // State persists within session await agentbase.runAgent({ message: "Modify those files", session: session.session }); ``` Learn more: [States Primitive](/primitives/essentials/states) ### With Prompts Different sessions can have different prompts: ```typescript theme={null} // Session 1: Data analyst const analyst = await agentbase.runAgent({ message: "Analyze this data", system: "You are a data analyst" }); // Session 2: Content writer (different session, different role) const writer = await agentbase.runAgent({ message: "Write a blog post", system: "You are a content writer" }); // Each session maintains its role throughout ``` Learn more: [Prompts Primitive](/primitives/essentials/prompts) ### With Multi-Agent Sessions can involve multiple agents: ```typescript theme={null} // Main session coordinates multiple agents const support = await agentbase.runAgent({ message: "I need help", system: "You are a routing agent", agents: [ { name: "Technical Support", description: "Handles technical issues" }, { name: "Billing Support", description: "Handles billing questions" } ] }); // All agent transfers happen within the same session ``` Learn more: [Multi-Agent Primitive](/primitives/essentials/multi-agents) ### With Custom Tools Tools are available throughout session: ```typescript theme={null} // Configure tools for entire session const session = await agentbase.runAgent({ message: "Access customer database", mcpServers: [{ serverName: 'crm', serverUrl: 'https://api.company.com/mcp' }] }); // Tools available in all subsequent requests await agentbase.runAgent({ message: "Fetch customer data", session: session.session // CRM tools still configured }); ``` Learn more: [Custom Tools Primitive](/primitives/essentials/custom-tools) ## Performance Considerations ### Session Startup Time * **New Session (Cold Start)**: 2-5 seconds to create environment * **Existing Session (Warm)**: Instant, environment already loaded * **Resumed Session (After Pause)**: 1-2 seconds to resume ```typescript theme={null} // Optimize by reusing sessions const sessionId = initResult.session; // All subsequent requests are warm starts for (let i = 0; i < 10; i++) { await agentbase.runAgent({ message: `Task ${i}`, session: sessionId // Fast: warm start }); } ``` ### Memory and Context Very long sessions may accumulate large context: * **Short sessions** (\<10 messages): Optimal performance * **Medium sessions** (10-50 messages): Good performance * **Long sessions** (50+ messages): Consider periodic summarization ```typescript theme={null} // For very long sessions, periodically summarize if (messageCount > 50) { const summary = await agentbase.runAgent({ message: "Summarize our conversation and key decisions so far", session: longSession }); // Store summary, potentially start new session with summary as context } ``` ### Resource Usage Monitor session resource consumption: ```typescript theme={null} async function monitorSession(sessionId: string) { // Check disk usage const diskCheck = await agentbase.runAgent({ message: "Check disk usage with df -h", session: sessionId }); // Check active processes const processCheck = await agentbase.runAgent({ message: "List running processes", session: sessionId }); // Log for monitoring console.log({ sessionId, disk: diskCheck.message, processes: processCheck.message }); } ``` ## Troubleshooting **Problem**: Error when trying to use session ID **Solutions**: * Verify session ID is correct * Check if session has expired * Implement fallback to create new session ```typescript theme={null} try { await agentbase.runAgent({ message: "Continue work", session: maybeExpiredSession }); } catch (error) { if (error.code === 'SESSION_NOT_FOUND') { // Session expired - start fresh or restore const newSession = await agentbase.runAgent({ message: "Start fresh session" }); // Update stored session ID await updateSessionId(newSession.session); } } ``` **Problem**: Agent doesn't remember previous messages **Solution**: Ensure you're passing the session ID ```typescript theme={null} // Wrong: Not passing session const step1 = await agentbase.runAgent({ message: "My name is Alice" }); const step2 = await agentbase.runAgent({ message: "What's my name?" // Missing: session: step1.session }); // Agent won't remember (different session) // Correct: Pass session ID const step2Fixed = await agentbase.runAgent({ message: "What's my name?", session: step1.session // ✓ Same session }); // Agent remembers: "Your name is Alice" ``` **Problem**: Requests to existing session are slow **Possible Causes**: * Session was paused and is resuming * Large message history * Heavy computational state **Solutions**: * Keep sessions active with periodic requests * Summarize long conversations * Clean up large files ```typescript theme={null} // Keep session warm setInterval(async () => { await agentbase.runAgent({ message: "status check", session: activeSessionId }); }, 4 * 60 * 1000); // Every 4 minutes (before 5-minute pause) ``` **Problem**: Unrelated context interfering with current task **Solution**: Use separate sessions for different workflows ```typescript theme={null} // Good: Separate sessions for separate concerns const projectA = await agentbase.runAgent({ message: "Work on project A" }); const projectB = await agentbase.runAgent({ message: "Work on project B" // Different session, clean context }); // Continue each independently await agentbase.runAgent({ message: "Continue project A", session: projectA.session }); ``` ## Related Primitives What persists within sessions Isolated environment for each session Managing conversation context effectively Multiple agents within one session ## Additional Resources Session parameters and options Retrieve session message history How persistence works **Remember**: Sessions are the foundation of continuity in Agentbase. Save session IDs, reuse them for related work, and use separate sessions for independent workflows. # States Source: https://docs.agentbase.sh/primitives/essentials/states Manage agent state, memory, and context across conversations and workflows > States enable agents to maintain context, remember past interactions, and build upon previous work across multiple requests and sessions. ## Overview The States primitive represents the agent's persistent memory and context management system. While sessions provide the container for conversations, states determine what information persists and how agents maintain context across interactions. This enables sophisticated workflows where agents can: * **Remember Context**: Maintain conversation history and relevant information across requests * **Build Incrementally**: Continue work from previous steps without starting over * **Track Progress**: Keep track of multi-step workflows and their current state * **Share Knowledge**: Make information available across different parts of a workflow * **Maintain Variables**: Store and retrieve data throughout the agent's execution Message history persists automatically at no cost for all conversations Files, installed packages, and system state persist within session sandboxes Each session maintains its own isolated state and context Agents build upon previous work without repeating completed steps ## How State Works in Agentbase Agentbase implements a two-tier state management model: ### 1. Conversational State (Message History) **Automatic & Free**: Every message in a session is automatically persisted: ```mermaid theme={null} graph LR A[Request 1] --> B[Message Store] C[Request 2] --> B D[Request 3] --> B B --> E[Agent Context] E --> F[Response] ``` * **What's Stored**: All user messages, agent responses, tool calls, and their results * **Cost**: Zero - message history is always free * **Retention**: Persists for the lifetime of the session * **Access**: Automatically included in agent context for subsequent requests ### 2. Computational State (Environment) **On-Demand Creation**: The sandbox environment state when agents perform operations: * **Files Created**: All files written persist in the session sandbox * **Packages Installed**: Dependencies remain installed across requests * **System State**: Environment variables, running processes, directory structure * **Browser State**: Cookies, local storage, authentication sessions **Session Continuity**: Both conversational and computational state are tied to session IDs. Reuse the same session ID to maintain all context. ## Code Examples ### Basic State Persistence ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // First request - creates state const step1 = await agentbase.runAgent({ message: "Create a file called data.json with some sample data" }); console.log('Session ID:', step1.session); // Output: Session ID: agent_session_abc123... // Second request - uses existing state const step2 = await agentbase.runAgent({ message: "Read the data.json file and summarize its contents", session: step1.session // Reuse session = reuse state }); // The file still exists! Agent can read it. ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # First request - creates state step1 = agentbase.run_agent( message="Create a file called data.json with some sample data" ) print(f"Session ID: {step1.session}") # Output: Session ID: agent_session_abc123... # Second request - uses existing state step2 = agentbase.run_agent( message="Read the data.json file and summarize its contents", session=step1.session # Reuse session = reuse state ) # The file still exists! Agent can read it. ``` ```bash cURL theme={null} # First request - creates state curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Create a file called data.json with some sample data" }' # Response includes session ID: agent_session_abc123 # Second request - uses existing state curl -X POST "https://api.agentbase.sh?session=agent_session_abc123" \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Read the data.json file and summarize its contents" }' # The file persists in the session ``` ### Multi-Step Workflow with State ```typescript TypeScript theme={null} // Step 1: Setup environment const setup = await agentbase.runAgent({ message: "Install pandas and numpy" }); // Step 2: Process data (packages still installed) const process = await agentbase.runAgent({ message: "Create a Python script to process sales.csv", session: setup.session }); // Step 3: Analyze (script and packages still available) const analyze = await agentbase.runAgent({ message: "Run the script and show the analysis", session: setup.session }); // Step 4: Visualize (all previous work available) const visualize = await agentbase.runAgent({ message: "Create a chart from the analysis results", session: setup.session }); // Each step builds on previous state ``` ```python Python theme={null} # Step 1: Setup environment setup = agentbase.run_agent( message="Install pandas and numpy" ) # Step 2: Process data (packages still installed) process = agentbase.run_agent( message="Create a Python script to process sales.csv", session=setup.session ) # Step 3: Analyze (script and packages still available) analyze = agentbase.run_agent( message="Run the script and show the analysis", session=setup.session ) # Step 4: Visualize (all previous work available) visualize = agentbase.run_agent( message="Create a chart from the analysis results", session=setup.session ) # Each step builds on previous state ``` ### Conversational Context ```typescript TypeScript theme={null} // Agent remembers conversation history const result1 = await agentbase.runAgent({ message: "My name is Alice and I work at TechCorp" }); const result2 = await agentbase.runAgent({ message: "What's my name?", session: result1.session }); // Agent responds: "Your name is Alice" const result3 = await agentbase.runAgent({ message: "Where do I work?", session: result1.session }); // Agent responds: "You work at TechCorp" // All previous messages are in context ``` ```python Python theme={null} # Agent remembers conversation history result1 = agentbase.run_agent( message="My name is Alice and I work at TechCorp" ) result2 = agentbase.run_agent( message="What's my name?", session=result1.session ) # Agent responds: "Your name is Alice" result3 = agentbase.run_agent( message="Where do I work?", session=result1.session ) # Agent responds: "You work at TechCorp" # All previous messages are in context ``` ### Stateful Development Workflow ```typescript TypeScript theme={null} // Create a complete development workflow with persistent state async function developmentWorkflow() { // Initialize project const init = await agentbase.runAgent({ message: "Create a new Node.js project with package.json" }); const sessionId = init.session; // Install dependencies await agentbase.runAgent({ message: "Install express, dotenv, and nodemon", session: sessionId }); // Create application await agentbase.runAgent({ message: "Create a basic Express server in src/index.js", session: sessionId }); // Add features await agentbase.runAgent({ message: "Add a /health endpoint to the server", session: sessionId }); // Test const test = await agentbase.runAgent({ message: "Start the server and test the health endpoint", session: sessionId }); return test; } ``` ```python Python theme={null} # Create a complete development workflow with persistent state async def development_workflow(): # Initialize project init = agentbase.run_agent( message="Create a new Node.js project with package.json" ) session_id = init.session # Install dependencies agentbase.run_agent( message="Install express, dotenv, and nodemon", session=session_id ) # Create application agentbase.run_agent( message="Create a basic Express server in src/index.js", session=session_id ) # Add features agentbase.run_agent( message="Add a /health endpoint to the server", session=session_id ) # Test test = agentbase.run_agent( message="Start the server and test the health endpoint", session=session_id ) return test ``` ## State Lifecycle ### State Creation State is created automatically on the first request in a session: ```typescript theme={null} // No session ID = new session = new state const result = await agentbase.runAgent({ message: "Start a new project" }); // Fresh state: // - Empty message history // - Clean file system // - No installed packages // - Default environment ``` ### State Persistence State persists throughout the session: ```typescript theme={null} // Same session = same state const continued = await agentbase.runAgent({ message: "Continue from where we left off", session: existingSessionId }); // Preserved state: // - All previous messages // - All created files // - All installed packages // - Environment variables // - Working directory ``` ### State Pause and Resume After 5 minutes of inactivity, the computational environment pauses: ```typescript theme={null} // Agent pauses after 5 minutes of no requests // ... 10 minutes pass ... // Resume automatically on next request const resumed = await agentbase.runAgent({ message: "Let's continue", session: pausedSessionId }); // State restored: // - Message history: ✓ intact // - Files: ✓ intact // - Packages: ✓ intact // - Running processes: ✗ stopped (need restart) ``` ### State Cleanup Sessions eventually expire after extended inactivity: ```typescript theme={null} // After session expires, state is cleaned up // Attempting to use expired session creates new session try { const result = await agentbase.runAgent({ message: "Resume old session", session: veryOldSessionId }); } catch (error) { if (error.code === 'SESSION_EXPIRED') { // Start fresh const newResult = await agentbase.runAgent({ message: "Start new session" }); } } ``` ## Use Cases ### 1. Iterative Development Build software incrementally: ```typescript theme={null} async function iterativeDevelopment() { // Session for the entire development process const session = (await agentbase.runAgent({ message: "Create a Python web scraper project structure" })).session; // Each step builds on the previous await agentbase.runAgent({ message: "Install beautifulsoup4 and requests", session }); await agentbase.runAgent({ message: "Create scraper.py with basic scraping logic", session }); await agentbase.runAgent({ message: "Add error handling to the scraper", session }); await agentbase.runAgent({ message: "Create tests for the scraper", session }); const final = await agentbase.runAgent({ message: "Run the tests and fix any issues", session }); return final; } ``` ### 2. Data Analysis Pipeline Process data through multiple stages: ```typescript theme={null} async function analysisPipeline(dataUrl: string) { // Start pipeline const download = await agentbase.runAgent({ message: `Download data from ${dataUrl}` }); const sessionId = download.session; // Clean data await agentbase.runAgent({ message: "Clean the data: remove duplicates, handle missing values", session: sessionId }); // Transform await agentbase.runAgent({ message: "Create derived features and aggregate by category", session: sessionId }); // Analyze await agentbase.runAgent({ message: "Perform statistical analysis and identify trends", session: sessionId }); // Visualize const final = await agentbase.runAgent({ message: "Create visualizations and save as report.pdf", session: sessionId }); return final; } ``` ### 3. Long-Running Support Sessions Maintain context throughout customer interactions: ```typescript theme={null} async function customerSupportSession(customerId: string) { // Lookup customer const lookup = await agentbase.runAgent({ message: `Look up customer ${customerId} details`, system: "You are a customer support agent" }); const sessionId = lookup.session; // Throughout the conversation, agent remembers everything const response1 = await agentbase.runAgent({ message: "Customer: I can't access my account", session: sessionId }); const response2 = await agentbase.runAgent({ message: "Customer: I've tried resetting my password", session: sessionId // Agent remembers the original issue and customer details }); const response3 = await agentbase.runAgent({ message: "Customer: That worked, thanks!", session: sessionId // Agent knows what solution was provided }); return sessionId; // Store for potential follow-up } ``` ### 4. Research and Compilation Gather information progressively: ```typescript theme={null} async function researchProject(topic: string) { // Start research const init = await agentbase.runAgent({ message: `Research ${topic} and create a document with findings` }); const sessionId = init.session; // Add more information await agentbase.runAgent({ message: "Search for recent developments in 2024", session: sessionId // Adds to existing document }); await agentbase.runAgent({ message: "Find case studies and real-world examples", session: sessionId // Appends to document }); await agentbase.runAgent({ message: "Add statistics and data points", session: sessionId // Enhances existing content }); const final = await agentbase.runAgent({ message: "Organize all findings into a structured report", session: sessionId // Works with all accumulated information }); return final; } ``` ### 5. Testing and Debugging Iteratively debug and test code: ```typescript theme={null} async function debugWorkflow() { // Create buggy code const code = await agentbase.runAgent({ message: "Create a Python script that processes user data" }); const sessionId = code.session; // Test it const test1 = await agentbase.runAgent({ message: "Run the script with test data", session: sessionId }); // Fix issues found await agentbase.runAgent({ message: "Fix the KeyError in the script", session: sessionId // Script still exists, just modify it }); // Test again const test2 = await agentbase.runAgent({ message: "Run the script again", session: sessionId }); // Add more test cases const final = await agentbase.runAgent({ message: "Test edge cases: empty input, large dataset", session: sessionId }); return final; } ``` ### 6. Document Generation Build documents incrementally: ```typescript theme={null} async function createProposal(clientName: string) { // Start document const init = await agentbase.runAgent({ message: `Create a project proposal document for ${clientName}` }); const sessionId = init.session; // Add sections progressively await agentbase.runAgent({ message: "Add executive summary section", session: sessionId }); await agentbase.runAgent({ message: "Add scope of work with 5 deliverables", session: sessionId }); await agentbase.runAgent({ message: "Add timeline and milestones", session: sessionId }); await agentbase.runAgent({ message: "Add pricing breakdown", session: sessionId }); const final = await agentbase.runAgent({ message: "Format as PDF and create summary slide deck", session: sessionId }); return final; } ``` ## Best Practices ### Session Management ```typescript theme={null} // Store session ID in your database async function startWorkflow(userId: string, workflowType: string) { const result = await agentbase.runAgent({ message: "Initialize workflow" }); // Save for later use await db.workflows.create({ userId, workflowType, sessionId: result.session, status: 'in_progress', createdAt: new Date() }); return result.session; } // Resume later async function continueWorkflow(workflowId: string, message: string) { const workflow = await db.workflows.findById(workflowId); return await agentbase.runAgent({ message, session: workflow.sessionId }); } ``` ```typescript theme={null} // Good: Separate sessions for unrelated tasks const customerAnalysis = await agentbase.runAgent({ message: "Analyze customer churn data" // New session, clean state }); const contentGeneration = await agentbase.runAgent({ message: "Generate marketing content" // Different session, different state }); // Avoid: Mixing unrelated work in one session const mixed = await agentbase.runAgent({ message: "Analyze customer data" }); await agentbase.runAgent({ message: "Now write marketing content", session: mixed.session // Confusing context with unrelated previous work }); ``` ```typescript theme={null} // Clean up large files to manage disk usage const analysis = await agentbase.runAgent({ message: "Process large_dataset.csv and analyze" }); const sessionId = analysis.session; // Continue with analysis results await agentbase.runAgent({ message: "Create summary report", session: sessionId }); // Clean up large files no longer needed await agentbase.runAgent({ message: "Delete large_dataset.csv and any temporary files", session: sessionId }); ``` ### State Organization **Modular State**: Organize files and data logically within sessions for easier navigation and management. ```typescript theme={null} // Well-organized state structure const project = await agentbase.runAgent({ message: `Create project structure: - src/ (source code) - tests/ (test files) - data/ (data files) - output/ (results and reports) - docs/ (documentation)` }); // Use throughout workflow await agentbase.runAgent({ message: "Create analysis script in src/analyze.py", session: project.session }); await agentbase.runAgent({ message: "Save results to output/results.json", session: project.session }); ``` ### State Recovery ```typescript theme={null} async function safeResume(sessionId: string, message: string) { try { return await agentbase.runAgent({ message, session: sessionId }); } catch (error) { if (error.code === 'SESSION_NOT_FOUND') { console.warn('Session expired, starting fresh'); // Either start new session or restore from checkpoint return await agentbase.runAgent({ message: `Resume workflow: ${message}`, system: "Previous session expired, recreate necessary state" }); } throw error; } } ``` ```typescript theme={null} // Save important state externally for recovery async function workflowWithCheckpoints() { const result = await agentbase.runAgent({ message: "Process data and create report" }); const sessionId = result.session; // Create checkpoint - extract important state const checkpoint = await agentbase.runAgent({ message: "List all created files and their purposes", session: sessionId }); // Store checkpoint externally await saveCheckpoint({ sessionId, timestamp: new Date(), files: checkpoint.message, context: "Data processing workflow" }); return result; } ``` ### Performance Optimization Minimize cold starts by reusing sessions for related work Group related tasks in single session to leverage state Remove unused files to stay within disk limits Install common dependencies once per session ## Integration with Other Primitives ### With Sessions Sessions provide the container for state: ```typescript theme={null} // Session = container, State = contents const session1 = await agentbase.runAgent({ message: "Task A" }); // Session 1 has its own state const session2 = await agentbase.runAgent({ message: "Task B" }); // Session 2 has completely separate state ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ### With Sandbox State exists within sandbox boundaries: ```typescript theme={null} // Each sandbox has isolated state const result = await agentbase.runAgent({ message: "Create sensitive_data.txt" }); // File exists only in this sandbox/session // Other sessions cannot access it ``` Learn more: [Sandbox Primitive](/primitives/environment/sandbox) ### With Computer Environment System state persists across requests: ```typescript theme={null} // Install once, use multiple times const setup = await agentbase.runAgent({ message: "Install tensorflow and keras" }); // Packages still installed const train = await agentbase.runAgent({ message: "Train a model using tensorflow", session: setup.session }); // Model file persists const evaluate = await agentbase.runAgent({ message: "Load and evaluate the trained model", session: setup.session }); ``` Learn more: [Computer Primitive](/primitives/environment/computer) ### With File System Files are the primary persistent state: ```typescript theme={null} // Create files that persist const files = await agentbase.runAgent({ message: "Create config.json, data.csv, and script.py" }); // All files still exist const modify = await agentbase.runAgent({ message: "Update config.json with new settings", session: files.session }); // Read any file from the session const read = await agentbase.runAgent({ message: "Show contents of all three files", session: files.session }); ``` Learn more: [File System Primitive](/primitives/environment/file-system) ## Performance Considerations ### State Size Monitor state size to avoid hitting limits: * **Message History**: Unlimited messages, but very long histories may impact performance * **File Storage**: 10GB per session limit * **Memory Usage**: 2-4GB depending on mode ```typescript theme={null} // Check disk usage const check = await agentbase.runAgent({ message: "Show disk usage with du -sh", session: existingSession }); // Clean up if needed if (usageHigh) { await agentbase.runAgent({ message: "Delete files in /tmp and other temporary directories", session: existingSession }); } ``` ### Context Window Management Very long message histories may need summarization: ```typescript theme={null} // For very long sessions, periodically summarize const summary = await agentbase.runAgent({ message: "Summarize our conversation so far and key decisions made", session: longSession }); // Store summary externally, potentially start new session // with summary as context ``` ### Cold Start vs. Warm Start * **Cold Start** (new session): \~2-5 seconds overhead * **Warm Start** (existing session): Instant, state already loaded * **Resumed** (paused session): \~1-2 seconds to resume ```typescript theme={null} // Optimize by reusing sessions const sessionId = await initializeOnce(); // All subsequent requests are warm starts for (const task of tasks) { await agentbase.runAgent({ message: task, session: sessionId // Fast, state already loaded }); } ``` ## Troubleshooting **Problem**: Changes don't persist between requests **Solution**: Verify you're using the same session ID ```typescript theme={null} // Wrong: Not passing session ID const step1 = await agentbase.runAgent({ message: "Create file.txt" }); const step2 = await agentbase.runAgent({ message: "Read file.txt" // Missing session: step1.session }); // Correct: Passing session ID const step2Fixed = await agentbase.runAgent({ message: "Read file.txt", session: step1.session // ✓ Reuses state }); ``` **Problem**: Session no longer available **Solution**: Implement expiration handling and state recovery ```typescript theme={null} async function robustWorkflow(maybeExpiredSession: string) { try { return await agentbase.runAgent({ message: "Continue work", session: maybeExpiredSession }); } catch (error) { if (error.code === 'SESSION_NOT_FOUND') { // Restore from checkpoint or start fresh const checkpoint = await loadCheckpoint(maybeExpiredSession); return await agentbase.runAgent({ message: `Resume: ${checkpoint.description}`, system: `Context: ${checkpoint.context}` }); } throw error; } } ``` **Problem**: Hit 10GB storage limit **Solution**: Clean up large files regularly ```typescript theme={null} // Monitor disk usage const usage = await agentbase.runAgent({ message: "Check disk usage and list large files", session: existingSession }); // Clean up await agentbase.runAgent({ message: "Delete temporary files and large downloads", session: existingSession }); ``` **Problem**: Previous state interfering with new tasks **Solution**: Start new session for unrelated work ```typescript theme={null} // Don't mix unrelated tasks // Instead of: const mixed = await agentbase.runAgent({ message: "Different task", session: existingSession // May have conflicting state }); // Do this: const clean = await agentbase.runAgent({ message: "Different task" // New session, clean state }); ``` ## Advanced Patterns ### State Snapshots Create snapshots of important state: ```typescript theme={null} async function createSnapshot(sessionId: string) { // List all important state const state = await agentbase.runAgent({ message: `Create a snapshot: 1. List all files in project directory 2. Export environment variables 3. List installed packages 4. Summarize current progress`, session: sessionId }); // Store snapshot externally return { sessionId, timestamp: new Date(), snapshot: state.message }; } // Restore from snapshot async function restoreFromSnapshot(snapshot: any) { return await agentbase.runAgent({ message: `Restore state: ${snapshot.snapshot}`, system: "Recreate the described environment and files" }); } ``` ### State Migration Move state between sessions: ```typescript theme={null} async function migrateState(oldSession: string, newSession: string) { // Export state from old session const exported = await agentbase.runAgent({ message: "Create export.tar.gz with all project files", session: oldSession }); // Import to new session await agentbase.runAgent({ message: "Extract and restore from export.tar.gz", session: newSession }); } ``` ### Conditional State Reset Reset parts of state while keeping others: ```typescript theme={null} async function partialReset(sessionId: string) { // Keep some state, reset other parts await agentbase.runAgent({ message: `Clean up state: - Keep: source files in src/ - Keep: configuration files - Delete: temporary files - Delete: cached data - Reset: output directory`, session: sessionId }); } ``` ## Related Primitives Container for state and conversations Isolated environment hosting state Primary mechanism for persistent state System state and environment persistence ## Additional Resources Understanding Agentbase's persistence model Session and state parameters Production patterns and tips **Remember**: State management is automatic in Agentbase. Focus on organizing your workflows logically, and the platform handles persistence, isolation, and cleanup. # Traces Source: https://docs.agentbase.sh/primitives/essentials/traces Real-time execution visibility and debugging through comprehensive trace data > Traces provide complete visibility into agent execution, exposing every decision, tool call, and reasoning step as a primitive for debugging, monitoring, and optimization. ## Overview The Traces primitive gives you real-time insight into agent execution by streaming detailed events about what the agent is thinking, which tools it's using, and how it's progressing toward task completion. Traces are the foundation for understanding, debugging, and optimizing agent behavior. Traces are essential for: * **Debugging**: Understand why agents make specific decisions or encounter errors * **Optimization**: Identify inefficiencies and opportunities for improvement * **Monitoring**: Track agent performance and behavior in production * **Audit**: Maintain detailed records of agent actions * **Learning**: Understand agent reasoning patterns and decision-making Receive execution events as they happen during agent processing See every thought, tool call, and intermediate result Well-defined event types make traces easy to parse and analyze Traces available automatically for every agent request ## How Traces Work ### Event Stream Traces are delivered as a stream of events: 1. **Agent Starts**: Execution begins 2. **Thinking Events**: Agent reasons about the task 3. **Tool Use Events**: Agent calls tools 4. **Tool Response Events**: Tools return results 5. **Step Completion**: Agent finishes a reasoning step 6. **Cost Events**: Cost incurred for operations 7. **Error Events**: Errors encountered during execution 8. **Completion**: Agent finishes successfully ### Event Structure Each trace event contains: * **Event Type**: What kind of event occurred * **Timestamp**: When the event happened * **Context**: Session ID, step number, etc. * **Payload**: Event-specific data * **Metadata**: Additional contextual information **Streaming by Default**: Set `stream: true` to receive events in real-time. Without streaming, you only get the final result. ## Code Examples ### Basic Trace Streaming ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Enable streaming to receive traces const result = await agentbase.runAgent({ message: "Analyze this data and create a report", mode: "base", stream: true // Enable trace streaming }); // Iterate over trace events for await (const event of result) { console.log(`[${event.type}]`, event); switch (event.type) { case 'agent_thinking': console.log('💭 Thinking:', event.content); break; case 'agent_tool_use': console.log('🔧 Using tool:', event.tool); console.log(' Input:', event.input); break; case 'agent_tool_response': console.log('✅ Tool response received'); break; case 'agent_step': console.log(`📍 Completed step ${event.stepNumber}`); break; case 'agent_cost': console.log(`💰 Cost: $${event.cost}`); break; case 'agent_message': console.log('📨 Final message:', event.content); break; case 'agent_error': console.error('❌ Error:', event.error); break; } } ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Enable streaming to receive traces result = agentbase.run_agent( message="Analyze this data and create a report", mode="base", stream=True # Enable trace streaming ) # Iterate over trace events for event in result: print(f"[{event.type}]", event) if event.type == 'agent_thinking': print(f"💭 Thinking: {event.content}") elif event.type == 'agent_tool_use': print(f"🔧 Using tool: {event.tool}") print(f" Input: {event.input}") elif event.type == 'agent_tool_response': print("✅ Tool response received") elif event.type == 'agent_step': print(f"📍 Completed step {event.step_number}") elif event.type == 'agent_cost': print(f"💰 Cost: ${event.cost}") elif event.type == 'agent_message': print(f"📨 Final message: {event.content}") elif event.type == 'agent_error': print(f"❌ Error: {event.error}") ``` ### Trace Collection and Analysis ```typescript TypeScript theme={null} // Collect and analyze trace data class TraceAnalyzer { private events: any[] = []; private startTime: number = Date.now(); async analyzeExecution(message: string) { this.events = []; this.startTime = Date.now(); const result = await agentbase.runAgent({ message, mode: "base", stream: true }); // Collect all events for await (const event of result) { this.events.push({ ...event, relativeTime: Date.now() - this.startTime }); } // Analyze collected events return this.generateAnalysis(); } generateAnalysis() { const thinking = this.events.filter(e => e.type === 'agent_thinking'); const toolUses = this.events.filter(e => e.type === 'agent_tool_use'); const steps = this.events.filter(e => e.type === 'agent_step'); const errors = this.events.filter(e => e.type === 'agent_error'); const totalDuration = Date.now() - this.startTime; const toolsUsed = toolUses.map(t => t.tool); const uniqueTools = [...new Set(toolsUsed)]; return { totalDuration, totalSteps: steps.length, thinkingEvents: thinking.length, toolCalls: toolUses.length, toolsUsed: uniqueTools, errors: errors.length, avgStepDuration: totalDuration / steps.length, events: this.events }; } getTimeline() { return this.events.map(event => ({ time: event.relativeTime, type: event.type, summary: this.summarizeEvent(event) })); } summarizeEvent(event: any): string { switch (event.type) { case 'agent_thinking': return `Thinking: ${event.content.substring(0, 50)}...`; case 'agent_tool_use': return `Tool: ${event.tool}`; case 'agent_step': return `Step ${event.stepNumber} complete`; case 'agent_error': return `Error: ${event.error}`; default: return event.type; } } } // Usage const analyzer = new TraceAnalyzer(); const analysis = await analyzer.analyzeExecution( "Research AI trends and write summary" ); console.log('Analysis:', analysis); console.log('Timeline:', analyzer.getTimeline()); ``` ```python Python theme={null} # Collect and analyze trace data class TraceAnalyzer: def __init__(self): self.events = [] self.start_time = time.time() async def analyze_execution(self, message: str): self.events = [] self.start_time = time.time() result = agentbase.run_agent( message=message, mode="base", stream=True ) # Collect all events for event in result: self.events.append({ **event.__dict__, 'relative_time': time.time() - self.start_time }) # Analyze collected events return self.generate_analysis() def generate_analysis(self): thinking = [e for e in self.events if e['type'] == 'agent_thinking'] tool_uses = [e for e in self.events if e['type'] == 'agent_tool_use'] steps = [e for e in self.events if e['type'] == 'agent_step'] errors = [e for e in self.events if e['type'] == 'agent_error'] total_duration = time.time() - self.start_time tools_used = [t['tool'] for t in tool_uses] unique_tools = list(set(tools_used)) return { 'total_duration': total_duration, 'total_steps': len(steps), 'thinking_events': len(thinking), 'tool_calls': len(tool_uses), 'tools_used': unique_tools, 'errors': len(errors), 'avg_step_duration': total_duration / len(steps) if steps else 0, 'events': self.events } # Usage analyzer = TraceAnalyzer() analysis = await analyzer.analyze_execution( "Research AI trends and write summary" ) print(f"Analysis: {analysis}") ``` ### Filtering and Focusing Traces ```typescript TypeScript theme={null} // Filter traces to specific event types async function focusedTracing(message: string, focusOn: string[]) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); const relevantEvents = []; for await (const event of result) { // Only process events we care about if (focusOn.includes(event.type)) { relevantEvents.push(event); switch (event.type) { case 'agent_tool_use': console.log(`Tool: ${event.tool}`); console.log(`Input: ${JSON.stringify(event.input, null, 2)}`); break; case 'agent_error': console.error(`Error detected: ${event.error}`); await notifyTeam('Agent error', event.error); break; } } } return relevantEvents; } // Focus on tool usage only const toolEvents = await focusedTracing( "Analyze customer data", ['agent_tool_use', 'agent_tool_response'] ); // Focus on errors const errors = await focusedTracing( "Risky operation", ['agent_error'] ); ``` ### Real-Time Progress Tracking ```typescript TypeScript theme={null} // Track progress in real-time async function trackProgress(message: string, onProgress: (progress: number) => void) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); let currentStep = 0; let estimatedTotalSteps = 10; // Will be updated for await (const event of result) { if (event.type === 'agent_step') { currentStep = event.stepNumber; // Calculate progress percentage const progress = Math.min((currentStep / estimatedTotalSteps) * 100, 95); // Call progress callback onProgress(progress); } if (event.type === 'agent_message') { // Task complete onProgress(100); } } } // Usage with UI updates await trackProgress( "Generate comprehensive report", (progress) => { updateProgressBar(progress); console.log(`Progress: ${progress.toFixed(0)}%`); } ); ``` ```python Python theme={null} # Track progress in real-time async def track_progress(message: str, on_progress: callable): result = agentbase.run_agent( message=message, mode="base", stream=True ) current_step = 0 estimated_total_steps = 10 # Will be updated for event in result: if event.type == 'agent_step': current_step = event.step_number # Calculate progress percentage progress = min((current_step / estimated_total_steps) * 100, 95) # Call progress callback on_progress(progress) if event.type == 'agent_message': # Task complete on_progress(100) # Usage with UI updates await track_progress( "Generate comprehensive report", lambda progress: update_progress_bar(progress) ) ``` ## Trace Event Types ### Agent Thinking Shows agent's internal reasoning: ```json theme={null} { "type": "agent_thinking", "content": "I need to first load the data file, then analyze it for trends. I'll use the file reading tool.", "timestamp": "2025-01-08T10:30:00Z", "session": "agent_session_abc123" } ``` ### Tool Use Agent calls a tool: ```json theme={null} { "type": "agent_tool_use", "tool": "file_read", "input": { "path": "/data/sales.csv" }, "timestamp": "2025-01-08T10:30:01Z" } ``` ### Tool Response Tool returns results: ```json theme={null} { "type": "agent_tool_response", "tool": "file_read", "response": { "content": "date,revenue,units\n2025-01-01,5000,100\n...", "success": true }, "duration": 45, "timestamp": "2025-01-08T10:30:02Z" } ``` ### Step Completion Agent completes a reasoning step: ```json theme={null} { "type": "agent_step", "stepNumber": 1, "session": "agent_session_abc123", "timestamp": "2025-01-08T10:30:05Z" } ``` ### Cost Tracking Cost incurred: ```json theme={null} { "type": "agent_cost", "cost": "0.025", "balance": 47.50, "session": "agent_session_abc123", "timestamp": "2025-01-08T10:30:05Z" } ``` ### Errors Error encountered: ```json theme={null} { "type": "agent_error", "error": "File not found: /data/sales.csv", "step": 1, "recoverable": true, "timestamp": "2025-01-08T10:30:03Z" } ``` ## Use Cases ### 1. Debugging Agent Behavior Understand why agents make specific decisions: ```typescript theme={null} // Investigate why agent chose specific tool async function debugToolChoice(message: string) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); const debugLog = []; for await (const event of result) { debugLog.push(event); if (event.type === 'agent_thinking') { console.log('🤔 Agent reasoning:', event.content); } if (event.type === 'agent_tool_use') { // Find reasoning that led to this tool choice const recentThinking = debugLog .filter(e => e.type === 'agent_thinking') .slice(-3); // Last 3 thinking events console.log('\n🔍 Why agent chose', event.tool); console.log('Recent reasoning:'); recentThinking.forEach(t => { console.log(` - ${t.content}`); }); console.log('\n'); } } return debugLog; } ``` ```typescript theme={null} // Track down source of errors async function traceError(message: string) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); const context = []; for await (const event of result) { context.push(event); if (event.type === 'agent_error') { console.error('\n⚠️ Error detected:', event.error); console.log('\n📝 Events leading to error:'); // Show last 5 events before error const leadingEvents = context.slice(-6, -1); leadingEvents.forEach((e, i) => { console.log(`${i + 1}. [${e.type}]`, summarize(e)); }); console.log('\n💡 Error analysis:'); console.log(' Step:', event.step); console.log(' Recoverable:', event.recoverable); console.log(' Suggestion:', suggestFix(event, leadingEvents)); } } } function suggestFix(error: any, leadingEvents: any[]): string { // Analyze error context and suggest fixes if (error.error.includes('not found')) { return 'Check if file path is correct and file exists'; } if (error.error.includes('permission')) { return 'Verify file permissions and access rights'; } return 'Review leading events for potential causes'; } ``` ### 2. Performance Optimization Identify and eliminate bottlenecks: ```typescript theme={null} // Find performance bottlenecks class PerformanceProfiler { async profileExecution(message: string) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); const profile = { toolDurations: new Map(), stepDurations: [], thinkingTime: 0, totalTime: 0 }; let stepStart = Date.now(); let executionStart = Date.now(); for await (const event of result) { const now = Date.now(); if (event.type === 'agent_tool_response') { // Track tool performance const durations = profile.toolDurations.get(event.tool) || []; durations.push(event.duration || 0); profile.toolDurations.set(event.tool, durations); } if (event.type === 'agent_step') { // Track step duration const stepDuration = now - stepStart; profile.stepDurations.push(stepDuration); stepStart = now; } if (event.type === 'agent_message') { profile.totalTime = now - executionStart; } } // Analyze bottlenecks return this.analyzeBottlenecks(profile); } analyzeBottlenecks(profile: any) { // Find slowest tools const toolStats = Array.from(profile.toolDurations.entries()).map(([tool, durations]) => ({ tool, calls: durations.length, avgDuration: durations.reduce((a, b) => a + b, 0) / durations.length, totalDuration: durations.reduce((a, b) => a + b, 0) })); toolStats.sort((a, b) => b.totalDuration - a.totalDuration); // Find slowest steps const avgStepDuration = profile.stepDurations.reduce((a, b) => a + b, 0) / profile.stepDurations.length; const slowSteps = profile.stepDurations .map((duration, index) => ({ step: index + 1, duration })) .filter(s => s.duration > avgStepDuration * 1.5); return { totalDuration: profile.totalTime, totalSteps: profile.stepDurations.length, avgStepDuration, bottlenecks: { slowestTools: toolStats.slice(0, 3), slowSteps }, recommendations: this.generateRecommendations(toolStats, slowSteps) }; } generateRecommendations(toolStats: any[], slowSteps: any[]): string[] { const recommendations = []; // Recommend caching for frequently called slow tools const frequentSlowTools = toolStats.filter(t => t.calls > 3 && t.avgDuration > 1000); if (frequentSlowTools.length > 0) { recommendations.push( `Consider caching results for: ${frequentSlowTools.map(t => t.tool).join(', ')}` ); } // Recommend parallelization if many slow steps if (slowSteps.length > 2) { recommendations.push('Consider parallelizing independent operations to reduce total time'); } return recommendations; } } // Usage const profiler = new PerformanceProfiler(); const report = await profiler.profileExecution("Complex data analysis task"); console.log('Performance Report:', report); ``` ### 3. Production Monitoring Monitor agent behavior in real-time: ```typescript theme={null} // Real-time production monitoring class ProductionMonitor { private metrics: any = { totalRequests: 0, successfulRequests: 0, failedRequests: 0, avgSteps: 0, avgDuration: 0, toolUsage: new Map() }; async monitorRequest(message: string) { this.metrics.totalRequests++; const startTime = Date.now(); let stepCount = 0; let success = false; try { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); for await (const event of result) { // Track tool usage if (event.type === 'agent_tool_use') { const count = this.metrics.toolUsage.get(event.tool) || 0; this.metrics.toolUsage.set(event.tool, count + 1); } // Track steps if (event.type === 'agent_step') { stepCount++; } // Track errors if (event.type === 'agent_error') { await this.recordError(event); } // Track success if (event.type === 'agent_message') { success = true; } } if (success) { this.metrics.successfulRequests++; } // Update averages const duration = Date.now() - startTime; this.updateAverages(stepCount, duration); // Check for anomalies await this.checkAnomalies(stepCount, duration); } catch (error) { this.metrics.failedRequests++; await this.recordFailure(error); } } updateAverages(steps: number, duration: number) { const n = this.metrics.totalRequests; this.metrics.avgSteps = ((this.metrics.avgSteps * (n - 1)) + steps) / n; this.metrics.avgDuration = ((this.metrics.avgDuration * (n - 1)) + duration) / n; } async checkAnomalies(steps: number, duration: number) { // Alert if execution significantly exceeds averages if (steps > this.metrics.avgSteps * 2) { await sendAlert({ type: 'anomaly', message: `High step count: ${steps} (avg: ${this.metrics.avgSteps})`, severity: 'warning' }); } if (duration > this.metrics.avgDuration * 3) { await sendAlert({ type: 'anomaly', message: `Slow execution: ${duration}ms (avg: ${this.metrics.avgDuration}ms)`, severity: 'warning' }); } } async recordError(event: any) { await sendToErrorTracking({ error: event.error, step: event.step, timestamp: event.timestamp, recoverable: event.recoverable }); } async recordFailure(error: any) { await sendToErrorTracking({ error: error.message, fatal: true, timestamp: new Date() }); } getMetrics() { return { ...this.metrics, successRate: this.metrics.successfulRequests / this.metrics.totalRequests, errorRate: this.metrics.failedRequests / this.metrics.totalRequests }; } } ``` ### 4. Learning from Agent Behavior Analyze patterns to improve prompts: ```typescript theme={null} // Analyze agent patterns async function analyzePatterns(messages: string[]) { const patterns = { commonTools: new Map(), avgStepsByTaskType: new Map(), successfulApproaches: [] }; for (const message of messages) { const result = await agentbase.runAgent({ message, mode: "base", stream: true }); const trace = { tools: [], steps: 0, success: false }; for await (const event of result) { if (event.type === 'agent_tool_use') { trace.tools.push(event.tool); const count = patterns.commonTools.get(event.tool) || 0; patterns.commonTools.set(event.tool, count + 1); } if (event.type === 'agent_step') { trace.steps++; } if (event.type === 'agent_message') { trace.success = true; } } // Categorize by task type const taskType = categorizeTask(message); const steps = patterns.avgStepsByTaskType.get(taskType) || []; steps.push(trace.steps); patterns.avgStepsByTaskType.set(taskType, steps); // Record successful approaches if (trace.success) { patterns.successfulApproaches.push({ taskType, tools: trace.tools, steps: trace.steps }); } } return generateInsights(patterns); } function generateInsights(patterns: any) { // Find most common tools const topTools = Array.from(patterns.commonTools.entries()) .sort((a, b) => b[1] - a[1]) .slice(0, 5); // Find optimal approaches const insights = { mostUsedTools: topTools.map(([tool]) => tool), taskTypePerformance: Array.from(patterns.avgStepsByTaskType.entries()).map(([type, steps]) => ({ taskType: type, avgSteps: steps.reduce((a, b) => a + b, 0) / steps.length, samples: steps.length })), recommendations: [] }; // Generate recommendations for (const approach of patterns.successfulApproaches) { if (approach.steps < 3) { insights.recommendations.push( `For ${approach.taskType}: Use tools ${approach.tools.join(', ')} (efficient approach)` ); } } return insights; } ``` ## Best Practices ### Efficient Trace Processing ```typescript theme={null} // Good: Process events as they arrive for await (const event of stream) { processEvent(event); // Handle immediately } // Avoid: Collecting all events in memory const allEvents = []; for await (const event of stream) { allEvents.push(event); // Memory intensive } ``` ```typescript theme={null} // Filter to only relevant events for await (const event of stream) { // Only process events we care about if (event.type === 'agent_error' || event.type === 'agent_tool_use') { await handleImportantEvent(event); } // Ignore other events } ``` ```typescript theme={null} try { for await (const event of stream) { await processEvent(event); } } catch (error) { console.error('Stream processing error:', error); // Stream errors shouldn't crash application } ``` ## Integration with Other Primitives ### With Hooks Combine traces with custom callbacks: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Task", stream: true, // Get traces hooks: { // Add custom logic onToolUse: async (event) => { // Hook called when trace event occurs await customToolAnalysis(event); } } }); ``` Learn more: [Hooks Primitive](/primitives/essentials/hooks) ### With Evals Use traces to validate agent behavior: ```typescript theme={null} // Validate agent behavior via traces const trace = []; const result = await agentbase.runAgent({ message: "Test case", stream: true }); for await (const event of result) { trace.push(event); } // Check that agent used expected tools const toolsUsed = trace .filter(e => e.type === 'agent_tool_use') .map(e => e.tool); expect(toolsUsed).toContain('database_query'); ``` Learn more: [Evals Primitive](/primitives/essentials/evals) ## Performance Considerations ### Streaming Overhead * **Network**: Minimal overhead for event streaming * **Processing**: Depends on your event handlers * **Memory**: Incremental processing uses constant memory * **Latency**: No additional latency added to agent execution ### Optimization Tips ```typescript theme={null} // Optimize trace processing const processedEvents = new Set(); for await (const event of stream) { // Deduplicate events if needed const eventKey = `${event.type}-${event.timestamp}`; if (processedEvents.has(eventKey)) continue; processedEvents.add(eventKey); // Async processing without blocking processEventAsync(event).catch(console.error); } ``` ## Troubleshooting **Solution**: Ensure streaming is enabled ```typescript theme={null} // Must set stream: true const result = await agentbase.runAgent({ message: "Task", stream: true // Required for traces }); ``` **Solution**: Some events may not occur for all requests ```typescript theme={null} // Not all requests will have errors // Not all tasks use tools // Handle optional events gracefully if (event.type === 'agent_error') { // May not occur } ``` ## Related Primitives Custom callbacks for trace events Test agents using trace data Monitor async task progress Debug error recovery with traces ## Additional Resources Complete event documentation Advanced debugging techniques Streaming parameters **Remember**: Traces are most powerful when processed incrementally. Stream events, filter to what matters, and handle them as they arrive for optimal performance and insights. # Versioning Source: https://docs.agentbase.sh/primitives/essentials/versioning Manage agent configurations, prompts, and tool versions with rollback capabilities > Versioning enables you to track, manage, and control different versions of your agent configurations, allowing safe experimentation, rollback, and deployment strategies. ## Overview The Versioning primitive provides version control for your agent configurations, including system prompts, tools, rules, and parameters. Like Git for code, versioning for agents lets you experiment safely, maintain production stability, and rollback when needed. Versioning is essential for: * **Safe Experimentation**: Test new prompts and configurations without affecting production * **Rollback Capability**: Quickly revert to previous working versions if issues arise * **A/B Testing**: Compare different agent configurations to find optimal setup * **Environment Management**: Maintain different configurations for dev, staging, and production * **Audit Trail**: Track changes to agent behavior over time Capture complete agent configuration at any point in time Revert to any previous version instantly if problems occur Run multiple versions simultaneously for comparison Complete audit trail of all configuration changes ## How Versioning Works ### Version Structure Each version is a complete snapshot of agent configuration: 1. **System Prompt**: The exact system prompt used 2. **Tools**: MCP server configurations and custom tools 3. **Rules**: All rules and constraints 4. **Parameters**: Model selection, temperature, mode settings 5. **Metadata**: Version number, timestamp, description, author ### Version Lifecycle Versions follow a controlled lifecycle: 1. **Creation**: Capture current configuration as new version 2. **Testing**: Validate version in non-production environment 3. **Deployment**: Promote version to production 4. **Monitoring**: Track performance and issues 5. **Rollback**: Revert to previous version if needed 6. **Archival**: Archive old versions for historical reference **Semantic Versioning**: Use semantic versioning (major.minor.patch) to communicate the nature of changes clearly. ## Code Examples ### Creating Versions ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Create a versioned agent configuration const v1 = await agentbase.createVersion({ name: "customer-support-v1.0.0", description: "Initial customer support agent", config: { system: "You are a friendly customer support specialist.", mode: "base", rules: [ "Always be polite and professional", "Verify user identity before sharing account details" ] } }); console.log('Version created:', v1.version); // "1.0.0" // Use the versioned configuration const result = await agentbase.runAgent({ message: "I need help with my account", version: "customer-support-v1.0.0" }); ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Create a versioned agent configuration v1 = agentbase.create_version( name="customer-support-v1.0.0", description="Initial customer support agent", config={ 'system': "You are a friendly customer support specialist.", 'mode': "base", 'rules': [ "Always be polite and professional", "Verify user identity before sharing account details" ] } ) print(f"Version created: {v1.version}") # "1.0.0" # Use the versioned configuration result = agentbase.run_agent( message="I need help with my account", version="customer-support-v1.0.0" ) ``` ### Updating Versions ```typescript TypeScript theme={null} // Create new version with improvements const v2 = await agentbase.createVersion({ name: "customer-support-v1.1.0", description: "Added empathy and faster response guidelines", basedOn: "customer-support-v1.0.0", // Track lineage config: { system: `You are a friendly and empathetic customer support specialist. Guidelines: - Respond quickly and efficiently - Show empathy for customer frustrations - Provide step-by-step solutions - Always verify identity before sharing account details`, mode: "base", rules: [ "Always be polite, professional, and empathetic", "Verify user identity before sharing account details", "Provide solutions in clear, numbered steps" ] }, changelog: [ "Added empathy guidance to system prompt", "Expanded guidelines for better clarity", "Added rule for step-by-step solutions" ] }); // Test new version const testResult = await agentbase.runAgent({ message: "I'm frustrated, my order hasn't arrived", version: "customer-support-v1.1.0" }); ``` ```python Python theme={null} # Create new version with improvements v2 = agentbase.create_version( name="customer-support-v1.1.0", description="Added empathy and faster response guidelines", based_on="customer-support-v1.0.0", # Track lineage config={ 'system': """You are a friendly and empathetic customer support specialist. Guidelines: - Respond quickly and efficiently - Show empathy for customer frustrations - Provide step-by-step solutions - Always verify identity before sharing account details""", 'mode': "base", 'rules': [ "Always be polite, professional, and empathetic", "Verify user identity before sharing account details", "Provide solutions in clear, numbered steps" ] }, changelog=[ "Added empathy guidance to system prompt", "Expanded guidelines for better clarity", "Added rule for step-by-step solutions" ] ) # Test new version test_result = agentbase.run_agent( message="I'm frustrated, my order hasn't arrived", version="customer-support-v1.1.0" ) ``` ### Version Comparison ```typescript TypeScript theme={null} // Compare two versions side-by-side async function compareVersions( message: string, versionA: string, versionB: string ) { const [resultA, resultB] = await Promise.all([ agentbase.runAgent({ message, version: versionA }), agentbase.runAgent({ message, version: versionB }) ]); return { versionA: { version: versionA, response: resultA.message, cost: resultA.cost }, versionB: { version: versionB, response: resultB.message, cost: resultB.cost } }; } // A/B test versions const comparison = await compareVersions( "How do I reset my password?", "customer-support-v1.0.0", "customer-support-v1.1.0" ); console.log('Version A:', comparison.versionA.response); console.log('Version B:', comparison.versionB.response); ``` ```python Python theme={null} # Compare two versions side-by-side async def compare_versions(message: str, version_a: str, version_b: str): result_a, result_b = await asyncio.gather( agentbase.run_agent(message=message, version=version_a), agentbase.run_agent(message=message, version=version_b) ) return { 'version_a': { 'version': version_a, 'response': result_a.message, 'cost': result_a.cost }, 'version_b': { 'version': version_b, 'response': result_b.message, 'cost': result_b.cost } } # A/B test versions comparison = await compare_versions( "How do I reset my password?", "customer-support-v1.0.0", "customer-support-v1.1.0" ) print(f"Version A: {comparison['version_a']['response']}") print(f"Version B: {comparison['version_b']['response']}") ``` ### Rollback ```typescript TypeScript theme={null} // Production is on v2.0.0, but issues detected const productionVersion = "customer-support-v2.0.0"; try { // Attempt to use current production version const result = await agentbase.runAgent({ message: "Test production version", version: productionVersion }); } catch (error) { console.error('Production version failed:', error); // Rollback to previous stable version await agentbase.setProductionVersion({ name: "customer-support", version: "customer-support-v1.1.0" // Last known good version }); console.log('Rolled back to v1.1.0'); // Log rollback for audit trail await logRollback({ from: "customer-support-v2.0.0", to: "customer-support-v1.1.0", reason: "Production errors detected", timestamp: new Date() }); } ``` ```python Python theme={null} # Production is on v2.0.0, but issues detected production_version = "customer-support-v2.0.0" try: # Attempt to use current production version result = agentbase.run_agent( message="Test production version", version=production_version ) except Exception as error: print(f"Production version failed: {error}") # Rollback to previous stable version agentbase.set_production_version( name="customer-support", version="customer-support-v1.1.0" # Last known good version ) print("Rolled back to v1.1.0") # Log rollback for audit trail await log_rollback({ 'from': "customer-support-v2.0.0", 'to': "customer-support-v1.1.0", 'reason': "Production errors detected", 'timestamp': datetime.now() }) ``` ### Environment-Based Versions ```typescript TypeScript theme={null} // Manage versions across environments class VersionManager { private environments = { development: "customer-support-dev", staging: "customer-support-staging", production: "customer-support-prod" }; async getVersionForEnvironment(env: string): Promise { const config = await agentbase.getVersionConfig(this.environments[env]); return config.currentVersion; } async promoteVersion(version: string, fromEnv: string, toEnv: string) { // Validate in source environment first const validation = await this.validateVersion(version, fromEnv); if (!validation.passed) { throw new Error(`Version ${version} failed validation in ${fromEnv}`); } // Promote to target environment await agentbase.setEnvironmentVersion({ environment: this.environments[toEnv], version }); console.log(`Promoted ${version} from ${fromEnv} to ${toEnv}`); } async validateVersion(version: string, env: string): Promise { // Run test suite against version const testCases = await loadTestCases(); const results = await Promise.all( testCases.map(test => agentbase.runAgent({ message: test.input, version }) ) ); const passed = results.every((r, i) => validateResponse(r, testCases[i].expected) ); return { passed, results }; } } // Usage const versionMgr = new VersionManager(); // Develop and test in dev await versionMgr.promoteVersion("v1.2.0", "development", "staging"); // After staging validation await versionMgr.promoteVersion("v1.2.0", "staging", "production"); ``` ## Version Management Patterns ### Semantic Versioning Follow semantic versioning conventions: **Breaking Changes**: Fundamental changes to agent behavior or interface ```typescript theme={null} // v1.0.0 → v2.0.0 const v2 = await agentbase.createVersion({ name: "support-agent-v2.0.0", description: "Complete rewrite with new capabilities", config: { system: "You are an AI-powered support specialist with access to advanced troubleshooting tools.", mcpServers: [ { serverName: "diagnostics", serverUrl: "https://api.company.com/mcp" } ], // Completely new approach and capabilities }, breaking: true, changelog: [ "BREAKING: Changed from basic support to advanced troubleshooting", "BREAKING: Added diagnostic tool requirements", "BREAKING: Modified response format" ] }); ``` **New Features**: Backwards-compatible improvements ```typescript theme={null} // v1.0.0 → v1.1.0 const v1_1 = await agentbase.createVersion({ name: "support-agent-v1.1.0", description: "Added multilingual support", basedOn: "support-agent-v1.0.0", config: { system: `You are a customer support specialist. NEW: Support multiple languages: - Auto-detect customer language - Respond in their preferred language - Maintain professional tone across languages`, // All previous capabilities maintained }, changelog: [ "Added multilingual support", "Improved language detection", "Maintained all v1.0.0 capabilities" ] }); ``` **Bug Fixes**: Backwards-compatible bug fixes ```typescript theme={null} // v1.1.0 → v1.1.1 const v1_1_1 = await agentbase.createVersion({ name: "support-agent-v1.1.1", description: "Fixed response formatting issue", basedOn: "support-agent-v1.1.0", config: { // Same configuration as v1.1.0 // with minor prompt adjustment system: `You are a customer support specialist. Support multiple languages... FIX: Always format responses with proper markdown`, }, changelog: [ "Fixed markdown formatting in responses", "Corrected edge case in language detection" ] }); ``` ### Branching Strategies Manage parallel development: ```typescript theme={null} // Main production line const main = "support-agent-v1.5.0"; // Experimental branch for new features const experimental = await agentbase.createVersion({ name: "support-agent-v2.0.0-beta.1", description: "Experimental: AI-driven sentiment analysis", basedOn: main, branch: "experimental-sentiment", config: { system: `${mainConfig.system} EXPERIMENTAL: Analyze customer sentiment and adapt response tone accordingly.`, } }); // Hotfix branch for urgent fixes const hotfix = await agentbase.createVersion({ name: "support-agent-v1.5.1", description: "Hotfix: Security validation issue", basedOn: main, branch: "hotfix-security", priority: "urgent" }); ``` ## Use Cases ### 1. Safe Production Deployment Deploy new versions without risk: ```typescript theme={null} async function safeDeployment() { // Current production version const production = "support-agent-v1.0.0"; // Create new version const newVersion = await agentbase.createVersion({ name: "support-agent-v1.1.0", description: "Improved response quality", config: { /* new configuration */ } }); // Test in staging const stagingTests = await runTestSuite("support-agent-v1.1.0"); if (stagingTests.passRate < 0.95) { console.log('Staging tests failed, not deploying'); return; } // Canary deployment: 5% of traffic await agentbase.setVersionTrafficSplit({ "support-agent-v1.0.0": 0.95, // 95% on old version "support-agent-v1.1.0": 0.05 // 5% on new version }); // Monitor canary performance await sleep(1 * 60 * 60 * 1000); // 1 hour const canaryMetrics = await getVersionMetrics("support-agent-v1.1.0"); if (canaryMetrics.errorRate < 0.01 && canaryMetrics.satisfaction > 4.0) { // Gradually increase traffic await agentbase.setVersionTrafficSplit({ "support-agent-v1.0.0": 0.50, "support-agent-v1.1.0": 0.50 }); await sleep(30 * 60 * 1000); // 30 minutes // Full rollout await agentbase.setVersionTrafficSplit({ "support-agent-v1.1.0": 1.0 }); console.log('Successfully deployed v1.1.0'); } else { // Rollback await agentbase.setVersionTrafficSplit({ "support-agent-v1.0.0": 1.0 }); console.log('Canary failed, rolled back'); } } ``` ### 2. A/B Testing for Optimization Test different approaches to find what works best: ```typescript theme={null} async function abTestPrompts() { // Version A: Concise style const versionA = await agentbase.createVersion({ name: "support-agent-concise", config: { system: "You are a customer support specialist. Be concise and direct.", rules: ["Keep responses under 100 words"] } }); // Version B: Detailed style const versionB = await agentbase.createVersion({ name: "support-agent-detailed", config: { system: "You are a customer support specialist. Provide thorough explanations.", rules: ["Include detailed step-by-step instructions"] } }); // Split traffic 50/50 await agentbase.setVersionTrafficSplit({ "support-agent-concise": 0.5, "support-agent-detailed": 0.5 }); // Collect metrics for 1 week await sleep(7 * 24 * 60 * 60 * 1000); // Analyze results const metricsA = await getVersionMetrics("support-agent-concise"); const metricsB = await getVersionMetrics("support-agent-detailed"); console.log('Version A (Concise):'); console.log(' Satisfaction:', metricsA.satisfaction); console.log(' Resolution Rate:', metricsA.resolutionRate); console.log(' Avg Response Time:', metricsA.avgResponseTime); console.log('Version B (Detailed):'); console.log(' Satisfaction:', metricsB.satisfaction); console.log(' Resolution Rate:', metricsB.resolutionRate); console.log(' Avg Response Time:', metricsB.avgResponseTime); // Choose winner const winner = metricsA.satisfaction > metricsB.satisfaction ? 'A' : 'B'; console.log(`Winner: Version ${winner}`); // Promote winner to production await agentbase.setProductionVersion({ name: "support-agent", version: winner === 'A' ? "support-agent-concise" : "support-agent-detailed" }); } ``` ### 3. Emergency Rollback Quickly revert problematic versions: ```typescript theme={null} // Monitor production version async function monitorProduction() { const currentVersion = await agentbase.getProductionVersion("support-agent"); const metrics = await getVersionMetrics(currentVersion, { window: '5m' // Last 5 minutes }); // Check for issues if (metrics.errorRate > 0.05 || metrics.avgResponseTime > 10000) { console.error('Production issues detected!'); // Automatic rollback const previousVersion = await agentbase.getPreviousVersion(currentVersion); await agentbase.setProductionVersion({ name: "support-agent", version: previousVersion }); // Alert team await sendAlert({ severity: 'critical', message: `Auto-rolled back from ${currentVersion} to ${previousVersion}`, reason: `Error rate: ${metrics.errorRate}, Response time: ${metrics.avgResponseTime}ms` }); // Create incident await createIncident({ title: `Production rollback: ${currentVersion}`, version: currentVersion, metrics }); } } // Run monitoring every minute setInterval(monitorProduction, 60 * 1000); ``` ### 4. Multi-Tenant Versioning Different versions for different customers: ```typescript theme={null} async function getCustomerVersion(customerId: string): Promise { const customer = await db.customers.findById(customerId); // Enterprise customers get latest features if (customer.tier === 'enterprise') { return "support-agent-v2.0.0"; } // Premium customers get stable version if (customer.tier === 'premium') { return "support-agent-v1.5.0"; } // Free tier gets basic version return "support-agent-v1.0.0"; } // Use customer-specific version const result = await agentbase.runAgent({ message: customerMessage, version: await getCustomerVersion(customerId) }); ``` ### 5. Feature Flags via Versioning Enable features selectively: ```typescript theme={null} // Create versions with different feature sets const versions = { base: "support-agent-v1.0.0", withSentiment: "support-agent-v1.0.0-sentiment", withMultilingual: "support-agent-v1.0.0-multilingual", withBoth: "support-agent-v1.0.0-full" }; async function getVersionWithFeatures(features: string[]): Promise { if (features.includes('sentiment') && features.includes('multilingual')) { return versions.withBoth; } if (features.includes('sentiment')) { return versions.withSentiment; } if (features.includes('multilingual')) { return versions.withMultilingual; } return versions.base; } // Use version based on enabled features const enabledFeatures = await getFeatureFlags(userId); const version = await getVersionWithFeatures(enabledFeatures); const result = await agentbase.runAgent({ message: userMessage, version }); ``` ## Best Practices ### Version Naming ```typescript theme={null} // Good: Clear semantic version "customer-support-v1.2.3" "data-analyst-v2.0.0" "content-gen-v1.0.0-beta.1" // Avoid: Unclear or inconsistent naming "customer-support-new" "agent-v2" "prod-version" ``` ```typescript theme={null} // Good: Descriptive version metadata await agentbase.createVersion({ name: "support-agent-v1.2.0", description: "Added multilingual support and improved empathy", tags: ["multilingual", "empathy", "production-ready"] }); ``` ```typescript theme={null} // Comprehensive changelog await agentbase.createVersion({ name: "support-agent-v1.2.0", changelog: [ "Added support for Spanish, French, German", "Improved empathy in frustration scenarios", "Fixed response formatting issue", "Updated security validation rules" ] }); ``` ### Testing Strategy Test versions thoroughly before production: ```typescript theme={null} // Comprehensive version testing async function testVersion(version: string): Promise { const tests = { functional: await runFunctionalTests(version), performance: await runPerformanceTests(version), security: await runSecurityTests(version), regression: await runRegressionTests(version) }; const passedAll = Object.values(tests).every(t => t.passed); return { version, passed: passedAll, tests, timestamp: new Date() }; } ``` ### Deployment Pipeline Implement structured deployment process: ```typescript theme={null} // Deployment pipeline class VersionDeploymentPipeline { async deploy(version: string) { // 1. Validate version exists await this.validateVersion(version); // 2. Run test suite const testResults = await testVersion(version); if (!testResults.passed) { throw new Error('Tests failed'); } // 3. Deploy to staging await this.deployToStaging(version); // 4. Run staging validation await this.validateStaging(version); // 5. Canary deployment await this.canaryDeploy(version, 0.05); // 6. Monitor canary await this.monitorCanary(version, 60 * 60 * 1000); // 1 hour // 7. Gradual rollout await this.gradualRollout(version); // 8. Full production await this.setProduction(version); // 9. Monitor production await this.monitorProduction(version); } } ``` ## Integration with Other Primitives ### With Evals Validate versions with automated testing: ```typescript theme={null} // Test version with eval suite const evalResults = await agentbase.runEvals({ version: "support-agent-v1.2.0", evalSuite: "production-readiness" }); if (evalResults.passRate > 0.95) { await promoteToProduction("support-agent-v1.2.0"); } ``` Learn more: [Evals Primitive](/primitives/essentials/evals) ### With Traces Monitor version performance through traces: ```typescript theme={null} // Compare traces between versions const traceA = await agentbase.getTraces({ version: "v1.0.0" }); const traceB = await agentbase.getTraces({ version: "v1.1.0" }); console.log('V1.0.0 avg steps:', avgSteps(traceA)); console.log('V1.1.0 avg steps:', avgSteps(traceB)); ``` Learn more: [Traces Primitive](/primitives/essentials/traces) ### With Persistence Maintain session state across version changes: ```typescript theme={null} // Session survives version changes const result1 = await agentbase.runAgent({ message: "Start project", version: "v1.0.0", session: mySession }); // Upgrade version mid-session const result2 = await agentbase.runAgent({ message: "Continue project", version: "v1.1.0", session: mySession // Session state preserved }); ``` Learn more: [Persistence Primitive](/primitives/essentials/persistence) ## Performance Considerations ### Version Overhead * **Version Lookup**: \< 10ms to resolve version * **Configuration Load**: \< 50ms to load version config * **No Runtime Impact**: Version selection happens before execution ### Storage and Retention * **Version Storage**: Unlimited versions per account * **Retention**: Versions retained indefinitely unless manually deleted * **Archive**: Old versions can be archived for historical reference ## Troubleshooting **Problem**: Specified version doesn't exist **Solution**: Verify version name and check available versions ```typescript theme={null} // List available versions const versions = await agentbase.listVersions("support-agent"); console.log('Available:', versions.map(v => v.name)); // Check if specific version exists const exists = await agentbase.versionExists("support-agent-v1.2.0"); ``` **Problem**: Version configuration has conflicting settings **Solution**: Validate configuration before creating version ```typescript theme={null} // Validate configuration const validation = await agentbase.validateVersionConfig({ system: "...", rules: [...], mcpServers: [...] }); if (!validation.valid) { console.error('Config errors:', validation.errors); } ``` ## Related Primitives Test and validate versions Monitor version performance Session state across versions Version lifecycle callbacks ## Additional Resources Version parameters Production deployment strategies Version management patterns **Remember**: Use semantic versioning, test thoroughly, deploy gradually, and always maintain the ability to rollback quickly if issues arise. # Crawl & Scrape Source: https://docs.agentbase.sh/primitives/extensions/crawl-scrape Extract data from websites with web crawling and scraping ## Overview The Crawl & Scrape extension enables agents to systematically extract data from websites, navigate multi-page structures, and gather information at scale. Unlike simple web requests, this extension provides intelligent crawling with rate limiting, session management, and structured data extraction. Navigate website structures automatically, following links and pagination Extract structured data from HTML, JSON, and APIs Respect robots.txt and avoid overwhelming servers Handle cookies, authentication, and stateful navigation ## How It Works Agents use the built-in `web` tool with crawl mode to systematically extract data from websites: Agent identifies the target website and data to extract Navigates to the target page using the browser environment Extracts relevant data using DOM selectors, regex, or structure Optionally follows links to crawl multiple pages Organizes extracted data into structured format ## Basic Usage ### Simple Page Scraping ```typescript theme={null} import Agentbase from "@agentbase/sdk"; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Scrape product information const result = await agentbase.runAgent({ message: "Go to example.com/products and extract all product names and prices", mode: "base" }); console.log('Extracted data:', result.content); ``` ```python theme={null} from agentbase import Agentbase client = Agentbase(api_key=os.environ.get("AGENTBASE_API_KEY")) # Scrape product information result = client.run_agent( message="Go to example.com/products and extract all product names and prices", mode="base" ) print("Extracted data:", result.content) ``` ```bash theme={null} curl -X POST https://api.agentbase.sh/run-agent \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Go to example.com/products and extract all product names and prices", "mode": "base" }' ``` ### Multi-Page Crawling ```typescript theme={null} // Crawl multiple pages with pagination const result = await agentbase.runAgent({ message: `Visit example.com/blog and extract: - All article titles - Author names - Publication dates - Follow pagination to get all articles from pages 1-5`, mode: "base" }); ``` ### Structured Data Extraction ```typescript theme={null} // Extract data in specific format const result = await agentbase.runAgent({ message: `Scrape example.com/directory and return data as JSON: { "listings": [ { "name": "...", "address": "...", "phone": "...", "rating": "..." } ] }`, mode: "base" }); const data = JSON.parse(result.content); ``` ## Use Cases ### 1. Competitive Intelligence Monitor competitor websites for pricing, features, and updates: ```typescript theme={null} async function monitorCompetitors(competitors: string[]) { const results = await Promise.all( competitors.map(async (url) => { return await agentbase.runAgent({ message: `Visit ${url} and extract: - All product names and prices - Key features - Any promotional banners - Last updated date`, mode: "base" }); }) ); return results.map((r, i) => ({ competitor: competitors[i], data: r.content })); } // Usage const intel = await monitorCompetitors([ 'https://competitor1.com/deploy/pricing', 'https://competitor2.com/products', 'https://competitor3.com/features' ]); ``` ### 2. Lead Generation Extract business contact information from directories: ```typescript theme={null} async function extractLeads(directoryUrl: string) { const result = await agentbase.runAgent({ message: `Scrape ${directoryUrl} and extract all business listings: - Business name - Industry/category - Contact email - Phone number - Website URL Follow pagination to get all listings. Return as CSV format.`, mode: "base" }); // Save to file fs.writeFileSync('leads.csv', result.content); return result.content; } ``` ### 3. Content Aggregation Aggregate content from multiple sources: ```typescript theme={null} async function aggregateNews(topics: string[]) { const articles = []; for (const topic of topics) { const result = await agentbase.runAgent({ message: `Search for recent articles about "${topic}" and extract: - Article title - Source/publication - Publication date - Summary - URL Get the 10 most recent articles.`, mode: "base" }); articles.push({ topic, articles: JSON.parse(result.content) }); } return articles; } // Usage const news = await aggregateNews([ 'AI developments', 'Cloud computing trends', 'Cybersecurity news' ]); ``` ### 4. Price Monitoring Track product prices across e-commerce sites: ```typescript theme={null} interface PriceAlert { product: string; targetPrice: number; urls: string[]; } async function monitorPrices(alerts: PriceAlert[]) { for (const alert of alerts) { for (const url of alert.urls) { const result = await agentbase.runAgent({ message: `Visit ${url} and extract the current price for ${alert.product}`, mode: "flash" }); // Parse price from response const priceMatch = result.content.match(/\$?([\d,]+\.?\d*)/); if (priceMatch) { const currentPrice = parseFloat(priceMatch[1].replace(',', '')); if (currentPrice <= alert.targetPrice) { await sendAlert({ product: alert.product, currentPrice, targetPrice: alert.targetPrice, url }); } } } } } ``` ### 5. Job Listings Aggregation Collect job postings from multiple boards: ```typescript theme={null} async function aggregateJobs(searchTerms: string[]) { const jobBoards = [ 'https://jobs.example.com', 'https://careers.example.org', 'https://opportunities.example.net' ]; const allJobs = []; for (const board of jobBoards) { for (const term of searchTerms) { const result = await agentbase.runAgent({ message: `Search for "${term}" on ${board} and extract: - Job title - Company name - Location - Salary (if available) - Posted date - Job URL Return as JSON array. Get the first 20 results.`, mode: "base" }); allJobs.push(...JSON.parse(result.content)); } } return allJobs; } ``` ### 6. Market Research Gather product reviews and ratings: ```typescript theme={null} async function collectReviews(productUrl: string) { const result = await agentbase.runAgent({ message: `Visit ${productUrl} and extract all customer reviews: - Reviewer name - Rating (stars) - Review text - Date - Verified purchase (if shown) Follow pagination to get all reviews. Return as JSON.`, mode: "base" }); const reviews = JSON.parse(result.content); // Analyze sentiment const analysis = await agentbase.runAgent({ message: `Analyze these reviews and provide: - Average rating - Common positive themes - Common negative themes - Overall sentiment Reviews: ${JSON.stringify(reviews.slice(0, 50))}`, mode: "base" }); return { reviews, analysis: analysis.content }; } ``` ## Best Practices Always respect website crawling policies: ```typescript theme={null} // ✅ Good: Mention respecting robots.txt const result = await agentbase.runAgent({ message: "Crawl example.com (respecting robots.txt) and extract product data", mode: "base" }); ``` **Why:** Violating robots.txt can get your IP blocked and is considered bad practice. Avoid overwhelming servers with requests: ```typescript theme={null} // ✅ Good: Stagger requests async function crawlWithDelay(urls: string[], delayMs: number = 2000) { const results = []; for (const url of urls) { const result = await agentbase.runAgent({ message: `Extract data from ${url}`, mode: "base" }); results.push(result); // Wait before next request if (urls.indexOf(url) < urls.length - 1) { await new Promise(resolve => setTimeout(resolve, delayMs)); } } return results; } ``` Expect and handle failures: ```typescript theme={null} async function scrapeSafely(url: string) { try { const result = await agentbase.runAgent({ message: `Extract data from ${url}. If the page is not found or blocked, return an error message.`, mode: "base" }); return { success: true, data: result.content }; } catch (error) { console.error(`Failed to scrape ${url}:`, error); return { success: false, error: error.message, url }; } } ``` Clearly specify desired output format: ```typescript theme={null} // ✅ Good: Specify format const result = await agentbase.runAgent({ message: `Extract product data and return as JSON: { "products": [ { "name": "string", "price": "number", "inStock": "boolean", "url": "string" } ] }`, mode: "base" }); // ❌ Bad: Vague format const result = await agentbase.runAgent({ message: "Get product data", mode: "base" }); ``` Avoid re-scraping unchanged data: ```typescript theme={null} import { LRUCache } from 'lru-cache'; const cache = new LRUCache({ max: 1000, ttl: 1000 * 60 * 60 // 1 hour }); async function scrapeWithCache(url: string) { // Check cache first const cached = cache.get(url); if (cached) { console.log('Cache hit:', url); return cached; } // Scrape if not cached const result = await agentbase.runAgent({ message: `Extract data from ${url}`, mode: "base" }); // Cache result cache.set(url, result.content); return result.content; } ``` Detect when websites update structure: ```typescript theme={null} async function detectChanges(url: string, expectedStructure: string[]) { const result = await agentbase.runAgent({ message: `Check if ${url} contains these elements: ${expectedStructure.join(', ')}. Return which are present and which are missing.`, mode: "flash" }); if (result.content.includes('missing')) { await alertTeam({ message: `Website structure changed: ${url}`, details: result.content }); } } ``` ## Advanced Patterns ### Parallel Scraping ```typescript theme={null} async function scrapeInParallel(urls: string[], concurrency: number = 5) { const results = []; for (let i = 0; i < urls.length; i += concurrency) { const batch = urls.slice(i, i + concurrency); const batchResults = await Promise.all( batch.map(url => agentbase.runAgent({ message: `Extract data from ${url}`, mode: "base" }) ) ); results.push(...batchResults); // Rate limit between batches if (i + concurrency < urls.length) { await new Promise(resolve => setTimeout(resolve, 2000)); } } return results; } ``` ### Recursive Crawling ```typescript theme={null} async function crawlSitemap(startUrl: string, maxDepth: number = 3) { const visited = new Set(); const results = []; async function crawlPage(url: string, depth: number) { if (depth > maxDepth || visited.has(url)) return; visited.add(url); const result = await agentbase.runAgent({ message: `Visit ${url} and: 1. Extract main content 2. Find all internal links 3. Return both as JSON`, mode: "base" }); results.push({ url, depth, content: result.content }); // Crawl linked pages const data = JSON.parse(result.content); for (const link of data.links || []) { await crawlPage(link, depth + 1); } } await crawlPage(startUrl, 0); return results; } ``` ## Performance Considerations For simple extraction tasks, use Flash mode: ```typescript theme={null} // Fast, cheap extraction mode: "flash" ``` Combine multiple extractions when possible Cache results to avoid re-scraping Be specific about what to extract to reduce processing ## Troubleshooting **Problem:** Agent can't access the page **Solutions:** * Check if URL is correct and accessible * Verify website doesn't block automated access * Try with different user agent * Check for CAPTCHA or bot detection **Problem:** Agent returns no or incomplete data **Solutions:** * Be more specific about what to extract * Check if page structure has changed * Verify data is visible (not behind JavaScript) * Try with more detailed instructions **Problem:** Website blocks requests **Solutions:** * Implement delays between requests * Reduce concurrency * Respect robots.txt * Contact website owner for API access ## Integration with Other Primitives Uses browser environment for navigation and rendering Save scraped data to files Maintain context across crawls Run long crawls asynchronously Find pages to scrape Store scraped data in databases ## Next Steps Search for pages before scraping Learn about browser capabilities Store scraped data efficiently Run long-running crawls # Data Connectors Source: https://docs.agentbase.sh/primitives/extensions/data-connectors Connect agents to databases, data warehouses, and data sources > Data Connectors enable agents to read from and write to databases, data warehouses, and various data sources, making it easy to work with structured and unstructured data across your organization. ## Overview The Data Connectors primitive provides agents with direct access to your data infrastructure. Whether you're working with SQL databases, NoSQL stores, data warehouses, or cloud storage, agents can query, analyze, and manipulate data using natural language. Data Connectors are essential for: * **Database Access**: Query and update SQL and NoSQL databases * **Data Analysis**: Analyze data across multiple sources * **Data Synchronization**: Keep data in sync across systems * **Reporting**: Generate reports from live data * **ETL Operations**: Extract, transform, and load data * **Data Validation**: Verify data integrity and quality Connect to PostgreSQL, MySQL, SQL Server, and more Access MongoDB, Redis, DynamoDB, and other NoSQL databases Query Snowflake, BigQuery, Redshift, and analytics platforms Read and write to S3, GCS, Azure Blob, and object storage ## How Data Connectors Work When you configure data connectors for an agent: 1. **Connection**: Agent establishes secure connection to data source 2. **Schema Discovery**: Automatically detects tables, columns, and relationships 3. **Query Generation**: Converts natural language to appropriate queries (SQL, NoSQL, etc.) 4. **Execution**: Runs queries with proper security and access controls 5. **Result Processing**: Formats and returns results in structured format 6. **Connection Pooling**: Maintains efficient connection management **Security First**: All database credentials are encrypted at rest and in transit. Connections use SSL/TLS when available. ## Supported Data Sources ### SQL Databases ```typescript theme={null} { dataConnectors: { postgres: { enabled: true }, mysql: { enabled: true }, sqlserver: { enabled: true }, oracle: { enabled: true }, sqlite: { enabled: true } } } ``` ### NoSQL Databases ```typescript theme={null} { dataConnectors: { mongodb: { enabled: true }, redis: { enabled: true }, dynamodb: { enabled: true }, cassandra: { enabled: true }, firebase: { enabled: true } } } ``` ### Data Warehouses ```typescript theme={null} { dataConnectors: { snowflake: { enabled: true }, bigquery: { enabled: true }, redshift: { enabled: true }, databricks: { enabled: true } } } ``` ### Cloud Storage ```typescript theme={null} { dataConnectors: { s3: { enabled: true }, gcs: { enabled: true }, azureBlob: { enabled: true } } } ``` ## Code Examples ### Basic SQL Query ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Query PostgreSQL database const result = await agentbase.runAgent({ message: "Show me all customers who signed up in the last 30 days", dataConnectors: { postgres: { enabled: true, connection: { host: process.env.DB_HOST, port: 5432, database: "production", user: process.env.DB_USER, password: process.env.DB_PASSWORD, ssl: true } } } }); console.log('Results:', result.data); // Agent generates and executes SQL query ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Query PostgreSQL database result = agentbase.run_agent( message="Show me all customers who signed up in the last 30 days", data_connectors={ "postgres": { "enabled": True, "connection": { "host": os.environ['DB_HOST'], "port": 5432, "database": "production", "user": os.environ['DB_USER'], "password": os.environ['DB_PASSWORD'], "ssl": True } } } ) print(f"Results: {result.data}") ``` ### Connection String ```typescript TypeScript theme={null} // Use connection string format const result = await agentbase.runAgent({ message: "Count total orders by status", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL // Format: postgresql://user:password@host:port/database } } }); ``` ```python Python theme={null} # Use connection string format result = agentbase.run_agent( message="Count total orders by status", data_connectors={ "postgres": { "enabled": True, "connection_string": os.environ['DATABASE_URL'] # Format: postgresql://user:password@host:port/database } } ) ``` ### NoSQL Query ```typescript TypeScript theme={null} // Query MongoDB const result = await agentbase.runAgent({ message: "Find all products with rating above 4.5 stars", dataConnectors: { mongodb: { enabled: true, connection: { uri: process.env.MONGODB_URI, database: "ecommerce", collection: "products" } } } }); // Agent generates MongoDB query console.log('Products:', result.data); ``` ```python Python theme={null} # Query MongoDB result = agentbase.run_agent( message="Find all products with rating above 4.5 stars", data_connectors={ "mongodb": { "enabled": True, "connection": { "uri": os.environ['MONGODB_URI'], "database": "ecommerce", "collection": "products" } } } ) print(f"Products: {result.data}") ``` ### Data Warehouse Query ```typescript TypeScript theme={null} // Query Snowflake data warehouse const result = await agentbase.runAgent({ message: "Show me total sales by region for Q4 2024", dataConnectors: { snowflake: { enabled: true, connection: { account: process.env.SNOWFLAKE_ACCOUNT, username: process.env.SNOWFLAKE_USER, password: process.env.SNOWFLAKE_PASSWORD, warehouse: "COMPUTE_WH", database: "ANALYTICS", schema: "SALES" } } } }); console.log('Sales data:', result.data); ``` ```python Python theme={null} # Query Snowflake data warehouse result = agentbase.run_agent( message="Show me total sales by region for Q4 2024", data_connectors={ "snowflake": { "enabled": True, "connection": { "account": os.environ['SNOWFLAKE_ACCOUNT'], "username": os.environ['SNOWFLAKE_USER'], "password": os.environ['SNOWFLAKE_PASSWORD'], "warehouse": "COMPUTE_WH", "database": "ANALYTICS", "schema": "SALES" } } } ) print(f"Sales data: {result.data}") ``` ### Multiple Data Sources ```typescript TypeScript theme={null} // Query across multiple databases const result = await agentbase.runAgent({ message: "Compare customer data between production DB and analytics warehouse", dataConnectors: { postgres: { enabled: true, connectionString: process.env.PRODUCTION_DB_URL, alias: "production" }, snowflake: { enabled: true, connection: snowflakeConfig, alias: "analytics" } }, system: `You have access to two databases: - production: Live PostgreSQL database - analytics: Snowflake data warehouse Compare customer counts and identify any discrepancies.` }); // Agent queries both sources and compares ``` ```python Python theme={null} # Query across multiple databases result = agentbase.run_agent( message="Compare customer data between production DB and analytics warehouse", data_connectors={ "postgres": { "enabled": True, "connection_string": os.environ['PRODUCTION_DB_URL'], "alias": "production" }, "snowflake": { "enabled": True, "connection": snowflake_config, "alias": "analytics" } }, system="""You have access to two databases: - production: Live PostgreSQL database - analytics: Snowflake data warehouse Compare customer counts and identify any discrepancies.""" ) ``` ### Write Operations ```typescript TypeScript theme={null} // Insert and update data const result = await agentbase.runAgent({ message: "Create a new customer record for John Doe (john@example.com)", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, permissions: { read: true, write: true // Enable write operations } } } }); // Agent generates INSERT statement console.log('Customer created:', result.data); ``` ```python Python theme={null} # Insert and update data result = agentbase.run_agent( message="Create a new customer record for John Doe (john@example.com)", data_connectors={ "postgres": { "enabled": True, "connection_string": os.environ['DATABASE_URL'], "permissions": { "read": True, "write": True # Enable write operations } } } ) print(f"Customer created: {result.data}") ``` ### Cloud Storage Access ```typescript TypeScript theme={null} // Read from S3 const result = await agentbase.runAgent({ message: "Read the latest sales report from S3", dataConnectors: { s3: { enabled: true, connection: { region: "us-east-1", accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, bucket: "company-reports" } } } }); // Agent lists and reads files from S3 console.log('Report data:', result.data); ``` ```python Python theme={null} # Read from S3 result = agentbase.run_agent( message="Read the latest sales report from S3", data_connectors={ "s3": { "enabled": True, "connection": { "region": "us-east-1", "access_key_id": os.environ['AWS_ACCESS_KEY_ID'], "secret_access_key": os.environ['AWS_SECRET_ACCESS_KEY'], "bucket": "company-reports" } } } ) print(f"Report data: {result.data}") ``` ### Caching Queries ```typescript TypeScript theme={null} // Cache expensive queries const result = await agentbase.runAgent({ message: "Show me top 10 selling products this month", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, caching: { enabled: true, ttl: 3600 // Cache for 1 hour } } } }); // Subsequent identical queries use cached results ``` ```python Python theme={null} # Cache expensive queries result = agentbase.run_agent( message="Show me top 10 selling products this month", data_connectors={ "postgres": { "enabled": True, "connection_string": os.environ['DATABASE_URL'], "caching": { "enabled": True, "ttl": 3600 # Cache for 1 hour } } } ) ``` ## Use Cases ### 1. Analytics Dashboard Generate real-time analytics from data warehouse: ```typescript TypeScript theme={null} const analyticsAgent = await agentbase.runAgent({ message: "Create a summary of key business metrics for this week", dataConnectors: { snowflake: { enabled: true, connection: snowflakeConfig } }, system: `Generate analytics report including: 1. Total revenue this week vs last week 2. New customer signups 3. Top 5 products by sales 4. Average order value 5. Customer churn rate Present results in a structured format with percentage changes.` }); // Agent queries warehouse and generates comprehensive report console.log('Analytics:', analyticsAgent.report); ``` ```python Python theme={null} analytics_agent = agentbase.run_agent( message="Create a summary of key business metrics for this week", data_connectors={ "snowflake": { "enabled": True, "connection": snowflake_config } }, system="""Generate analytics report including: 1. Total revenue this week vs last week 2. New customer signups 3. Top 5 products by sales 4. Average order value 5. Customer churn rate Present results in a structured format with percentage changes.""" ) print(f"Analytics: {analytics_agent.report}") ``` ### 2. Data Quality Validation Validate data integrity across systems: ```typescript theme={null} const validationAgent = await agentbase.runAgent({ message: "Check data quality in customer table", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL } }, system: `Perform data quality checks: 1. Find duplicate email addresses 2. Identify missing required fields 3. Check for invalid phone number formats 4. Find customers with future birth dates 5. Detect orphaned records (references to non-existent data) Report issues with counts and examples.` }); // Agent runs validation queries and reports issues if (validationAgent.issues.length > 0) { console.log('Data quality issues:', validationAgent.issues); } ``` ### 3. ETL Pipeline Extract, transform, and load data: ```typescript theme={null} const etlAgent = await agentbase.runAgent({ message: "Sync customer data from production to analytics warehouse", dataConnectors: { postgres: { enabled: true, connectionString: process.env.PRODUCTION_DB_URL, alias: "source" }, snowflake: { enabled: true, connection: snowflakeConfig, alias: "destination", permissions: { read: true, write: true } } }, system: `ETL Process: 1. Extract: Get customers modified in last 24 hours from source 2. Transform: Clean data, standardize formats, enrich with metadata 3. Load: Upsert into destination warehouse 4. Verify: Validate row counts match 5. Log: Record sync statistics` }); console.log('ETL completed:', etlAgent.stats); ``` ### 4. Customer Lookup Build customer service tools: ```typescript theme={null} const customerLookup = await agentbase.runAgent({ message: "Find customer information for email: customer@example.com", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL } }, system: `Look up customer and return: - Basic info (name, email, phone) - Account status and tier - Recent orders (last 5) - Support tickets (open and recent closed) - Lifetime value - Last interaction date Format as a customer profile card.` }); // Returns comprehensive customer data console.log('Customer profile:', customerLookup.profile); ``` ### 5. Report Generation Generate custom reports from data: ```typescript theme={null} const reportAgent = await agentbase.runAgent({ message: "Generate monthly sales report for January 2024", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL } }, system: `Generate comprehensive sales report: 1. Total sales by product category 2. Sales by region 3. Top 10 customers by revenue 4. Sales rep performance 5. Month-over-month growth 6. Forecast for next month based on trends Include visualizations and insights.` }); // Agent queries data and generates formatted report ``` ### 6. Database Migration Migrate data between databases: ```typescript theme={null} const migrationAgent = await agentbase.runAgent({ message: "Migrate users table from MySQL to PostgreSQL", dataConnectors: { mysql: { enabled: true, connection: mysqlConfig, alias: "source" }, postgres: { enabled: true, connection: postgresConfig, alias: "destination", permissions: { read: true, write: true } } }, system: `Migration process: 1. Read schema from source users table 2. Create equivalent table in destination if not exists 3. Copy data in batches of 1000 4. Validate data integrity 5. Create indexes 6. Report migration statistics` }); ``` ## Best Practices ### Security **Read-Only by Default**: Data connectors are read-only by default. Explicitly enable write permissions only when needed. ```typescript theme={null} // Good: Read-only database user dataConnectors: { postgres: { enabled: true, connection: { user: "readonly_user", // User with SELECT only password: process.env.DB_READONLY_PASSWORD } } } // For write operations, use dedicated user dataConnectors: { postgres: { enabled: true, connection: { user: "app_writer", password: process.env.DB_WRITER_PASSWORD }, permissions: { read: true, write: true } } } ``` ```typescript theme={null} // Restrict to specific schemas or tables dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, scope: { schemas: ["public", "analytics"], tables: ["customers", "orders", "products"], excludeTables: ["admin_users", "api_keys"] } } } ``` ```typescript theme={null} // Configure connection pool dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, pool: { min: 2, max: 10, acquireTimeout: 30000, idleTimeout: 10000 } } } ``` ```typescript theme={null} // Log all queries for audit trail dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, logging: { enabled: true, logQueries: true, logResults: false, // Don't log sensitive data logErrors: true } } } ``` ### Performance **Cache Frequently Accessed Data**: Enable caching for queries that run frequently and don't need real-time data. ```typescript theme={null} dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, timeout: 30000, // 30 second timeout statementTimeout: 20000 // 20 second query timeout } } ``` ```typescript theme={null} system: `When querying data: - Always use LIMIT clause for large tables - Default to 100 rows unless more are specifically needed - Use pagination for large result sets - Warn if query would return more than 1000 rows` ``` ```typescript theme={null} message: `Analyze query performance and suggest indexes`, system: `When running queries: - Use EXPLAIN to analyze query plans - Identify missing indexes - Suggest index creation for slow queries - Avoid table scans on large tables` ``` ```typescript theme={null} // Process data in batches const result = await agentbase.runAgent({ message: "Update all customer records to add loyalty_points field", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, permissions: { write: true } } }, system: `Update customers in batches: - Process 1000 records at a time - Use transactions for consistency - Commit after each batch - Log progress` }); ``` ### Data Integrity ```typescript theme={null} system: `For write operations: - Always use transactions - Validate data before commit - Rollback on any error - Log transaction details` ``` ```typescript theme={null} system: `Before inserting/updating data: - Validate required fields are present - Check data types match schema - Verify foreign key references exist - Ensure unique constraints won't be violated - Confirm data is within valid ranges` ``` ```typescript theme={null} dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, errorHandling: { retryOnConnectionError: true, maxRetries: 3, retryDelay: 1000, logErrors: true } } } ``` ## Integration with Other Primitives ### With RAG Combine database queries with semantic search: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Find similar customer support cases to this one", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL } }, datastores: [{ id: "ds_support_cases", name: "Support Cases Knowledge Base" }] }); // Agent queries database and semantic knowledge base ``` Learn more: [RAG Primitive](/primitives/extensions/rag) ### With Workflow Automate data processing workflows: ```typescript theme={null} const dataWorkflow = { name: "daily_data_sync", steps: [ { id: "extract", type: "agent_task", config: { message: "Extract new records from source database", dataConnectors: { mysql: { enabled: true } } } }, { id: "transform", type: "agent_task", config: { message: "Transform and clean data" } }, { id: "load", type: "agent_task", config: { message: "Load into destination warehouse", dataConnectors: { snowflake: { enabled: true } } } } ] }; ``` Learn more: [Workflow Primitive](/primitives/extensions/workflow) ### With Memory Remember query patterns and preferences: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Show me the usual sales report", memory: { namespace: `user_${userId}`, enabled: true }, dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL } } }); // Agent remembers user's preferred report format and filters ``` Learn more: [Memory Primitive](/primitives/extensions/memory) ## Performance Considerations ### Query Optimization * **Query Planning**: Analyze query plans before execution * **Index Usage**: Ensure queries use appropriate indexes * **Result Limiting**: Always limit result sets to needed rows * **Caching**: Cache frequently accessed, slowly changing data ```typescript theme={null} // Monitor query performance const metrics = await agentbase.getDataConnectorMetrics({ connector: "postgres", timeRange: "1h" }); console.log('Avg query time:', metrics.avgQueryTime); console.log('Slow queries:', metrics.slowQueries); console.log('Cache hit rate:', metrics.cacheHitRate); ``` ### Connection Management * **Pool Size**: Configure appropriate connection pool sizes * **Connection Reuse**: Reuse connections across queries * **Timeout Management**: Set appropriate timeouts * **Cleanup**: Close idle connections ```typescript theme={null} dataConnectors: { postgres: { enabled: true, pool: { min: 2, max: 10, acquireTimeout: 30000, idleTimeout: 10000, evictionRunInterval: 10000 } } } ``` ### Cost Optimization **Monitor Warehouse Usage**: Data warehouse queries can be expensive. Monitor usage and optimize expensive queries. ```typescript theme={null} // Set query cost limits dataConnectors: { snowflake: { enabled: true, connection: snowflakeConfig, costLimits: { maxQueryCost: 10.00, // USD alertThreshold: 0.8, blockExpensiveQueries: true } } } ``` ## Troubleshooting **Problem**: Cannot connect to database **Solutions**: * Verify connection credentials are correct * Check network connectivity and firewall rules * Ensure database server is running * Verify SSL/TLS settings match requirements * Check IP whitelist if applicable ```typescript theme={null} // Test connection const test = await agentbase.testDataConnector({ type: "postgres", connectionString: process.env.DATABASE_URL }); if (!test.success) { console.error('Connection error:', test.error); console.log('Suggestion:', test.suggestion); } ``` **Problem**: Queries timing out **Solutions**: * Increase timeout limits * Optimize slow queries with indexes * Reduce result set size * Use query caching * Consider breaking into smaller queries ```typescript theme={null} dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, timeout: 60000, // Increase to 60 seconds statementTimeout: 45000 } } ``` **Problem**: Access denied errors **Solutions**: * Verify user has required permissions * Check table/schema access rights * Enable write permissions if needed * Review database user grants * Check row-level security policies ```typescript theme={null} // Grant appropriate permissions dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, permissions: { read: true, write: true, // Enable if needed delete: false // Explicitly disable dangerous operations } } } ``` **Problem**: Agent can't see tables or columns **Solutions**: * Verify user has permissions to read schema * Check search\_path for PostgreSQL * Specify schemas explicitly * Refresh schema cache ```typescript theme={null} // Explicitly specify schemas dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, scope: { schemas: ["public", "app_schema"], refreshSchema: true } } } ``` ## Advanced Patterns ### Query Result Streaming Stream large result sets: ```typescript theme={null} dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, streaming: { enabled: true, batchSize: 1000 } } } // Agent streams results in batches ``` ### Multi-tenancy Isolate data by tenant: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Show customer orders", dataConnectors: { postgres: { enabled: true, connectionString: process.env.DATABASE_URL, tenantIsolation: { enabled: true, tenantId: currentTenant.id, tenantColumn: "tenant_id" } } } }); // Agent automatically filters all queries by tenant_id ``` ### Change Data Capture Monitor database changes: ```typescript theme={null} const cdc = await agentbase.createDataConnectorListener({ connector: "postgres", tables: ["orders", "customers"], events: ["insert", "update", "delete"], callback: async (change) => { await agentbase.runAgent({ message: `Process database change: ${change.operation} on ${change.table}`, context: { change } }); } }); ``` ## Related Primitives Combine with semantic search on database content Connect to external APIs and services Automate data processing workflows Schedule recurring data operations ## Additional Resources Complete data connectors API documentation Full list of supported data sources Best practices for secure database access **Pro Tip**: Use read-only replicas for analytics queries to avoid impacting production database performance. Agent can automatically route queries to appropriate databases. # Integrations Source: https://docs.agentbase.sh/primitives/extensions/integrations Connect agents to external services, APIs, and third-party platforms > Integrations enable agents to interact with external services, APIs, and platforms seamlessly, extending their capabilities to work with your existing tools and systems. ## Overview The Integrations primitive provides a unified interface for agents to connect with external services, from SaaS platforms to custom APIs. Rather than building custom connectors for each service, Agentbase provides pre-built integrations and a framework for creating custom ones. Integrations are essential for: * **Service Connectivity**: Connect to popular platforms like Slack, GitHub, Salesforce, etc. * **API Access**: Interact with any REST API or web service * **OAuth Management**: Handle authentication flows automatically * **Rate Limiting**: Built-in rate limit handling and retry logic * **Error Handling**: Graceful degradation when services are unavailable * **Data Synchronization**: Keep data in sync across multiple systems 200+ ready-to-use integrations for popular services Build custom connectors for any API or service Automatic OAuth 2.0 flow handling with token refresh Receive real-time events from external services ## How Integrations Work When you enable integrations for an agent: 1. **Authentication**: Agent authenticates with service using API keys or OAuth 2. **Discovery**: Agent discovers available actions and endpoints 3. **Execution**: Agent calls service APIs to perform actions 4. **Response Handling**: Processes responses and handles errors 5. **State Management**: Maintains connection state and credentials 6. **Rate Limiting**: Automatically throttles requests within service limits **Secure Credentials**: API keys and OAuth tokens are encrypted at rest and never exposed in logs or responses. ## Pre-built Integrations ### Communication Platforms ```typescript theme={null} { integrations: { slack: { enabled: true }, discord: { enabled: true }, teams: { enabled: true }, telegram: { enabled: true } } } ``` ### Developer Tools ```typescript theme={null} { integrations: { github: { enabled: true }, gitlab: { enabled: true }, jira: { enabled: true }, linear: { enabled: true } } } ``` ### CRM & Sales ```typescript theme={null} { integrations: { salesforce: { enabled: true }, hubspot: { enabled: true }, pipedrive: { enabled: true }, zendesk: { enabled: true } } } ``` ## Code Examples ### Basic Integration ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Use Slack integration const result = await agentbase.runAgent({ message: "Send a message to #general channel about today's standup", integrations: { slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } } } }); // Agent automatically uses Slack API to send message ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Use Slack integration result = agentbase.run_agent( message="Send a message to #general channel about today's standup", integrations={ "slack": { "enabled": True, "credentials": { "token": os.environ['SLACK_TOKEN'] } } } ) # Agent automatically uses Slack API to send message ``` ### OAuth Integration ```typescript TypeScript theme={null} // Configure OAuth integration const result = await agentbase.runAgent({ message: "Create a new GitHub issue for the bug I mentioned", integrations: { github: { enabled: true, oauth: { clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, redirectUri: "https://yourapp.com/oauth/callback", scopes: ["repo", "issues"] } } }, userId: "user_123" // Link OAuth token to user }); // Agent handles OAuth flow and uses authenticated API ``` ```python Python theme={null} # Configure OAuth integration result = agentbase.run_agent( message="Create a new GitHub issue for the bug I mentioned", integrations={ "github": { "enabled": True, "oauth": { "client_id": os.environ['GITHUB_CLIENT_ID'], "client_secret": os.environ['GITHUB_CLIENT_SECRET'], "redirect_uri": "https://yourapp.com/oauth/callback", "scopes": ["repo", "issues"] } } }, user_id="user_123" # Link OAuth token to user ) ``` ### Multiple Integrations ```typescript TypeScript theme={null} // Use multiple integrations together const result = await agentbase.runAgent({ message: "When a GitHub issue is created, notify the team in Slack and create a Jira ticket", integrations: { github: { enabled: true, credentials: { token: process.env.GITHUB_TOKEN } }, slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } }, jira: { enabled: true, credentials: { email: process.env.JIRA_EMAIL, apiToken: process.env.JIRA_TOKEN, domain: "yourcompany.atlassian.net" } } } }); // Agent coordinates across all three services ``` ```python Python theme={null} # Use multiple integrations together result = agentbase.run_agent( message="When a GitHub issue is created, notify the team in Slack and create a Jira ticket", integrations={ "github": { "enabled": True, "credentials": {"token": os.environ['GITHUB_TOKEN']} }, "slack": { "enabled": True, "credentials": {"token": os.environ['SLACK_TOKEN']} }, "jira": { "enabled": True, "credentials": { "email": os.environ['JIRA_EMAIL'], "api_token": os.environ['JIRA_TOKEN'], "domain": "yourcompany.atlassian.net" } } } ) ``` ### Custom API Integration ```typescript TypeScript theme={null} // Integrate with custom API const result = await agentbase.runAgent({ message: "Get customer data from our internal API", integrations: { custom: { name: "company-api", baseUrl: "https://api.company.com", authentication: { type: "bearer", token: process.env.COMPANY_API_KEY }, endpoints: [ { name: "get_customer", method: "GET", path: "/customers/:id", description: "Get customer by ID" }, { name: "update_customer", method: "PUT", path: "/customers/:id", description: "Update customer information" } ] } } }); // Agent can call your custom API ``` ```python Python theme={null} # Integrate with custom API result = agentbase.run_agent( message="Get customer data from our internal API", integrations={ "custom": { "name": "company-api", "base_url": "https://api.company.com", "authentication": { "type": "bearer", "token": os.environ['COMPANY_API_KEY'] }, "endpoints": [ { "name": "get_customer", "method": "GET", "path": "/customers/:id", "description": "Get customer by ID" }, { "name": "update_customer", "method": "PUT", "path": "/customers/:id", "description": "Update customer information" } ] } } ) ``` ### Webhook Integration ```typescript TypeScript theme={null} // Set up webhook to receive events const webhook = await agentbase.createWebhook({ integration: "stripe", events: ["payment_intent.succeeded", "invoice.paid"], url: "https://yourapp.com/webhooks/stripe", secret: process.env.STRIPE_WEBHOOK_SECRET }); // Handle webhook events with agent app.post('/webhooks/stripe', async (req, res) => { const event = req.body; const result = await agentbase.runAgent({ message: `Process Stripe ${event.type} event`, context: { event: event.data.object }, integrations: { stripe: { enabled: true, credentials: { apiKey: process.env.STRIPE_API_KEY } }, slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } } }, system: `Process the Stripe event: - Update customer record - Send confirmation email - Notify team in Slack - Update analytics` }); res.json({ received: true }); }); ``` ```python Python theme={null} # Set up webhook to receive events webhook = agentbase.create_webhook( integration="stripe", events=["payment_intent.succeeded", "invoice.paid"], url="https://yourapp.com/webhooks/stripe", secret=os.environ['STRIPE_WEBHOOK_SECRET'] ) # Handle webhook events with agent @app.post('/webhooks/stripe') async def handle_stripe_webhook(request): event = await request.json() result = agentbase.run_agent( message=f"Process Stripe {event['type']} event", context={ "event": event['data']['object'] }, integrations={ "stripe": { "enabled": True, "credentials": {"api_key": os.environ['STRIPE_API_KEY']} }, "slack": { "enabled": True, "credentials": {"token": os.environ['SLACK_TOKEN']} } }, system="""Process the Stripe event: - Update customer record - Send confirmation email - Notify team in Slack - Update analytics""" ) return {"received": True} ``` ### Integration with Rate Limiting ```typescript TypeScript theme={null} // Configure rate limiting for integration const result = await agentbase.runAgent({ message: "Fetch data from external API", integrations: { custom: { name: "external-api", baseUrl: "https://api.external.com", rateLimit: { requestsPerSecond: 10, requestsPerMinute: 100, retryAfter: true, // Respect Retry-After header backoff: "exponential" }, credentials: { apiKey: process.env.EXTERNAL_API_KEY } } } }); // Agent automatically throttles requests ``` ```python Python theme={null} # Configure rate limiting for integration result = agentbase.run_agent( message="Fetch data from external API", integrations={ "custom": { "name": "external-api", "base_url": "https://api.external.com", "rate_limit": { "requests_per_second": 10, "requests_per_minute": 100, "retry_after": True, # Respect Retry-After header "backoff": "exponential" }, "credentials": { "api_key": os.environ['EXTERNAL_API_KEY'] } } } ) ``` ## Use Cases ### 1. Customer Support Automation Integrate support tools for automated ticket handling: ```typescript TypeScript theme={null} const supportAgent = await agentbase.runAgent({ message: "Handle new support ticket", context: { ticket: ticketData }, integrations: { zendesk: { enabled: true, credentials: { email: process.env.ZENDESK_EMAIL, apiToken: process.env.ZENDESK_TOKEN, subdomain: "yourcompany" } }, slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } }, salesforce: { enabled: true, credentials: { instanceUrl: process.env.SF_INSTANCE_URL, accessToken: process.env.SF_ACCESS_TOKEN } } }, system: `Handle support ticket: 1. Classify ticket urgency and category 2. Look up customer in Salesforce 3. If high priority, notify team in Slack 4. Provide initial response in Zendesk 5. Create case in Salesforce if needed` }); ``` ```python Python theme={null} support_agent = agentbase.run_agent( message="Handle new support ticket", context={ "ticket": ticket_data }, integrations={ "zendesk": { "enabled": True, "credentials": { "email": os.environ['ZENDESK_EMAIL'], "api_token": os.environ['ZENDESK_TOKEN'], "subdomain": "yourcompany" } }, "slack": { "enabled": True, "credentials": {"token": os.environ['SLACK_TOKEN']} }, "salesforce": { "enabled": True, "credentials": { "instance_url": os.environ['SF_INSTANCE_URL'], "access_token": os.environ['SF_ACCESS_TOKEN'] } } }, system="""Handle support ticket: 1. Classify ticket urgency and category 2. Look up customer in Salesforce 3. If high priority, notify team in Slack 4. Provide initial response in Zendesk 5. Create case in Salesforce if needed""" ) ``` ### 2. DevOps Automation Automate development workflows: ```typescript theme={null} const devopsAgent = await agentbase.runAgent({ message: "Deploy new version to production", integrations: { github: { enabled: true, credentials: { token: process.env.GITHUB_TOKEN } }, slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } }, datadog: { enabled: true, credentials: { apiKey: process.env.DATADOG_API_KEY, appKey: process.env.DATADOG_APP_KEY } }, pagerduty: { enabled: true, credentials: { apiKey: process.env.PAGERDUTY_KEY } } }, system: `Deploy to production: 1. Create GitHub release from tag 2. Announce deployment in Slack 3. Monitor Datadog for errors (30 min window) 4. If error rate > 5%, rollback and page on-call 5. If successful, update deployment docs` }); ``` ### 3. Sales Pipeline Management Sync leads across CRM and communication platforms: ```typescript theme={null} const salesAgent = await agentbase.runAgent({ message: "New lead from website form", context: { lead: leadData }, integrations: { hubspot: { enabled: true, credentials: { apiKey: process.env.HUBSPOT_KEY } }, slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } }, calendly: { enabled: true, credentials: { apiKey: process.env.CALENDLY_KEY } } }, system: `Process new lead: 1. Create contact in HubSpot 2. Enrich with company data 3. Score lead based on criteria 4. If qualified, notify sales team in Slack 5. Send personalized email with Calendly link 6. Update lead status to "contacted"` }); ``` ### 4. Financial Reconciliation Integrate accounting and payment systems: ```typescript theme={null} const financeAgent = await agentbase.runAgent({ message: "Reconcile today's transactions", integrations: { stripe: { enabled: true, credentials: { apiKey: process.env.STRIPE_KEY } }, quickbooks: { enabled: true, oauth: { accessToken: process.env.QB_ACCESS_TOKEN, refreshToken: process.env.QB_REFRESH_TOKEN, realmId: process.env.QB_REALM_ID } }, slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } } }, system: `Reconcile transactions: 1. Fetch today's Stripe transactions 2. Match with QuickBooks invoices 3. Create journal entries for matched items 4. Flag unmatched transactions 5. Send reconciliation report to #finance Slack channel 6. If discrepancies > $100, alert accounting team` }); ``` ### 5. Content Distribution Publish content across multiple platforms: ```typescript theme={null} const contentAgent = await agentbase.runAgent({ message: "Publish this blog post across all channels", context: { blogPost: { title: "Product Update: New Features", content: "...", image: "https://..." } }, integrations: { wordpress: { enabled: true, credentials: { url: "https://blog.company.com", username: process.env.WP_USER, password: process.env.WP_PASS } }, twitter: { enabled: true, oauth: { /* Twitter OAuth */ } }, linkedin: { enabled: true, oauth: { /* LinkedIn OAuth */ } }, mailchimp: { enabled: true, credentials: { apiKey: process.env.MAILCHIMP_KEY } } }, system: `Publish content: 1. Post full article to WordPress blog 2. Create Twitter thread with key points 3. Share on LinkedIn company page 4. Send newsletter via Mailchimp 5. Track engagement across platforms` }); ``` ### 6. HR Onboarding Automate employee onboarding across systems: ```typescript theme={null} const hrAgent = await agentbase.runAgent({ message: "Onboard new employee", context: { employee: newHireData }, integrations: { bamboohr: { enabled: true, credentials: { subdomain: "company", apiKey: process.env.BAMBOO_KEY } }, gsuite: { enabled: true, oauth: { /* Google OAuth */ } }, slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } }, github: { enabled: true, credentials: { token: process.env.GITHUB_TOKEN } } }, system: `Onboard employee: 1. Create BambooHR profile 2. Create Google Workspace account 3. Add to Slack workspace 4. Invite to GitHub organization 5. Send welcome email with credentials 6. Create onboarding checklist 7. Notify team of new hire` }); ``` ## Best Practices ### Credential Management **Never Hardcode Credentials**: Always use environment variables or secure vaults for API keys and secrets. ```typescript theme={null} // Good: Environment variables integrations: { slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN } } } // Bad: Hardcoded credentials integrations: { slack: { enabled: true, credentials: { token: "xoxb-1234567890-..." // NEVER DO THIS } } } ``` ```typescript theme={null} // Link OAuth tokens to specific users const result = await agentbase.runAgent({ message: "Access my GitHub repos", userId: currentUser.id, // Important for OAuth integrations: { github: { enabled: true, oauth: { clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, scopes: ["repo"] } } } }); // Agent uses user's OAuth token, not a shared service token ``` ```typescript theme={null} // Implement key rotation async function rotateApiKeys() { // Generate new API key const newKey = await generateNewKey(); // Update in secure storage await updateSecureStorage("API_KEY", newKey); // Revoke old key after grace period setTimeout(() => { revokeOldKey(); }, 24 * 60 * 60 * 1000); // 24 hours } // Run monthly ``` ### Error Handling **Graceful Degradation**: Design integrations to fail gracefully when services are unavailable. ```typescript theme={null} const result = await agentbase.runAgent({ message: "Send notification to team", integrations: { slack: { enabled: true, credentials: { token: process.env.SLACK_TOKEN }, fallback: "email" // Fallback to email if Slack fails } }, system: `Send team notification. If Slack is unavailable: - Fall back to email - Log the failure - Retry Slack after 5 minutes` }); ``` ```typescript theme={null} integrations: { external_api: { enabled: true, retry: { maxAttempts: 3, backoff: "exponential", initialDelay: 1000, maxDelay: 10000, retryableErrors: [429, 500, 502, 503, 504] } } } ``` ```typescript theme={null} // Track integration success rates async function monitorIntegrations() { const metrics = await agentbase.getIntegrationMetrics({ timeRange: "24h" }); metrics.forEach(integration => { if (integration.errorRate > 0.05) { // Alert if error rate > 5% sendAlert(`${integration.name} error rate: ${integration.errorRate}`); } }); } ``` ### Performance Optimization ```typescript theme={null} integrations: { external_api: { enabled: true, caching: { enabled: true, ttl: 3600, // Cache for 1 hour keyGenerator: (request) => { // Custom cache key based on request return `${request.endpoint}-${request.params.id}`; } } } } ``` ```typescript theme={null} // Batch multiple requests for efficiency const result = await agentbase.runAgent({ message: "Update 100 customer records", integrations: { salesforce: { enabled: true, batching: { enabled: true, batchSize: 25, // Salesforce limit delayBetweenBatches: 1000 } } } }); ``` ```typescript theme={null} // Good: Event-driven with webhooks await agentbase.createWebhook({ integration: "stripe", events: ["payment_intent.succeeded"] }); // Avoid: Constant polling setInterval(async () => { // Don't poll for new payments every minute const payments = await checkForNewPayments(); }, 60000); ``` ## Integration with Other Primitives ### With Workflow Orchestrate multi-service workflows: ```typescript theme={null} const workflow = { name: "lead_qualification", steps: [ { id: "enrich_lead", type: "agent_task", config: { message: "Enrich lead data from external sources", integrations: { clearbit: { enabled: true } } } }, { id: "create_crm_record", type: "agent_task", config: { message: "Create HubSpot contact", integrations: { hubspot: { enabled: true } } } }, { id: "notify_sales", type: "agent_task", config: { message: "Notify sales team in Slack", integrations: { slack: { enabled: true } } } } ] }; ``` Learn more: [Workflow Primitive](/primitives/extensions/workflow) ### With Custom Tools Combine integrations with custom tools: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Process customer order", integrations: { stripe: { enabled: true }, shopify: { enabled: true } }, mcpServers: [{ serverName: "inventory-system", serverUrl: "https://api.company.com/inventory" }] }); // Agent can use Stripe, Shopify, and custom inventory tools ``` Learn more: [Custom Tools Primitive](/primitives/essentials/custom-tools) ### With Memory Remember integration preferences: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Send update to team", memory: { namespace: `user_${userId}`, enabled: true }, integrations: { slack: { enabled: true }, teams: { enabled: true } } }); // Agent remembers user prefers Slack over Teams ``` Learn more: [Memory Primitive](/primitives/extensions/memory) ## Performance Considerations ### Rate Limiting * **API Limits**: Respect third-party API rate limits * **Automatic Throttling**: Agentbase handles rate limiting automatically * **Burst Protection**: Prevents exceeding burst limits * **Cost Management**: Track API usage to manage costs ```typescript theme={null} // Monitor rate limit usage const usage = await agentbase.getIntegrationUsage({ integration: "github", timeRange: "1h" }); console.log('Requests used:', usage.requestsUsed); console.log('Requests remaining:', usage.requestsRemaining); console.log('Reset time:', usage.resetTime); ``` ### Connection Pooling * **Persistent Connections**: Reuse connections across requests * **Connection Limits**: Configure max concurrent connections * **Timeout Management**: Set appropriate timeouts ```typescript theme={null} integrations: { database: { enabled: true, pool: { min: 2, max: 10, acquireTimeout: 30000, idleTimeout: 10000 } } } ``` ### Cost Optimization **Monitor Integration Costs**: Track API usage to optimize costs and avoid unexpected bills. ```typescript theme={null} // Set usage limits integrations: { openai: { enabled: true, limits: { maxRequestsPerDay: 1000, maxCostPerDay: 50.00, // USD alertThreshold: 0.8 // Alert at 80% of limit } } } ``` ## Troubleshooting **Problem**: Integration fails with auth errors **Solutions**: * Verify API key is correct and not expired * Check OAuth token hasn't been revoked * Ensure correct scopes are granted * Verify service isn't experiencing outages * Check for IP whitelist restrictions ```typescript theme={null} // Debug authentication const result = await agentbase.testIntegration({ integration: "salesforce", credentials: { instanceUrl: process.env.SF_INSTANCE_URL, accessToken: process.env.SF_ACCESS_TOKEN } }); if (!result.success) { console.error('Auth error:', result.error); console.log('Suggestion:', result.suggestion); } ``` **Problem**: Getting rate limit errors from service **Solutions**: * Enable automatic retry with backoff * Reduce request frequency * Implement request batching * Use caching to reduce API calls * Consider upgrading service tier ```typescript theme={null} integrations: { api: { enabled: true, rateLimit: { requestsPerSecond: 5, // Reduce from 10 backoff: "exponential", maxRetries: 5 } } } ``` **Problem**: Requests timing out before completion **Solutions**: * Increase timeout limit * Check network connectivity * Verify service isn't slow/degraded * Consider breaking into smaller requests * Use background processing for long operations ```typescript theme={null} integrations: { slow_api: { enabled: true, timeout: 60000, // Increase to 60 seconds retry: { maxAttempts: 2, retryableErrors: [408, 504] // Timeout errors } } } ``` **Problem**: Webhooks configured but events not arriving **Solutions**: * Verify webhook URL is publicly accessible * Check webhook secret matches * Ensure correct events are subscribed * Verify firewall/security rules * Check service webhook logs ```typescript theme={null} // Test webhook endpoint const test = await agentbase.testWebhook({ url: "https://yourapp.com/webhook", integration: "stripe" }); console.log('Webhook test:', test.success); console.log('Response:', test.response); ``` ## Advanced Patterns ### Circuit Breaker Pattern Prevent cascading failures: ```typescript theme={null} integrations: { external_api: { enabled: true, circuitBreaker: { enabled: true, failureThreshold: 5, // Open after 5 failures timeout: 60000, // Try again after 60s monitoringPeriod: 10000 // Monitor 10s window } } } ``` ### Saga Pattern for Distributed Transactions Coordinate multi-service transactions: ```typescript theme={null} const saga = { steps: [ { action: "reserve_inventory", compensation: "release_inventory" }, { action: "charge_payment", compensation: "refund_payment" }, { action: "create_shipment", compensation: "cancel_shipment" } ] }; // If any step fails, run compensations in reverse ``` ### Integration Health Checks Monitor integration availability: ```typescript theme={null} // Periodic health checks setInterval(async () => { const health = await agentbase.checkIntegrationHealth({ integrations: ["stripe", "salesforce", "slack"] }); health.forEach(integration => { if (integration.status !== "healthy") { sendAlert(`${integration.name} is ${integration.status}`); } }); }, 60000); // Check every minute ``` ## Related Primitives Build custom MCP tools for specialized integrations Orchestrate multi-integration workflows Advanced OAuth and auth management Connect to databases and data sources ## Additional Resources Complete integrations API documentation Browse 200+ pre-built integrations Build your own integrations **Pro Tip**: Start with pre-built integrations when available, then extend with custom tools for specific needs. This gives you the best of both worlds - quick setup and full customization. # MCP (Model Context Protocol) Source: https://docs.agentbase.sh/primitives/extensions/mcp Connect agents to external tools, APIs, and services using the open Model Context Protocol standard > Connect external tools and services using Model Context Protocol > MCP (Model Context Protocol) allows agents to access your external tools, APIs, and databases seamlessly. Learn more at [modelcontextprotocol.io](https://modelcontextprotocol.io/docs/getting-started/intro). ## Basic Usage ```javascript theme={null} theme={null} const response = await agentbase.runAgent({ message: "Get customer data for user ID 12345", mcpServers: [ { serverName: "customer-api", serverUrl: "https://api.yourcompany.com/mcp" } ] }); ``` ## Common Use Cases **Database Integration:** ```javascript theme={null} theme={null} mcpServers: [{ serverName: "company-db", serverUrl: "https://db-mcp.yourcompany.com" }] ``` **API Integration:** ```javascript theme={null} theme={null} mcpServers: [{ serverName: "inventory-api", serverUrl: "https://inventory-mcp.yourcompany.com" }] ``` **Multiple MCP Servers:** ```javascript theme={null} theme={null} mcpServers: [ { serverName: "crm-tools", serverUrl: "https://crm-mcp.yourcompany.com" }, { serverName: "payment-gateway", serverUrl: "https://payments-mcp.yourcompany.com" } ] ``` ## MCP Server Requirements Your MCP server needs: * HTTP endpoint accepting MCP-formatted requests * Tool definitions with parameters * Authentication handling * Standard response format **Pro tip**: Start with simple MCP integrations and gradually add complexity. Test MCP server connectivity and tool availability before deploying to production. # Memory Source: https://docs.agentbase.sh/primitives/extensions/memory Enable agents to remember context, conversations, and data across sessions > Memory gives agents the ability to retain and recall information across sessions, enabling personalized interactions, context continuity, and intelligent decision-making based on historical data. ## Overview The Memory primitive empowers agents with persistent storage and retrieval of information across multiple sessions and interactions. Unlike session-based state that exists only within a single conversation, memory provides long-term retention of facts, preferences, conversation history, and learned patterns. Memory is essential for: * **Personalization**: Remember user preferences, habits, and historical interactions * **Context Continuity**: Maintain conversation context across multiple sessions * **Knowledge Accumulation**: Build up domain knowledge over time * **Relationship Building**: Create more natural, personalized user experiences * **Efficient Workflows**: Avoid asking users to repeat information * **Pattern Recognition**: Learn from past interactions to improve future responses Store important information automatically or explicitly during agent execution Query memories using natural language with vector-based semantic search Organize memories by user, session, or custom namespaces for multi-tenant applications Memories include timestamps for time-based retrieval and context ## How Memory Works When you enable memory for an agent: 1. **Storage**: Agent stores important facts, preferences, and context during execution 2. **Indexing**: Memories are indexed using vector embeddings for semantic search 3. **Retrieval**: Agent automatically recalls relevant memories based on current context 4. **Integration**: Retrieved memories are injected into agent context for informed responses 5. **Updates**: Memories can be updated, deleted, or marked as outdated over time 6. **Scoping**: Memories are isolated by namespace (user ID, workspace, etc.) **Privacy & Control**: Memories are scoped per user/namespace and can be deleted at any time. Agentbase provides full GDPR compliance for memory management. ## Memory Types ### User Memory Store user-specific preferences and information: ```typescript theme={null} // User preferences and facts { type: "user", namespace: "user_12345", memories: [ "User prefers concise responses", "User's timezone is PST", "User works in healthcare industry", "User last ordered Product X on 2024-01-15" ] } ``` ### Conversation Memory Maintain conversation context and history: ```typescript theme={null} // Conversation context { type: "conversation", namespace: "session_abc123", memories: [ "User asked about pricing on 2024-01-10", "User mentioned a bug in the mobile app", "Promised to follow up by end of week" ] } ``` ### Knowledge Memory Store domain knowledge and learned information: ```typescript theme={null} // Domain knowledge { type: "knowledge", namespace: "company_docs", memories: [ "Company uses AWS for infrastructure", "Support hours are 9am-5pm EST", "Refund policy is 30 days" ] } ``` ## Code Examples ### Basic Memory Usage ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Enable memory for a user const result = await agentbase.runAgent({ message: "Remember that I prefer morning meetings and I'm allergic to shellfish", memory: { namespace: "user_12345", enabled: true } }); // Agent automatically stores this information // Future conversations will recall these preferences ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Enable memory for a user result = agentbase.run_agent( message="Remember that I prefer morning meetings and I'm allergic to shellfish", memory={ "namespace": "user_12345", "enabled": True } ) # Agent automatically stores this information # Future conversations will recall these preferences ``` ```bash cURL theme={null} curl -X POST https://api.agentbase.sh \ -H "Authorization: Bearer $AGENTBASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "message": "Remember that I prefer morning meetings and I am allergic to shellfish", "memory": { "namespace": "user_12345", "enabled": true } }' ``` ### Retrieving Memories ```typescript TypeScript theme={null} // Agent automatically retrieves relevant memories const result = await agentbase.runAgent({ message: "Schedule a meeting with the team", memory: { namespace: "user_12345", enabled: true } }); // Agent recalls "I prefer morning meetings" and suggests morning times ``` ```python Python theme={null} # Agent automatically retrieves relevant memories result = agentbase.run_agent( message="Schedule a meeting with the team", memory={ "namespace": "user_12345", "enabled": True } ) # Agent recalls "I prefer morning meetings" and suggests morning times ``` ### Explicit Memory Storage ```typescript TypeScript theme={null} // Store specific memories explicitly via API await agentbase.storeMemory({ namespace: "user_12345", memories: [ { content: "User's favorite color is blue", metadata: { category: "preferences", confidence: 1.0 } }, { content: "User completed onboarding on 2024-01-15", metadata: { category: "milestones", timestamp: "2024-01-15T10:00:00Z" } } ] }); ``` ```python Python theme={null} # Store specific memories explicitly via API agentbase.store_memory( namespace="user_12345", memories=[ { "content": "User's favorite color is blue", "metadata": { "category": "preferences", "confidence": 1.0 } }, { "content": "User completed onboarding on 2024-01-15", "metadata": { "category": "milestones", "timestamp": "2024-01-15T10:00:00Z" } } ] ) ``` ### Querying Memories ```typescript TypeScript theme={null} // Search memories semantically const memories = await agentbase.queryMemories({ namespace: "user_12345", query: "What are the user's food preferences?", limit: 5 }); console.log(memories); // [ // { content: "User is allergic to shellfish", relevance: 0.95 }, // { content: "User prefers vegetarian options", relevance: 0.87 } // ] ``` ```python Python theme={null} # Search memories semantically memories = agentbase.query_memories( namespace="user_12345", query="What are the user's food preferences?", limit=5 ) print(memories) # [ # { "content": "User is allergic to shellfish", "relevance": 0.95 }, # { "content": "User prefers vegetarian options", "relevance": 0.87 } # ] ``` ### Memory with Time Filters ```typescript TypeScript theme={null} // Retrieve recent memories only const recentMemories = await agentbase.queryMemories({ namespace: "user_12345", query: "recent interactions", timeFilter: { after: "2024-01-01T00:00:00Z", before: "2024-01-31T23:59:59Z" }, limit: 10 }); // Get memories from specific time period ``` ```python Python theme={null} # Retrieve recent memories only recent_memories = agentbase.query_memories( namespace="user_12345", query="recent interactions", time_filter={ "after": "2024-01-01T00:00:00Z", "before": "2024-01-31T23:59:59Z" }, limit=10 ) # Get memories from specific time period ``` ### Deleting Memories ```typescript TypeScript theme={null} // Delete specific memories await agentbase.deleteMemories({ namespace: "user_12345", memoryIds: ["mem_abc123", "mem_def456"] }); // Delete all memories for a namespace await agentbase.deleteMemories({ namespace: "user_12345", deleteAll: true }); ``` ```python Python theme={null} # Delete specific memories agentbase.delete_memories( namespace="user_12345", memory_ids=["mem_abc123", "mem_def456"] ) # Delete all memories for a namespace agentbase.delete_memories( namespace="user_12345", delete_all=True ) ``` ## Use Cases ### 1. Personalized Customer Support Create support agents that remember customer history: ```typescript TypeScript theme={null} const support = await agentbase.runAgent({ message: "I'm having issues with my account", memory: { namespace: `customer_${customerId}`, enabled: true }, system: `You are a customer support agent. Use memory to: - Recall previous support tickets and resolutions - Remember customer preferences and communication style - Track ongoing issues and promises made - Personalize responses based on customer history` }); // Agent automatically recalls: // - "Customer prefers email over phone" // - "Had billing issue resolved on 2024-01-10" // - "Premium tier customer since 2023" ``` ```python Python theme={null} support = agentbase.run_agent( message="I'm having issues with my account", memory={ "namespace": f"customer_{customer_id}", "enabled": True }, system="""You are a customer support agent. Use memory to: - Recall previous support tickets and resolutions - Remember customer preferences and communication style - Track ongoing issues and promises made - Personalize responses based on customer history""" ) # Agent automatically recalls: # - "Customer prefers email over phone" # - "Had billing issue resolved on 2024-01-10" # - "Premium tier customer since 2023" ``` ### 2. Executive Assistant Build assistants that remember user preferences and context: ```typescript theme={null} const assistant = await agentbase.runAgent({ message: "Schedule meetings for next week", memory: { namespace: `user_${userId}`, enabled: true }, system: `You are a personal executive assistant. Remember and use: - User's calendar preferences (morning meetings, lunch blocks) - Recurring commitments and constraints - Preferred meeting locations - Communication preferences with different contacts - Travel schedules and time zones` }); // Agent recalls: // - "User blocks 12-1pm for lunch" // - "Prefers video calls for external meetings" // - "Traveling to NYC Jan 15-17" ``` ### 3. Learning Companion Create educational agents that track progress: ```typescript theme={null} const tutor = await agentbase.runAgent({ message: "Let's continue our Python lesson", memory: { namespace: `student_${studentId}`, enabled: true }, system: `You are a programming tutor. Track and recall: - Topics already covered - Student's strengths and weaknesses - Questions asked and concepts mastered - Preferred learning style - Projects in progress` }); // Agent recalls: // - "Completed variables and loops lessons" // - "Struggling with object-oriented concepts" // - "Prefers hands-on examples" // - "Working on calculator project" ``` ### 4. Sales Assistant Remember prospect interactions and preferences: ```typescript theme={null} const sales = await agentbase.runAgent({ message: "Follow up with prospect about demo", memory: { namespace: `prospect_${prospectId}`, enabled: true }, system: `You are a sales development representative. Remember: - Previous conversations and pain points discussed - Decision makers and stakeholders identified - Budget and timeline information - Competitor mentions - Objections raised and addressed` }); // Agent recalls: // - "Interested in enterprise plan" // - "Budget approved for Q2" // - "Currently using Competitor X" // - "CTO is key decision maker" ``` ### 5. Health & Wellness Coach Track user goals and progress: ```typescript theme={null} const coach = await agentbase.runAgent({ message: "How did my workout go this week?", memory: { namespace: `user_${userId}`, enabled: true }, system: `You are a health and wellness coach. Track: - Fitness goals and milestones - Workout history and progress - Dietary preferences and restrictions - Sleep patterns - Energy levels and mood` }); // Agent recalls: // - "Goal: Run 5K by March" // - "Completed 3 workouts this week" // - "Vegetarian diet" // - "Best workout time is morning" ``` ### 6. Research Assistant Accumulate knowledge across research sessions: ```typescript theme={null} const researcher = await agentbase.runAgent({ message: "Continue research on renewable energy", memory: { namespace: `project_${projectId}`, enabled: true }, system: `You are a research assistant. Remember: - Research topics explored - Key findings and sources - Questions to investigate - Hypotheses formed - Papers read and summarized` }); // Agent recalls: // - "Reviewed 12 papers on solar efficiency" // - "Key finding: efficiency increased 15% since 2020" // - "To investigate: cost trends in battery storage" ``` ## Best Practices ### Memory Scope Design ```typescript theme={null} // Good: Scope by user for personalization memory: { namespace: `user_${userId}`, enabled: true } // Each user gets isolated memory ``` ```typescript theme={null} // For shared knowledge within organizations memory: { namespace: `org_${orgId}`, enabled: true } // Team-wide knowledge accessible to all members ``` ```typescript theme={null} // For project-specific context memory: { namespace: `project_${projectId}`, enabled: true } // Isolate project-related information ``` ```typescript theme={null} // Combine scopes for granular control memory: { namespace: `org_${orgId}_user_${userId}`, enabled: true } // User-specific memories within organization context ``` ### Memory Storage Guidelines **Be Specific**: Store concrete, actionable information rather than vague generalizations. "User prefers meetings at 10am" is more useful than "User likes mornings." ```typescript theme={null} // Good: Extract and store facts await agentbase.storeMemory({ namespace: "user_123", memories: [ { content: "User allergic to peanuts" }, { content: "User's birthday is March 15" }, { content: "User prefers dark mode in UI" } ] }); // Avoid: Storing full conversation text await agentbase.storeMemory({ namespace: "user_123", memories: [ { content: "User: I'm allergic to peanuts. Agent: I'll remember that." } ] }); ``` ```typescript theme={null} // Include relevant metadata await agentbase.storeMemory({ namespace: "user_123", memories: [ { content: "User completed Python course", metadata: { category: "education", timestamp: "2024-01-15T10:00:00Z", confidence: 1.0, source: "course_platform" } } ] }); ``` ```typescript theme={null} // Remove or update outdated memories // First, query for existing memory const oldMemories = await agentbase.queryMemories({ namespace: "user_123", query: "user address" }); // Delete old address await agentbase.deleteMemories({ namespace: "user_123", memoryIds: oldMemories.map(m => m.id) }); // Store new address await agentbase.storeMemory({ namespace: "user_123", memories: [ { content: "User's address is 123 New St, Boston, MA", metadata: { updatedAt: new Date().toISOString() } } ] }); ``` ### Privacy and Compliance **PII Handling**: Be mindful of storing personally identifiable information (PII). Implement proper data retention policies and provide users with memory deletion capabilities. ```typescript theme={null} // Implement user data deletion async function deleteUserData(userId: string) { // Delete all user memories for GDPR compliance await agentbase.deleteMemories({ namespace: `user_${userId}`, deleteAll: true }); console.log(`All data deleted for user ${userId}`); } // Provide users with memory viewing async function getUserMemories(userId: string) { const memories = await agentbase.queryMemories({ namespace: `user_${userId}`, query: "*", // Get all memories limit: 1000 }); return memories; } // Allow users to delete specific memories async function deleteSpecificMemory(userId: string, memoryId: string) { await agentbase.deleteMemories({ namespace: `user_${userId}`, memoryIds: [memoryId] }); } ``` ### Memory Retrieval Optimization ```typescript theme={null} // Don't retrieve too many memories at once const memories = await agentbase.queryMemories({ namespace: "user_123", query: "user preferences", limit: 10 // Top 10 most relevant }); // Too many memories can dilute context and increase costs ``` ```typescript theme={null} // Good: Specific query const foodPrefs = await agentbase.queryMemories({ namespace: "user_123", query: "dietary restrictions and food allergies" }); // Avoid: Overly broad query const everything = await agentbase.queryMemories({ namespace: "user_123", query: "everything about the user" }); ``` ```typescript theme={null} // Use metadata to filter memories const preferences = await agentbase.queryMemories({ namespace: "user_123", query: "user preferences", filter: { category: "preferences" } }); ``` ## Integration with Other Primitives ### With Sessions Combine session state with long-term memory: ```typescript theme={null} // Long-term memory + session-specific state const result = await agentbase.runAgent({ message: "Continue our conversation", session: sessionId, // Session-specific conversation memory: { namespace: `user_${userId}`, // Long-term user memory enabled: true } }); // Session maintains conversation flow // Memory provides long-term context and personalization ``` Learn more: [Sessions Primitive](/primitives/essentials/sessions) ### With Multi-Agent Systems Share knowledge across specialized agents: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Help me with my order", memory: { namespace: `customer_${customerId}`, enabled: true }, agents: [ { name: "Order Specialist", description: "Handles order questions", // Accesses same customer memory }, { name: "Billing Specialist", description: "Handles billing questions", // Accesses same customer memory } ] }); // All agents share customer memory ``` Learn more: [Multi-Agent Primitive](/primitives/essentials/multi-agents) ### With RAG Combine semantic memory with document retrieval: ```typescript theme={null} const result = await agentbase.runAgent({ message: "What did we discuss about the Q4 strategy?", memory: { namespace: `team_${teamId}`, enabled: true }, datastores: [ { id: "ds_company_docs", name: "Company Documents" } ] }); // Memory: Recalls specific discussions and decisions // RAG: Retrieves relevant documents and references ``` Learn more: [RAG Primitive](/primitives/extensions/rag) ### With Prompts Guide memory usage with system prompts: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Plan my week", memory: { namespace: `user_${userId}`, enabled: true }, system: `You are a personal assistant. ALWAYS recall from memory: - User's work schedule and commitments - Personal preferences for meeting times - Recurring tasks and habits - Goals and priorities Store in memory: - New commitments mentioned - Updated preferences - Completed tasks and milestones` }); ``` Learn more: [Prompts Primitive](/primitives/essentials/prompts) ## Performance Considerations ### Memory Retrieval Latency * **Cold Start**: First memory query in a session: \~200-500ms * **Warm Cache**: Subsequent queries: \~50-100ms * **Optimization**: Limit retrieved memories to top 5-10 most relevant ```typescript theme={null} // Efficient: Retrieve only what's needed const memories = await agentbase.queryMemories({ namespace: "user_123", query: "current projects", limit: 5 // Just the most relevant }); // Less efficient: Retrieving too much const allMemories = await agentbase.queryMemories({ namespace: "user_123", query: "*", limit: 100 // Probably overkill }); ``` ### Token Usage Memories consume input tokens when injected into agent context: ```typescript theme={null} // Each memory retrieved adds to token count // 10 memories × 50 tokens each = 500 tokens // Optimize by being selective about retrieval memory: { namespace: "user_123", enabled: true, maxMemories: 5 // Limit automatic retrieval } ``` ### Storage Costs **Storage Pricing**: Memory storage is included in your plan up to limits. See pricing page for details. * Keep memories concise and factual * Delete outdated or irrelevant memories * Implement retention policies for automatic cleanup ```typescript theme={null} // Clean up old memories periodically async function cleanupOldMemories(namespace: string, daysOld: number) { const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - daysOld); const oldMemories = await agentbase.queryMemories({ namespace, query: "*", timeFilter: { before: cutoffDate.toISOString() }, limit: 1000 }); if (oldMemories.length > 0) { await agentbase.deleteMemories({ namespace, memoryIds: oldMemories.map(m => m.id) }); console.log(`Deleted ${oldMemories.length} old memories`); } } ``` ## Troubleshooting **Problem**: Agent doesn't use stored memories in responses **Solutions**: * Verify memory is enabled with `enabled: true` * Check namespace matches between storage and retrieval * Ensure memories are relevant to current query (semantic match) * Add guidance in system prompt to use memory * Query memories manually to verify they exist ```typescript theme={null} // Debug memory retrieval const memories = await agentbase.queryMemories({ namespace: "user_123", query: "test query", limit: 10 }); console.log("Retrieved memories:", memories); // If empty, memories may not be stored correctly ``` **Problem**: Agent retrieves memories that aren't relevant **Solutions**: * Make memory content more specific and detailed * Add category metadata for filtering * Use more specific queries when retrieving * Reduce the number of memories retrieved * Delete outdated or low-quality memories ```typescript theme={null} // Add category metadata for better filtering await agentbase.storeMemory({ namespace: "user_123", memories: [ { content: "User prefers dark mode", metadata: { category: "ui_preferences" } } ] }); // Filter by category when retrieving const uiMemories = await agentbase.queryMemories({ namespace: "user_123", query: "interface preferences", filter: { category: "ui_preferences" } }); ``` **Problem**: Memories leaking between users or contexts **Solutions**: * Always use unique, consistent namespace identifiers * Include user ID or tenant ID in namespace * Validate namespace before storage/retrieval * Implement namespace access controls ```typescript theme={null} // Ensure namespace consistency function getMemoryNamespace(userId: string): string { if (!userId) { throw new Error("User ID required for memory namespace"); } return `user_${userId}`; } // Use helper function consistently const result = await agentbase.runAgent({ message: "Hello", memory: { namespace: getMemoryNamespace(userId), enabled: true } }); ``` **Problem**: Multiple similar memories causing confusion **Solutions**: * Query existing memories before storing new ones * Update existing memories instead of creating duplicates * Implement deduplication logic * Add timestamps to identify most recent information ```typescript theme={null} // Check for existing memory before storing async function updateOrCreateMemory( namespace: string, content: string, category: string ) { // Check for existing const existing = await agentbase.queryMemories({ namespace, query: content, filter: { category } }); // Delete old versions if (existing.length > 0) { await agentbase.deleteMemories({ namespace, memoryIds: existing.map(m => m.id) }); } // Store new version await agentbase.storeMemory({ namespace, memories: [ { content, metadata: { category, updatedAt: new Date().toISOString() } } ] }); } ``` ## Advanced Patterns ### Confidence Scoring Track confidence in stored information: ```typescript theme={null} await agentbase.storeMemory({ namespace: "user_123", memories: [ { content: "User mentioned interest in photography", metadata: { confidence: 0.8, // Mentioned once source: "chat", timestamp: new Date().toISOString() } } ] }); // Later, increase confidence after confirmation await agentbase.storeMemory({ namespace: "user_123", memories: [ { content: "User is a professional photographer", metadata: { confidence: 1.0, // Confirmed source: "profile", timestamp: new Date().toISOString() } } ] }); ``` ### Hierarchical Memory Organize memories in hierarchies: ```typescript theme={null} // Organization-level memory (shared) await agentbase.storeMemory({ namespace: "org_acme", memories: [ { content: "Company uses Slack for communication" }, { content: "Office hours are 9am-5pm EST" } ] }); // Team-level memory await agentbase.storeMemory({ namespace: "org_acme_team_engineering", memories: [ { content: "Team does daily standups at 10am" }, { content: "Sprint planning every other Monday" } ] }); // User-level memory (most specific) await agentbase.storeMemory({ namespace: "org_acme_team_engineering_user_123", memories: [ { content: "User leads frontend development" }, { content: "User mentoring 2 junior developers" } ] }); ``` ### Memory Decay Implement time-based memory importance: ```typescript theme={null} async function getMemoriesWithDecay( namespace: string, query: string ) { const memories = await agentbase.queryMemories({ namespace, query, limit: 20 }); // Calculate age-based relevance const now = new Date(); const scoredMemories = memories.map(memory => { const age = now - new Date(memory.timestamp); const daysSinceCreated = age / (1000 * 60 * 60 * 24); // Decay factor: newer memories are more relevant const decayFactor = Math.exp(-daysSinceCreated / 30); // 30 day half-life return { ...memory, adjustedRelevance: memory.relevance * decayFactor }; }); // Sort by adjusted relevance return scoredMemories.sort( (a, b) => b.adjustedRelevance - a.adjustedRelevance ); } ``` ## Related Primitives Maintain conversation state within a single session Retrieve information from document datastores Share memory across specialized agents Guide agents on memory usage patterns ## Additional Resources Complete memory API documentation GDPR compliance and data handling Memory optimization patterns **Remember**: Memory is most powerful when it stores specific, actionable facts rather than general information. Focus on what will make future interactions more personalized and efficient. # Orchestration Source: https://docs.agentbase.sh/primitives/extensions/orchestration Coordinate multiple agents, workflows, and systems for complex operations > Orchestration enables the coordination of multiple agents, workflows, and external systems to solve complex problems that require specialized capabilities and parallel execution. ## Overview The Orchestration primitive provides the framework for coordinating complex operations across multiple agents, workflows, and systems. Unlike single-agent execution or linear workflows, orchestration manages parallel operations, dynamic task distribution, resource allocation, and inter-agent communication. Orchestration is essential for: * **Complex Problem Solving**: Break down complex tasks across specialized agents * **Parallel Execution**: Run multiple operations simultaneously for efficiency * **Resource Management**: Allocate tasks based on agent capabilities and availability * **Dynamic Coordination**: Adapt execution based on intermediate results * **System Integration**: Coordinate across multiple external systems and services * **Scalability**: Handle high-volume operations with automatic load distribution Manage multiple specialized agents working together on complex tasks Intelligently route tasks to appropriate agents based on capabilities Execute multiple operations concurrently for optimal performance Maintain consistent state across distributed agent executions ## How Orchestration Works When you use orchestration: 1. **Task Analysis**: Orchestrator analyzes the problem and identifies sub-tasks 2. **Agent Selection**: Routes tasks to appropriate specialized agents 3. **Parallel Execution**: Executes independent tasks concurrently 4. **Result Aggregation**: Collects and synthesizes results from all agents 5. **Dependency Management**: Ensures tasks execute in proper order when dependent 6. **Error Handling**: Manages failures and retries across distributed execution **Intelligent Routing**: The orchestrator automatically selects the best agent for each task based on capabilities, availability, and past performance. ## Orchestration Patterns ### Hub-and-Spoke Central orchestrator coordinates multiple specialized agents: ```mermaid theme={null} graph TD O[Orchestrator] --> A1[Data Agent] O --> A2[Analysis Agent] O --> A3[Report Agent] A1 --> O A2 --> O A3 --> O ``` ### Pipeline Sequential processing through specialized agents: ```mermaid theme={null} graph LR Input --> A1[Extract Agent] A1 --> A2[Transform Agent] A2 --> A3[Load Agent] A3 --> Output ``` ### Map-Reduce Parallel processing with aggregation: ```mermaid theme={null} graph TD Input --> M[Map/Split] M --> W1[Worker 1] M --> W2[Worker 2] M --> W3[Worker 3] W1 --> R[Reduce/Aggregate] W2 --> R W3 --> R R --> Output ``` ## Code Examples ### Basic Orchestration ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Define specialized agents const agents = [ { name: "Research Agent", description: "Researches topics and gathers information", system: "You are a research specialist. Gather comprehensive information on assigned topics." }, { name: "Analysis Agent", description: "Analyzes data and identifies patterns", system: "You are a data analyst. Analyze information and identify key insights." }, { name: "Writing Agent", description: "Creates written content and reports", system: "You are a professional writer. Create clear, compelling content." } ]; // Orchestrate complex task const result = await agentbase.orchestrate({ task: "Create a comprehensive market analysis report for electric vehicles", agents: agents, strategy: "parallel" // Execute tasks in parallel when possible }); console.log('Orchestration result:', result.output); ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Define specialized agents agents = [ { "name": "Research Agent", "description": "Researches topics and gathers information", "system": "You are a research specialist. Gather comprehensive information on assigned topics." }, { "name": "Analysis Agent", "description": "Analyzes data and identifies patterns", "system": "You are a data analyst. Analyze information and identify key insights." }, { "name": "Writing Agent", "description": "Creates written content and reports", "system": "You are a professional writer. Create clear, compelling content." } ] # Orchestrate complex task result = agentbase.orchestrate( task="Create a comprehensive market analysis report for electric vehicles", agents=agents, strategy="parallel" # Execute tasks in parallel when possible ) print(f"Orchestration result: {result.output}") ``` ### Explicit Task Distribution ```typescript TypeScript theme={null} // Define specific tasks for each agent const orchestration = await agentbase.orchestrate({ tasks: [ { id: "research", agent: "Research Agent", task: "Research current electric vehicle market trends and competitors", dependencies: [] }, { id: "analyze_data", agent: "Analysis Agent", task: "Analyze the research data and identify key market patterns", dependencies: ["research"] // Waits for research to complete }, { id: "create_visualizations", agent: "Analysis Agent", task: "Create charts and graphs of market data", dependencies: ["analyze_data"] }, { id: "write_report", agent: "Writing Agent", task: "Write comprehensive market analysis report", dependencies: ["analyze_data", "create_visualizations"] } ], agents: agents }); console.log('Final report:', orchestration.results['write_report']); ``` ```python Python theme={null} # Define specific tasks for each agent orchestration = agentbase.orchestrate( tasks=[ { "id": "research", "agent": "Research Agent", "task": "Research current electric vehicle market trends and competitors", "dependencies": [] }, { "id": "analyze_data", "agent": "Analysis Agent", "task": "Analyze the research data and identify key market patterns", "dependencies": ["research"] # Waits for research to complete }, { "id": "create_visualizations", "agent": "Analysis Agent", "task": "Create charts and graphs of market data", "dependencies": ["analyze_data"] }, { "id": "write_report", "agent": "Writing Agent", "task": "Write comprehensive market analysis report", "dependencies": ["analyze_data", "create_visualizations"] } ], agents=agents ) print(f"Final report: {orchestration.results['write_report']}") ``` ### Map-Reduce Pattern ```typescript TypeScript theme={null} // Process large dataset in parallel const mapReduce = await agentbase.orchestrate({ pattern: "map-reduce", map: { agent: "Processing Agent", task: "Analyze customer feedback", input: customerFeedbackList, // Array of 1000 feedback items batchSize: 50 // Process 50 items per agent instance }, reduce: { agent: "Aggregation Agent", task: "Synthesize insights from all processed feedback" }, agents: [ { name: "Processing Agent", system: "Analyze customer feedback and extract sentiment, topics, and key issues." }, { name: "Aggregation Agent", system: "Combine analysis results and identify overall patterns and priorities." } ] }); console.log('Aggregated insights:', mapReduce.result); ``` ```python Python theme={null} # Process large dataset in parallel map_reduce = agentbase.orchestrate( pattern="map-reduce", map={ "agent": "Processing Agent", "task": "Analyze customer feedback", "input": customer_feedback_list, # Array of 1000 feedback items "batch_size": 50 # Process 50 items per agent instance }, reduce={ "agent": "Aggregation Agent", "task": "Synthesize insights from all processed feedback" }, agents=[ { "name": "Processing Agent", "system": "Analyze customer feedback and extract sentiment, topics, and key issues." }, { "name": "Aggregation Agent", "system": "Combine analysis results and identify overall patterns and priorities." } ] ) print(f"Aggregated insights: {map_reduce.result}") ``` ### Dynamic Agent Routing ```typescript TypeScript theme={null} // Let orchestrator decide which agents to use const dynamic = await agentbase.orchestrate({ task: "I need help analyzing Q4 financial data and creating a presentation", agents: [ { name: "Financial Analyst", description: "Expert in financial analysis and reporting", capabilities: ["financial_analysis", "data_processing"] }, { name: "Data Scientist", description: "Expert in statistical analysis and ML", capabilities: ["statistics", "machine_learning", "data_visualization"] }, { name: "Presentation Designer", description: "Expert in creating presentations and slides", capabilities: ["presentation_design", "visual_communication"] }, { name: "Business Strategist", description: "Expert in business strategy and insights", capabilities: ["strategy", "business_insights"] } ], routing: "automatic" // Orchestrator selects appropriate agents }); // Orchestrator automatically routes: // - Financial analysis → Financial Analyst // - Data visualization → Data Scientist // - Presentation creation → Presentation Designer // - Strategic insights → Business Strategist ``` ```python Python theme={null} # Let orchestrator decide which agents to use dynamic = agentbase.orchestrate( task="I need help analyzing Q4 financial data and creating a presentation", agents=[ { "name": "Financial Analyst", "description": "Expert in financial analysis and reporting", "capabilities": ["financial_analysis", "data_processing"] }, { "name": "Data Scientist", "description": "Expert in statistical analysis and ML", "capabilities": ["statistics", "machine_learning", "data_visualization"] }, { "name": "Presentation Designer", "description": "Expert in creating presentations and slides", "capabilities": ["presentation_design", "visual_communication"] }, { "name": "Business Strategist", "description": "Expert in business strategy and insights", "capabilities": ["strategy", "business_insights"] } ], routing="automatic" # Orchestrator selects appropriate agents ) ``` ### Monitoring Orchestration ```typescript TypeScript theme={null} // Monitor orchestration progress const orchestration = await agentbase.orchestrate({ task: "Complex multi-step analysis", agents: agents, onProgress: (update) => { console.log(`Task ${update.taskId}: ${update.status}`); console.log(`Progress: ${update.completed}/${update.total}`); console.log(`Current agent: ${update.currentAgent}`); } }); // Get detailed execution trace const trace = await agentbase.getOrchestrationTrace({ orchestrationId: orchestration.id }); trace.steps.forEach(step => { console.log(`${step.agent}: ${step.task} - ${step.duration}ms`); }); ``` ```python Python theme={null} # Monitor orchestration progress def on_progress(update): print(f"Task {update.task_id}: {update.status}") print(f"Progress: {update.completed}/{update.total}") print(f"Current agent: {update.current_agent}") orchestration = agentbase.orchestrate( task="Complex multi-step analysis", agents=agents, on_progress=on_progress ) # Get detailed execution trace trace = agentbase.get_orchestration_trace( orchestration_id=orchestration.id ) for step in trace.steps: print(f"{step.agent}: {step.task} - {step.duration}ms") ``` ## Use Cases ### 1. Comprehensive Research Reports Orchestrate research, analysis, and writing: ```typescript theme={null} const researchOrchestration = { task: "Create comprehensive analysis of renewable energy trends", agents: [ { name: "Web Researcher", description: "Searches and gathers information from web sources", tools: ["web_search", "web_scrape"] }, { name: "Academic Researcher", description: "Searches academic papers and journals", tools: ["academic_search"] }, { name: "Data Analyst", description: "Analyzes numerical data and trends", tools: ["data_analysis", "visualization"] }, { name: "Report Writer", description: "Synthesizes information into comprehensive reports", tools: ["document_creation"] } ], tasks: [ { id: "web_research", agent: "Web Researcher", task: "Research current renewable energy market trends" }, { id: "academic_research", agent: "Academic Researcher", task: "Find recent academic papers on renewable energy technology" }, { id: "data_analysis", agent: "Data Analyst", task: "Analyze renewable energy adoption statistics", dependencies: ["web_research"] }, { id: "create_report", agent: "Report Writer", task: "Create comprehensive report synthesizing all research", dependencies: ["web_research", "academic_research", "data_analysis"] } ] }; const report = await agentbase.orchestrate(researchOrchestration); ``` ### 2. E-Commerce Order Processing Coordinate order fulfillment across multiple systems: ```typescript theme={null} const orderOrchestration = await agentbase.orchestrate({ task: `Process order ${orderId}`, agents: [ { name: "Inventory Agent", description: "Manages inventory checking and allocation", mcpServers: [{ serverName: "inventory-system" }] }, { name: "Payment Agent", description: "Handles payment processing", mcpServers: [{ serverName: "payment-gateway" }] }, { name: "Shipping Agent", description: "Manages shipping and logistics", mcpServers: [{ serverName: "shipping-service" }] }, { name: "Notification Agent", description: "Sends customer notifications", mcpServers: [{ serverName: "email-service" }] } ], tasks: [ { id: "check_inventory", agent: "Inventory Agent", task: "Check inventory availability for all items" }, { id: "reserve_items", agent: "Inventory Agent", task: "Reserve inventory for order", dependencies: ["check_inventory"] }, { id: "process_payment", agent: "Payment Agent", task: "Process customer payment", dependencies: ["reserve_items"] }, { id: "create_shipment", agent: "Shipping Agent", task: "Create shipping label and schedule pickup", dependencies: ["process_payment"] }, { id: "send_confirmation", agent: "Notification Agent", task: "Send order confirmation to customer", dependencies: ["process_payment"] }, { id: "send_tracking", agent: "Notification Agent", task: "Send tracking information to customer", dependencies: ["create_shipment"] } ] }); ``` ### 3. Content Production Pipeline Orchestrate content creation workflow: ```typescript theme={null} const contentPipeline = await agentbase.orchestrate({ pattern: "pipeline", stages: [ { name: "Ideation", agent: "Content Strategist", task: "Generate content ideas based on topic: {{topic}}" }, { name: "Research", agent: "Researcher", task: "Research facts and data for content ideas" }, { name: "Writing", agent: "Copywriter", task: "Write engaging content based on research" }, { name: "Editing", agent: "Editor", task: "Edit content for clarity, grammar, and style" }, { name: "SEO Optimization", agent: "SEO Specialist", task: "Optimize content for search engines" }, { name: "Visual Design", agent: "Designer", task: "Create visual assets for content" }, { name: "Publishing", agent: "Publisher", task: "Format and publish content to CMS" } ], input: { topic: "AI in Healthcare" } }); ``` ### 4. Customer Support Triage Route and handle support tickets: ```typescript theme={null} const supportOrchestration = await agentbase.orchestrate({ task: "Handle incoming support tickets", agents: [ { name: "Triage Agent", description: "Categorizes and prioritizes support tickets" }, { name: "Technical Support", description: "Handles technical issues and bugs", capabilities: ["technical_troubleshooting"] }, { name: "Billing Support", description: "Handles billing and payment questions", capabilities: ["billing", "payments"] }, { name: "Account Support", description: "Handles account access and settings", capabilities: ["account_management"] }, { name: "Escalation Agent", description: "Escalates complex issues to human support" } ], routing: "automatic", pattern: "hub-spoke" // Triage agent routes to specialists }); // For each ticket, triage agent determines: // - Urgency level // - Category (technical, billing, account) // - Appropriate specialist agent // - Whether escalation is needed ``` ### 5. Data Processing Pipeline Process large datasets with parallel agents: ```typescript theme={null} const dataProcessing = await agentbase.orchestrate({ pattern: "map-reduce", map: { agent: "Data Processor", task: "Clean and validate data records", input: rawDataRecords, batchSize: 1000, parallel: 10 // Run 10 processors in parallel }, reduce: { agent: "Data Aggregator", task: "Merge processed data and generate summary statistics" }, agents: [ { name: "Data Processor", system: `Clean and validate data records: - Remove duplicates - Validate formats - Normalize values - Flag anomalies` }, { name: "Data Aggregator", system: `Merge results and create: - Summary statistics - Data quality report - Anomaly report` } ] }); console.log('Processed records:', dataProcessing.totalRecords); console.log('Quality score:', dataProcessing.qualityScore); ``` ### 6. Software Development Workflow Coordinate development tasks: ```typescript theme={null} const devOrchestration = await agentbase.orchestrate({ task: "Implement new feature: user authentication", agents: [ { name: "Architect", description: "Designs system architecture and technical approach" }, { name: "Backend Developer", description: "Implements backend API and services" }, { name: "Frontend Developer", description: "Implements UI components" }, { name: "QA Engineer", description: "Creates tests and validates functionality" }, { name: "DevOps Engineer", description: "Handles deployment and infrastructure" } ], tasks: [ { id: "design", agent: "Architect", task: "Design authentication system architecture" }, { id: "backend_api", agent: "Backend Developer", task: "Implement authentication API endpoints", dependencies: ["design"] }, { id: "frontend_ui", agent: "Frontend Developer", task: "Implement login and registration UI", dependencies: ["design"] }, { id: "backend_tests", agent: "QA Engineer", task: "Create backend API tests", dependencies: ["backend_api"] }, { id: "frontend_tests", agent: "QA Engineer", task: "Create frontend UI tests", dependencies: ["frontend_ui"] }, { id: "deployment", agent: "DevOps Engineer", task: "Deploy authentication service to staging", dependencies: ["backend_tests", "frontend_tests"] } ] }); ``` ## Best Practices ### Agent Design ```typescript theme={null} // Good: Focused, specialized agents agents: [ { name: "Data Extractor", description: "Extracts data from sources", capabilities: ["data_extraction"] }, { name: "Data Transformer", description: "Transforms and cleans data", capabilities: ["data_transformation"] }, { name: "Data Loader", description: "Loads data to destinations", capabilities: ["data_loading"] } ] // Avoid: Jack-of-all-trades agents agents: [ { name: "Data Agent", description: "Does everything with data" } ] ``` ```typescript theme={null} // Define specific capabilities for routing { name: "Financial Analyst", description: "Analyzes financial data and creates reports", capabilities: [ "financial_modeling", "revenue_analysis", "cost_analysis", "forecasting" ], tools: ["excel", "tableau", "sql"] } ``` ```typescript theme={null} // Good: Appropriate task granularity tasks: [ { task: "Research competitor pricing" }, { task: "Analyze pricing data" }, { task: "Create pricing recommendation" } ] // Avoid: Too granular tasks: [ { task: "Open browser" }, { task: "Navigate to competitor site" }, { task: "Find pricing page" }, // Too many tiny steps ] // Avoid: Too coarse tasks: [ { task: "Do everything related to pricing analysis" } ] ``` ### Dependency Management **Minimize Dependencies**: Reduce dependencies between tasks to enable more parallel execution. Tasks with fewer dependencies complete faster. ```typescript theme={null} // Efficient: Parallel-friendly dependency structure tasks: [ { id: "task1", dependencies: [] }, { id: "task2", dependencies: [] }, { id: "task3", dependencies: [] }, { id: "task4", dependencies: ["task1", "task2", "task3"] } ] // Tasks 1-3 run in parallel, task 4 waits for all // Inefficient: Sequential dependency chain tasks: [ { id: "task1", dependencies: [] }, { id: "task2", dependencies: ["task1"] }, { id: "task3", dependencies: ["task2"] }, { id: "task4", dependencies: ["task3"] } ] // All tasks must run sequentially ``` ### Error Handling **Graceful Degradation**: Design orchestrations to handle partial failures gracefully. Not all tasks may complete successfully. ```typescript theme={null} const resilientOrchestration = await agentbase.orchestrate({ task: "Gather market data from multiple sources", agents: agents, errorHandling: { strategy: "continue", // Continue despite failures maxFailures: 2, // Fail orchestration if more than 2 tasks fail retryFailedTasks: true, retryConfig: { maxAttempts: 3, backoff: "exponential" } }, tasks: [ { id: "source1", agent: "Data Collector", task: "Fetch data from API 1", optional: true // Can fail without stopping orchestration }, { id: "source2", agent: "Data Collector", task: "Fetch data from API 2", optional: true }, { id: "source3", agent: "Data Collector", task: "Fetch data from API 3", optional: true }, { id: "aggregate", agent: "Data Aggregator", task: "Aggregate data from successful sources", dependencies: ["source1", "source2", "source3"], waitForAll: false // Proceed with available data } ] }); ``` ### Resource Management ```typescript theme={null} // Control concurrent execution const orchestration = await agentbase.orchestrate({ tasks: largeBatchOfTasks, agents: agents, concurrency: { maxParallel: 10, // Max 10 tasks running simultaneously perAgent: 3 // Max 3 tasks per agent } }); ``` ```typescript theme={null} // Process large datasets in batches const batchOrchestration = await agentbase.orchestrate({ pattern: "map-reduce", map: { input: largeDataset, // 10,000 items batchSize: 100, // Process 100 at a time maxConcurrentBatches: 5 } }); ``` ```typescript theme={null} // Set appropriate timeouts tasks: [ { id: "quick_task", timeout: 30000 // 30 seconds }, { id: "long_running", timeout: 600000 // 10 minutes } ] ``` ## Integration with Other Primitives ### With Workflows Combine orchestration with structured workflows: ```typescript theme={null} const result = await agentbase.orchestrate({ task: "Process customer orders", agents: [ { name: "Order Processor", workflow: orderFulfillmentWorkflow } ], tasks: orderIds.map(id => ({ id: `process_${id}`, agent: "Order Processor", task: `Process order ${id}`, input: { orderId: id } })) }); // Each agent executes a workflow for their tasks ``` Learn more: [Workflow Primitive](/primitives/extensions/workflow) ### With Memory Share knowledge across orchestrated agents: ```typescript theme={null} const result = await agentbase.orchestrate({ task: "Customer support analysis", memory: { namespace: "customer_support", enabled: true, shared: true // All agents share memory }, agents: [ { name: "Ticket Analyzer" }, { name: "Trend Analyzer" }, { name: "Report Generator" } ] }); // All agents can access and contribute to shared memory ``` Learn more: [Memory Primitive](/primitives/extensions/memory) ### With Custom Tools Provide specialized tools to agents: ```typescript theme={null} const result = await agentbase.orchestrate({ task: "Sales pipeline analysis", agents: [ { name: "CRM Agent", mcpServers: [ { serverName: "salesforce", serverUrl: "..." } ] }, { name: "Analytics Agent", mcpServers: [ { serverName: "analytics-tools", serverUrl: "..." } ] } ] }); ``` Learn more: [Custom Tools Primitive](/primitives/essentials/custom-tools) ### With Multi-Agent Transfer Enable agent-to-agent transfers: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Help me with my order", agents: [ { name: "Router", description: "Routes to appropriate specialist" }, { name: "Order Specialist", description: "Handles order questions" }, { name: "Billing Specialist", description: "Handles billing questions" } ] }); // Router agent can transfer to specialists as needed ``` Learn more: [Multi-Agent Primitive](/primitives/essentials/multi-agents) ## Performance Considerations ### Parallel vs Sequential ```typescript theme={null} // Sequential execution const sequential = await agentbase.orchestrate({ tasks: [ { id: "task1", duration: 5000 }, { id: "task2", duration: 3000, dependencies: ["task1"] }, { id: "task3", duration: 4000, dependencies: ["task2"] } ] }); // Total time: 5000 + 3000 + 4000 = 12,000ms // Parallel execution const parallel = await agentbase.orchestrate({ tasks: [ { id: "task1", duration: 5000 }, { id: "task2", duration: 3000 }, { id: "task3", duration: 4000 } ] }); // Total time: max(5000, 3000, 4000) = 5,000ms ``` ### Cost Optimization **Batch Similar Tasks**: Group similar operations to reduce overhead and improve efficiency. ```typescript theme={null} // Less efficient: Many small orchestrations for (const item of items) { await agentbase.orchestrate({ task: `Process ${item}`, agents: agents }); } // More efficient: Single orchestration with batched tasks await agentbase.orchestrate({ tasks: items.map(item => ({ id: item.id, agent: "Processor", task: `Process ${item}` })), agents: agents, concurrency: { maxParallel: 10 } }); ``` ### Monitoring and Metrics ```typescript theme={null} // Track orchestration performance const orchestration = await agentbase.orchestrate({ task: "Complex analysis", agents: agents, monitoring: { trackMetrics: true, logLevel: "info" } }); // Get performance metrics const metrics = await agentbase.getOrchestrationMetrics({ orchestrationId: orchestration.id }); console.log('Total duration:', metrics.totalDuration); console.log('Parallel efficiency:', metrics.parallelEfficiency); console.log('Agent utilization:', metrics.agentUtilization); console.log('Cost breakdown:', metrics.costByAgent); ``` ## Troubleshooting **Problem**: Tasks run sequentially despite no dependencies **Solutions**: * Verify tasks have no dependencies defined * Check concurrency limits aren't too restrictive * Ensure enough agent instances are available * Review agent capability matching ```typescript theme={null} // Verify parallel-friendly configuration { tasks: [ { id: "task1", dependencies: [] }, // No dependencies { id: "task2", dependencies: [] }, // No dependencies { id: "task3", dependencies: [] } // No dependencies ], concurrency: { maxParallel: 10 // Allow parallel execution } } ``` **Problem**: Wrong agents being selected for tasks **Solutions**: * Make agent descriptions more specific * Add explicit capability definitions * Use explicit agent assignment instead of automatic routing * Review task descriptions for clarity ```typescript theme={null} // Explicit agent assignment tasks: [ { id: "financial_analysis", agent: "Financial Analyst", // Explicit assignment task: "Analyze Q4 financial data" } ] ``` **Problem**: Orchestration times out before completion **Solutions**: * Increase overall orchestration timeout * Optimize slow tasks * Increase parallel execution * Break into smaller orchestrations ```typescript theme={null} const orchestration = await agentbase.orchestrate({ task: "Long running analysis", timeout: 1800000, // 30 minute timeout concurrency: { maxParallel: 20 // More parallelism } }); ``` **Problem**: Tasks waiting for each other creating deadlock **Solutions**: * Review dependency graph for cycles * Ensure dependencies are acyclic (DAG) * Use visualization tools to inspect dependencies * Simplify dependency structure ```typescript theme={null} // Detect circular dependencies function detectCycles(tasks) { const visited = new Set(); const stack = new Set(); function hasCycle(taskId) { if (stack.has(taskId)) return true; if (visited.has(taskId)) return false; visited.add(taskId); stack.add(taskId); const task = tasks.find(t => t.id === taskId); for (const dep of task.dependencies || []) { if (hasCycle(dep)) return true; } stack.delete(taskId); return false; } for (const task of tasks) { if (hasCycle(task.id)) { throw new Error('Circular dependency detected'); } } } ``` ## Advanced Patterns ### Conditional Orchestration Adapt execution based on intermediate results: ```typescript theme={null} const adaptiveOrchestration = await agentbase.orchestrate({ task: "Adaptive market analysis", agents: agents, adaptive: true, onTaskComplete: async (task, result) => { // Add tasks based on results if (result.needsDeepDive) { return { newTasks: [ { id: "deep_analysis", agent: "Research Agent", task: "Deep dive into identified trend" } ] }; } } }); ``` ### Hierarchical Orchestration Orchestrations calling orchestrations: ```typescript theme={null} const parentOrchestration = await agentbase.orchestrate({ tasks: [ { id: "region_americas", type: "orchestration", orchestration: regionalAnalysisOrchestration, input: { region: "Americas" } }, { id: "region_emea", type: "orchestration", orchestration: regionalAnalysisOrchestration, input: { region: "EMEA" } }, { id: "region_apac", type: "orchestration", orchestration: regionalAnalysisOrchestration, input: { region: "APAC" } }, { id: "global_synthesis", agent: "Global Analyst", task: "Synthesize regional analyses", dependencies: ["region_americas", "region_emea", "region_apac"] } ] }); ``` ### Event-Driven Orchestration Trigger orchestrations from events: ```typescript theme={null} // Register event handler await agentbase.registerEventHandler({ event: "order.created", orchestration: orderProcessingOrchestration, config: { debounce: 5000, // Wait 5s for batch batch: true // Batch multiple orders } }); // Events trigger orchestration automatically ``` ## Related Primitives Structure multi-step processes with defined logic Enable collaboration between agents Execute tasks concurrently for performance Run orchestrations asynchronously ## Additional Resources Complete orchestration API docs Common design patterns Real-world examples **Remember**: Orchestration shines for complex tasks requiring multiple specialized agents. For simpler multi-step processes, consider using workflows instead. # Scheduling Source: https://docs.agentbase.sh/primitives/extensions/scheduling Schedule agent executions at specific times, intervals, and recurring patterns > Scheduling enables agents to run automatically on time-based schedules, from simple recurring tasks to complex time-orchestrated workflows, ensuring critical operations happen exactly when needed. ## Overview The Scheduling primitive allows you to execute agents at specified times using cron expressions, intervals, or custom schedules. Whether you need daily reports, hourly data syncs, or one-time future executions, scheduling makes it effortless to automate time-based operations. Scheduling is essential for: * **Recurring Tasks**: Run agents daily, weekly, monthly, or custom intervals * **Batch Processing**: Process data during off-peak hours * **Regular Reports**: Generate and distribute reports on schedule * **Maintenance Operations**: Perform cleanup and optimization tasks * **Time-Based Triggers**: Execute agents at specific times or dates * **Multi-Region Coordination**: Schedule across different time zones Use familiar cron syntax for flexible scheduling Schedule in any time zone with automatic DST handling Execute agents at a specific future time Automatic retry for missed or failed executions ## How Scheduling Works When you schedule an agent: 1. **Definition**: Schedule created with cron expression or specific time 2. **Registration**: Schedule registered with execution engine 3. **Monitoring**: System continuously monitors scheduled times 4. **Execution**: Agent executes automatically at scheduled time 5. **Completion**: Results logged and next execution calculated 6. **Repeat**: Process repeats for recurring schedules **Guaranteed Execution**: Schedules use at-least-once execution semantics. Missed executions are caught up automatically. ## Schedule Types ### Cron Schedules ```typescript theme={null} { type: "cron", expression: "0 9 * * *", // Every day at 9 AM timezone: "America/New_York" } ``` ### Interval Schedules ```typescript theme={null} { type: "interval", every: "1h", // Every 1 hour startTime: "2024-02-01T00:00:00Z" } ``` ### One-Time Schedules ```typescript theme={null} { type: "once", executeAt: "2024-02-15T14:30:00Z" } ``` ### Complex Schedules ```typescript theme={null} { type: "complex", schedules: [ { cron: "0 9 * * 1-5", timezone: "US/Eastern" }, // Weekdays 9 AM EST { cron: "0 12 * * 6,0", timezone: "US/Pacific" } // Weekends 12 PM PST ] } ``` ## Code Examples ### Basic Cron Schedule ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Schedule daily report const schedule = await agentbase.scheduleAgent({ name: "daily_sales_report", schedule: "0 9 * * *", // Every day at 9 AM timezone: "America/New_York", agent: { message: "Generate daily sales report", system: `Create report including: - Total sales for previous day - Top selling products - New customers - Key metrics vs targets Send report to team via Slack.`, dataConnectors: { postgres: { enabled: true } }, integrations: { slack: { enabled: true } } } }); console.log('Schedule created:', schedule.id); console.log('Next run:', schedule.nextRun); ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Schedule daily report schedule = agentbase.schedule_agent( name="daily_sales_report", schedule="0 9 * * *", # Every day at 9 AM timezone="America/New_York", agent={ "message": "Generate daily sales report", "system": """Create report including: - Total sales for previous day - Top selling products - New customers - Key metrics vs targets Send report to team via Slack.""", "data_connectors": { "postgres": {"enabled": True} }, "integrations": { "slack": {"enabled": True} } } ) print(f"Schedule created: {schedule.id}") print(f"Next run: {schedule.next_run}") ``` ### Interval Schedule ```typescript TypeScript theme={null} // Run every hour const hourlySync = await agentbase.scheduleAgent({ name: "hourly_data_sync", interval: "1h", agent: { message: "Sync data from external API", system: "Fetch latest data and update database" } }); // Run every 15 minutes const frequentCheck = await agentbase.scheduleAgent({ name: "health_check", interval: "15m", agent: { message: "Check system health", system: "Monitor services and alert if issues detected" } }); ``` ```python Python theme={null} # Run every hour hourly_sync = agentbase.schedule_agent( name="hourly_data_sync", interval="1h", agent={ "message": "Sync data from external API", "system": "Fetch latest data and update database" } ) # Run every 15 minutes frequent_check = agentbase.schedule_agent( name="health_check", interval="15m", agent={ "message": "Check system health", "system": "Monitor services and alert if issues detected" } ) ``` ### One-Time Execution ```typescript TypeScript theme={null} // Schedule for specific future time const oneTime = await agentbase.scheduleAgent({ name: "quarter_end_report", executeAt: "2024-03-31T23:59:00Z", agent: { message: "Generate Q1 financial report", system: "Compile comprehensive Q1 financial analysis" } }); // Schedule in 24 hours const delayed = await agentbase.scheduleAgent({ name: "follow_up_email", executeIn: "24h", agent: { message: "Send follow-up email to lead", context: { leadId: "lead_123" } } }); ``` ```python Python theme={null} # Schedule for specific future time one_time = agentbase.schedule_agent( name="quarter_end_report", execute_at="2024-03-31T23:59:00Z", agent={ "message": "Generate Q1 financial report", "system": "Compile comprehensive Q1 financial analysis" } ) # Schedule in 24 hours delayed = agentbase.schedule_agent( name="follow_up_email", execute_in="24h", agent={ "message": "Send follow-up email to lead", "context": { "lead_id": "lead_123" } } ) ``` ### Business Hours Schedule ```typescript TypeScript theme={null} // Run only during business hours const businessHours = await agentbase.scheduleAgent({ name: "customer_support_check", schedule: "0 9-17 * * 1-5", // 9 AM - 5 PM, Monday - Friday timezone: "America/New_York", agent: { message: "Check pending support tickets", system: "Review and assign urgent tickets during business hours" } }); ``` ```python Python theme={null} # Run only during business hours business_hours = agentbase.schedule_agent( name="customer_support_check", schedule="0 9-17 * * 1-5", # 9 AM - 5 PM, Monday - Friday timezone="America/New_York", agent={ "message": "Check pending support tickets", "system": "Review and assign urgent tickets during business hours" } ) ``` ### Monthly Schedule ```typescript TypeScript theme={null} // First day of every month const monthlyReport = await agentbase.scheduleAgent({ name: "monthly_financial_report", schedule: "0 0 1 * *", // Midnight on 1st of each month timezone: "America/New_York", agent: { message: "Generate monthly financial report", system: `Create comprehensive monthly report: - Revenue and expenses - Profit margins - Cash flow analysis - Budget variance - Key metrics and KPIs Distribute to finance team and executives.` } }); // Last day of every month const monthEnd = await agentbase.scheduleAgent({ name: "month_end_close", schedule: "0 23 L * *", // 11 PM on last day of month timezone: "America/New_York", agent: { message: "Perform month-end closing procedures", system: "Run accounting close process" } }); ``` ```python Python theme={null} # First day of every month monthly_report = agentbase.schedule_agent( name="monthly_financial_report", schedule="0 0 1 * *", # Midnight on 1st of each month timezone="America/New_York", agent={ "message": "Generate monthly financial report", "system": """Create comprehensive monthly report: - Revenue and expenses - Profit margins - Cash flow analysis - Budget variance - Key metrics and KPIs Distribute to finance team and executives.""" } ) ``` ### Complex Multi-Schedule ```typescript TypeScript theme={null} // Different schedules for different days const complexSchedule = await agentbase.scheduleAgent({ name: "adaptive_backup", schedules: [ { cron: "0 2 * * 1-5", // Weekdays at 2 AM config: { backupType: "incremental" } }, { cron: "0 1 * * 0", // Sundays at 1 AM config: { backupType: "full" } } ], timezone: "UTC", agent: { message: "Perform database backup", context: { backupType: "{{schedule.config.backupType}}" }, system: "Run backup based on schedule type" } }); ``` ```python Python theme={null} # Different schedules for different days complex_schedule = agentbase.schedule_agent( name="adaptive_backup", schedules=[ { "cron": "0 2 * * 1-5", # Weekdays at 2 AM "config": {"backup_type": "incremental"} }, { "cron": "0 1 * * 0", # Sundays at 1 AM "config": {"backup_type": "full"} } ], timezone="UTC", agent={ "message": "Perform database backup", "context": { "backup_type": "{{schedule.config.backup_type}}" }, "system": "Run backup based on schedule type" } ) ``` ### Schedule with Conditions ```typescript TypeScript theme={null} // Only run if condition is met const conditionalSchedule = await agentbase.scheduleAgent({ name: "conditional_cleanup", schedule: "0 3 * * *", // Daily at 3 AM preCheck: { condition: "SELECT COUNT(*) FROM temp_data WHERE created_at < NOW() - INTERVAL '7 days'", runIfGreaterThan: 0 }, agent: { message: "Clean up old temporary data", system: "Delete temp data older than 7 days" } }); ``` ```python Python theme={null} # Only run if condition is met conditional_schedule = agentbase.schedule_agent( name="conditional_cleanup", schedule="0 3 * * *", # Daily at 3 AM pre_check={ "condition": "SELECT COUNT(*) FROM temp_data WHERE created_at < NOW() - INTERVAL '7 days'", "run_if_greater_than": 0 }, agent={ "message": "Clean up old temporary data", "system": "Delete temp data older than 7 days" } ) ``` ### Manage Schedules ```typescript TypeScript theme={null} // List all schedules const schedules = await agentbase.getSchedules({ status: "active", sortBy: "nextRun" }); // Get specific schedule const schedule = await agentbase.getSchedule("schedule_123"); console.log('Next run:', schedule.nextRun); console.log('Last run:', schedule.lastRun); console.log('Execution count:', schedule.executionCount); // Pause schedule await agentbase.pauseSchedule("schedule_123"); // Resume schedule await agentbase.resumeSchedule("schedule_123"); // Delete schedule await agentbase.deleteSchedule("schedule_123"); // Update schedule await agentbase.updateSchedule("schedule_123", { schedule: "0 10 * * *", // Change to 10 AM timezone: "America/Los_Angeles" }); ``` ```python Python theme={null} # List all schedules schedules = agentbase.get_schedules( status="active", sort_by="next_run" ) # Get specific schedule schedule = agentbase.get_schedule("schedule_123") print(f"Next run: {schedule.next_run}") print(f"Last run: {schedule.last_run}") print(f"Execution count: {schedule.execution_count}") # Pause schedule agentbase.pause_schedule("schedule_123") # Resume schedule agentbase.resume_schedule("schedule_123") # Delete schedule agentbase.delete_schedule("schedule_123") # Update schedule agentbase.update_schedule("schedule_123", { "schedule": "0 10 * * *", # Change to 10 AM "timezone": "America/Los_Angeles" }) ``` ## Use Cases ### 1. Daily Reporting Automate daily business reports: ```typescript theme={null} await agentbase.scheduleAgent({ name: "morning_report", schedule: "0 8 * * 1-5", // Weekdays at 8 AM timezone: "America/New_York", agent: { message: "Generate morning executive brief", system: `Create morning report including: 1. Yesterday's Performance - Revenue vs target - New customers - Churn rate - Support tickets 2. Today's Focus - Key meetings - Important deadlines - Critical tasks 3. Alerts - Systems issues - Budget concerns - Urgent items Format as executive summary and send via email and Slack.`, integrations: { slack: { enabled: true }, sendgrid: { enabled: true } } } }); ``` ### 2. Data Synchronization Sync data between systems: ```typescript theme={null} await agentbase.scheduleAgent({ name: "crm_warehouse_sync", interval: "1h", // Every hour agent: { message: "Sync CRM data to warehouse", system: `ETL Process: 1. Extract new/modified records from Salesforce (last hour) 2. Transform data to warehouse schema 3. Load into Snowflake data warehouse 4. Validate row counts match 5. Log sync statistics 6. Alert if errors exceed threshold`, integrations: { salesforce: { enabled: true } }, dataConnectors: { snowflake: { enabled: true } } } }); ``` ### 3. System Maintenance Schedule maintenance tasks: ```typescript theme={null} await agentbase.scheduleAgent({ name: "database_maintenance", schedule: "0 2 * * 0", // Sundays at 2 AM timezone: "UTC", agent: { message: "Perform weekly database maintenance", system: `Maintenance tasks: 1. Vacuum and analyze tables 2. Rebuild indexes 3. Update statistics 4. Archive old data 5. Check disk space 6. Verify backups 7. Generate health report`, dataConnectors: { postgres: { enabled: true } } }, notifications: { onSuccess: ["devops@company.com"], onFailure: ["devops@company.com", "oncall@company.com"] } }); ``` ### 4. Content Publishing Schedule content distribution: ```typescript theme={null} await agentbase.scheduleAgent({ name: "weekly_newsletter", schedule: "0 10 * * 3", // Wednesdays at 10 AM timezone: "America/New_York", agent: { message: "Send weekly newsletter", system: `Newsletter workflow: 1. Curate top blog posts from last week 2. Gather customer success stories 3. Include product updates 4. Add upcoming events 5. Generate personalized content per segment 6. Send via Mailchimp 7. Track engagement metrics`, integrations: { mailchimp: { enabled: true }, wordpress: { enabled: true } } } }); ``` ### 5. Compliance and Auditing Regular compliance checks: ```typescript theme={null} await agentbase.scheduleAgent({ name: "security_audit", schedule: "0 0 1 * *", // Monthly on 1st at midnight timezone: "UTC", agent: { message: "Perform monthly security audit", system: `Security audit checklist: 1. Review user access permissions 2. Check for inactive accounts (disable if > 90 days) 3. Audit API key usage 4. Review security logs for anomalies 5. Scan for vulnerable dependencies 6. Verify encryption configurations 7. Generate compliance report 8. Distribute to security team`, skills: ["security_audit"] } }); ``` ### 6. Customer Engagement Automated customer touchpoints: ```typescript theme={null} // Trial ending reminder await agentbase.scheduleAgent({ name: "trial_ending_reminders", schedule: "0 10 * * *", // Daily at 10 AM agent: { message: "Send trial ending reminders", system: `Find trials ending in 3 days: 1. Query users with trial_end_date = TODAY + 3 2. For each user: - Send personalized email - Highlight value received during trial - Include upgrade incentive - Schedule follow-up call 3. Log outreach in CRM`, dataConnectors: { postgres: { enabled: true } }, integrations: { sendgrid: { enabled: true }, salesforce: { enabled: true } } } }); ``` ## Best Practices ### Cron Expression Tips ```typescript theme={null} // Every day at midnight schedule: "0 0 * * *" // Every weekday at 9 AM schedule: "0 9 * * 1-5" // Every hour on the hour schedule: "0 * * * *" // Every 30 minutes schedule: "*/30 * * * *" // First day of month at noon schedule: "0 12 1 * *" // Last day of month at 11 PM schedule: "0 23 L * *" // Weekends only at 8 AM schedule: "0 8 * * 6,0" ``` ```typescript theme={null} // Validate cron expression const validation = await agentbase.validateSchedule({ schedule: "0 9 * * 1-5", timezone: "America/New_York" }); console.log('Valid:', validation.valid); console.log('Next 5 runs:', validation.nextRuns); ``` ```typescript theme={null} // Good: Named time zone (handles DST automatically) timezone: "America/New_York" // Avoid: UTC offset (doesn't handle DST) timezone: "UTC-5" ``` ### Schedule Management **Monitor Schedule Health**: Regularly review schedule execution history to catch failures early. ```typescript theme={null} { schedule: "0 2 * * *", executionWindow: { start: "02:00", end: "04:00", timezone: "UTC" }, // If can't execute at 2 AM, can run anytime until 4 AM catchUpMissed: true } ``` ```typescript theme={null} { schedule: "0 9 * * *", retry: { enabled: true, maxAttempts: 3, backoff: "exponential", initialDelay: 300000 // 5 minutes } } ``` ```typescript theme={null} { schedule: "*/5 * * * *", // Every 5 minutes concurrency: { policy: "skip", // Skip if previous still running // Other options: "queue", "cancel_previous" }, timeout: 300000 // 5 minute timeout } ``` ```typescript theme={null} // Schedule expires after date { schedule: "0 9 * * *", expiresAt: "2024-12-31T23:59:59Z", onExpiration: "archive" // or "delete" } // Or after number of executions { schedule: "0 12 * * *", maxExecutions: 30, // Run 30 times then stop onComplete: "notify_owner" } ``` ### Performance ```typescript theme={null} // Schedule heavy tasks during off-peak hours { name: "data_processing", schedule: "0 2 * * *", // 2 AM when traffic is low agent: { message: "Process large dataset", optimization: { priority: "low", // Don't compete with user-facing tasks useSpotInstances: true } } } ``` ```typescript theme={null} // Avoid thundering herd const schedules = []; for (let i = 0; i < 10; i++) { schedules.push( agentbase.scheduleAgent({ name: `batch_processor_${i}`, schedule: `${i * 5} * * * *`, // Stagger by 5 minutes agent: { message: "Process batch", context: { batchId: i } } }) ); } ``` ```typescript theme={null} // Track schedule performance const metrics = await agentbase.getScheduleMetrics({ scheduleId: "schedule_123", timeRange: "7d" }); console.log('Avg execution time:', metrics.avgExecutionTime); console.log('Success rate:', metrics.successRate); console.log('Resource usage:', metrics.resourceUsage); ``` ## Integration with Other Primitives ### With Workflow Schedule workflow executions: ```typescript theme={null} await agentbase.scheduleWorkflow({ schedule: "0 0 * * *", // Daily at midnight timezone: "UTC", workflow: { id: "daily_etl_pipeline", input: { date: "{{execution_date}}" } } }); ``` Learn more: [Workflow Primitive](/primitives/extensions/workflow) ### With Tasks Create scheduled task generation: ```typescript theme={null} await agentbase.scheduleAgent({ schedule: "0 9 * * 1", // Every Monday at 9 AM agent: { message: "Create weekly tasks", capabilities: { tasks: { enabled: true } }, system: "Generate weekly sprint tasks based on roadmap" } }); ``` Learn more: [Tasks Primitive](/primitives/extensions/tasks) ### With Memory Remember schedule execution context: ```typescript theme={null} await agentbase.scheduleAgent({ schedule: "0 */6 * * *", // Every 6 hours agent: { message: "Check for updates", memory: { namespace: "scheduled_checker", enabled: true }, system: "Remember what was checked last time to avoid duplicates" } }); ``` Learn more: [Memory Primitive](/primitives/extensions/memory) ## Performance Considerations ### Execution Precision * **Cron Schedules**: ±1 second precision * **Interval Schedules**: ±100ms precision * **One-Time Schedules**: ±1 second precision ### Scalability * **Concurrent Schedules**: Thousands of active schedules * **Execution Rate**: Thousands of executions per minute * **Time Zone Support**: All IANA time zones ### Cost Optimization ```typescript theme={null} // Optimize costs for frequent schedules { schedule: "*/1 * * * *", // Every minute optimization: { skipIfNoWork: true, // Skip execution if no pending work earlyExit: true, // Exit early if nothing to do cacheResults: 300 // Cache for 5 minutes } } ``` ## Troubleshooting **Problem**: Schedule created but not executing **Solutions**: * Verify schedule is active/enabled * Check cron expression is valid * Verify time zone is correct * Review execution history for errors * Check for conflicting schedules ```typescript theme={null} // Debug schedule const debug = await agentbase.debugSchedule("schedule_123"); console.log('Is active:', debug.isActive); console.log('Next run:', debug.nextRun); console.log('Last error:', debug.lastError); console.log('Cron valid:', debug.cronValid); ``` **Problem**: Schedules being skipped **Solutions**: * Enable catch-up for missed executions * Increase execution window * Check system load during scheduled time * Review concurrency settings * Verify timeout isn't too short ```typescript theme={null} { schedule: "0 9 * * *", catchUpMissed: true, // Run missed executions executionWindow: { start: "09:00", end: "11:00" // Can run anytime in this window } } ``` **Problem**: Schedule running at wrong time **Solutions**: * Verify time zone string is correct * Check for DST transitions * Use UTC for consistency * Test schedule with multiple dates ```typescript theme={null} // Validate time zone and get next runs const validation = await agentbase.validateSchedule({ schedule: "0 9 * * *", timezone: "America/New_York", showNext: 10 // Show next 10 runs }); validation.nextRuns.forEach(run => { console.log('Will run at:', run.local, '(', run.utc, 'UTC)'); }); ``` **Problem**: New execution starting while previous still running **Solutions**: * Increase timeout * Set concurrency policy to skip * Optimize agent execution time * Reduce schedule frequency ```typescript theme={null} { schedule: "*/5 * * * *", timeout: 240000, // 4 minutes (less than 5 min interval) concurrency: { policy: "skip" // Don't start if already running } } ``` ## Advanced Patterns ### Dynamic Scheduling Adjust schedule based on conditions: ```typescript theme={null} // Change frequency based on load await agentbase.createAdaptiveSchedule({ name: "adaptive_processor", baseSchedule: "*/30 * * * *", // Start with every 30 min adjustments: [ { condition: "queue_length > 1000", schedule: "*/5 * * * *" // Increase to every 5 min }, { condition: "queue_length < 100", schedule: "0 * * * *" // Decrease to hourly } ] }); ``` ### Schedule Dependencies Chain schedules: ```typescript theme={null} // Schedule B waits for Schedule A await agentbase.scheduleAgent({ name: "schedule_b", dependsOn: ["schedule_a"], schedule: "0 10 * * *", waitForDependencies: true, agent: { message: "Process data after Schedule A completes" } }); ``` ### Holiday Handling Skip holidays automatically: ```typescript theme={null} { schedule: "0 9 * * 1-5", // Weekdays excludeDates: [ "2024-01-01", // New Year "2024-07-04", // Independence Day "2024-12-25" // Christmas ], holidayCalendar: "US", // Or use standard holiday calendar skipHolidays: true } ``` ## Related Primitives Event-driven agent execution Schedule complex workflows Run scheduled agents asynchronously Create scheduled task generation ## Additional Resources Complete scheduling API documentation Cron expression syntax and examples Supported time zones and DST handling **Pro Tip**: Use [crontab.guru](https://crontab.guru/) to test and validate cron expressions before deploying schedules. This helps avoid scheduling errors. # Tasks Source: https://docs.agentbase.sh/primitives/extensions/tasks Create, manage, and track discrete units of work for agents > Tasks enable agents to break down complex objectives into manageable units of work, track progress, and coordinate execution across multiple steps and agents. ## Overview The Tasks primitive provides a structured way to define, assign, execute, and monitor discrete units of work. Unlike workflows which define processes, tasks represent individual actionable items that can be tracked, prioritized, and completed independently or as part of larger objectives. Tasks are essential for: * **Work Breakdown**: Decompose complex goals into manageable chunks * **Progress Tracking**: Monitor completion status and progress * **Prioritization**: Organize work by importance and urgency * **Delegation**: Assign tasks to specific agents or humans * **Dependencies**: Define task relationships and execution order * **Accountability**: Track who did what and when Agents can create tasks autonomously or from user requests Track task lifecycle from creation to completion Define task relationships and execution order Assign tasks to agents or human team members ## How Tasks Work When you enable tasks for an agent: 1. **Creation**: Tasks are created with description, priority, and metadata 2. **Assignment**: Tasks assigned to agents or humans with appropriate context 3. **Execution**: Assigned party works on and completes task 4. **Tracking**: Status updates tracked throughout lifecycle 5. **Completion**: Task marked complete with results and artifacts 6. **Review**: Optional review and approval processes **Persistent State**: Tasks persist across sessions and can be resumed at any time, making them ideal for long-running work. ## Task States ### Lifecycle States ```typescript theme={null} { status: "pending" | "in_progress" | "blocked" | "completed" | "cancelled" } ``` * **pending**: Task created but not started * **in\_progress**: Actively being worked on * **blocked**: Waiting for dependency or external input * **completed**: Successfully finished * **cancelled**: Abandoned or no longer needed ### Priority Levels ```typescript theme={null} { priority: "critical" | "high" | "medium" | "low" } ``` ## Code Examples ### Basic Task Creation ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Agent creates tasks autonomously const result = await agentbase.runAgent({ message: "Plan the launch of our new product next month", capabilities: { tasks: { enabled: true } }, system: `Break down the product launch into specific tasks. For each task: - Clear, actionable description - Appropriate priority - Estimated duration - Required resources - Dependencies on other tasks` }); // Agent creates structured task list console.log('Tasks created:', result.tasks); ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Agent creates tasks autonomously result = agentbase.run_agent( message="Plan the launch of our new product next month", capabilities={ "tasks": { "enabled": True } }, system="""Break down the product launch into specific tasks. For each task: - Clear, actionable description - Appropriate priority - Estimated duration - Required resources - Dependencies on other tasks""" ) print(f"Tasks created: {result.tasks}") ``` ### Create Task Manually ```typescript TypeScript theme={null} // Explicitly create a task const task = await agentbase.createTask({ title: "Review Q4 financial reports", description: "Analyze Q4 financials and prepare summary for board meeting", priority: "high", assignee: "finance_agent", dueDate: "2024-02-15", tags: ["finance", "quarterly-review"], metadata: { department: "finance", estimatedHours: 4 } }); console.log('Task created:', task.id); ``` ```python Python theme={null} # Explicitly create a task task = agentbase.create_task( title="Review Q4 financial reports", description="Analyze Q4 financials and prepare summary for board meeting", priority="high", assignee="finance_agent", due_date="2024-02-15", tags=["finance", "quarterly-review"], metadata={ "department": "finance", "estimated_hours": 4 } ) print(f"Task created: {task.id}") ``` ### Task with Dependencies ```typescript TypeScript theme={null} // Create tasks with dependencies const task1 = await agentbase.createTask({ title: "Design database schema", priority: "high" }); const task2 = await agentbase.createTask({ title: "Implement API endpoints", priority: "high", dependencies: [task1.id], // Depends on task1 blockedUntil: task1.id }); const task3 = await agentbase.createTask({ title: "Write API documentation", priority: "medium", dependencies: [task2.id] // Depends on task2 }); // Tasks execute in order: task1 → task2 → task3 ``` ```python Python theme={null} # Create tasks with dependencies task1 = agentbase.create_task( title="Design database schema", priority="high" ) task2 = agentbase.create_task( title="Implement API endpoints", priority="high", dependencies=[task1.id], # Depends on task1 blocked_until=task1.id ) task3 = agentbase.create_task( title="Write API documentation", priority="medium", dependencies=[task2.id] # Depends on task2 ) # Tasks execute in order: task1 → task2 → task3 ``` ### Assign Task to Agent ```typescript TypeScript theme={null} // Assign task and let agent complete it const result = await agentbase.runAgent({ message: "Complete task: Write blog post about new features", taskId: task.id, capabilities: { tasks: { enabled: true, autoUpdate: true // Automatically update task status } } }); // Agent works on task and updates status console.log('Task status:', result.task.status); console.log('Task result:', result.task.result); ``` ```python Python theme={null} # Assign task and let agent complete it result = agentbase.run_agent( message="Complete task: Write blog post about new features", task_id=task.id, capabilities={ "tasks": { "enabled": True, "auto_update": True # Automatically update task status } } ) print(f"Task status: {result.task.status}") print(f"Task result: {result.task.result}") ``` ### Query Tasks ```typescript TypeScript theme={null} // Get all pending tasks const pendingTasks = await agentbase.getTasks({ status: "pending", priority: ["high", "critical"], sortBy: "priority", limit: 20 }); // Get tasks by tag const financeTasks = await agentbase.getTasks({ tags: ["finance"], status: ["pending", "in_progress"] }); // Get overdue tasks const overdueTasks = await agentbase.getTasks({ overdue: true, assignee: "current_user" }); console.log('Pending tasks:', pendingTasks); ``` ```python Python theme={null} # Get all pending tasks pending_tasks = agentbase.get_tasks( status="pending", priority=["high", "critical"], sort_by="priority", limit=20 ) # Get tasks by tag finance_tasks = agentbase.get_tasks( tags=["finance"], status=["pending", "in_progress"] ) # Get overdue tasks overdue_tasks = agentbase.get_tasks( overdue=True, assignee="current_user" ) print(f"Pending tasks: {pending_tasks}") ``` ### Update Task Status ```typescript TypeScript theme={null} // Update task progress await agentbase.updateTask(taskId, { status: "in_progress", progress: 0.5, // 50% complete notes: "Completed research phase, starting implementation" }); // Mark task complete await agentbase.updateTask(taskId, { status: "completed", progress: 1.0, result: { output: "Blog post draft", artifacts: ["blog-post.md"], metrics: { wordCount: 1500, timeSpent: "3 hours" } } }); ``` ```python Python theme={null} # Update task progress agentbase.update_task(task_id, { "status": "in_progress", "progress": 0.5, # 50% complete "notes": "Completed research phase, starting implementation" }) # Mark task complete agentbase.update_task(task_id, { "status": "completed", "progress": 1.0, "result": { "output": "Blog post draft", "artifacts": ["blog-post.md"], "metrics": { "word_count": 1500, "time_spent": "3 hours" } } }) ``` ### Recurring Tasks ```typescript TypeScript theme={null} // Create recurring task const recurringTask = await agentbase.createTask({ title: "Generate weekly analytics report", description: "Compile and send weekly performance metrics", priority: "medium", recurring: { enabled: true, schedule: "0 9 * * 1", // Every Monday at 9 AM timezone: "America/New_York" }, assignee: "analytics_agent" }); // Agent automatically creates new instance each week ``` ```python Python theme={null} # Create recurring task recurring_task = agentbase.create_task( title="Generate weekly analytics report", description="Compile and send weekly performance metrics", priority="medium", recurring={ "enabled": True, "schedule": "0 9 * * 1", # Every Monday at 9 AM "timezone": "America/New_York" }, assignee="analytics_agent" ) # Agent automatically creates new instance each week ``` ### Task Templates ```typescript TypeScript theme={null} // Create task template const template = await agentbase.createTaskTemplate({ name: "onboard_new_customer", title: "Onboard new customer: {{customerName}}", tasks: [ { title: "Send welcome email", priority: "high", assignee: "email_agent" }, { title: "Create account in CRM", priority: "high", assignee: "crm_agent", dependencies: [0] // Depends on welcome email }, { title: "Schedule kickoff call", priority: "medium", assignee: "scheduling_agent", dependencies: [1] } ] }); // Use template to create tasks const tasks = await agentbase.createTasksFromTemplate("onboard_new_customer", { customerName: "Acme Corp", customerEmail: "contact@acme.com" }); ``` ```python Python theme={null} # Create task template template = agentbase.create_task_template( name="onboard_new_customer", title="Onboard new customer: {{customerName}}", tasks=[ { "title": "Send welcome email", "priority": "high", "assignee": "email_agent" }, { "title": "Create account in CRM", "priority": "high", "assignee": "crm_agent", "dependencies": [0] # Depends on welcome email }, { "title": "Schedule kickoff call", "priority": "medium", "assignee": "scheduling_agent", "dependencies": [1] } ] ) # Use template to create tasks tasks = agentbase.create_tasks_from_template("onboard_new_customer", { "customerName": "Acme Corp", "customerEmail": "contact@acme.com" }) ``` ## Use Cases ### 1. Project Management Break down projects into trackable tasks: ```typescript theme={null} const projectAgent = await agentbase.runAgent({ message: "Plan the development of our mobile app", capabilities: { tasks: { enabled: true } }, system: `Create a comprehensive task breakdown for mobile app development. Include tasks for: - Requirements gathering - Design (UI/UX) - Frontend development - Backend API development - Testing (unit, integration, E2E) - Deployment - Documentation For each task: - Assign to appropriate team/agent - Set realistic estimates - Define dependencies - Specify acceptance criteria` }); // Agent creates structured project plan with tasks ``` ### 2. Content Creation Pipeline Manage content creation workflow: ```typescript theme={null} const contentTasks = await agentbase.runAgent({ message: "Create tasks for this month's blog content", capabilities: { tasks: { enabled: true } }, system: `Create tasks for 4 blog posts this month. For each post: 1. Research topic (priority: high) 2. Draft content (depends on research) 3. Create graphics (depends on draft) 4. SEO optimization (depends on draft) 5. Editorial review (depends on all above) 6. Publish (depends on review approval) Stagger due dates throughout the month.` }); ``` ### 3. Customer Onboarding Automate onboarding task creation: ```typescript theme={null} const onboardingAgent = await agentbase.runAgent({ message: "Create onboarding tasks for new customer: Acme Corp", context: { customer: { name: "Acme Corp", plan: "enterprise", employees: 500 } }, capabilities: { tasks: { enabled: true } }, system: `Create onboarding task list: Day 1: - Send welcome email - Create accounts - Send access credentials Week 1: - Schedule kickoff call - Complete setup call - Share documentation Week 2: - Check-in call - Address questions - Gather feedback Assign tasks to appropriate team members.` }); ``` ### 4. Incident Response Create incident resolution tasks: ```typescript theme={null} const incidentAgent = await agentbase.runAgent({ message: "Critical: Production database is down", capabilities: { tasks: { enabled: true } }, system: `Create incident response tasks: Immediate (Priority: Critical): - Alert on-call engineer - Create status page update - Start incident war room Investigation (Priority: High): - Check database logs - Review recent deployments - Analyze error patterns Resolution (Priority: High): - Identify root cause - Implement fix - Verify service restored Follow-up (Priority: Medium): - Write post-mortem - Document lessons learned - Create prevention tasks Track all tasks in incident ticket.` }); ``` ### 5. Daily Standup Automation Generate daily task summaries: ```typescript theme={null} const standupAgent = await agentbase.runAgent({ message: "Generate my standup update", capabilities: { tasks: { enabled: true } }, system: `Create standup update based on my tasks: Yesterday: - List completed tasks - Note any blockers Today: - List in-progress tasks - Highlight priorities Blockers: - List any blocked tasks - Identify what's needed to unblock Format as concise standup message.` }); ``` ### 6. Sales Pipeline Tasks Track sales activities: ```typescript theme={null} const salesAgent = await agentbase.runAgent({ message: "Create follow-up tasks for new lead: Jane Smith", context: { lead: { name: "Jane Smith", company: "Tech Startup Inc", interest: "Enterprise plan" } }, capabilities: { tasks: { enabled: true } }, system: `Create sales follow-up tasks: Day 1: - Send personalized intro email - Connect on LinkedIn Day 3: - Follow-up call - Send product demo video Day 7: - Schedule live demo - Send pricing information Day 14: - Check-in email - Share case studies Set reminders and track completion.` }); ``` ## Best Practices ### Task Design ```typescript theme={null} // Good: Specific, single-purpose tasks await agentbase.createTask({ title: "Write introduction section", description: "Draft the introduction for the blog post (200-300 words)" }); await agentbase.createTask({ title: "Create featured image", description: "Design featured image for blog post (1200x630px)" }); // Avoid: Overly broad tasks await agentbase.createTask({ title: "Complete blog post", description: "Do everything for the blog post" }); ``` ```typescript theme={null} // Good: Clear, actionable description { title: "Review pull request #1234", description: `Review PR #1234: - Check code quality and style - Verify tests pass - Ensure documentation updated - Approve or request changes` } // Avoid: Vague description { title: "Check PR", description: "Look at the code" } ``` ```typescript theme={null} // Include estimated duration { title: "Implement user authentication", dueDate: "2024-02-15", estimatedHours: 8, metadata: { complexity: "high", dependencies: ["database-setup", "api-framework"] } } ``` ```typescript theme={null} // Organize tasks with tags { title: "Fix login bug", tags: ["bug", "auth", "high-priority", "frontend"], priority: "high" } // Query by tags later const authTasks = await agentbase.getTasks({ tags: ["auth"] }); ``` ### Task Management **Review Tasks Regularly**: Set up periodic reviews of task lists to update priorities and remove obsolete tasks. ```typescript theme={null} system: `Prioritize tasks using: Critical: System down, security breach, data loss High: Blocking other work, customer-facing issues Medium: Important but not urgent Low: Nice to have, future improvements Consider: - Business impact - Dependencies - Deadlines - Resource availability` ``` ```typescript theme={null} // Mark task as blocked await agentbase.updateTask(taskId, { status: "blocked", blockReason: "Waiting for design approval", blockedBy: designTaskId, blockedUntil: "2024-02-10" }); // Automatically unblock when dependency completes ``` ```typescript theme={null} // Update progress regularly await agentbase.updateTask(taskId, { progress: 0.75, timeSpent: 6, // hours notes: "API implementation complete, working on tests" }); ``` ```typescript theme={null} // Periodically archive old completed tasks async function archiveOldTasks() { const oldTasks = await agentbase.getTasks({ status: "completed", completedBefore: "2024-01-01" // Older than 30 days }); for (const task of oldTasks) { await agentbase.archiveTask(task.id); } } ``` ### Collaboration ```typescript theme={null} // Assign based on expertise const task = await agentbase.createTask({ title: "Optimize database queries", assignee: "database_specialist_agent", ccUsers: ["team_lead", "backend_team"] }); // Or let agent decide message: "Assign this task to the best team member", system: "Consider workload, expertise, and availability" ``` ```typescript theme={null} { title: "Fix checkout page error", description: "...", resources: [ { type: "error_log", url: "..." }, { type: "screenshot", url: "..." }, { type: "documentation", url: "..." } ], context: { errorMessage: "Payment gateway timeout", affectedUsers: 127, firstOccurred: "2024-01-15T10:30:00Z" } } ``` ```typescript theme={null} // Add comments to tasks await agentbase.addTaskComment(taskId, { author: "agent_123", text: "Completed initial investigation. Root cause identified.", timestamp: new Date().toISOString() }); // Subscribe to task updates await agentbase.subscribeToTask(taskId, { userId: currentUser.id, notifications: ["status_change", "comments", "completion"] }); ``` ## Integration with Other Primitives ### With Workflow Combine tasks with workflows: ```typescript theme={null} const workflow = { name: "feature_development", steps: [ { id: "create_tasks", type: "agent_task", config: { message: "Break down feature into development tasks", capabilities: { tasks: { enabled: true } } } }, { id: "assign_tasks", type: "agent_task", config: { message: "Assign tasks to team members" } }, { id: "monitor_progress", type: "agent_task", config: { message: "Monitor task completion", schedule: "0 9 * * *" // Check daily } } ] }; ``` Learn more: [Workflow Primitive](/primitives/extensions/workflow) ### With Memory Remember task preferences: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Create tasks for the new project", memory: { namespace: `user_${userId}`, enabled: true }, capabilities: { tasks: { enabled: true } } }); // Agent remembers user's preferred task structure ``` Learn more: [Memory Primitive](/primitives/extensions/memory) ### With Scheduling Schedule task creation: ```typescript theme={null} // Auto-create tasks on schedule await agentbase.scheduleAgent({ schedule: "0 9 * * 1", // Every Monday message: "Create tasks for this week's sprint", capabilities: { tasks: { enabled: true } } }); ``` Learn more: [Scheduling Primitive](/primitives/extensions/scheduling) ## Performance Considerations ### Task Volume * **Scalability**: System handles thousands of active tasks * **Query Performance**: Index tasks by status, priority, assignee * **Archival**: Archive completed tasks to maintain performance ```typescript theme={null} // Efficient task querying const tasks = await agentbase.getTasks({ status: ["pending", "in_progress"], assignee: currentAgent, limit: 50, // Paginate results offset: 0 }); ``` ### Real-time Updates * **Webhooks**: Receive real-time task updates * **Polling**: Query for task changes periodically * **WebSocket**: Subscribe to live task updates ```typescript theme={null} // Subscribe to task updates const subscription = await agentbase.subscribeToTasks({ filters: { assignee: "current_agent" }, onUpdate: (task) => { console.log('Task updated:', task); } }); ``` ## Troubleshooting **Problem**: Agent doesn't create tasks as expected **Solutions**: * Verify tasks capability is enabled * Check system prompt includes task creation instructions * Ensure agent has permissions to create tasks * Review agent response for task creation attempts ```typescript theme={null} // Debug task creation const result = await agentbase.runAgent({ message: "Create tasks for project", capabilities: { tasks: { enabled: true, debug: true } } }); console.log('Task creation attempts:', result.debug.taskAttempts); ``` **Problem**: Circular dependencies preventing task completion **Solutions**: * Review task dependency graph * Identify circular references * Break circular dependencies * Update task dependencies ```typescript theme={null} // Check for circular dependencies const graph = await agentbase.getTaskDependencyGraph(projectId); const cycles = detectCycles(graph); if (cycles.length > 0) { console.log('Circular dependencies found:', cycles); } ``` **Problem**: Too many tasks overwhelming assignees **Solutions**: * Balance task distribution * Adjust priorities * Delegate or reassign tasks * Extend deadlines ```typescript theme={null} // Rebalance tasks const overloaded = await agentbase.getTaskStats({ groupBy: "assignee" }); for (const agent of overloaded) { if (agent.taskCount > threshold) { // Reassign low-priority tasks } } ``` ## Advanced Patterns ### Task Automation Auto-complete simple tasks: ```typescript theme={null} capabilities: { tasks: { enabled: true, autoComplete: { enabled: true, conditions: [ { tag: "automated", confidence: 0.9 } ] } } } ``` ### Task Templates with Variations Create flexible templates: ```typescript theme={null} const template = await agentbase.createTaskTemplate({ name: "bug_fix", variations: { severity: { critical: { priority: "critical", dueInHours: 2 }, high: { priority: "high", dueInHours: 24 }, medium: { priority: "medium", dueInDays: 7 } } } }); ``` ### Smart Task Routing Route tasks based on content: ```typescript theme={null} system: `Analyze new tasks and assign to: - Backend team: API, database, server tasks - Frontend team: UI, UX, client tasks - DevOps team: Infrastructure, deployment tasks - QA team: Testing, bug verification tasks Consider current workload and expertise.` ``` ## Related Primitives Orchestrate multi-step processes with tasks Schedule recurring task creation Remember task patterns and preferences Distribute tasks across specialized agents ## Additional Resources Complete tasks API documentation Pre-built task templates library Task management strategies **Pro Tip**: Use task templates for recurring work patterns. This ensures consistency and saves time on task creation. # Trigger Source: https://docs.agentbase.sh/primitives/extensions/trigger Execute agents automatically based on events, conditions, and external signals > Triggers enable agents to respond automatically to events, changes, and conditions, creating reactive and autonomous agent behaviors without manual intervention. ## Overview The Trigger primitive allows you to automate agent execution based on various signals - from webhook events to database changes to time-based schedules. Instead of manually invoking agents, triggers create event-driven architectures where agents respond intelligently to your environment. Triggers are essential for: * **Event-Driven Automation**: React to external events automatically * **Real-Time Processing**: Process events as they occur * **Condition-Based Execution**: Run agents when specific conditions are met * **Autonomous Operations**: Build self-managing systems * **Integration Workflows**: Connect disparate systems through agents * **Monitoring and Alerting**: Detect and respond to issues automatically Respond to webhooks, API events, and system notifications Execute agents on time-based schedules (cron, intervals) React to database changes and data updates Execute when specific conditions or thresholds are met ## How Triggers Work When you set up a trigger: 1. **Registration**: Trigger registered with event source or condition 2. **Monitoring**: System continuously monitors for trigger conditions 3. **Detection**: Trigger condition detected or event received 4. **Activation**: Agent execution initiated automatically 5. **Context Passing**: Event data passed to agent as context 6. **Completion**: Agent processes event and performs actions **Reliable Execution**: Triggers use at-least-once delivery semantics with automatic retries for failed executions. ## Trigger Types ### Webhook Triggers ```typescript theme={null} { type: "webhook", events: ["payment.succeeded", "user.created"], source: "stripe" | "github" | "custom" } ``` ### Schedule Triggers ```typescript theme={null} { type: "schedule", schedule: "0 9 * * *", // Cron expression timezone: "America/New_York" } ``` ### Data Change Triggers ```typescript theme={null} { type: "data_change", source: "database", table: "orders", operations: ["insert", "update", "delete"] } ``` ### Condition Triggers ```typescript theme={null} { type: "condition", condition: "temperature > 100", checkInterval: "5m" } ``` ## Code Examples ### Webhook Trigger ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Create webhook trigger const trigger = await agentbase.createTrigger({ name: "stripe_payment_succeeded", type: "webhook", source: "stripe", events: ["payment_intent.succeeded"], agent: { message: "Process successful payment", system: `When payment succeeds: - Update order status - Send confirmation email - Update analytics - Notify fulfillment team`, integrations: { stripe: { enabled: true }, sendgrid: { enabled: true } } } }); console.log('Webhook URL:', trigger.webhookUrl); // Configure this URL in Stripe dashboard ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Create webhook trigger trigger = agentbase.create_trigger( name="stripe_payment_succeeded", type="webhook", source="stripe", events=["payment_intent.succeeded"], agent={ "message": "Process successful payment", "system": """When payment succeeds: - Update order status - Send confirmation email - Update analytics - Notify fulfillment team""", "integrations": { "stripe": {"enabled": True}, "sendgrid": {"enabled": True} } } ) print(f"Webhook URL: {trigger.webhook_url}") ``` ### Schedule Trigger ```typescript TypeScript theme={null} // Daily scheduled report const dailyReport = await agentbase.createTrigger({ name: "daily_analytics_report", type: "schedule", schedule: "0 9 * * *", // Every day at 9 AM timezone: "America/New_York", agent: { message: "Generate daily analytics report", system: `Create report including: - Yesterday's key metrics - Week-over-week trends - Notable anomalies - Action items`, dataConnectors: { postgres: { enabled: true } }, integrations: { slack: { enabled: true } } } }); console.log('Next run:', dailyReport.nextRun); ``` ```python Python theme={null} # Daily scheduled report daily_report = agentbase.create_trigger( name="daily_analytics_report", type="schedule", schedule="0 9 * * *", # Every day at 9 AM timezone="America/New_York", agent={ "message": "Generate daily analytics report", "system": """Create report including: - Yesterday's key metrics - Week-over-week trends - Notable anomalies - Action items""", "data_connectors": { "postgres": {"enabled": True} }, "integrations": { "slack": {"enabled": True} } } ) print(f"Next run: {daily_report.next_run}") ``` ### Database Change Trigger ```typescript TypeScript theme={null} // React to database changes const dbTrigger = await agentbase.createTrigger({ name: "new_order_processor", type: "data_change", source: { type: "postgres", connectionString: process.env.DATABASE_URL, table: "orders", operations: ["insert"] }, agent: { message: "Process new order", context: { orderData: "{{event.new_row}}" // New order data }, system: `For each new order: - Validate order data - Check inventory availability - Calculate shipping cost - Send confirmation email - Create fulfillment task` } }); ``` ```python Python theme={null} # React to database changes db_trigger = agentbase.create_trigger( name="new_order_processor", type="data_change", source={ "type": "postgres", "connection_string": os.environ['DATABASE_URL'], "table": "orders", "operations": ["insert"] }, agent={ "message": "Process new order", "context": { "order_data": "{{event.new_row}}" # New order data }, "system": """For each new order: - Validate order data - Check inventory availability - Calculate shipping cost - Send confirmation email - Create fulfillment task""" } ) ``` ### Condition Trigger ```typescript TypeScript theme={null} // Monitor metrics and alert const alertTrigger = await agentbase.createTrigger({ name: "high_error_rate_alert", type: "condition", condition: { metric: "error_rate", operator: "greater_than", threshold: 0.05, // 5% error rate window: "5m" // Over 5 minute window }, checkInterval: "1m", // Check every minute agent: { message: "High error rate detected", system: `Incident response: - Gather error logs and metrics - Identify affected services - Page on-call engineer - Create incident ticket - Post to status page - Start war room if critical` } }); ``` ```python Python theme={null} # Monitor metrics and alert alert_trigger = agentbase.create_trigger( name="high_error_rate_alert", type="condition", condition={ "metric": "error_rate", "operator": "greater_than", "threshold": 0.05, # 5% error rate "window": "5m" # Over 5 minute window }, check_interval="1m", # Check every minute agent={ "message": "High error rate detected", "system": """Incident response: - Gather error logs and metrics - Identify affected services - Page on-call engineer - Create incident ticket - Post to status page - Start war room if critical""" } ) ``` ### File System Trigger ```typescript TypeScript theme={null} // Watch for new files const fileWatcher = await agentbase.createTrigger({ name: "process_uploaded_files", type: "file_system", source: { path: "/uploads", pattern: "*.csv", events: ["created"] }, agent: { message: "Process new CSV file", context: { filePath: "{{event.file_path}}", fileName: "{{event.file_name}}" }, system: `Process CSV file: - Validate file format - Parse and validate data - Import to database - Generate import report - Notify uploader of results` } }); ``` ```python Python theme={null} # Watch for new files file_watcher = agentbase.create_trigger( name="process_uploaded_files", type="file_system", source={ "path": "/uploads", "pattern": "*.csv", "events": ["created"] }, agent={ "message": "Process new CSV file", "context": { "file_path": "{{event.file_path}}", "file_name": "{{event.file_name}}" }, "system": """Process CSV file: - Validate file format - Parse and validate data - Import to database - Generate import report - Notify uploader of results""" } ) ``` ### Compound Triggers ```typescript TypeScript theme={null} // Multiple conditions must be met const compoundTrigger = await agentbase.createTrigger({ name: "high_value_customer_signup", type: "compound", conditions: [ { type: "webhook", source: "stripe", event: "customer.created" }, { type: "condition", check: "{{customer.plan}} === 'enterprise'" }, { type: "condition", check: "{{customer.employees}} > 100" } ], operator: "and", // All conditions must be true agent: { message: "High-value customer signed up", system: `VIP onboarding: - Assign dedicated account manager - Schedule white-glove onboarding - Send personalized welcome package - Create custom implementation plan - Notify executive team` } }); ``` ```python Python theme={null} # Multiple conditions must be met compound_trigger = agentbase.create_trigger( name="high_value_customer_signup", type="compound", conditions=[ { "type": "webhook", "source": "stripe", "event": "customer.created" }, { "type": "condition", "check": "{{customer.plan}} === 'enterprise'" }, { "type": "condition", "check": "{{customer.employees}} > 100" } ], operator="and", # All conditions must be true agent={ "message": "High-value customer signed up", "system": """VIP onboarding: - Assign dedicated account manager - Schedule white-glove onboarding - Send personalized welcome package - Create custom implementation plan - Notify executive team""" } ) ``` ### Trigger with Filters ```typescript TypeScript theme={null} // Filter events before triggering const filteredTrigger = await agentbase.createTrigger({ name: "priority_support_tickets", type: "webhook", source: "zendesk", events: ["ticket.created"], filters: [ { field: "priority", operator: "in", values: ["high", "urgent"] }, { field: "customer.tier", operator: "equals", value: "enterprise" } ], agent: { message: "Handle priority support ticket", system: `Priority ticket protocol: - Auto-assign to senior support engineer - Create Slack notification in #support-urgent - Set 2-hour response SLA - Escalate to manager if not assigned in 15 minutes` } }); ``` ```python Python theme={null} # Filter events before triggering filtered_trigger = agentbase.create_trigger( name="priority_support_tickets", type="webhook", source="zendesk", events=["ticket.created"], filters=[ { "field": "priority", "operator": "in", "values": ["high", "urgent"] }, { "field": "customer.tier", "operator": "equals", "value": "enterprise" } ], agent={ "message": "Handle priority support ticket", "system": """Priority ticket protocol: - Auto-assign to senior support engineer - Create Slack notification in #support-urgent - Set 2-hour response SLA - Escalate to manager if not assigned in 15 minutes""" } ) ``` ## Use Cases ### 1. Payment Processing Automate payment handling: ```typescript theme={null} // Payment success trigger await agentbase.createTrigger({ name: "payment_succeeded", type: "webhook", source: "stripe", events: ["payment_intent.succeeded"], agent: { message: "Process successful payment", context: { payment: "{{event.data.object}}" }, integrations: { stripe: { enabled: true }, quickbooks: { enabled: true }, sendgrid: { enabled: true } }, system: `Payment success workflow: 1. Update order status to 'paid' 2. Create invoice in QuickBooks 3. Send payment receipt to customer 4. Trigger fulfillment process 5. Update customer lifetime value 6. Add to revenue reports` } }); // Payment failed trigger await agentbase.createTrigger({ name: "payment_failed", type: "webhook", source: "stripe", events: ["payment_intent.payment_failed"], agent: { message: "Handle failed payment", system: `Payment failure workflow: 1. Log failure reason 2. Send payment retry email to customer 3. Update order status to 'payment_failed' 4. Create follow-up task for sales team 5. If multiple failures, flag account for review` } }); ``` ### 2. CI/CD Automation Trigger deployments and notifications: ```typescript theme={null} await agentbase.createTrigger({ name: "deploy_on_merge", type: "webhook", source: "github", events: ["pull_request"], filters: [ { field: "action", operator: "equals", value: "closed" }, { field: "merged", operator: "equals", value: true }, { field: "base.ref", operator: "equals", value: "main" } ], agent: { message: "Deploy merged changes", context: { pr: "{{event.pull_request}}", commits: "{{event.pull_request.commits}}" }, integrations: { github: { enabled: true }, slack: { enabled: true } }, system: `Deployment workflow: 1. Run test suite 2. Build production artifacts 3. Deploy to staging 4. Run smoke tests 5. If tests pass, deploy to production 6. Notify team in Slack 7. Create deployment log entry` } }); ``` ### 3. Customer Support Automation Auto-respond to support tickets: ```typescript theme={null} await agentbase.createTrigger({ name: "new_support_ticket", type: "webhook", source: "zendesk", events: ["ticket.created"], agent: { message: "Handle new support ticket", context: { ticket: "{{event.ticket}}" }, integrations: { zendesk: { enabled: true }, salesforce: { enabled: true } }, system: `Support ticket workflow: 1. Analyze ticket content and categorize 2. Check for similar resolved tickets 3. Look up customer in Salesforce 4. If common issue, provide auto-response with solution 5. If complex, assign to appropriate specialist 6. If VIP customer, escalate immediately 7. Set SLA based on priority and customer tier` } }); ``` ### 4. Inventory Management Monitor and reorder inventory: ```typescript theme={null} await agentbase.createTrigger({ name: "low_inventory_alert", type: "condition", condition: { source: "database", query: "SELECT * FROM inventory WHERE quantity < reorder_point", checkInterval: "1h" }, agent: { message: "Handle low inventory", context: { lowStockItems: "{{query_results}}" }, integrations: { inventory_system: { enabled: true }, supplier_api: { enabled: true } }, system: `Inventory replenishment: 1. Calculate reorder quantity based on demand forecast 2. Check supplier availability and lead times 3. Create purchase orders 4. Send POs to suppliers 5. Update expected delivery dates 6. Notify warehouse team 7. If critical item, expedite shipping` } }); ``` ### 5. Security Monitoring Detect and respond to security events: ```typescript theme={null} await agentbase.createTrigger({ name: "suspicious_login_activity", type: "condition", condition: { metric: "failed_login_attempts", operator: "greater_than", threshold: 5, window: "5m", groupBy: "ip_address" }, agent: { message: "Potential security threat detected", context: { ipAddress: "{{event.ip_address}}", attempts: "{{event.count}}" }, integrations: { auth_system: { enabled: true }, pagerduty: { enabled: true } }, system: `Security response: 1. Block IP address temporarily 2. Review recent activity from this IP 3. Check if any accounts compromised 4. Send security alert to team 5. If accounts affected, force password reset 6. Log incident for review 7. Update firewall rules if needed` } }); ``` ### 6. Content Publishing Automate content distribution: ```typescript theme={null} await agentbase.createTrigger({ name: "publish_blog_post", type: "file_system", source: { path: "/content/blog/published", pattern: "*.md", events: ["created", "modified"] }, agent: { message: "Publish blog post", context: { content: "{{file_content}}", fileName: "{{file_name}}" }, integrations: { wordpress: { enabled: true }, twitter: { enabled: true }, linkedin: { enabled: true }, mailchimp: { enabled: true } }, system: `Content publishing workflow: 1. Parse markdown and extract metadata 2. Generate featured image if not provided 3. Publish to WordPress blog 4. Create social media posts 5. Schedule newsletter 6. Update content calendar 7. Notify content team` } }); ``` ## Best Practices ### Trigger Design ```typescript theme={null} // Good: Specific filters reduce unnecessary executions { type: "webhook", source: "github", events: ["pull_request"], filters: [ { field: "action", operator: "equals", value: "opened" }, { field: "draft", operator: "equals", value: false }, { field: "base.ref", operator: "equals", value: "main" } ] } // Avoid: Too broad, triggers on every PR event { type: "webhook", source: "github", events: ["pull_request"] } ``` ```typescript theme={null} { name: "payment_processor", type: "webhook", retry: { enabled: true, maxAttempts: 3, backoff: "exponential", initialDelay: 1000 }, onFailure: { action: "notify", channels: ["email", "slack"], escalateAfter: 3 // Escalate after all retries fail } } ``` ```typescript theme={null} { name: "long_running_task", type: "schedule", agent: { message: "Process daily batch", timeout: 3600000 // 1 hour timeout }, executionTimeout: 3600000 } ``` ```typescript theme={null} { name: "order_processor", type: "webhook", idempotency: { enabled: true, keyField: "order_id", // Prevent duplicate processing ttl: 86400 // 24 hours } } ``` ### Security **Validate Webhook Signatures**: Always verify webhook signatures to ensure requests are from trusted sources. ```typescript theme={null} { type: "webhook", source: "stripe", security: { verifySignature: true, secret: process.env.STRIPE_WEBHOOK_SECRET } } ``` ```typescript theme={null} { name: "data_sync", type: "data_change", permissions: { tables: ["orders", "customers"], // Only these tables operations: ["insert", "update"], // No deletes conditions: "user_id = {{current_user_id}}" // Row-level security } } ``` ```typescript theme={null} // Set up monitoring { name: "critical_trigger", monitoring: { enabled: true, alertOn: { failureRate: 0.1, // Alert if 10% failures latency: 5000, // Alert if latency > 5s volume: { min: 10, max: 1000 } // Alert on unusual volume } } } ``` ### Performance **Batch Processing**: For high-volume triggers, batch events together to reduce execution overhead. ```typescript theme={null} { type: "data_change", source: { table: "events" }, batching: { enabled: true, maxSize: 100, // Process up to 100 events together maxWait: 5000 // Or wait max 5 seconds } } ``` ```typescript theme={null} { name: "api_webhook", type: "webhook", rateLimit: { maxExecutionsPerMinute: 60, queueExcess: true // Queue excess events } } ``` ```typescript theme={null} { type: "schedule", schedule: "* * * * *", // Every minute agent: { message: "Check for work", preCheck: "SELECT COUNT(*) FROM pending_tasks", skipIfEmpty: true // Skip if no work to do } } ``` ## Integration with Other Primitives ### With Workflow Trigger complex workflows: ```typescript theme={null} await agentbase.createTrigger({ name: "order_fulfillment", type: "webhook", source: "shopify", events: ["orders/create"], workflow: { id: "order_fulfillment_workflow", input: { order: "{{event.order}}" } } }); ``` Learn more: [Workflow Primitive](/primitives/extensions/workflow) ### With Tasks Create tasks from triggers: ```typescript theme={null} await agentbase.createTrigger({ name: "bug_report", type: "webhook", source: "github", events: ["issues"], filters: [{ field: "labels", operator: "contains", value: "bug" }], agent: { message: "Create bug triage task", capabilities: { tasks: { enabled: true } } } }); ``` Learn more: [Tasks Primitive](/primitives/extensions/tasks) ### With Memory Remember trigger execution context: ```typescript theme={null} await agentbase.createTrigger({ name: "customer_interaction", type: "webhook", source: "intercom", events: ["conversation.user.created"], agent: { message: "Handle customer message", memory: { namespace: "customer_{{event.user_id}}", enabled: true } } }); ``` Learn more: [Memory Primitive](/primitives/extensions/memory) ## Performance Considerations ### Trigger Latency * **Webhook Triggers**: \< 100ms processing time * **Schedule Triggers**: Precision within 1 second * **Condition Triggers**: Depends on check interval * **Database Triggers**: Real-time (\< 1s lag) ### Scalability * **Concurrent Executions**: Thousands of triggers simultaneously * **Event Throughput**: Millions of events per day * **Queue Management**: Automatic queuing during high volume ### Cost Optimization ```typescript theme={null} // Optimize costs { name: "expensive_operation", type: "schedule", schedule: "0 2 * * *", // Run during off-peak hours agent: { message: "Process batch", optimization: { useSpotInstances: true, batchSize: "adaptive" } } } ``` ## Troubleshooting **Problem**: Trigger configured but not executing **Solutions**: * Verify trigger is enabled * Check filters aren't too restrictive * Verify webhook URL is correctly configured * Test condition logic manually * Check webhook signature validation ```typescript theme={null} // Debug trigger const debug = await agentbase.testTrigger({ triggerId: "trigger_123", sampleEvent: testEvent }); console.log('Would trigger:', debug.wouldTrigger); console.log('Filters passed:', debug.filtersMatched); console.log('Reason:', debug.reason); ``` **Problem**: Same event triggering multiple times **Solutions**: * Enable idempotency keys * Check for webhook retries * Verify event deduplication * Review trigger conditions ```typescript theme={null} // Enable idempotency { name: "order_processor", idempotency: { enabled: true, keyField: "order_id", ttl: 86400 } } ``` **Problem**: Slow trigger execution **Solutions**: * Optimize agent execution time * Use async processing for long tasks * Reduce complexity of filters * Consider batching events ```typescript theme={null} // Use background processing { name: "slow_task", type: "webhook", agent: { message: "Process event", background: true // Run asynchronously } } ``` **Problem**: Too many trigger executions **Solutions**: * Add rate limiting * Implement more specific filters * Use batching * Add cooldown period ```typescript theme={null} // Add rate limiting { name: "high_volume_trigger", rateLimit: { maxExecutionsPerMinute: 60, cooldownPeriod: 1000 // 1s between executions } } ``` ## Advanced Patterns ### Trigger Chaining Chain multiple triggers: ```typescript theme={null} // First trigger creates data await agentbase.createTrigger({ name: "step1", type: "webhook", source: "api", onSuccess: { emitEvent: "step1_completed" } }); // Second trigger responds to first await agentbase.createTrigger({ name: "step2", type: "event", events: ["step1_completed"], agent: { message: "Continue workflow" } }); ``` ### Smart Throttling Intelligent rate limiting: ```typescript theme={null} { name: "adaptive_trigger", type: "webhook", throttling: { mode: "adaptive", baseRate: 100, // Events per minute increaseOn: "low_latency", decreaseOn: "high_error_rate" } } ``` ### Multi-Region Triggers Deploy triggers across regions: ```typescript theme={null} { name: "global_webhook", type: "webhook", multiRegion: { enabled: true, regions: ["us-east-1", "eu-west-1", "ap-south-1"], routing: "nearest" // Route to nearest region } } ``` ## Related Primitives Advanced time-based trigger scheduling Trigger complex multi-step workflows Lifecycle hooks for agent execution Run triggered agents asynchronously ## Additional Resources Complete triggers API documentation Available trigger events by source Trigger design patterns and recipes **Pro Tip**: Start with simple triggers and add complexity gradually. Test triggers with sample events before deploying to production to ensure they behave as expected. # Web Search Source: https://docs.agentbase.sh/primitives/extensions/web-search Enable agents to search the web and access real-time information from the internet > Web Search empowers agents to find current information on the internet, access news, research topics, and retrieve up-to-date data beyond their training cutoff. ## Overview The Web Search primitive gives agents the ability to search the internet in real-time, enabling them to access current information, news, facts, and data that may not be in their training data or your internal knowledge bases. This bridges the gap between static knowledge and dynamic, ever-changing web content. Web Search is essential for: * **Current Events**: Access latest news and developments * **Real-Time Data**: Get current prices, weather, sports scores, etc. * **Research**: Find information on any topic from the web * **Fact-Checking**: Verify information against multiple sources * **Market Intelligence**: Research competitors, trends, and market data * **Comprehensive Answers**: Combine internal knowledge with web content Search current web content, not limited to training data cutoff Aggregate information from multiple search results automatically Built-in content filtering and safe search capabilities Automatically cite web sources with URLs ## How Web Search Works When web search is enabled: 1. **Query Generation**: Agent formulates search query based on user question 2. **Search Execution**: Query is sent to search engine 3. **Result Retrieval**: Top search results are retrieved 4. **Content Extraction**: Relevant content is extracted from result pages 5. **Synthesis**: Agent synthesizes information from multiple sources 6. **Citation**: Sources are cited with URLs in the response **Privacy**: Web searches are performed on behalf of your agent. Search queries and results are processed in accordance with your privacy settings. ## Code Examples ### Basic Web Search ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Enable web search const result = await agentbase.runAgent({ message: "What are the latest developments in quantum computing?", webSearch: { enabled: true } }); console.log('Answer:', result.message); console.log('Sources:', result.sources); // Sources include URLs from web search ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Enable web search result = agentbase.run_agent( message="What are the latest developments in quantum computing?", web_search={ "enabled": True } ) print(f"Answer: {result.message}") print(f"Sources: {result.sources}") # Sources include URLs from web search ``` ### Web Search with Filters ```typescript TypeScript theme={null} // Filter search results const result = await agentbase.runAgent({ message: "Latest AI research papers", webSearch: { enabled: true, filters: { timeRange: "past_week", // Only recent results safeSearch: "strict", region: "us", language: "en" } } }); ``` ```python Python theme={null} # Filter search results result = agentbase.run_agent( message="Latest AI research papers", web_search={ "enabled": True, "filters": { "time_range": "past_week", # Only recent results "safe_search": "strict", "region": "us", "language": "en" } } ) ``` ### Domain-Specific Search ```typescript TypeScript theme={null} // Search specific domains const result = await agentbase.runAgent({ message: "Python async/await best practices", webSearch: { enabled: true, domains: [ "stackoverflow.com", "docs.python.org", "realpython.com" ] } }); // Only searches specified domains ``` ```python Python theme={null} # Search specific domains result = agentbase.run_agent( message="Python async/await best practices", web_search={ "enabled": True, "domains": [ "stackoverflow.com", "docs.python.org", "realpython.com" ] } ) # Only searches specified domains ``` ### Combining Web Search with RAG ```typescript TypeScript theme={null} // Use both internal docs and web search const result = await agentbase.runAgent({ message: "How does our product compare to the latest market alternatives?", datastores: [ { id: productDocs, name: "Product Documentation" } ], webSearch: { enabled: true, filters: { timeRange: "past_month" } }, system: `You are a product analyst. Combine: - Internal product documentation (via RAG) - Latest market information (via web search) Provide comprehensive competitive analysis.` }); // Agent uses both internal knowledge and web research ``` ```python Python theme={null} # Use both internal docs and web search result = agentbase.run_agent( message="How does our product compare to the latest market alternatives?", datastores=[ { "id": product_docs, "name": "Product Documentation" } ], web_search={ "enabled": True, "filters": { "time_range": "past_month" } }, system="""You are a product analyst. Combine: - Internal product documentation (via RAG) - Latest market information (via web search) Provide comprehensive competitive analysis.""" ) # Agent uses both internal knowledge and web research ``` ### Controlling Number of Search Results ```typescript TypeScript theme={null} // Customize search depth const result = await agentbase.runAgent({ message: "Comprehensive review of electric vehicles in 2024", webSearch: { enabled: true, maxResults: 10, // Fetch top 10 results depth: "comprehensive" // deep, standard, or quick } }); // Agent synthesizes information from multiple sources ``` ```python Python theme={null} # Customize search depth result = agentbase.run_agent( message="Comprehensive review of electric vehicles in 2024", web_search={ "enabled": True, "max_results": 10, # Fetch top 10 results "depth": "comprehensive" # deep, standard, or quick } ) # Agent synthesizes information from multiple sources ``` ## Use Cases ### 1. News and Current Events Stay informed on latest developments: ```typescript theme={null} const newsAgent = await agentbase.runAgent({ message: "Summarize today's major tech news", webSearch: { enabled: true, filters: { timeRange: "past_day", domains: [ "techcrunch.com", "theverge.com", "arstechnica.com", "wired.com" ] } }, system: `You are a tech news analyst. Provide: - Summary of major stories - Key takeaways - Links to full articles - Categorize by topic (AI, hardware, software, business)` }); ``` ### 2. Market Research Research competitors and market trends: ```typescript theme={null} const marketResearch = await agentbase.runAgent({ message: "What are the top CRM platforms for small businesses in 2024?", webSearch: { enabled: true, filters: { timeRange: "past_3_months" } }, system: `You are a market research analyst. Research and provide: - Top platforms and their features - Pricing comparison - User reviews and ratings - Market share insights - Cite sources for all data` }); ``` ### 3. Real-Time Data Lookup Access current information: ```typescript theme={null} const realTimeAgent = await agentbase.runAgent({ message: "What's the current weather in Tokyo and the USD to JPY exchange rate?", webSearch: { enabled: true, depth: "quick" // Fast lookup }, system: `Provide current, accurate information. Always cite the source and timestamp.` }); ``` ### 4. Academic Research Find scholarly articles and papers: ```typescript theme={null} const academicAgent = await agentbase.runAgent({ message: "Recent peer-reviewed research on CRISPR gene editing applications", webSearch: { enabled: true, domains: [ "scholar.google.com", "pubmed.ncbi.nlm.nih.gov", "arxiv.org" ], filters: { timeRange: "past_year" } }, system: `You are an academic research assistant. Find and summarize: - Peer-reviewed publications - Key findings and methodologies - Citations in proper format - Links to full papers` }); ``` ### 5. Product Recommendations Research and recommend products: ```typescript theme={null} const shoppingAgent = await agentbase.runAgent({ message: "Best noise-canceling headphones under $300 for travel", webSearch: { enabled: true, filters: { timeRange: "past_6_months" // Recent reviews } }, system: `You are a product research assistant. Research and provide: - Top recommended products - Pros and cons of each - Price comparison - User ratings and reviews - Where to buy - Cite review sources` }); ``` ### 6. Technical Troubleshooting Find solutions to technical problems: ```typescript theme={null} const troubleshootAgent = await agentbase.runAgent({ message: "How to fix CORS errors in Next.js API routes", webSearch: { enabled: true, domains: [ "stackoverflow.com", "github.com", "nextjs.org" ] }, system: `You are a technical support assistant. Find and provide: - Clear explanation of the issue - Step-by-step solutions - Code examples - Common pitfalls - Links to documentation and discussions` }); ``` ### 7. Travel Planning Research destinations and travel information: ```typescript theme={null} const travelAgent = await agentbase.runAgent({ message: "Plan a 5-day trip to Barcelona - best attractions, hotels, and restaurants", webSearch: { enabled: true, filters: { timeRange: "past_year", // Current travel info language: "en" } }, system: `You are a travel planning assistant. Research and create itinerary with: - Top attractions and activities - Hotel recommendations by area - Restaurant suggestions - Transportation tips - Estimated costs - Cite travel guides and review sites` }); ``` ## Best Practices ### Query Formulation **Let Agent Formulate Queries**: The agent will automatically formulate effective search queries. Your prompt should focus on what information you need, not how to search for it. ```typescript theme={null} // Good: Clear information need "What are the latest features in Python 3.12?" "Compare pricing of top 5 project management tools" "Recent developments in renewable energy technology" // Avoid: Trying to write search queries "Search for 'Python 3.12 new features'" "Google 'project management tools pricing'" ``` ```typescript theme={null} // Good: Specify recency when needed { message: "Latest iPhone release details", webSearch: { enabled: true, filters: { timeRange: "past_week" // Recent info } } } // For evergreen topics, recency less important { message: "How does photosynthesis work?", webSearch: { enabled: true // No time filter needed } } ``` ```typescript theme={null} // Good: Filter for authoritative sources { message: "Latest CDC guidelines on vaccinations", webSearch: { enabled: true, domains: ["cdc.gov", "who.int", "nih.gov"] } } // Good: Exclude unreliable sources { webSearch: { enabled: true, excludeDomains: [ "example-spam-site.com", "unreliable-source.net" ] } } ``` ### Source Verification **Verify Critical Information**: Web search returns information from the internet, which may not always be accurate. Always verify critical information from authoritative sources. ```typescript theme={null} const result = await agentbase.runAgent({ message: "What are the tax implications of cryptocurrency trading?", webSearch: { enabled: true, domains: [ "irs.gov", // Official sources "tax.gov" ] }, system: `You are a tax information assistant. Important: - Only cite official government sources for tax information - Clearly state this is not professional tax advice - Recommend consulting a tax professional - Indicate if information may be outdated`, rules: [ "Only use official government sources for tax information", "Clearly state this is general information, not professional advice", "Recommend consulting a tax professional for specific situations" ] }); ``` ### Performance Optimization ```typescript theme={null} // Efficient: Appropriate depth for task const quickFact = await agentbase.runAgent({ message: "What's the population of Tokyo?", webSearch: { enabled: true, depth: "quick", // Fast lookup maxResults: 3 } }); // Comprehensive: When depth needed const deepResearch = await agentbase.runAgent({ message: "Comprehensive analysis of remote work trends post-pandemic", webSearch: { enabled: true, depth: "comprehensive", // Thorough research maxResults: 15 } }); ``` ### Safe Search ```typescript theme={null} // Always use safe search for user-facing applications const result = await agentbase.runAgent({ message: userQuery, webSearch: { enabled: true, filters: { safeSearch: "strict" // Filter inappropriate content } } }); ``` ## Integration with Other Primitives ### With RAG Combine internal knowledge with web research: ```typescript theme={null} const result = await agentbase.runAgent({ message: "How does our product stack up against recent competitor releases?", datastores: [{ id: productDocs }], // Internal docs webSearch: { enabled: true }, // Web research system: `Compare our product features (from internal docs) with competitor information (from web search). Provide: - Feature comparison table - Competitive advantages - Areas for improvement` }); ``` Learn more: [RAG Primitive](/primitives/extensions/rag) ### With Memory Remember research topics and preferences: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Find more articles on topics we discussed before", memory: { namespace: `user_${userId}`, enabled: true }, webSearch: { enabled: true } }); // Agent recalls previous research topics from memory // and searches for related content ``` Learn more: [Memory Primitive](/primitives/extensions/memory) ### With Workflows Include web research in automated workflows: ```typescript theme={null} const workflow = { name: "weekly_market_report", steps: [ { id: "search_news", type: "agent_task", config: { message: "Find top industry news from this week", webSearch: { enabled: true } } }, { id: "analyze_trends", type: "agent_task", config: { message: "Analyze trends from the news", webSearch: { enabled: true } } }, { id: "create_report", type: "agent_task", config: { message: "Create weekly report with findings" } } ] }; await agentbase.executeWorkflow({ workflow }); ``` Learn more: [Workflow Primitive](/primitives/extensions/workflow) ## Performance Considerations ### Search Latency * **Quick search**: \~1-2 seconds * **Standard search**: \~2-4 seconds * **Comprehensive search**: \~4-8 seconds Factors: * Number of results requested * Search depth * Content extraction complexity ### Cost Optimization **Cache Common Queries**: For frequently asked questions, consider caching results instead of repeated web searches. ```typescript theme={null} // Implement caching for common queries const cache = new Map(); async function searchWithCache(query: string) { const cacheKey = query.toLowerCase(); // Check cache if (cache.has(cacheKey)) { const cached = cache.get(cacheKey); if (Date.now() - cached.timestamp < 3600000) { // 1 hour return cached.result; } } // Perform search const result = await agentbase.runAgent({ message: query, webSearch: { enabled: true } }); // Cache result cache.set(cacheKey, { result, timestamp: Date.now() }); return result; } ``` ### Rate Limiting ```typescript theme={null} // Implement rate limiting for web searches import { RateLimiter } from 'rate-limiter-flexible'; const limiter = new RateLimiter({ points: 100, // Number of searches duration: 3600 // Per hour }); async function rateLimitedSearch(query: string) { try { await limiter.consume(userId, 1); return await agentbase.runAgent({ message: query, webSearch: { enabled: true } }); } catch (error) { throw new Error('Rate limit exceeded. Please try again later.'); } } ``` ## Troubleshooting **Problem**: Web search returns no results **Solutions**: * Broaden search query * Remove strict domain filters * Adjust time range filter * Check if query is too specific * Verify search is enabled ```typescript theme={null} // Broaden search webSearch: { enabled: true, filters: { timeRange: "any", // Remove time restriction // Remove domain filters } } ``` **Problem**: Search returns off-topic results **Solutions**: * Make query more specific * Use domain filtering * Adjust prompt to be clearer * Use negative keywords ```typescript theme={null} { message: "JavaScript frameworks (not Java)", webSearch: { enabled: true, excludeTerms: ["Java"] // Exclude Java results } } ``` **Problem**: Results are old or outdated **Solutions**: * Add time range filter * Specify need for recent information in prompt * Check source dates in citations ```typescript theme={null} webSearch: { enabled: true, filters: { timeRange: "past_month" // Recent results only } } ``` **Problem**: Searches taking too long **Solutions**: * Reduce maxResults * Use "quick" depth * Limit domains to search * Simplify query ```typescript theme={null} webSearch: { enabled: true, depth: "quick", maxResults: 3, domains: ["wikipedia.org"] // Single reliable source } ``` ## Advanced Features ### Multi-Query Search Search for multiple related topics: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Research both electric vehicle market trends AND battery technology advances", webSearch: { enabled: true, multiQuery: true // Performs separate searches and synthesizes }, system: `Research both topics thoroughly and show how they relate.` }); ``` ### Source Diversity Ensure diverse perspectives: ```typescript theme={null} const result = await agentbase.runAgent({ message: "What are different perspectives on remote work?", webSearch: { enabled: true, diverseSources: true, // Get results from variety of sources maxResults: 10 } }); ``` ### Fact Verification Cross-reference information: ```typescript theme={null} const result = await agentbase.runAgent({ message: "Is it true that coffee is good for your health?", webSearch: { enabled: true, verifyFacts: true, // Check multiple sources domains: [ "nih.gov", "mayoclinic.org", "health.harvard.edu" ] }, system: `Verify this claim against multiple authoritative sources. Indicate if sources disagree.` }); ``` ## Related Primitives Search internal documents and knowledge bases Extract content from specific websites Remember previous research and topics Automate research workflows ## Additional Resources Complete web search API docs Optimize search effectiveness Web search examples **Remember**: Web search provides access to current information but requires verification. Always cite sources and encourage users to verify critical information from authoritative sources. # Workflow Source: https://docs.agentbase.sh/primitives/extensions/workflow Orchestrate multi-step processes and automate complex business workflows > Workflows enable agents to execute complex, multi-step processes with conditional logic, loops, error handling, and human-in-the-loop approval points. ## Overview The Workflow primitive transforms agents into powerful automation engines capable of orchestrating sophisticated business processes. Instead of handling single requests, workflow-enabled agents can execute multi-step procedures, coordinate between different systems, handle branching logic, and maintain process state across extended operations. Workflows are essential for: * **Process Automation**: Automate repetitive multi-step business processes * **Complex Operations**: Coordinate tasks requiring multiple systems and approvals * **Reliability**: Built-in error handling, retries, and rollback capabilities * **Visibility**: Track execution progress and audit process completion * **Human Oversight**: Integrate approval gates and decision points * **State Management**: Maintain process state across hours or days Define workflows as structured graphs with nodes, edges, and conditions Workflow state persists automatically, surviving restarts and failures Built-in retry logic, error recovery, and rollback mechanisms Integrate approval gates and manual decision points seamlessly ## How Workflows Work When you execute a workflow: 1. **Definition**: Define workflow steps, transitions, and conditions 2. **Initialization**: Workflow engine creates execution context and state 3. **Execution**: Agent executes steps sequentially or in parallel 4. **State Tracking**: Current step, variables, and progress are persisted 5. **Branching**: Conditional logic determines next steps based on results 6. **Completion**: Workflow completes with final output or error state **Durability**: Workflows are durable by default. They can survive system restarts and continue from the last completed step. ## Workflow Components ### Steps Individual units of work within a workflow: ```typescript theme={null} { id: "fetch_customer", type: "agent_task", description: "Retrieve customer information", config: { message: "Get customer details for ID: {{customerId}}", mcpServers: [{ serverName: "crm" }] } } ``` ### Transitions Define flow between steps: ```typescript theme={null} { from: "fetch_customer", to: "check_balance", condition: "{{customer.status}} === 'active'" } ``` ### Decision Points Branch based on conditions: ```typescript theme={null} { id: "check_amount", type: "decision", conditions: [ { when: "{{amount}} > 10000", goto: "require_approval" }, { when: "{{amount}} <= 10000", goto: "process_payment" } ] } ``` ## Code Examples ### Basic Workflow ```typescript TypeScript theme={null} import { Agentbase } from '@agentbase/sdk'; const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY }); // Define a simple workflow const workflow = { name: "customer_onboarding", steps: [ { id: "create_account", type: "agent_task", config: { message: "Create customer account with email: {{email}}" } }, { id: "send_welcome_email", type: "agent_task", config: { message: "Send welcome email to {{email}}" } }, { id: "setup_billing", type: "agent_task", config: { message: "Setup billing for customer {{customerId}}" } } ], transitions: [ { from: "create_account", to: "send_welcome_email" }, { from: "send_welcome_email", to: "setup_billing" } ] }; // Execute workflow const result = await agentbase.executeWorkflow({ workflow, input: { email: "user@example.com" } }); console.log('Workflow completed:', result.status); ``` ```python Python theme={null} from agentbase import Agentbase agentbase = Agentbase(api_key=os.environ['AGENTBASE_API_KEY']) # Define a simple workflow workflow = { "name": "customer_onboarding", "steps": [ { "id": "create_account", "type": "agent_task", "config": { "message": "Create customer account with email: {{email}}" } }, { "id": "send_welcome_email", "type": "agent_task", "config": { "message": "Send welcome email to {{email}}" } }, { "id": "setup_billing", "type": "agent_task", "config": { "message": "Setup billing for customer {{customerId}}" } } ], "transitions": [ {"from": "create_account", "to": "send_welcome_email"}, {"from": "send_welcome_email", "to": "setup_billing"} ] } # Execute workflow result = agentbase.execute_workflow( workflow=workflow, input={ "email": "user@example.com" } ) print(f"Workflow completed: {result.status}") ``` ### Conditional Workflow ```typescript TypeScript theme={null} // Workflow with conditional branching const approvalWorkflow = { name: "expense_approval", steps: [ { id: "validate_expense", type: "agent_task", config: { message: "Validate expense report for amount: {{amount}}" } }, { id: "check_amount", type: "decision", conditions: [ { when: "{{amount}} > 1000", goto: "manager_approval" }, { when: "{{amount}} <= 1000", goto: "auto_approve" } ] }, { id: "manager_approval", type: "human_approval", config: { approvers: ["manager@company.com"], message: "Please approve expense of ${{amount}}" } }, { id: "auto_approve", type: "agent_task", config: { message: "Automatically approve expense of ${{amount}}" } }, { id: "process_payment", type: "agent_task", config: { message: "Process payment of ${{amount}} to {{employee}}" } } ], transitions: [ { from: "validate_expense", to: "check_amount" }, { from: "manager_approval", to: "process_payment" }, { from: "auto_approve", to: "process_payment" } ] }; const result = await agentbase.executeWorkflow({ workflow: approvalWorkflow, input: { amount: 1500, employee: "john@company.com" } }); ``` ```python Python theme={null} # Workflow with conditional branching approval_workflow = { "name": "expense_approval", "steps": [ { "id": "validate_expense", "type": "agent_task", "config": { "message": "Validate expense report for amount: {{amount}}" } }, { "id": "check_amount", "type": "decision", "conditions": [ { "when": "{{amount}} > 1000", "goto": "manager_approval" }, { "when": "{{amount}} <= 1000", "goto": "auto_approve" } ] }, { "id": "manager_approval", "type": "human_approval", "config": { "approvers": ["manager@company.com"], "message": "Please approve expense of ${{amount}}" } }, { "id": "auto_approve", "type": "agent_task", "config": { "message": "Automatically approve expense of ${{amount}}" } }, { "id": "process_payment", "type": "agent_task", "config": { "message": "Process payment of ${{amount}} to {{employee}}" } } ], "transitions": [ {"from": "validate_expense", "to": "check_amount"}, {"from": "manager_approval", "to": "process_payment"}, {"from": "auto_approve", "to": "process_payment"} ] } result = agentbase.execute_workflow( workflow=approval_workflow, input={ "amount": 1500, "employee": "john@company.com" } ) ``` ### Parallel Execution ```typescript TypeScript theme={null} // Execute steps in parallel for efficiency const parallelWorkflow = { name: "data_enrichment", steps: [ { id: "fetch_customer", type: "agent_task", config: { message: "Get customer data for {{customerId}}" } }, { id: "parallel_enrichment", type: "parallel", branches: [ { id: "get_credit_score", type: "agent_task", config: { message: "Fetch credit score for {{customerId}}" } }, { id: "get_purchase_history", type: "agent_task", config: { message: "Fetch purchase history for {{customerId}}" } }, { id: "get_social_profile", type: "agent_task", config: { message: "Fetch social media profile for {{customerId}}" } } ] }, { id: "generate_report", type: "agent_task", config: { message: "Generate customer insight report" } } ], transitions: [ { from: "fetch_customer", to: "parallel_enrichment" }, { from: "parallel_enrichment", to: "generate_report" } ] }; const result = await agentbase.executeWorkflow({ workflow: parallelWorkflow, input: { customerId: "cust_123" } }); ``` ```python Python theme={null} # Execute steps in parallel for efficiency parallel_workflow = { "name": "data_enrichment", "steps": [ { "id": "fetch_customer", "type": "agent_task", "config": { "message": "Get customer data for {{customerId}}" } }, { "id": "parallel_enrichment", "type": "parallel", "branches": [ { "id": "get_credit_score", "type": "agent_task", "config": { "message": "Fetch credit score for {{customerId}}" } }, { "id": "get_purchase_history", "type": "agent_task", "config": { "message": "Fetch purchase history for {{customerId}}" } }, { "id": "get_social_profile", "type": "agent_task", "config": { "message": "Fetch social media profile for {{customerId}}" } } ] }, { "id": "generate_report", "type": "agent_task", "config": { "message": "Generate customer insight report" } } ], "transitions": [ {"from": "fetch_customer", "to": "parallel_enrichment"}, {"from": "parallel_enrichment", "to": "generate_report"} ] } result = agentbase.execute_workflow( workflow=parallel_workflow, input={ "customerId": "cust_123" } ) ``` ### Error Handling and Retry ```typescript TypeScript theme={null} // Workflow with error handling const resilientWorkflow = { name: "api_integration", steps: [ { id: "call_external_api", type: "agent_task", config: { message: "Call external API endpoint", retry: { maxAttempts: 3, backoff: "exponential", initialDelay: 1000 } }, onError: "log_failure" }, { id: "process_response", type: "agent_task", config: { message: "Process API response" } }, { id: "log_failure", type: "agent_task", config: { message: "Log API failure and send alert" } } ], transitions: [ { from: "call_external_api", to: "process_response" } ] }; const result = await agentbase.executeWorkflow({ workflow: resilientWorkflow, input: { endpoint: "https://api.example.com/data" } }); ``` ```python Python theme={null} # Workflow with error handling resilient_workflow = { "name": "api_integration", "steps": [ { "id": "call_external_api", "type": "agent_task", "config": { "message": "Call external API endpoint", "retry": { "maxAttempts": 3, "backoff": "exponential", "initialDelay": 1000 } }, "onError": "log_failure" }, { "id": "process_response", "type": "agent_task", "config": { "message": "Process API response" } }, { "id": "log_failure", "type": "agent_task", "config": { "message": "Log API failure and send alert" } } ], "transitions": [ {"from": "call_external_api", "to": "process_response"} ] } result = agentbase.execute_workflow( workflow=resilient_workflow, input={ "endpoint": "https://api.example.com/data" } ) ``` ### Monitoring Workflow Progress ```typescript TypeScript theme={null} // Start workflow execution const execution = await agentbase.executeWorkflow({ workflow: myWorkflow, input: { customerId: "123" } }); // Check workflow status const status = await agentbase.getWorkflowStatus({ executionId: execution.id }); console.log('Current step:', status.currentStep); console.log('Progress:', status.completedSteps, '/', status.totalSteps); console.log('Status:', status.status); // running, completed, failed, waiting // Get detailed execution history const history = await agentbase.getWorkflowHistory({ executionId: execution.id }); history.steps.forEach(step => { console.log(`${step.id}: ${step.status} (${step.duration}ms)`); }); ``` ```python Python theme={null} # Start workflow execution execution = agentbase.execute_workflow( workflow=my_workflow, input={"customerId": "123"} ) # Check workflow status status = agentbase.get_workflow_status( execution_id=execution.id ) print(f"Current step: {status.current_step}") print(f"Progress: {status.completed_steps}/{status.total_steps}") print(f"Status: {status.status}") # running, completed, failed, waiting # Get detailed execution history history = agentbase.get_workflow_history( execution_id=execution.id ) for step in history.steps: print(f"{step.id}: {step.status} ({step.duration}ms)") ``` ## Use Cases ### 1. Customer Onboarding Automate multi-step onboarding process: ```typescript theme={null} const onboardingWorkflow = { name: "customer_onboarding", steps: [ { id: "verify_email", type: "agent_task", config: { message: "Send verification email to {{email}} and wait for confirmation" } }, { id: "create_account", type: "agent_task", config: { message: "Create account in CRM for {{email}}" } }, { id: "setup_profile", type: "agent_task", config: { message: "Create user profile with preferences" } }, { id: "assign_rep", type: "agent_task", config: { message: "Assign account representative based on region {{region}}" } }, { id: "send_welcome_kit", type: "agent_task", config: { message: "Send welcome kit and schedule kickoff call" } }, { id: "notify_team", type: "agent_task", config: { message: "Notify sales team of new customer onboarded" } } ] }; // Execute for new customer await agentbase.executeWorkflow({ workflow: onboardingWorkflow, input: { email: "newcustomer@example.com", region: "west" } }); ``` ### 2. Order Fulfillment Orchestrate e-commerce order processing: ```typescript theme={null} const orderWorkflow = { name: "order_fulfillment", steps: [ { id: "validate_order", type: "agent_task", config: { message: "Validate order {{orderId}} for completeness and accuracy" } }, { id: "check_inventory", type: "agent_task", config: { message: "Check inventory for all items in order" } }, { id: "inventory_decision", type: "decision", conditions: [ { when: "{{inventory.available}} === false", goto: "backorder_notification" }, { when: "{{inventory.available}} === true", goto: "process_payment" } ] }, { id: "process_payment", type: "agent_task", config: { message: "Process payment for order {{orderId}}" } }, { id: "create_shipment", type: "agent_task", config: { message: "Create shipment and generate shipping label" } }, { id: "notify_warehouse", type: "agent_task", config: { message: "Notify warehouse to pick and pack order" } }, { id: "send_tracking", type: "agent_task", config: { message: "Send tracking information to customer" } }, { id: "backorder_notification", type: "agent_task", config: { message: "Notify customer of backorder and estimated ship date" } } ] }; ``` ### 3. Content Publishing Pipeline Automate content creation and publishing: ```typescript theme={null} const contentWorkflow = { name: "content_publishing", steps: [ { id: "draft_content", type: "agent_task", config: { message: "Create blog post draft on topic: {{topic}}" } }, { id: "editorial_review", type: "human_approval", config: { approvers: ["editor@company.com"], message: "Review and approve content draft", timeout: 86400000 // 24 hours } }, { id: "generate_images", type: "agent_task", config: { message: "Generate featured image and social media graphics" } }, { id: "seo_optimization", type: "agent_task", config: { message: "Optimize content for SEO including meta tags and keywords" } }, { id: "publish_blog", type: "agent_task", config: { message: "Publish post to company blog" } }, { id: "social_media_posts", type: "parallel", branches: [ { id: "post_twitter", type: "agent_task", config: { message: "Create and schedule Twitter post" } }, { id: "post_linkedin", type: "agent_task", config: { message: "Create and schedule LinkedIn post" } }, { id: "post_facebook", type: "agent_task", config: { message: "Create and schedule Facebook post" } } ] }, { id: "notify_team", type: "agent_task", config: { message: "Notify marketing team that content is published" } } ] }; ``` ### 4. Incident Response Automate IT incident management: ```typescript theme={null} const incidentWorkflow = { name: "incident_response", steps: [ { id: "detect_incident", type: "agent_task", config: { message: "Analyze alert and classify incident severity" } }, { id: "severity_check", type: "decision", conditions: [ { when: "{{severity}} === 'critical'", goto: "page_oncall" }, { when: "{{severity}} === 'high'", goto: "create_ticket" }, { when: "{{severity}} === 'low'", goto: "auto_remediate" } ] }, { id: "page_oncall", type: "agent_task", config: { message: "Page on-call engineer and create war room" } }, { id: "create_ticket", type: "agent_task", config: { message: "Create incident ticket and assign to team" } }, { id: "auto_remediate", type: "agent_task", config: { message: "Attempt automatic remediation steps" } }, { id: "gather_diagnostics", type: "agent_task", config: { message: "Collect logs, metrics, and diagnostic information" } }, { id: "notify_stakeholders", type: "agent_task", config: { message: "Send status updates to stakeholders" } }, { id: "post_incident_report", type: "agent_task", config: { message: "Generate post-incident report and action items" } } ] }; ``` ### 5. Data Pipeline ETL workflow for data processing: ```typescript theme={null} const etlWorkflow = { name: "daily_data_pipeline", steps: [ { id: "extract_data", type: "parallel", branches: [ { id: "extract_salesforce", type: "agent_task", config: { message: "Extract data from Salesforce" } }, { id: "extract_database", type: "agent_task", config: { message: "Extract data from production database" } }, { id: "extract_api", type: "agent_task", config: { message: "Extract data from external APIs" } } ] }, { id: "transform_data", type: "agent_task", config: { message: "Clean, normalize, and transform extracted data" } }, { id: "validate_quality", type: "agent_task", config: { message: "Run data quality checks and validations" } }, { id: "quality_decision", type: "decision", conditions: [ { when: "{{quality.passed}} === false", goto: "alert_data_team" }, { when: "{{quality.passed}} === true", goto: "load_warehouse" } ] }, { id: "load_warehouse", type: "agent_task", config: { message: "Load data into data warehouse" } }, { id: "update_dashboards", type: "agent_task", config: { message: "Refresh BI dashboards and reports" } }, { id: "alert_data_team", type: "agent_task", config: { message: "Alert data team of quality issues" } } ] }; // Schedule to run daily await agentbase.scheduleWorkflow({ workflow: etlWorkflow, schedule: "0 2 * * *", // 2 AM daily timezone: "America/New_York" }); ``` ### 6. Employee Offboarding Automate employee exit process: ```typescript theme={null} const offboardingWorkflow = { name: "employee_offboarding", steps: [ { id: "hr_approval", type: "human_approval", config: { approvers: ["hr@company.com"], message: "Confirm offboarding for {{employeeName}}" } }, { id: "revoke_access", type: "parallel", branches: [ { id: "disable_email", type: "agent_task", config: { message: "Disable email account" } }, { id: "revoke_github", type: "agent_task", config: { message: "Remove from GitHub organization" } }, { id: "revoke_aws", type: "agent_task", config: { message: "Revoke AWS access" } }, { id: "disable_slack", type: "agent_task", config: { message: "Deactivate Slack account" } } ] }, { id: "collect_equipment", type: "agent_task", config: { message: "Send equipment return instructions to {{employeeName}}" } }, { id: "knowledge_transfer", type: "agent_task", config: { message: "Document knowledge transfer and handoff tasks" } }, { id: "exit_interview", type: "agent_task", config: { message: "Schedule and conduct exit interview" } }, { id: "notify_team", type: "agent_task", config: { message: "Notify team of departure and transition plan" } }, { id: "final_payroll", type: "agent_task", config: { message: "Process final paycheck and benefits termination" } } ] }; ``` ## Best Practices ### Workflow Design ```typescript theme={null} // Good: Single-purpose steps { id: "validate_email", type: "agent_task", config: { message: "Validate email format" } }, { id: "check_email_exists", type: "agent_task", config: { message: "Check if email already registered" } } // Avoid: Multiple responsibilities in one step { id: "handle_email", type: "agent_task", config: { message: "Validate email, check if exists, and send confirmation" } } ``` ```typescript theme={null} // Good: Clear, descriptive IDs { id: "send_welcome_email", id: "verify_payment_method", id: "create_customer_record" } // Avoid: Vague or numbered IDs { id: "step1", id: "do_stuff", id: "process" } ``` ```typescript theme={null} // Include error paths and edge cases { id: "process_payment", type: "agent_task", config: { message: "Process payment" }, onError: "handle_payment_failure" }, { id: "handle_payment_failure", type: "decision", conditions: [ { when: "{{error.type}} === 'insufficient_funds'", goto: "notify_insufficient_funds" }, { when: "{{error.type}} === 'card_declined'", goto: "request_alternate_payment" }, { when: "{{error.type}} === 'network_error'", goto: "retry_payment" } ] } ``` ```typescript theme={null} // Execute independent operations in parallel { id: "send_notifications", type: "parallel", branches: [ { id: "send_email", type: "agent_task", config: { message: "Send email notification" } }, { id: "send_sms", type: "agent_task", config: { message: "Send SMS notification" } }, { id: "send_slack", type: "agent_task", config: { message: "Send Slack notification" } } ] } ``` ### Error Handling **Always Handle Failures**: Every workflow should have error handling strategies for critical steps. Unhandled errors can leave workflows in inconsistent states. ```typescript theme={null} // Comprehensive error handling const robustWorkflow = { name: "critical_operation", steps: [ { id: "critical_step", type: "agent_task", config: { message: "Perform critical operation", retry: { maxAttempts: 3, backoff: "exponential", initialDelay: 1000, maxDelay: 10000 }, timeout: 30000 // 30 second timeout }, onError: "handle_critical_failure", onTimeout: "handle_timeout" }, { id: "handle_critical_failure", type: "agent_task", config: { message: "Rollback changes and alert team" } }, { id: "handle_timeout", type: "agent_task", config: { message: "Log timeout and schedule retry" } } ] }; ``` ### State Management **Use Workflow Variables**: Store intermediate results in workflow variables for use in later steps. ```typescript theme={null} // Access results from previous steps const workflow = { name: "customer_lookup", steps: [ { id: "fetch_customer", type: "agent_task", config: { message: "Get customer {{customerId}}" }, output: "customer" // Store result in variable }, { id: "check_status", type: "decision", conditions: [ { when: "{{customer.status}} === 'active'", goto: "process_order" }, { when: "{{customer.status}} === 'inactive'", goto: "reactivate_account" } ] } ] }; ``` ### Testing Workflows ```typescript theme={null} // Test workflows before production async function testWorkflow() { const testInput = { customerId: "test_customer_123", amount: 100 }; try { const result = await agentbase.executeWorkflow({ workflow: myWorkflow, input: testInput, dryRun: true // Test mode - doesn't execute side effects }); console.log('Workflow validation:', result.validation); console.log('Expected steps:', result.executionPlan); } catch (error) { console.error('Workflow validation failed:', error); } } ``` ## Integration with Other Primitives ### With Custom Tools Use custom tools within workflow steps: ```typescript theme={null} const result = await agentbase.executeWorkflow({ workflow: orderWorkflow, input: { orderId: "123" }, mcpServers: [ { serverName: "payment-gateway", serverUrl: "https://api.company.com/payments" }, { serverName: "inventory-system", serverUrl: "https://api.company.com/inventory" } ] }); // Workflow steps can use payment and inventory tools ``` Learn more: [Custom Tools Primitive](/primitives/essentials/custom-tools) ### With Memory Maintain context across workflow executions: ```typescript theme={null} const result = await agentbase.executeWorkflow({ workflow: supportWorkflow, input: { ticketId: "456" }, memory: { namespace: `customer_${customerId}`, enabled: true } }); // Workflow can recall customer history and preferences ``` Learn more: [Memory Primitive](/primitives/extensions/memory) ### With Multi-Agent Delegate workflow steps to specialized agents: ```typescript theme={null} const workflow = { steps: [ { id: "legal_review", type: "agent_task", config: { message: "Review contract for legal compliance", agent: "legal_specialist" } }, { id: "financial_review", type: "agent_task", config: { message: "Review contract for financial terms", agent: "financial_specialist" } } ] }; ``` Learn more: [Multi-Agent Primitive](/primitives/essentials/multi-agents) ## Performance Considerations ### Execution Time * **Sequential Steps**: Execute one after another, total time is sum of all steps * **Parallel Steps**: Execute simultaneously, total time is longest branch * **Optimization**: Use parallel execution for independent operations ```typescript theme={null} // Sequential: 3 + 2 + 4 = 9 seconds total const sequential = { steps: [ { id: "step1", duration: 3000 }, { id: "step2", duration: 2000 }, { id: "step3", duration: 4000 } ] }; // Parallel: max(3, 2, 4) = 4 seconds total const parallel = { steps: [ { id: "parallel_steps", type: "parallel", branches: [ { id: "step1", duration: 3000 }, { id: "step2", duration: 2000 }, { id: "step3", duration: 4000 } ] } ] }; ``` ### State Persistence * **Checkpoint Frequency**: State saved after each step completion * **Storage Cost**: Minimal - workflow state is compact JSON * **Recovery**: Resume from last completed step on failure ### Timeout Management ```typescript theme={null} // Set appropriate timeouts for long-running steps { id: "ml_training", type: "agent_task", config: { message: "Train machine learning model", timeout: 3600000 // 1 hour timeout for long operation } } ``` ## Troubleshooting **Problem**: Workflow shows as running but not progressing **Solutions**: * Check if waiting for human approval * Verify timeout configurations aren't too long * Check agent logs for errors * Cancel and restart workflow if necessary ```typescript theme={null} // Check workflow status const status = await agentbase.getWorkflowStatus({ executionId: execution.id }); console.log('Current step:', status.currentStep); console.log('Waiting for:', status.waitingFor); // approval, timeout, etc. // Cancel if stuck if (status.status === 'stuck') { await agentbase.cancelWorkflow({ executionId: execution.id }); } ``` **Problem**: Workflow fails without executing error handler **Solutions**: * Ensure onError step ID exists in workflow * Check error handler step configuration * Add retry logic before error handling * Review error logs for root cause ```typescript theme={null} // Proper error handling configuration { id: "critical_step", type: "agent_task", config: { message: "Critical operation", retry: { maxAttempts: 3, backoff: "exponential" } }, onError: "handle_error", // Make sure this step exists! onTimeout: "handle_timeout" } ``` **Problem**: Decision steps not routing correctly **Solutions**: * Verify condition syntax is correct * Check variable names match step outputs * Add default fallback condition * Log variable values for debugging ```typescript theme={null} { id: "decision_step", type: "decision", conditions: [ { when: "{{amount}} > 1000", goto: "high_value_path" }, { when: "{{amount}} <= 1000", goto: "normal_path" }, { when: "true", // Fallback condition goto: "default_path" } ] } ``` **Problem**: Parallel execution times out before all branches complete **Solutions**: * Increase timeout for parallel step * Optimize slow branches * Consider sequential execution for long-running tasks * Add retry logic to individual branches ```typescript theme={null} { id: "parallel_operations", type: "parallel", config: { timeout: 300000, // 5 minutes for all branches waitForAll: true, // Wait for all to complete failFast: false // Don't fail if one branch fails }, branches: [ // Branches here ] } ``` ## Advanced Patterns ### Sub-Workflows Call workflows from within workflows: ```typescript theme={null} { id: "process_each_item", type: "loop", items: "{{order.items}}", workflow: itemProcessingWorkflow } ``` ### Dynamic Workflow Generation Generate workflows programmatically: ```typescript theme={null} function generateApprovalWorkflow(approvalLevels: string[]) { const steps = approvalLevels.map((level, index) => ({ id: `approval_${index}`, type: "human_approval", config: { approvers: [level], message: `Level ${index + 1} approval required` } })); return { name: "dynamic_approval", steps }; } const workflow = generateApprovalWorkflow([ "manager@company.com", "director@company.com", "vp@company.com" ]); ``` ### Compensation Patterns Rollback on failure: ```typescript theme={null} const sagaWorkflow = { steps: [ { id: "reserve_inventory", type: "agent_task", config: { message: "Reserve inventory items" }, compensation: "release_inventory" }, { id: "charge_payment", type: "agent_task", config: { message: "Charge customer payment" }, compensation: "refund_payment", onError: "run_compensations" // Trigger rollback }, { id: "release_inventory", type: "agent_task", config: { message: "Release inventory reservation" } }, { id: "refund_payment", type: "agent_task", config: { message: "Refund customer payment" } } ] }; ``` ## Related Primitives Coordinate multiple agents and workflows Run workflows asynchronously in background Use custom tools within workflow steps Trigger workflows from external events ## Additional Resources Complete workflow API documentation Common workflow design patterns Real-world workflow examples **Remember**: Workflows are most effective for multi-step processes with clear stages and decision points. For simple sequential tasks, direct agent execution may be more appropriate. # Overview Source: https://docs.agentbase.sh/primitives/overview Understanding the building blocks of Agentbase agents ## What Are Agent Primitives? Agent primitives are the fundamental building blocks that make up Agentbase agents. Understanding these primitives helps you build more sophisticated and capable agents. Execution environments where agents operate Core capabilities every agent needs Advanced features for specialized use cases ## Environment Primitives The runtime environment where agents execute tasks. Isolated, secure execution environment for each agent Persistent file storage and management Full Linux environment with shell access Web browser automation and interaction ## Essential Primitives Core capabilities that power agent functionality. * **[Prompts](/primitives/essentials/prompts)** - Natural language instructions and system prompts * **[Custom Tools](/primitives/essentials/custom-tools)** - Extend agent capabilities with your own tools * **[Hooks](/primitives/essentials/hooks)** - Event-driven triggers and callbacks * **[States](/primitives/essentials/states)** - Manage agent state and variables * **[Sessions](/primitives/essentials/sessions)** - Persistent conversations and context * **[Persistence](/primitives/essentials/persistence)** - Long-term data storage * **[Context Management](/primitives/essentials/context-management)** - Optimize context window usage * **[Multi-Agents](/primitives/essentials/multi-agents)** - Coordinate multiple agents * **[Parallelization](/primitives/essentials/parallelization)** - Run tasks concurrently * **[Background](/primitives/essentials/background)** - Long-running async operations * **[Self-Healing](/primitives/essentials/self-healing)** - Automatic error recovery * **[Self-Evolving](/primitives/essentials/self-evolving)** - Agents that improve over time * **[Versioning](/primitives/essentials/versioning)** - Track and manage agent versions * **[Traces](/primitives/essentials/traces)** - Detailed execution logs and debugging * **[Evals](/primitives/essentials/evals)** - Quality assurance and testing ## Extension Primitives Advanced features for specialized use cases. * **[Memory](/primitives/extensions/memory)** - Long-term memory and recall * **[RAG](/primitives/extensions/rag)** - Retrieval-Augmented Generation * **[Workflow](/primitives/extensions/workflow)** - Complex multi-step workflows * **[Orchestration](/primitives/extensions/orchestration)** - Coordinate complex agent systems * **[Data Connectors](/primitives/extensions/data-connectors)** - Connect to external data sources * **[Integrations](/primitives/extensions/integrations)** - Third-party service integrations * **[MCP](/primitives/extensions/mcp)** - Model Context Protocol support * **[Web Search](/primitives/extensions/web-search)** - Real-time web search * **[Crawl & Scrape](/primitives/extensions/crawl-scrape)** - Extract data from websites * **[OCR](/primitives/extensions/ocr)** - Extract text from images * **[Email](/primitives/extensions/email)** - Send and receive emails * **[Voice](/primitives/extensions/voice)** - Voice interaction and synthesis * **[Interface](/primitives/extensions/interface)** - UI components and widgets * **[Authentication](/primitives/extensions/authentication)** - User authentication and authorization * **[Tasks](/primitives/extensions/tasks)** - Structured task management * **[Skills](/primitives/extensions/skills)** - Reusable agent capabilities * **[Trigger](/primitives/extensions/trigger)** - Event-based automation * **[Scheduling](/primitives/extensions/scheduling)** - Time-based execution ## How Primitives Work Together Primitives combine to create powerful agent capabilities: ```mermaid theme={null} graph TB A[User Request] --> B[Prompts] B --> C[Agent Reasoning] C --> D[Custom Tools] D --> E[Environment] E --> F[Sandbox] E --> G[File System] E --> H[Browser] C --> I[Extensions] I --> J[Web Search] I --> K[RAG] I --> L[Memory] F --> M[Sessions] G --> M H --> M M --> N[Persistence] C --> O[Traces] O --> P[Response] ``` ### Example: Research Agent A research agent might use these primitives: User provides research query through natural language prompt Agent uses web search to find relevant sources Navigates to websites and extracts content Stores and retrieves information from documents Saves research findings and generates report Maintains context across multiple queries Logs all steps for debugging and optimization ## Choosing the Right Primitives Begin with essential primitives (prompts, sessions, file system) Incorporate extensions when requirements grow More primitives = more complexity (balance capability vs. efficiency) Use traces and evals to validate primitive interactions ## Common Patterns ### Pattern 1: Simple Task Execution **Primitives:** Prompts + Sandbox + Traces ```typescript theme={null} // Simple code execution const result = await agentbase.runAgent({ message: "Create a Python function to calculate fibonacci", mode: "base" }); ``` ### Pattern 2: Stateful Conversation **Primitives:** Prompts + Sessions + Context Management ```typescript theme={null} // Multi-turn conversation const result1 = await agentbase.runAgent({ message: "Analyze data.csv" }); const result2 = await agentbase.runAgent({ message: "Now create a visualization", session: result1.session }); ``` ### Pattern 3: Research & Analysis **Primitives:** Web Search + Browser + RAG + File System ```typescript theme={null} // Research task const result = await agentbase.runAgent({ message: "Research our top 3 competitors and create a comparison report", mode: "max" }); ``` ### Pattern 4: Automated Workflow **Primitives:** Scheduling + Tasks + Hooks + Email ```typescript theme={null} // Scheduled automation const result = await agentbase.runAgent({ message: "Check competitor pricing daily and email me if prices change", mode: "base" }); ``` ### Pattern 5: Multi-Agent System **Primitives:** Multi-Agents + Orchestration + Parallelization ```typescript theme={null} // Coordinated agents const result = await agentbase.runAgent({ message: "Use one agent to gather data and another to analyze it", mode: "max" }); ``` ## Learning Path Understand the [sandbox](/primitives/environment/sandbox), [file system](/primitives/environment/file-system), and [computer](/primitives/environment/computer) primitives Learn [prompts](/primitives/essentials/prompts), [sessions](/primitives/essentials/sessions), and [custom tools](/primitives/essentials/custom-tools) Explore extensions like [web search](/primitives/extensions/web-search), [RAG](/primitives/extensions/rag), and [memory](/primitives/extensions/memory) as needed Use [traces](/primitives/essentials/traces), [evals](/primitives/essentials/evals), and [versioning](/primitives/essentials/versioning) ## Next Steps Start with execution environments Learn core capabilities Explore advanced features See primitives in action # Python SDK Source: https://docs.agentbase.sh/resources/sdk/python Official Python SDK for the Agentbase API > The official Python SDK for seamless integration with Agentbase agents. ## Installation **[View on PyPI →](https://pypi.org/project/agentbase-sdk/)** ```bash theme={null} pip install agentbase-sdk ``` ## Quick Start ```python theme={null} from agentbase import Agentbase client = Agentbase(api_key="your-api-key") # Run an agent (root-level method) response = client.run_agent( message="Hello, analyze this data for me" ) # Or use the agent resource response2 = client.agent.run( message="Hello, analyze this data for me" ) # Handle streaming response for event in response: print(event) ``` ## Configuration ```python theme={null} from agentbase import Agentbase client = Agentbase( api_key="your-api-key", base_url="https://api.agentbase.sh", # optional timeout=30 # optional, in seconds ) ``` ## API Methods ### Root-Level Methods #### client.run\_agent() Run an agent directly from the root client: ```python theme={null} stream = client.run_agent( message="Your task here", # required session="session-id", # optional: continue conversation mode="base", # optional: "base" | "flash" | "max", defaults to "base" system="You are a helpful assistant", # optional: system prompt rules=["Be concise", "Show examples"], # optional: array of constraints workflows=[ # optional: declarative workflows { "id": "workflow_1", "name": "example_workflow", "description": "Example workflow description", "steps": [ { "id": "step_1", "name": "first_step", "description": "What this step should accomplish", "depends_on": [], "optional": False, # optional "retry_policy": { # optional "max_attempts": 3, "backoff": "exponential" }, "output_schema": { # optional "type": "object", "properties": { "result": {"type": "string"} } } } ] } ], mcp_servers=[ # optional: MCP server configs { "serverName": "my-api", "serverUrl": "https://api.example.com/mcp" } ], background=False, # optional: run agent asynchronously, defaults to False callback={ # optional: use with background=True "url": "https://your-server.com/webhook", "headers": { "Authorization": "Bearer your-token" } }, datastores=[ # optional: data sources for the agent { "id": "ds_1234567890abcdef", "name": "my-datastore" } ], queries=[ # optional: custom datastore queries { "name": "getUserById", "description": "Fetch user details by their ID", "query": "SELECT * FROM users WHERE id = ?" } ], streaming_tokens=False, # optional: stream tokens, defaults to False final_output={ # optional: structured final output "name": "task_summary", "strict": True, "schema": { "type": "object", "properties": { "summary": {"type": "string"}, "outcome": { "type": "string", "enum": ["success", "partial_success", "failure"] } }, "required": ["summary", "outcome"] } } ) ``` ### Agent Resource #### client.agent.run() Run an agent using the agent resource (accepts same parameters as `client.run_agent()`): ```python theme={null} stream = client.agent.run( message="Your task here", # required session="session-id", # optional mode="base", # optional system="You are a helpful assistant", # optional rules=["Be concise", "Show examples"], # optional workflows=[...], # optional mcp_servers=[...], # optional background=False, # optional callback={...}, # optional datastores=[...], # optional queries=[...], # optional streaming_tokens=False, # optional final_output={...} # optional ) ``` ### Messages Resource #### client.messages.get() Retrieve messages from an agent session: ```python theme={null} messages = client.messages.get(session="session-id") ``` #### client.messages.clear() Clear all messages from an agent session: ```python theme={null} result = client.messages.clear(session="session-id") ``` ## Error Handling ```python theme={null} from agentbase import Agentbase, AgentbaseError try: response = client.run_agent(message="Your task") except AgentbaseError as e: print(f"API Error: {e.message}") print(f"Status: {e.status}") except Exception as e: print(f"Unexpected error: {e}") ``` ## Type Hints ```python theme={null} from typing import List, Dict, Optional, Iterator, TypedDict, Any class WorkflowStep(TypedDict, total=False): id: str name: str description: str depends_on: List[str] optional: bool retry_policy: Dict[str, Any] output_schema: Dict[str, Any] class Workflow(TypedDict): id: str name: str description: str steps: List[WorkflowStep] class MCPServer(TypedDict): serverName: str serverUrl: str class CallbackConfig(TypedDict, total=False): url: str headers: Dict[str, str] class Datastore(TypedDict): id: str name: str class Query(TypedDict): name: str description: str query: str class FinalOutputConfig(TypedDict): name: str strict: bool schema: Dict[str, Any] class AgentEvent(TypedDict, total=False): type: str content: str session: str cost: str balance: float def run_agent( message: str, session: Optional[str] = None, mode: Optional[str] = None, system: Optional[str] = None, rules: Optional[List[str]] = None, workflows: Optional[List[Workflow]] = None, mcp_servers: Optional[List[MCPServer]] = None, background: bool = False, callback: Optional[CallbackConfig] = None, datastores: Optional[List[Datastore]] = None, queries: Optional[List[Query]] = None, streaming_tokens: bool = False, final_output: Optional[FinalOutputConfig] = None ) -> Iterator[AgentEvent]: pass ``` ## Examples ### Basic Chat ```python theme={null} chat = client.run_agent( message="What's the weather like today?" ) for event in chat: if event["type"] == "agent_message": print(f"Agent: {event['content']}") ``` ### With Session Continuity ```python theme={null} session_id = None # First message response1 = client.run_agent( message="Hello, I'm working on a Python project" ) for event in response1: if "session" in event: session_id = event["session"] # Continue conversation response2 = client.agent.run( message="Can you help me with async programming?", session=session_id ) ``` ### Cost Tracking ```python theme={null} total_cost = 0 response = client.run_agent( message="Analyze this dataset" ) for event in response: if event["type"] == "agent_cost": cost = float(event.get("cost", 0)) total_cost += cost print(f"Current cost: ${event['cost']}") print(f"Total spent: ${total_cost}") ``` ### Async Support ```python theme={null} import asyncio from agentbase import AsyncAgentbase async def main(): client = AsyncAgentbase(api_key="your-api-key") response = await client.run_agent( message="Analyze this data asynchronously" ) async for event in response: print(event) # Run the async function asyncio.run(main()) ``` ### Context Manager ```python theme={null} with Agentbase(api_key="your-api-key") as client: response = client.run_agent(message="Your task") for event in response: print(event) ``` ## Advanced Usage ### Custom HTTP Client ```python theme={null} import httpx from agentbase import Agentbase # Use custom HTTP client custom_http_client = httpx.Client(timeout=60) client = Agentbase( api_key="your-api-key", http_client=custom_http_client ) ``` ### Retry Configuration ```python theme={null} from agentbase import Agentbase from agentbase.retry import RetryConfig client = Agentbase( api_key="your-api-key", retry_config=RetryConfig( max_retries=3, backoff_factor=1.5 ) ) ``` ## Resources * **GitHub Repository**: [agentbase-python](https://github.com/AgentbaseHQ/agentbase-python) * **PyPI Package**: [agentbase-sdk](https://pypi.org/project/agentbase-sdk/) * **Issues & Support**: [GitHub Issues](https://github.com/AgentbaseHQ/agentbase-python/issues) ## What's Next? Use Agentbase with TypeScript/JavaScript Complete API documentation See more integration examples # React SDK Source: https://docs.agentbase.sh/resources/sdk/react Official React SDK for building agent interfaces with Agentbase > The official React SDK for building interactive agent interfaces with hooks and components. ## Installation ```bash theme={null} npm install @agentbase-sdk/react # or yarn add @agentbase-sdk/react ``` ## Quick Start ### 1. Create a Server-Side API Route The React SDK calls a server-side endpoint to keep your Agentbase API key secure. Here's an example using Next.js App Router: ```typescript theme={null} // app/api/agent/route.ts import Agentbase from "agentbase-sdk"; import { NextRequest } from "next/server"; // Initialize Agentbase client (reuse across requests) const agentbase = new Agentbase({ apiKey: process.env.AGENTBASE_API_KEY!, }); export const runtime = "edge"; // Optional: Use Edge Runtime for better performance export async function POST(req: NextRequest) { try { // Parse request body const body = await req.json(); const { message, session, system, mode = "fast", rules, mcp_servers, agents, streaming_tokens = false, } = body; // Validate required fields if (!message) { return new Response("Message is required", { status: 400 }); } // Prepare Agentbase parameters const params: any = { message, mode, streaming_tokens, }; if (session) params.session = session; if (system) params.system = system; if (rules) params.rules = rules; if (mcp_servers) params.mcp_servers = mcp_servers; if (agents) params.agents = agents; // Create a TransformStream to convert async iterator to ReadableStream const encoder = new TextEncoder(); const stream = new TransformStream(); const writer = stream.writable.getWriter(); // Start streaming in the background (async () => { try { const responseStream = await agentbase.runAgent(params); for await (const response of responseStream) { // Format as Server-Sent Events const data = `data: ${JSON.stringify(response)}\n\n`; await writer.write(encoder.encode(data)); } await writer.close(); } catch (error) { console.error("Streaming error:", error); await writer.abort(error); } })(); // Return the stream as SSE return new Response(stream.readable, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", Connection: "keep-alive", }, }); } catch (error) { console.error("Chat API error:", error); return new Response("Internal server error", { status: 500 }); } } ``` ### 2. Use the useAgent Hook in Your Component ```typescript theme={null} "use client"; import { useAgent } from "@agentbase-sdk/react"; import { useState } from "react"; export default function Chat() { const [input, setInput] = useState(""); const { messages, send, stop, clear, isRunning, error, session } = useAgent({ api: "/api/agent", system: "You are a helpful AI assistant. Be concise and friendly.", mode: "fast", onError: (error) => { console.error("Agent error:", error); }, }); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (!input.trim() || isRunning) return; send(input); setInput(""); }; return (
{/* Session Info */} {session &&
Session: {session.substring(0, 8)}...
} {/* Error Display */} {error &&
Error: {error.message}
} {/* Messages */}
{messages.map((message, msgIndex) => (
{message.role === "user" ? "You" : "Assistant"}: {/* Render all content items */} {message.content.map((item, index) => (
{item.type === "text" && (
{item.text}
)} {item.type === "thinking" && (
💭 {item.text}
)} {item.type === "tool_use" && (
🔧 Tool Use:
{item.text}
)} {item.type === "tool_response" && (
✅ Tool Result:
{item.text}
)} {item.type === "transfer" && (
🔄 Transferred to: {item.agent} {item.context &&
{item.context}
}
)}
))}
))} {/* Loading indicator */} {isRunning &&
...
}
{/* Controls */} {/* Input Form */}
setInput(e.target.value)} placeholder="Type your message..." disabled={isRunning} /> {isRunning ? ( ) : ( )}
); } ``` ## API Reference ### useAgent(options) The main hook for building agent interfaces. #### Options ```typescript theme={null} interface UseAgentOptions { // Required: API endpoint to call api: string; // Optional: System prompt for the agent system?: string; // Optional: Agent mode (default: "fast") mode?: "flash" | "fast" | "max"; // Optional: Rules for the agent rules?: string[]; // Optional: MCP servers configuration mcpServers?: Array<{ serverName: string; serverUrl: string; }>; // Optional: Agent handoffs for multi-agent flows agents?: Array<{ name: string; description?: string; }>; // Optional: Stream tokens individually streamingTokens?: boolean; // Optional: Initial messages initialMessages?: Message[]; // Optional: Error callback onError?: (error: Error) => void; // Optional: Custom headers and body headers?: Record; body?: Record; } ``` #### Returns ```typescript theme={null} interface UseAgentReturn { // Message history messages: Message[]; // Send a message to the agent send: (message: string) => Promise; // Stop the current agent run stop: () => void; // Clear all messages (locally and on server) clear: () => Promise; // State isRunning: boolean; error: Error | null; session: string | null; } ``` ### Message Types The hook handles various message types from the agent: ```typescript theme={null} interface Message { role: "user" | "assistant"; content: ContentItem[]; } type ContentItem = | { type: "text"; text: string } | { type: "thinking"; text: string } | { type: "tool_use"; text: string } | { type: "tool_response"; text: string } | { type: "transfer"; agent: string; context?: string }; ``` ## Examples ### Basic Chat Interface ```typescript theme={null} "use client"; import { useAgent } from "@agentbase-sdk/react"; import { useState } from "react"; export default function BasicChat() { const [input, setInput] = useState(""); const { messages, send, isRunning } = useAgent({ api: "/api/agent", }); return (
{messages.map((msg, i) => (
{msg.role}: {msg.content.map((item, j) => ( {item.type === "text" && item.text} ))}
))}
{ e.preventDefault(); send(input); setInput(""); }}> setInput(e.target.value)} disabled={isRunning} />
); } ``` ### With System Prompt and Rules ```typescript theme={null} const { messages, send } = useAgent({ api: "/api/agent", system: "You are a coding assistant specializing in React.", mode: "max", rules: [ "Always explain your code changes", "Use TypeScript when possible", "Follow React best practices" ], }); ``` ### Multi-Agent Handoffs ```typescript theme={null} const { messages, send } = useAgent({ api: "/api/agent", system: "You are a customer support agent.", agents: [ { name: "technical_support", description: "Handles technical issues and debugging" }, { name: "billing_support", description: "Handles billing and payment questions" } ], }); ``` ### With Error Handling ```typescript theme={null} const { messages, send, error } = useAgent({ api: "/api/agent", onError: (error) => { console.error("Agent error:", error); // Custom error handling logic }, }); // Display errors in UI {error && (
Error: {error.message}
)} ``` ### Session Persistence ```typescript theme={null} const { session, messages } = useAgent({ api: "/api/agent", }); // Session ID is automatically managed // Use it to track conversations useEffect(() => { if (session) { console.log("Current session:", session); } }, [session]); ``` ## Resources * **GitHub Repository**: [@agentbase-sdk/react](https://github.com/AgentbaseHQ/agentbase-sdk) * **NPM Package**: [@agentbase-sdk/react](https://www.npmjs.com/package/@agentbase-sdk/react) ## What's Next? Server-side TypeScript integration Use Agentbase with Python Complete API documentation # TypeScript SDK Source: https://docs.agentbase.sh/resources/sdk/typescript Official TypeScript/JavaScript SDK for the Agentbase API > The official TypeScript SDK for seamless integration with Agentbase agents. ## Installation ```bash theme={null} npm install agentbase-sdk # or yarn add agentbase-sdk ``` ## Quick Start ```typescript theme={null} import { Agentbase } from "agentbase-sdk"; const client = new Agentbase({ apiKey: "your-api-key", }); // Run an agent (root-level method) const response = await client.runAgent({ message: "Hello, analyze this data for me", }); // Or use the agent resource const response2 = await client.agent.run({ message: "Hello, analyze this data for me", }); // Handle streaming response for await (const event of response) { console.log(event); } ``` ## Configuration ```typescript theme={null} const client = new Agentbase({ apiKey: "your-api-key", baseURL: "https://api.agentbase.sh", // optional timeout: 30000, // optional, in milliseconds }); ``` ## API Methods ### Root-Level Methods #### client.runAgent() Run an agent directly from the root client: ```typescript theme={null} const stream = await client.runAgent({ message: "Your task here", // required session: "session-id", // optional: continue conversation mode: "fast", // optional: "fast" | "flash" | "max", defaults to "fast" system: "You are a helpful assistant", // optional: system prompt rules: ["Be concise", "Show examples"], // optional: array of constraints workflows: [ // optional: declarative workflows { id: "workflow_1", name: "example_workflow", description: "Example workflow description", steps: [ { id: "step_1", name: "first_step", description: "What this step should accomplish", depends_on: [], optional: false, // optional retry_policy: { // optional max_attempts: 3, backoff: "exponential", }, output_schema: { // optional type: "object", properties: { result: { type: "string" }, }, }, }, ], }, ], mcp_servers: [ // optional: MCP server configs { serverName: "my-api", serverUrl: "https://api.example.com/mcp", }, ], background: false, // optional: run agent asynchronously, defaults to false callback: { // optional: use with background: true url: "https://your-server.com/webhook", headers: { Authorization: "Bearer your-token", }, }, datastores: [ // optional: data sources for the agent { id: "ds_1234567890abcdef", name: "my-datastore", }, ], queries: [ // optional: custom datastore queries { name: "getUserById", description: "Fetch user details by their ID", query: "SELECT * FROM users WHERE id = ?", }, ], streaming_tokens: false, // optional: stream tokens, defaults to false final_output: { // optional: structured final output name: "task_summary", strict: true, schema: { type: "object", properties: { summary: { type: "string" }, outcome: { type: "string", enum: ["success", "partial_success", "failure"], }, }, required: ["summary", "outcome"], }, }, }); ``` ### Agent Resource #### client.agent.run() Run an agent using the agent resource (accepts same parameters as `client.runAgent()`): ```typescript theme={null} const stream = await client.agent.run({ message: "Your task here", // required session: "session-id", // optional mode: "fast", // optional system: "You are a helpful assistant", // optional rules: ["Be concise", "Show examples"], // optional workflows: [...], // optional mcp_servers: [...], // optional background: false, // optional callback: {...}, // optional datastores: [...], // optional queries: [...], // optional streaming_tokens: false, // optional final_output: {...} // optional }); ``` ### Messages Resource #### client.messages.get() Retrieve messages from an agent session: ```typescript theme={null} const messages = await client.messages.get({ session: "session-id", }); ``` #### client.messages.clear() Clear all messages from an agent session: ```typescript theme={null} const result = await client.messages.clear({ session: "session-id", }); ``` ## Error Handling ```typescript theme={null} try { const response = await client.runAgent({ message: "Your task", }); } catch (error) { if (error instanceof AgentbaseError) { console.error("API Error:", error.message); console.error("Status:", error.status); } else { console.error("Unexpected error:", error); } } ``` ## TypeScript Types ```typescript theme={null} interface RunAgentParams { message: string; session?: string; mode?: "fast" | "flash" | "max"; system?: string; rules?: string[]; workflows?: Workflow[]; mcp_servers?: MCPServer[]; background?: boolean; callback?: CallbackConfig; datastores?: Datastore[]; queries?: Query[]; streaming_tokens?: boolean; final_output?: FinalOutputConfig; } interface Workflow { id: string; name: string; description: string; steps: WorkflowStep[]; } interface WorkflowStep { id: string; name: string; description: string; depends_on: string[]; optional?: boolean; retry_policy?: { max_attempts: number; backoff: "linear" | "exponential"; }; output_schema?: Record; } interface MCPServer { serverName: string; serverUrl: string; } interface CallbackConfig { url: string; headers?: Record; } interface Datastore { id: string; name: string; } interface Query { name: string; description: string; query: string; } interface FinalOutputConfig { name: string; strict: boolean; schema: Record; } interface AgentEvent { type: string; content?: string; session?: string; cost?: string; balance?: number; } ``` ## Examples ### Basic Chat ```typescript theme={null} const chat = await client.runAgent({ message: "What's the weather like today?", }); for await (const event of chat) { if (event.type === "agent_message") { console.log("Agent:", event.content); } } ``` ### With Session Continuity ```typescript theme={null} let sessionId: string | undefined; // First message const response1 = await client.runAgent({ message: "Hello, I'm working on a React project", }); for await (const event of response1) { if (event.session) sessionId = event.session; } // Continue conversation const response2 = await client.agent.run({ message: "Can you help me with state management?", session: sessionId, }); ``` ### Cost Tracking ```typescript theme={null} let totalCost = 0; const response = await client.runAgent({ message: "Analyze this dataset", }); for await (const event of response) { if (event.type === "agent_cost") { totalCost += parseFloat(event.cost || "0"); console.log(`Current cost: $${event.cost}`); console.log(`Total spent: $${totalCost}`); } } ``` ## Resources * **GitHub Repository**: [agentbase-sdk](https://github.com/AgentbaseHQ/agentbase-sdk) * **NPM Package**: [agentbase-sdk](https://www.npmjs.com/package/agentbase-sdk) * **Issues & Support**: [GitHub Issues](https://github.com/AgentbaseHQ/agentbase-sdk/issues) ## What's Next? Use Agentbase with Python Complete API documentation See more integration examples