# Astreus AI Documentation - Full Text Generated for Large Language Models URL: https://astreus.org/llms-full.txt Total Documents: 42 *** # Commands URL: /docs/cli/commands Source: /app/src/content/docs/cli/commands.mdx Complete reference for all Astreus CLI commands and keyboard shortcuts. Use these commands to manage your agent development sessions, switch models, and organize your workflow. ## Slash Commands | Command | Description | | -------------------- | -------------------------------------------------------- | | `/model [name]` | Change the AI model (opens selector if no name given) | | `/provider [name]` | Change the AI provider (opens selector if no name given) | | `/sessions` | Open session manager | | `/new` | Start a new chat session | | `/attach ` | Attach a file or folder | | `/attachments` | Show current attachments | | `/clear-attachments` | Clear all attachments | | `/pwd` | Show current working directory | | `/tools` | Show registered tools | | `/graph` | Show graph/session state | | `/settings` | Open settings panel | | `/clear` | Clear chat history | | `/help` | Show available commands | | `/exit` | Exit the CLI | ## Command Aliases For faster typing, you can use these shortcuts: | Alias | Full Command | | --------------- | -------------------- | | `/session` | `/sessions` | | `/add` or `/a` | `/attach` | | `/ca` | `/clear-attachments` | | `/status` | `/graph` | | `/quit` or `/q` | `/exit` | ## Keyboard Shortcuts | Shortcut | Action | | -------- | --------------------------------------- | | `Ctrl+C` | Exit CLI | | `Escape` | Cancel current operation | | `↑/↓` | Navigate command history or suggestions | | `Tab` | Autocomplete command | | `?` | Toggle command shortcuts display | ## Built-in File Tools The CLI provides powerful file system tools for managing your agent projects. The AI uses these to create agents, plugins, configurations, and modify your code: | Tool | Description | | ------------------ | ------------------------------------------------------- | | `read_file` | Read the contents of a file | | `write_file` | Write content to a file (creates directories if needed) | | `edit_file` | Edit a file by replacing specific content | | `list_directory` | List contents of a directory | | `create_directory` | Create a new directory | | `delete_file` | Delete a file or directory | | `move_file` | Move or rename a file or directory | | `search_files` | Search for files by name pattern | ## Session Management ### View Sessions ``` /sessions ``` Opens the session manager where you can: * View all saved sessions * Switch between sessions * Delete old sessions * See session metadata (date, messages, model) ### Start New Session ``` /new ``` Creates a fresh session while preserving the previous one. ### Session Auto-Save All conversations are automatically saved. When you restart the CLI, you can resume where you left off. ## File Attachments ### Attach a File ``` /attach ./src/index.ts ``` Attaches a file to the conversation context. The AI can read and reference this file. ### Attach a Folder ``` /attach ./src ``` Attaches an entire folder. When a folder is attached, it becomes the working directory for file operations. ### Drag and Drop You can also drag and drop file paths directly into the terminal. ### View Attachments ``` /attachments ``` Shows all currently attached files and folders. ### Clear Attachments ``` /clear-attachments ``` Or use the shortcut: ``` /ca ``` ## Model Switching ### Quick Switch ``` /model gpt-4o ``` Switches to the specified model immediately. ### Interactive Selection ``` /model ``` Opens an interactive model selector with all available models for the current provider. ### Change Provider ``` /provider claude ``` Switches to a different provider. You'll need the appropriate API key configured. ## Example Session: Building an Agent ``` You: /attach ./my-agent Attached folder: ./my-agent (working directory set) You: What's the current agent configuration? Astreus: Let me check the project structure. [Tool: list_directory] Listing ./my-agent... [Tool: read_file] Reading ./my-agent/src/agent.ts... This is an Astreus agent project with: - Agent configured with GPT-4o model - Memory enabled for conversation persistence - No knowledge base configured yet - No custom plugins You: Add a knowledge base and ingest our docs folder Astreus: I'll add knowledge base support to your agent. [Tool: edit_file] Updating ./my-agent/src/agent.ts... [Tool: write_file] Creating ./my-agent/src/ingest-docs.ts... Done! I've updated your agent with: - Knowledge base enabled in agent config - Created ingest-docs.ts script to load your documentation - Run `npx ts-node src/ingest-docs.ts` to ingest docs You: Create a plugin for fetching weather data Astreus: I'll create a weather plugin for your agent. [Tool: create_directory] Creating ./my-agent/src/plugins... [Tool: write_file] Creating ./my-agent/src/plugins/weather.ts... [Tool: edit_file] Updating ./my-agent/src/agent.ts to register plugin... Done! Weather plugin created with: - get_weather tool for current conditions - get_forecast tool for 5-day forecast - Proper TypeScript types and error handling - Registered in your agent configuration ``` ## Example Session: Scaffolding a New Agent ``` You: Create a code review agent that can analyze PRs Astreus: I'll create a complete code review agent project. [Tool: create_directory] Creating ./code-review-agent... [Tool: write_file] Creating package.json... [Tool: write_file] Creating tsconfig.json... [Tool: write_file] Creating .env.example... [Tool: write_file] Creating src/agent.ts... [Tool: write_file] Creating src/index.ts... [Tool: write_file] Creating src/plugins/github.ts... Done! Code review agent created with: - Claude model (better for code analysis) - GitHub plugin for PR fetching - Memory for tracking reviewed PRs - System prompt optimized for code review Run these commands to get started: cd code-review-agent npm install cp .env.example .env # Add your API keys npm run dev ``` *** # Configuration URL: /docs/cli/configuration Source: /app/src/content/docs/cli/configuration.mdx Configure Astreus CLI with environment variables for full customization. These settings control both the CLI itself and the underlying Astreus framework features you can use during agent development. ## Environment Setup Create a `.env` file in your home directory or export variables in your shell profile. ## Complete Configuration ```bash # ===== CLI SETTINGS ===== # Default provider and model ASTREUS_PROVIDER=openai # openai, claude, gemini, ollama ASTREUS_MODEL=gpt-4o # Default model name # ===== LLM PROVIDERS API KEYS ===== # OpenAI OPENAI_API_KEY=sk-your-openai-api-key-here OPENAI_VISION_API_KEY=sk-your-vision-api-key-here # Optional OPENAI_EMBEDDING_API_KEY=sk-your-embedding-api-key # Optional # Anthropic Claude ANTHROPIC_API_KEY=your-anthropic-api-key-here ANTHROPIC_VISION_API_KEY=your-vision-api-key-here # Optional # Google Gemini GEMINI_API_KEY=your-gemini-api-key-here GEMINI_VISION_API_KEY=your-vision-api-key-here # Optional GEMINI_EMBEDDING_API_KEY=your-embedding-api-key # Optional # Ollama (for local models) OLLAMA_HOST=http://localhost:11434 # ===== DATABASE CONFIGURATION ===== # Main Application Database (Agents, Memory, Tasks, etc.) DB_URL=sqlite://./astreus.db # PostgreSQL (production recommended) # DB_URL=postgresql://username:password@localhost:5432/astreus_db # ===== KNOWLEDGE/RAG SYSTEM ===== # Knowledge Vector Database (PostgreSQL with pgvector required) KNOWLEDGE_DB_URL=postgresql://username:password@localhost:5432/knowledge_db # ===== APPLICATION SETTINGS ===== NODE_ENV=development # development | production | test LOG_LEVEL=info # debug | info | warn | error | silent # ===== DATABASE ENCRYPTION ===== ENCRYPTION_ENABLED=true ENCRYPTION_MASTER_KEY=your-256-bit-encryption-key-here ENCRYPTION_ALGORITHM=aes-256-gcm ``` ## Required Variables At minimum, you need one LLM provider API key: ```bash # Choose one: export OPENAI_API_KEY=sk-... # or export ANTHROPIC_API_KEY=... # or export GEMINI_API_KEY=... # or just run Ollama locally ``` ## Default Provider & Model Set your preferred defaults: ```bash # Always start with Claude export ASTREUS_PROVIDER=claude export ASTREUS_MODEL=claude-sonnet-4-20250514 # Or start with local Ollama export ASTREUS_PROVIDER=ollama export ASTREUS_MODEL=llama3 ``` ## Database Configuration ### SQLite (Default) For local development, SQLite works out of the box: ```bash DB_URL=sqlite://./astreus.db ``` ### PostgreSQL (Production) For production or shared environments: ```bash DB_URL=postgresql://user:password@localhost:5432/astreus_db ``` ### Knowledge Database If using RAG/Knowledge features, you need PostgreSQL with pgvector: ```bash KNOWLEDGE_DB_URL=postgresql://user:password@localhost:5432/knowledge_db ``` ## Security Settings ### Encryption Enable encryption for sensitive data: ```bash ENCRYPTION_ENABLED=true ENCRYPTION_MASTER_KEY=your-256-bit-key-here ENCRYPTION_ALGORITHM=aes-256-gcm ``` Generate a secure key: ```bash openssl rand -hex 32 ``` ### Logging Control log verbosity: ```bash # Options: debug | info | warn | error | silent LOG_LEVEL=info ``` ## Shell Profile Setup Add to your `~/.bashrc`, `~/.zshrc`, or `~/.profile`: ```bash # Astreus CLI Configuration export OPENAI_API_KEY="sk-your-key" export ASTREUS_PROVIDER="openai" export ASTREUS_MODEL="gpt-4o" ``` Then reload: ```bash source ~/.zshrc # or ~/.bashrc ``` ## Verify Configuration Check your configuration: ```bash # Start CLI and check settings astreus /settings ``` This opens the settings panel showing your current configuration. ## Agent Development Workflow For the best agent development experience: ### 1. Set Up Multiple Providers Configure multiple API keys so you can test your agents across different LLMs: ```bash # All providers configured export OPENAI_API_KEY="sk-..." export ANTHROPIC_API_KEY="sk-ant-..." export GEMINI_API_KEY="..." ``` ### 2. Use Project Attachments When working on an agent project, attach the folder for full context: ```bash astreus /attach ./my-agent-project ``` The CLI will understand your project structure, existing code, and configurations. ### 3. Iterate with Sessions Your development sessions are automatically saved. Return to continue where you left off: ```bash astreus /sessions # See and restore previous sessions ``` ### 4. Test Different Models Once your agent code is generated, test how it behaves with different underlying models: ```bash /provider claude # Test with Claude /provider openai # Test with GPT-4o /provider ollama # Test locally ``` *** # Installation URL: /docs/cli/installation Source: /app/src/content/docs/cli/installation.mdx Get Astreus CLI up and running in minutes. The CLI is your AI-powered assistant for building agents with the Astreus framework. ## Requirements * Node.js >= 22.0.0 * One of the supported LLM provider API keys * Familiarity with the [Astreus framework](/docs/framework/intro) ## Install Globally Install Astreus CLI globally using npm: ```bash npm install -g @astreus-ai/astreus-cli ``` Or with pnpm: ```bash pnpm add -g @astreus-ai/astreus-cli ``` Or with yarn: ```bash yarn global add @astreus-ai/astreus-cli ``` ## Run Without Installing You can also run directly with npx: ```bash npx @astreus-ai/astreus-cli ``` ## Quick Start 1. Set up your API key: ```bash export OPENAI_API_KEY=your-api-key ``` 2. Start the CLI: ```bash astreus ``` 3. Start chatting with your AI agent! ## Usage Options ```bash # Start the interactive CLI astreus # Start with a specific provider via environment variable ASTREUS_PROVIDER=claude astreus # Start with a specific model via environment variable ASTREUS_MODEL=gpt-4o astreus # Combine provider and model ASTREUS_PROVIDER=claude ASTREUS_MODEL=claude-sonnet-4-20250514 astreus ``` ## Verify Installation Check that Astreus CLI is installed correctly: ```bash astreus --version ``` ## Next Steps * [Commands](/docs/cli/commands) - Learn all available commands * [Providers](/docs/cli/providers) - Configure different LLM providers * [Configuration](/docs/cli/configuration) - Set up environment variables *** # Introduction URL: /docs/cli/intro Source: /app/src/content/docs/cli/intro.mdx AI-powered development assistant for building agents with the Astreus framework. The CLI helps you create, test, and iterate on AI agents directly from your terminal - with full knowledge of the Astreus SDK. ## Why Astreus CLI? The Astreus CLI is designed for developers who know the Astreus framework and want to accelerate their agent development workflow. It provides: * **Astreus SDK Expert** - The AI understands the complete Astreus framework: Agent creation, memory, knowledge base, plugins, MCP, sub-agents, graphs, and more * **Project Scaffolding** - Generate complete agent projects with proper structure, types, and configurations * **Code Generation** - Create agents, plugins, tools, and integrations with production-ready code * **Multi-Provider Testing** - Switch between OpenAI, Claude, Gemini, and local models to test your agents * **File Operations** - AI can read, write, and edit your project files directly * **Session Persistence** - Continue agent development across multiple sessions ## Who Is This For? The CLI is built for developers who: * Are familiar with the [Astreus framework](/docs/framework/intro) and want to build AI agents * Want an AI assistant that understands Astreus patterns and best practices * Need to quickly scaffold agent projects or generate boilerplate code * Want to iterate on agent configurations and test different approaches ## Quick Example ```bash # Install and start npm install -g @astreus-ai/astreus-cli export OPENAI_API_KEY=your-api-key astreus ``` ``` You: Create a customer support agent with memory and a knowledge base for our FAQ Astreus: I'll create a customer support agent for you. [Tool: list_directory] Checking current directory... [Tool: create_directory] Creating src/... [Tool: write_file] Creating src/agent.ts... [Tool: write_file] Creating src/index.ts... [Tool: write_file] Creating package.json... [Tool: write_file] Creating .env.example... Done! I've created a complete customer support agent with: - Memory enabled for conversation history - Knowledge base setup for FAQ documents - Streaming responses configured - TypeScript with proper types Run `npm install && npm run dev` to start the agent. ``` ## What Can You Build? | Use Case | CLI Helps You With | | --------------------- | ---------------------------------------------------------------- | | Conversational Agents | Memory configuration, context management, streaming setup | | RAG Agents | Knowledge base integration, document ingestion, retrieval tuning | | Tool-Using Agents | Plugin creation, tool definitions, handler implementations | | Multi-Agent Systems | Sub-agent coordination, graph workflows, task delegation | | MCP Integrations | Server configuration, tool discovery, capability mapping | ## Key Features | Feature | Description | | ------------------- | ------------------------------------------------------- | | Framework Knowledge | Built-in understanding of Astreus SDK patterns and APIs | | Code Generation | Create agents, plugins, and complete projects | | Multi-Provider | Test with OpenAI, Claude, Gemini, or Ollama | | File Tools | Read, write, edit project files directly | | Session Memory | Continue development across sessions | | Project Context | Attach folders to give AI full project awareness | ## Next Steps * [Installation](/docs/cli/installation) - Get started with installation * [Commands](/docs/cli/commands) - Learn all available commands * [Providers](/docs/cli/providers) - Configure LLM providers * [Framework Docs](/docs/framework/intro) - Learn the Astreus framework *** # Providers URL: /docs/cli/providers Source: /app/src/content/docs/cli/providers.mdx Astreus CLI supports multiple LLM providers. Switch between them seamlessly to test your agents with different models and find the best fit for your use case. ## Supported Providers ### OpenAI The default provider with access to GPT models. ```bash export OPENAI_API_KEY=sk-your-api-key astreus ``` **Available Models:** * `gpt-4o` (default) - Most capable * `gpt-4o-mini` - Fast and efficient * `gpt-4-turbo` - GPT-4 Turbo * `gpt-4` - Original GPT-4 * `gpt-3.5-turbo` - Fast and cost-effective ### Anthropic (Claude) Access Claude models for nuanced conversations. ```bash export ANTHROPIC_API_KEY=your-api-key ASTREUS_PROVIDER=claude astreus ``` **Available Models:** * `claude-sonnet-4-20250514` (default) - Claude Sonnet 4 * `claude-3-5-sonnet-20241022` - Claude 3.5 Sonnet ### Google (Gemini) Use Google's Gemini models. ```bash export GEMINI_API_KEY=your-api-key ASTREUS_PROVIDER=gemini astreus ``` **Available Models:** * `gemini-pro` (default) - Gemini Pro * `gemini-pro-vision` - Vision capable ### Ollama (Local Models) Run models locally with Ollama. No API key required. ```bash # Make sure Ollama is running ollama serve # Start CLI with Ollama ASTREUS_PROVIDER=ollama astreus ``` **Available Models:** * `llama3` (default) - Llama 3 * `llama2` - Llama 2 * `mistral` - Mistral * `codellama` - Code-focused Llama ## Switching Providers ### At Startup Use environment variables: ```bash ASTREUS_PROVIDER=claude ASTREUS_MODEL=claude-sonnet-4-20250514 astreus ``` ### During Session Use slash commands to switch: ``` /provider claude /model claude-sonnet-4-20250514 ``` Or open the interactive selector: ``` /provider /model ``` ## Provider Configuration ### Custom Endpoints For enterprise deployments or proxies: ```bash # Ollama on different host export OLLAMA_HOST=http://192.168.1.100:11434 ``` ### Vision Support Some providers support vision (image) capabilities: ```bash # Separate API key for vision (optional) export OPENAI_VISION_API_KEY=sk-your-vision-key export ANTHROPIC_VISION_API_KEY=your-vision-key export GEMINI_VISION_API_KEY=your-vision-key ``` ### Embedding Support For memory and knowledge features: ```bash export OPENAI_EMBEDDING_API_KEY=sk-your-embedding-key export GEMINI_EMBEDDING_API_KEY=your-embedding-key ``` ## Model Selection for Agent Development Choose the right model based on the type of agent you're building: | Agent Type | Recommended Model | Why | | ----------------------- | ------------------------------------ | ------------------------------------------------------ | | Code Analysis Agent | `claude-sonnet-4-20250514` | Excellent at understanding code structure and patterns | | Complex Reasoning Agent | `gpt-4o`, `claude-sonnet-4-20250514` | Best for multi-step reasoning and planning | | Fast Response Agent | `gpt-4o-mini`, `gemini-pro` | Low latency for real-time interactions | | Tool-Heavy Agent | `gpt-4o` | Reliable function calling and tool use | | Long Context Agent | `claude-sonnet-4-20250514` | 200k context window for large documents | | Local/Private Agent | `llama3`, `codellama` | No data leaves your machine | | Cost-Sensitive Agent | `gpt-3.5-turbo`, Ollama | Minimize API costs | ## Testing Agents Across Providers When building agents, it's useful to test with different providers: ``` # Start developing with fast, cheap model /provider openai /model gpt-4o-mini # Test complex reasoning with top models /provider claude /model claude-sonnet-4-20250514 # Test locally before deployment /provider ollama /model llama3 ``` This workflow helps you understand how your agent performs across different LLMs and find the best balance of capability, speed, and cost for your use case. *** # Configuration URL: /docs/create/configuration Source: /app/src/content/docs/create/configuration.mdx Environment variables and configuration options for your Astreus agent project. ## Environment Setup After creating your project, copy the example environment file: ```bash cp .env.example .env ``` Then edit `.env` with your configuration. ## Provider-Specific Configuration The generated `.env.example` depends on your selected provider: ### OpenAI ```bash OPENAI_API_KEY=your-api-key-here ``` ### Anthropic ```bash ANTHROPIC_API_KEY=your-api-key-here ``` ### Google Gemini ```bash GEMINI_API_KEY=your-api-key-here ``` ### Ollama ```bash # Ollama runs locally, no API key needed OLLAMA_HOST=http://localhost:11434 ``` ### Multiple Providers ```bash # Add API keys for providers you want to use OPENAI_API_KEY=your-openai-key ANTHROPIC_API_KEY=your-anthropic-key GEMINI_API_KEY=your-gemini-key ``` ## Complete Configuration For production deployments, you may need additional configuration: ```bash # ===== LLM PROVIDERS API KEYS ===== # OpenAI OPENAI_API_KEY=sk-your-openai-api-key-here OPENAI_VISION_API_KEY=sk-your-vision-api-key-here # Optional OPENAI_EMBEDDING_API_KEY=sk-your-embedding-api-key # Optional # Anthropic Claude ANTHROPIC_API_KEY=your-anthropic-api-key-here ANTHROPIC_VISION_API_KEY=your-vision-api-key-here # Optional # Google Gemini GEMINI_API_KEY=your-gemini-api-key-here GEMINI_VISION_API_KEY=your-vision-api-key-here # Optional GEMINI_EMBEDDING_API_KEY=your-embedding-api-key # Optional # Ollama (for local models) OLLAMA_HOST=http://localhost:11434 # ===== DATABASE CONFIGURATION ===== # Main Application Database (Agents, Memory, Tasks, etc.) DB_URL=sqlite://./astreus.db # PostgreSQL (production recommended) # DB_URL=postgresql://username:password@localhost:5432/astreus_db # ===== KNOWLEDGE/RAG SYSTEM ===== # Knowledge Vector Database (PostgreSQL with pgvector required) KNOWLEDGE_DB_URL=postgresql://username:password@localhost:5432/knowledge_db # ===== APPLICATION SETTINGS ===== NODE_ENV=development # development | production | test LOG_LEVEL=info # debug | info | warn | error | silent # ===== DATABASE ENCRYPTION ===== ENCRYPTION_ENABLED=true ENCRYPTION_MASTER_KEY=your-256-bit-encryption-key-here ENCRYPTION_ALGORITHM=aes-256-gcm ``` ## Database Configuration ### SQLite (Development) Default and zero-config for development: ```bash DB_URL=sqlite://./astreus.db ``` ### PostgreSQL (Production) Recommended for production deployments: ```bash DB_URL=postgresql://user:password@localhost:5432/astreus_db ``` ### Knowledge Database Required for RAG features. Must be PostgreSQL with pgvector: ```bash KNOWLEDGE_DB_URL=postgresql://user:password@localhost:5432/knowledge_db ``` #### Setting up pgvector Using Docker: ```yaml # docker-compose.yml services: postgres: image: pgvector/pgvector:pg16 environment: POSTGRES_USER: astreus POSTGRES_PASSWORD: password POSTGRES_DB: knowledge_db ports: - "5432:5432" ``` ```bash docker-compose up -d ``` ## Security ### Encryption Keys Generate a secure encryption key: ```bash openssl rand -hex 32 ``` Add to your environment: ```bash ENCRYPTION_ENABLED=true ENCRYPTION_MASTER_KEY=your-generated-key ENCRYPTION_ALGORITHM=aes-256-gcm ``` ### Production Checklist * [ ] Use PostgreSQL instead of SQLite * [ ] Enable encryption * [ ] Set `NODE_ENV=production` * [ ] Use `LOG_LEVEL=warn` or `error` * [ ] Store secrets in environment, not files * [ ] Use a secrets manager (Vault, AWS Secrets, etc.) ## Default Models by Provider | Provider | Default Model | | --------- | -------------------------- | | OpenAI | `gpt-4o` | | Anthropic | `claude-sonnet-4-20250514` | | Google | `gemini-2.0-flash` | | Ollama | `llama3` | *** # Features URL: /docs/create/features Source: /app/src/content/docs/create/features.mdx Detailed explanation of each feature you can include when scaffolding a new agent. ## Memory Enable persistent memory for your agent. The agent remembers conversations across sessions using vector search for efficient retrieval. ```typescript const agent = await Agent.create({ name: 'my-agent', model: 'gpt-4o', memory: true, }); await agent.ask("My name is John"); // Later, even in a new session: await agent.ask("What's my name?"); // "Your name is John" ``` **Use cases:** * Personal assistants that remember user preferences * Customer support bots with conversation history * Long-running agents that need context persistence ## Knowledge (RAG) Add document retrieval capabilities. Ingest PDFs, text files, and other documents into a searchable knowledge base. ```typescript const agent = await Agent.create({ name: 'my-agent', model: 'gpt-4o', knowledge: true, }); // Add documents to knowledge base await agent.addKnowledgeFromFile('./docs/guide.pdf', { category: 'docs' }); await agent.addKnowledgeFromFile('./docs/api.md', { category: 'api' }); // Agent answers from documents await agent.ask("What does the guide say about authentication?"); ``` **Use cases:** * Documentation Q\&A bots * Research assistants * Knowledge management systems **Requirements:** PostgreSQL with pgvector extension ## Graph Workflows Create complex multi-step workflows with DAG-based task orchestration. Define dependencies between tasks and run them in parallel where possible. ```typescript import { Agent, Graph } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'my-agent', model: 'gpt-4o' }); const graph = new Graph({ name: 'research-workflow' }, agent); // Define workflow nodes const researchNode = graph.addTaskNode({ prompt: 'Research the topic thoroughly' }); const analyzeNode = graph.addTaskNode({ prompt: 'Analyze the research findings', dependsOn: [researchNode] }); const writeNode = graph.addTaskNode({ prompt: 'Write a comprehensive report', dependsOn: [analyzeNode] }); // Execute the workflow const result = await graph.run(); console.log(result.results); ``` **Use cases:** * Multi-step content generation * Data processing pipelines * Complex decision workflows ## Sub-Agents Coordinate multiple specialized agents for complex tasks. Each sub-agent can have its own configuration and expertise. ```typescript // Create specialized agents const researcher = await Agent.create({ name: 'researcher', model: 'gpt-4o', systemPrompt: 'You are a research specialist.' }); const writer = await Agent.create({ name: 'writer', model: 'gpt-4o', systemPrompt: 'You are a professional writer.' }); // Main agent coordinates sub-agents const agent = await Agent.create({ name: 'coordinator', model: 'gpt-4o' }); const result = await agent.executeWithSubAgents( 'Research and write an article about quantum computing', [researcher, writer] ); ``` **Use cases:** * Content creation pipelines * Expert systems with multiple domains * Parallel task execution ## Custom Plugins Extend your agent with custom tools. Define parameters, descriptions, and handlers for each tool. ```typescript const weatherPlugin = { name: 'weather-plugin', version: '1.0.0', description: 'Get weather information', tools: [{ name: 'get_weather', description: 'Get current weather for a location', parameters: { location: { type: 'string', description: 'City name', required: true } }, handler: async ({ location }) => { const response = await fetch(`https://api.weather.com/${location}`); const data = await response.json(); return { success: true, data }; } }] }; const agent = await Agent.create({ name: 'my-agent', model: 'gpt-4o' }); await agent.registerPlugin(weatherPlugin); // Agent can now use the weather tool await agent.ask("What's the weather in Tokyo?"); ``` **Use cases:** * API integrations * Database operations * Custom business logic ## MCP Integration Model Context Protocol support for standardized tool integration. Connect to MCP-compatible services and tools. ```typescript const agent = await Agent.create({ name: 'my-agent', model: 'gpt-4o', mcp: { servers: [ { name: 'filesystem', command: 'mcp-server-filesystem' }, { name: 'github', command: 'mcp-server-github' } ] } }); ``` **Use cases:** * File system operations * GitHub integration * Standardized tool ecosystem ## Feature Combinations Features work together seamlessly: ```typescript const agent = await Agent.create({ name: 'advanced-agent', model: 'gpt-4o', memory: true, // Remember conversations knowledge: true, // Access documents mcp: { // Use MCP tools servers: [ { name: 'filesystem', command: 'mcp-server-filesystem' } ] } }); // Register custom plugins await agent.registerPlugin(myCustomPlugin); // Use with graph workflows const graph = new Graph({ name: 'workflow' }, agent); ``` *** # Introduction URL: /docs/create/intro Source: /app/src/content/docs/create/intro.mdx Scaffold new Astreus AI agent projects with best practices and sensible defaults. Interactively configure your agent with the features you need. ## Why Create Astreus Agent? Starting a new AI agent project from scratch can be tedious. `create-astreus-agent` handles the boilerplate so you can focus on building: * **Interactive Setup** - Answer a few questions, get a fully configured project * **Feature Selection** - Only include what you need (memory, RAG, graphs, etc.) * **Multi-Provider Ready** - Pre-configured for any LLM provider * **TypeScript Support** - Full type safety out of the box * **Best Practices** - Project structure that scales ## Quick Start ```bash npx create-astreus-agent my-agent cd my-agent npm install npm run dev ``` That's it! You have a working AI agent. ## What You Get ``` my-agent/ ├── src/ │ └── index.ts # Main entry point with agent setup ├── package.json # Dependencies and scripts ├── tsconfig.json # TypeScript configuration ├── .env.example # Environment variables template ├── .gitignore # Git ignore rules └── README.md # Project documentation ``` ## Interactive Setup The CLI guides you through configuration: ``` ? What is your project name? my-agent ? Which features do you want to include? ◉ Memory - Persistent agent memory ◉ Knowledge (RAG) - Document retrieval ◯ Graph Workflows - Task orchestration ◯ Sub-Agents - Multi-agent coordination ? Which LLM provider? OpenAI ? Use TypeScript? Yes ``` ## Next Steps * [Quick Start](/docs/create/quickstart) - Create your first agent * [Features](/docs/create/features) - Available features explained * [Configuration](/docs/create/configuration) - Environment setup *** # Quick Start URL: /docs/create/quickstart Source: /app/src/content/docs/create/quickstart.mdx Create your first Astreus agent project in under 5 minutes. ## Installation Methods ### Using npx (Recommended) ```bash npx create-astreus-agent my-agent ``` ### Using npm create ```bash npm create astreus-agent my-agent ``` ### Using pnpm ```bash pnpm create astreus-agent my-agent ``` ## Interactive Setup ### 1. Project Name ``` ? What is your project name? my-agent ``` Enter your project name. A new directory will be created. Only letters, numbers, dashes, and underscores are allowed. ### 2. Feature Selection ``` ? Which features do you want to include? ◉ Memory - Persistent agent memory with vector search ◉ Knowledge (RAG) - Document ingestion and retrieval ◯ Graph Workflows - DAG-based task orchestration ◯ Sub-Agents - Multi-agent coordination ◯ Custom Plugins - Extensible tool system ◯ MCP Integration - Model Context Protocol support ``` Use arrow keys and space to select features. All features are optional. ### 3. LLM Provider ``` ? Which LLM provider do you want to use? ● OpenAI - GPT-4, GPT-3.5 ○ Anthropic - Claude ○ Google - Gemini ○ Ollama - Local models ○ Multiple providers - Configure later ``` Choose your preferred provider or select "Multiple providers" to configure later. ### 4. TypeScript ``` ? Use TypeScript? Yes ``` TypeScript is recommended for better developer experience. ## Post-Installation After the project is created: ```bash # Navigate to project cd my-agent # Install dependencies npm install # Copy environment template cp .env.example .env # Edit .env with your API keys nano .env # or use your preferred editor # Start the agent npm run dev ``` ## Example: First Conversation Once running, your agent is ready: ```typescript import { Agent } from '@astreus-ai/astreus'; import 'dotenv/config'; const agent = await Agent.create({ name: 'my-agent', model: 'gpt-4o', memory: true, }); // Have a conversation const response = await agent.ask("Hello! What can you help me with?"); console.log(response); ``` ## Generated Code The CLI generates a complete `src/index.ts`: ```typescript import { Agent } from '@astreus-ai/astreus'; import 'dotenv/config'; async function main() { console.log('Starting Astreus Agent...\n'); const agent = await Agent.create({ name: 'my-agent', model: 'gpt-4o', systemPrompt: 'You are a helpful AI assistant powered by Astreus.', memory: true, }); // Interactive loop const readline = await import('readline'); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); console.log('Agent ready! Type your message (or "exit" to quit):\n'); const prompt = () => { rl.question('You: ', async (input) => { if (input.toLowerCase() === 'exit') { console.log('\nGoodbye!'); rl.close(); process.exit(0); } try { const response = await agent.ask(input); console.log(`\nAgent: ${response}\n`); } catch (error) { console.error('Error:', error instanceof Error ? error.message : error); } prompt(); }); }; prompt(); } main().catch(console.error); ``` ## Requirements * Node.js >= 22.0.0 * npm, yarn, or pnpm * LLM provider API key (or Ollama for local models) ## Next Steps * [Features](/docs/create/features) - Learn about each feature * [Configuration](/docs/create/configuration) - Environment setup *** # Templates URL: /docs/create/templates Source: /app/src/content/docs/create/templates.mdx Information about project templates and common configurations. ## Default Project When you run `create-astreus-agent`, you get an interactive setup that generates a project based on your selections. ```bash npx create-astreus-agent my-agent ``` The generated project includes everything you need to get started. ## Generated Project Structure ``` my-agent/ ├── src/ │ └── index.ts # Main entry point with agent setup ├── package.json # Dependencies and scripts ├── tsconfig.json # TypeScript configuration (if TypeScript selected) ├── .env.example # Environment variables template ├── .gitignore # Git ignore rules └── README.md # Project documentation ``` ## Package.json Scripts ```json { "scripts": { "dev": "tsx src/index.ts", "build": "tsc", "start": "node dist/index.js" } } ``` ## Common Configurations ### Basic Chat Agent Select only Memory feature for a simple conversational agent: ``` ? Which features do you want to include? ◉ Memory - Persistent agent memory with vector search ◯ Knowledge (RAG) ◯ Graph Workflows ◯ Sub-Agents ◯ Custom Plugins ◯ MCP Integration ``` ### RAG-Enabled Agent Select Memory and Knowledge for document-aware responses: ``` ? Which features do you want to include? ◉ Memory - Persistent agent memory with vector search ◉ Knowledge (RAG) - Document ingestion and retrieval ◯ Graph Workflows ◯ Sub-Agents ◯ Custom Plugins ◯ MCP Integration ``` ### Full-Featured Agent Select all features for maximum capabilities: ``` ? Which features do you want to include? ◉ Memory - Persistent agent memory with vector search ◉ Knowledge (RAG) - Document ingestion and retrieval ◉ Graph Workflows - DAG-based task orchestration ◉ Sub-Agents - Multi-agent coordination ◉ Custom Plugins - Extensible tool system ◉ MCP Integration - Model Context Protocol support ``` ## Provider-Specific Setup ### OpenAI Default model: `gpt-4o` Generated `.env.example`: ``` OPENAI_API_KEY=your-api-key-here ``` ### Anthropic (Claude) Default model: `claude-sonnet-4-20250514` Generated `.env.example`: ``` ANTHROPIC_API_KEY=your-api-key-here ``` ### Google (Gemini) Default model: `gemini-2.0-flash` Generated `.env.example`: ``` GEMINI_API_KEY=your-api-key-here ``` ### Ollama (Local) Default model: `llama3` Generated `.env.example`: ``` # Ollama runs locally, no API key needed OLLAMA_HOST=http://localhost:11434 ``` ### Multiple Providers Generated `.env.example`: ``` # Add API keys for providers you want to use OPENAI_API_KEY=your-openai-key ANTHROPIC_API_KEY=your-anthropic-key GEMINI_API_KEY=your-gemini-key ``` ## Feature Comparison | Feature | Use Case | | ---------- | -------------------------------------------------- | | Memory | Remembering user preferences, conversation history | | Knowledge | Documentation Q\&A, research assistants | | Graph | Multi-step workflows, pipelines | | Sub-Agents | Specialized tasks, parallel processing | | Plugins | Custom tools, API integrations | | MCP | Standardized tool ecosystem | ## Next Steps After creating your project: ```bash cd my-agent npm install cp .env.example .env # Edit .env with your API keys npm run dev ``` See [Configuration](/docs/create/configuration) for detailed environment setup. *** # Agent Persistence URL: /docs/examples/agent-persistence Source: /app/src/content/docs/examples/agent-persistence.mdx import { DocImage } from '@/components/DocImage'; Save and load agents from database for reusability. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/agent-persistence npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## Agent Persistence ```typescript import { Agent } from '@astreus-ai/astreus'; // Create and save an agent const agent = await Agent.create({ name: 'ProjectAssistant', model: 'gpt-4o', memory: true, systemPrompt: 'You are a project management assistant.' }); // Use the agent await agent.ask("Remember that our project deadline is March 15th"); // Later, load the same agent by name const loadedAgent = await Agent.findByName('ProjectAssistant'); const response = await loadedAgent?.ask("What is our project deadline?"); console.log(response); // Should remember March 15th ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` ## Repository The complete example is available on GitHub: [examples/agent-persistence](https://github.com/astreus-ai/examples/tree/main/agent-persistence) *** # Agent with Knowledge URL: /docs/examples/agent-with-knowledge Source: /app/src/content/docs/examples/agent-with-knowledge.mdx import { DocImage } from '@/components/DocImage'; Create agents with knowledge base capabilities for enhanced information retrieval. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/agent-with-knowledge npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env # LLM API key OPENAI_API_KEY=sk-your-openai-api-key-here # Knowledge database (required for RAG) KNOWLEDGE_DB_URL=postgresql://username:password@localhost:5432/knowledge_db # Main database for agent persistence DB_URL=sqlite://./astreus.db ``` ## Knowledge Agent ```typescript import { Agent } from '@astreus-ai/astreus'; // Create agent with knowledge enabled const agent = await Agent.create({ name: 'CosmosBot', model: 'gpt-4o', embeddingModel: 'text-embedding-3-small', // Specify embedding model directly knowledge: true, systemPrompt: 'You can search and retrieve information from scientific knowledge bases about the cosmos and universe.' }); // Add knowledge from scientific book about the sun and cosmos await agent.addKnowledgeFromFile( './data/The Sun\'s Light and Heat.pdf', { category: 'solar-physics', version: '1.0' } ); // Agent automatically uses knowledge in conversations const response = await agent.ask("What is Correction for Atmospheric Absorption? Explain."); console.log(response); // Uses knowledge base automatically ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` ## Repository The complete example is available on GitHub: [examples/agent-with-knowledge](https://github.com/astreus-ai/examples/tree/main/agent-with-knowledge) *** # Agent with Memory URL: /docs/examples/agent-with-memory Source: /app/src/content/docs/examples/agent-with-memory.mdx import { DocImage } from '@/components/DocImage'; Build agents with persistent memory capabilities. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/agent-with-memory npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here # Database for memory storage DB_URL=sqlite://./astreus.db ``` ## Memory Agent ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'MemoryBot', model: 'gpt-4o', memory: true, systemPrompt: 'You remember our conversation history.' }); // First conversation const response1 = await agent.ask("My name is John and I like TypeScript"); console.log(response1); // Later conversation - agent remembers const response2 = await agent.ask("What's my name and what do I like?"); console.log(response2); // Should remember John and TypeScript ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` ## Repository The complete example is available on GitHub: [examples/agent-with-memory](https://github.com/astreus-ai/examples/tree/main/agent-with-memory) *** # Agent with Vision URL: /docs/examples/agent-with-vision Source: /app/src/content/docs/examples/agent-with-vision.mdx import { DocImage } from '@/components/DocImage'; Create agents capable of processing and analyzing images. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/agent-with-vision npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env # Vision-capable model API key OPENAI_API_KEY=sk-your-openai-api-key-here # Database for agent persistence DB_URL=sqlite://./astreus.db ``` ## Vision Agent ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'VisionBot', model: 'gpt-4o', visionModel: 'gpt-4o', vision: true, systemPrompt: 'You can analyze and describe images in detail.' }); // Analyze an image const result = await agent.ask("Analyze this image and describe what you see", { attachments: [{ type: 'image', path: './screenshot.png' }] }); console.log(result); // Detailed image analysis ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` ## Repository The complete example is available on GitHub: [examples/agent-with-vision](https://github.com/astreus-ai/examples/tree/main/agent-with-vision) *** # Basic Graphs URL: /docs/examples/basic-graphs Source: /app/src/content/docs/examples/basic-graphs.mdx import { DocImage } from '@/components/DocImage'; Create simple workflow graphs to orchestrate multi-step processes. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/basic-graphs npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## Basic Graph Workflow ```typescript import { Agent, Graph } from '@astreus-ai/astreus'; // Create an agent const agent = await Agent.create({ name: 'WorkflowAgent', model: 'gpt-4o' }); // Create a simple sequential graph const graph = new Graph({ name: 'research-workflow' }, agent); // Add tasks with dependencies const research = graph.addTaskNode({ prompt: 'Research artificial intelligence trends' }); const summary = graph.addTaskNode({ prompt: 'Summarize the research findings', dependencies: [research] }); // Execute the workflow const results = await graph.run(); // Parse the result and extract the response if (results.success && results.results[summary]) { const summaryResult = JSON.parse(results.results[summary]); console.log(summaryResult.response); } ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` ## Repository The complete example is available on GitHub: [examples/basic-graphs](https://github.com/astreus-ai/examples/tree/main/basic-graphs) *** # Complex Workflows URL: /docs/examples/complex-workflows Source: /app/src/content/docs/examples/complex-workflows.mdx import { DocImage } from '@/components/DocImage'; Build sophisticated multi-agent workflows with advanced orchestration patterns. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/complex-workflows npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## Multi-Agent Workflow ```typescript import { Agent, Graph } from '@astreus-ai/astreus'; // Create specialized agents const researcher = await Agent.create({ name: 'Researcher', model: 'gpt-4o', systemPrompt: 'You research topics thoroughly.' }); const writer = await Agent.create({ name: 'Writer', model: 'gpt-4o', systemPrompt: 'You create engaging content.' }); // Create workflow pipeline const pipeline = new Graph({ name: 'content-pipeline' }, researcher); // Define workflow steps const research = pipeline.addTaskNode({ prompt: 'Research AI trends in 2024', agentId: researcher.id }); const article = pipeline.addTaskNode({ prompt: 'Write an article based on the research', agentId: writer.id, dependencies: [research] }); // Execute the workflow const results = await pipeline.run(); // Parse the result and extract the response if (results.success && results.results[article]) { const articleResult = JSON.parse(results.results[article]); console.log(articleResult.response); } ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` ## Repository The complete example is available on GitHub: [examples/complex-workflows](https://github.com/astreus-ai/examples/tree/main/complex-workflows) *** # Context Compression URL: /docs/examples/context-compression Source: /app/src/content/docs/examples/context-compression.mdx import { DocImage } from '@/components/DocImage'; Use Astreus's auto context compression system to automatically manage long conversations by summarizing older messages while preserving important context. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/context-compression npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## Auto Context Compression The `autoContextCompression` feature automatically summarizes older messages when the conversation gets too long, maintaining context while reducing token usage: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'ContextAgent', model: 'gpt-4o', memory: true, autoContextCompression: true, systemPrompt: 'You can handle very long conversations efficiently.' }); // Have a long conversation for (let i = 1; i <= 20; i++) { await agent.ask(`Tell me an interesting fact about space. This is message #${i}.`); } // Test memory - agent should remember early facts despite context compression const response = await agent.ask("What was the first space fact you told me?"); console.log(response); ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` ## Repository The complete example is available on GitHub: [examples/context-compression](https://github.com/astreus-ai/examples/tree/main/context-compression) *** # Custom Plugins URL: /docs/examples/custom-plugins Source: /app/src/content/docs/examples/custom-plugins.mdx import { DocImage } from '@/components/DocImage'; Create and register custom plugins with tools for agents. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/custom-plugins npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## Custom Weather Plugin ```typescript import { Agent, ToolDefinition, PluginDefinition } from '@astreus-ai/astreus'; // Define a custom tool const weatherTool: ToolDefinition = { name: 'get_weather', description: 'Get current weather for a location', parameters: { location: { name: 'location', type: 'string', description: 'City name', required: true }, units: { name: 'units', type: 'string', description: 'Temperature units (celsius or fahrenheit)', required: false, enum: ['celsius', 'fahrenheit'] } }, handler: async (params) => { // Simulate weather API call const weather = { temperature: 22, conditions: 'sunny', location: params.location as string }; return { success: true, data: weather }; } }; // Create plugin const weatherPlugin: PluginDefinition = { name: 'weather-plugin', version: '1.0.0', description: 'Weather information tools', tools: [weatherTool] }; // Create agent and register plugin const agent = await Agent.create({ name: 'WeatherAgent', model: 'gpt-4o' }); await agent.registerPlugin(weatherPlugin); // Use the plugin in conversation const response = await agent.ask("What's the weather like in Tokyo?"); console.log(response); // Agent automatically uses the weather tool ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` If you built from scratch, create an `index.ts` file with the code above and run: ```bash npx tsx index.ts ``` ## Repository The complete example is available on GitHub: [examples/custom-plugins](https://github.com/astreus-ai/examples/tree/main/custom-plugins) *** # Graph + Sub-Agents URL: /docs/examples/graph-sub-agents Source: /app/src/content/docs/examples/graph-sub-agents.mdx import { DocImage } from '@/components/DocImage'; Combine Graph workflows with Sub-Agent coordination for sophisticated hierarchical task distribution. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/graph-sub-agents npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here ANTHROPIC_API_KEY=your-anthropic-api-key-here DB_URL=sqlite://./astreus.db ``` ## Graph + Sub-Agent Integration ```typescript import { Agent, Graph } from '@astreus-ai/astreus'; // Create specialized sub-agents const researcher = await Agent.create({ name: 'ResearchSpecialist', model: 'gpt-4o', systemPrompt: 'You conduct thorough research and gather comprehensive information.', knowledge: true, memory: true }); const analyst = await Agent.create({ name: 'DataAnalyst', model: 'gpt-4o', systemPrompt: 'You analyze data and provide actionable insights.', useTools: true }); const writer = await Agent.create({ name: 'ContentWriter', model: 'claude-3-5-sonnet-20241022', systemPrompt: 'You create compelling, well-structured content.', vision: true }); // Create main coordinator agent with sub-agents const coordinator = await Agent.create({ name: 'ProjectCoordinator', model: 'gpt-4o', systemPrompt: 'You coordinate complex projects using specialized sub-agents.', subAgents: [researcher, analyst, writer] }); // Create graph with sub-agent awareness const projectGraph = new Graph({ name: 'Market Analysis Project', subAgentAware: true, maxConcurrency: 2 }, coordinator); // Add tasks that leverage sub-agents const researchTask = projectGraph.addTaskNode({ name: 'Market Research', prompt: 'Research the AI healthcare market, including key players, market size, and growth trends', useSubAgents: true, subAgentDelegation: 'auto' }); const analysisTask = projectGraph.addTaskNode({ name: 'Data Analysis', prompt: 'Analyze the research data and identify key opportunities and challenges', dependencies: [researchTask], useSubAgents: true, subAgentCoordination: 'parallel' }); const reportTask = projectGraph.addTaskNode({ name: 'Executive Report', prompt: 'Create a comprehensive executive report with recommendations', dependencies: [analysisTask], useSubAgents: true }); // Execute the graph with intelligent sub-agent coordination const result = await projectGraph.run(); // Display results console.log('Project completed:', result.success); console.log(`Tasks completed: ${result.completedNodes}/${result.completedNodes + result.failedNodes}`); console.log(`Duration: ${result.duration}ms`); // Display task results if (result.results) { console.log('\nTask Results:'); for (const [nodeId, nodeResult] of Object.entries(result.results)) { console.log(`\n${nodeId}:`, nodeResult); } } // Get the final report from the last task const finalReport = result.results?.[reportTask]; if (finalReport) { console.log('\n=== Final Executive Report ==='); console.log(finalReport); } ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` If you built from scratch, create an `index.ts` file with the code above and run: ```bash npx tsx index.ts ``` ## Repository The complete example is available on GitHub: [examples/graph-sub-agents](https://github.com/astreus-ai/examples/tree/main/graph-sub-agents) *** # MCP Integration URL: /docs/examples/mcp-integration Source: /app/src/content/docs/examples/mcp-integration.mdx import { DocImage } from '@/components/DocImage'; Connect agents with external tools using Model Context Protocol. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/mcp-integration npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## MCP Server Integration ```typescript import { config } from 'dotenv'; import { Agent, Graph } from '@astreus-ai/astreus'; config(); async function main() { const mainAgent = await Agent.create({ name: 'FileAnalysisAgent', model: 'gpt-4o', systemPrompt: 'You are a file analysis agent that processes files using graph-based workflows and MCP tools.' }); const mcpConfig = { name: 'filesystem', command: "npx", args: ["@modelcontextprotocol/server-filesystem", process.cwd()] }; await mainAgent.addMCPServers([mcpConfig]); await new Promise(resolve => setTimeout(resolve, 3000)); const analysisGraph = new Graph({ name: 'File Summary Workflow', maxConcurrency: 1 }, mainAgent); const readTask = analysisGraph.addTaskNode({ name: 'File Reading', prompt: 'Read the content of "./info.txt" file and analyze it.', priority: 1 }); const summaryTask = analysisGraph.addTaskNode({ name: 'Summary Creation', prompt: 'Based on the analyzed file content from the previous task, create a concise summary and save it as "./summary.txt" file.', dependencies: [readTask], priority: 2 }); const result = await analysisGraph.run({ stream: true, onChunk: (chunk) => { console.log(chunk); } }); } main().catch(console.error); ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` If you built from scratch, create an `index.ts` file with the code above and run: ```bash npx tsx index.ts ``` ## Repository The complete example is available on GitHub: [examples/mcp-integration](https://github.com/astreus-ai/examples/tree/main/mcp-integration) *** # Scheduled Workflows URL: /docs/examples/scheduled-workflows Source: /app/src/content/docs/examples/scheduled-workflows.mdx import { DocImage } from '@/components/DocImage'; Build time-based automated workflows with simple schedule strings and dependency management. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/scheduled-workflows npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db NODE_ENV=development ``` ## Quick Test Example (Seconds) ```typescript import { Agent, Graph } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'ContentAgent', model: 'gpt-4o', systemPrompt: 'You are a content creation specialist.' }); const graph = new Graph({ name: 'Quick Test Pipeline', description: 'Test automated workflow with seconds interval', maxConcurrency: 2 }, agent); // Run after 5 seconds const researchNode = graph.addTaskNode({ name: 'Content Research', prompt: 'Research trending topics in AI and technology. Find 3-5 compelling topics for blog content.', schedule: 'after:5s' }); // Run after 10 seconds const creationNode = graph.addTaskNode({ name: 'Content Creation', prompt: 'Based on the research findings, create a short blog post summary on one of the trending topics.', schedule: 'after:10s', dependsOn: ['Content Research'] }); // Run after 15 seconds const seoNode = graph.addTaskNode({ name: 'SEO Optimization', prompt: 'Optimize the blog post for SEO: add meta description and keywords.', schedule: 'after:15s', dependsOn: ['Content Creation'] }); // Run after 20 seconds const publishNode = graph.addTaskNode({ name: 'Content Publishing', prompt: 'Create a social media post for the optimized content.', schedule: 'after:20s', dependsOn: ['SEO Optimization'] }); console.log('Starting scheduled workflow test...'); console.log('Tasks will run at:'); console.log('- Research: 5 seconds from now'); console.log('- Creation: 10 seconds from now'); console.log('- SEO: 15 seconds from now'); console.log('- Publishing: 20 seconds from now\n'); // Run the graph and get results const result = await graph.run(); // Display execution results console.log('\n=== Workflow Execution Results ==='); console.log('Success:', result.success); console.log(`Completed: ${result.completedNodes} tasks`); console.log(`Failed: ${result.failedNodes} tasks`); console.log(`Duration: ${result.duration}ms`); // Display each task result if (result.results) { console.log('\n=== Task Results ==='); for (const [nodeId, nodeResult] of Object.entries(result.results)) { console.log(`\n[${nodeId}]:`); console.log(nodeResult); } } // Check for errors if (result.errors && Object.keys(result.errors).length > 0) { console.log('\n=== Errors ==='); for (const [nodeId, error] of Object.entries(result.errors)) { console.log(`[${nodeId}]: ${error}`); } } console.log('\n✅ Scheduled workflow test completed!'); ``` ## Daily Content Pipeline (Production) For production use with actual daily schedules: ```typescript // Schedule format examples: // 'daily@06:00' - Every day at 6 AM // 'weekly@monday@09:00' - Every Monday at 9 AM // 'monthly@15@10:00' - 15th of every month at 10 AM // 'after:5s' - After 5 seconds (for testing) // 'after:2h' - After 2 hours // 'every:30m' - Every 30 minutes const researchNode = graph.addTaskNode({ name: 'Content Research', prompt: 'Research trending topics in AI and technology.', schedule: 'daily@06:00' }); ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` If you built from scratch, create an `index.ts` file with the code above and run: ```bash npx tsx index.ts ``` ## Repository The complete example is available on GitHub: [examples/scheduled-workflows](https://github.com/astreus-ai/examples/tree/main/scheduled-workflows) *** # Advanced Sub-Agents URL: /docs/examples/sub-agents-advanced Source: /app/src/content/docs/examples/sub-agents-advanced.mdx import { DocImage } from '@/components/DocImage'; Build sophisticated multi-agent workflows with complex coordination patterns and specialized capabilities. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/sub-agents-advanced npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here ANTHROPIC_API_KEY=your-anthropic-api-key-here DB_URL=sqlite://./astreus.db ``` ## Multi-Model Agent Team ```typescript import { Agent } from '@astreus-ai/astreus'; // Create diverse agent team with different models const strategicPlanner = await Agent.create({ name: 'StrategicPlanner', model: 'gpt-4o', // High reasoning for strategy systemPrompt: 'You are a strategic business consultant with deep analytical thinking.', memory: true, knowledge: true }); const creativeWriter = await Agent.create({ name: 'CreativeWriter', model: 'claude-3-5-sonnet-20241022', // Excellent for creative writing systemPrompt: 'You are a creative copywriter who crafts compelling narratives.', vision: true }); const dataScientist = await Agent.create({ name: 'DataScientist', model: 'gpt-4o', // Strong analytical capabilities systemPrompt: 'You are a data scientist specializing in statistical analysis and insights.', useTools: true }); const executiveTeam = await Agent.create({ name: 'ExecutiveTeam', model: 'gpt-4o', // High-level coordination systemPrompt: 'You coordinate executive-level strategic initiatives across expert teams.', subAgents: [strategicPlanner, creativeWriter, dataScientist] }); const businessPlan = await executiveTeam.ask( 'Develop comprehensive go-to-market strategy for AI-powered healthcare platform', { useSubAgents: true, delegation: 'auto', coordination: 'sequential' } ); console.log('Business plan completed:', businessPlan); ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` If you built from scratch, create an `index.ts` file with the code above and run: ```bash npx tsx index.ts ``` ## Repository The complete example is available on GitHub: [examples/sub-agents-advanced](https://github.com/astreus-ai/examples/tree/main/sub-agents-advanced) *** # Basic Sub-Agents URL: /docs/examples/sub-agents-basic Source: /app/src/content/docs/examples/sub-agents-basic.mdx import { DocImage } from '@/components/DocImage'; Create and coordinate multiple AI agents for complex task delegation. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/sub-agents-basic npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## Simple Sub-Agent Setup ```typescript import { Agent } from '@astreus-ai/astreus'; // Create specialized sub-agents const researcher = await Agent.create({ name: 'Researcher', model: 'gpt-4o', systemPrompt: 'You are an expert researcher who gathers comprehensive information.' }); const writer = await Agent.create({ name: 'Writer', model: 'gpt-4o', systemPrompt: 'You are a skilled writer who creates clear, engaging content.' }); // Create main coordinator agent const mainAgent = await Agent.create({ name: 'Coordinator', model: 'gpt-4o', systemPrompt: 'You coordinate tasks between specialized agents.', subAgents: [researcher, writer] }); // Use auto delegation const result = await mainAgent.ask( 'Research artificial intelligence trends and write a summary', { useSubAgents: true, delegation: 'auto' } ); console.log(result); ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` If you built from scratch, create an `index.ts` file with the code above and run: ```bash npx tsx index.ts ``` ## Repository The complete example is available on GitHub: [examples/sub-agents-basic](https://github.com/astreus-ai/examples/tree/main/sub-agents-basic) *** # Task Attachments URL: /docs/examples/task-attachments Source: /app/src/content/docs/examples/task-attachments.mdx import { DocImage } from '@/components/DocImage'; Attach multiple file types to tasks for comprehensive analysis. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/task-attachments npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## Task with Multiple Attachments ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'AnalysisAgent', model: 'gpt-4o', visionModel: 'gpt-4o', // Specify vision model directly vision: true // Enable vision for images }); // Code review task with multiple file types const reviewTask = await agent.createTask({ prompt: `Perform a comprehensive analysis: 1. Review the code for security issues 2. Check the design mockup for usability 3. Verify dependencies are up to date 4. Review documentation completeness`, attachments: [ { type: 'code', path: './src/auth/login.ts', name: 'Login Controller', language: 'typescript' }, { type: 'image', path: './designs/login-ui.png', name: 'Login UI Mockup' }, { type: 'json', path: './package.json', name: 'Dependencies' }, { type: 'markdown', path: './docs/api.md', name: 'API Documentation' } ], metadata: { type: 'comprehensive-review', priority: 'high' } }); const result = await agent.executeTask(reviewTask.id); console.log('Analysis complete:', result.response); ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` If you built from scratch, create an `index.ts` file with the code above and run: ```bash npx tsx index.ts ``` ## Repository The complete example is available on GitHub: [examples/task-attachments](https://github.com/astreus-ai/examples/tree/main/task-attachments) *** # Your First Agent URL: /docs/examples/your-first-agent Source: /app/src/content/docs/examples/your-first-agent.mdx import { DocImage } from '@/components/DocImage'; Create your first AI agent with Astreus framework. ## Quick Start ### Clone the Complete Example The easiest way to get started is to clone the complete example repository: ```bash git clone https://github.com/astreus-ai/examples cd examples/your-first-agent npm install ``` ### Or Install Package Only If you prefer to build from scratch: ```bash npm install @astreus-ai/astreus ``` ## Environment Setup ```bash # .env OPENAI_API_KEY=sk-your-openai-api-key-here DB_URL=sqlite://./astreus.db ``` ## Basic Agent ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'MyFirstAgent', model: 'gpt-4o', systemPrompt: 'You are a helpful assistant.' }); // Create and execute a task const task = await agent.createTask({ prompt: "Hello, introduce yourself" }); const result = await agent.executeTask(task.id); console.log(result.response); ``` ## Running the Example If you cloned the repository: ```bash npm run dev ``` If you built from scratch, create an `index.ts` file with the code above and run: ```bash npx tsx index.ts ``` ## Repository The complete example is available on GitHub: [examples/your-first-agent](https://github.com/astreus-ai/examples/tree/main/your-first-agent) *** # Agent URL: /docs/framework/agent Source: /app/src/content/docs/framework/agent.mdx import { DocImage } from '@/components/DocImage'; **Core AI entity with modular capabilities and decorator-based composition** ## Overview Agents are the fundamental building blocks in Astreus. They provide intelligent conversation capabilities with configurable features like memory, tools, knowledge bases, and vision processing. Each agent operates independently with its own context, memory, and specialized capabilities. ## Creating an Agent Creating an agent in Astreus is straightforward: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'MyAssistant', // Unique name for the agent model: 'gpt-4o', // LLM model to use systemPrompt: 'You are a helpful assistant', // Custom instructions memory: true // Enable persistent memory }); ``` ## Choosing the LLM Model Astreus supports multiple LLM providers out of the box: ```typescript const agent = await Agent.create({ name: 'MyAssistant', model: 'gpt-4.5' // Set model here. Latest: 'gpt-4.5', 'claude-sonnet-4-20250514', 'gemini-2.5-pro', 'deepseek-r1' }); ``` [Learn supported LLM providers and models →](/docs/framework/llm) ## Agent Attributes Agents can be configured with various attributes to customize their behavior: ### Core Attributes ```typescript interface AgentConfig { name: string; // Unique identifier for the agent description?: string; // Agent description model?: string; // LLM model to use (default: 'gpt-4o-mini') embeddingModel?: string; // Specific model for embeddings (auto-detected) visionModel?: string; // Specific model for vision (auto-detected) temperature?: number; // Control response randomness (0-1, default: 0.7) maxTokens?: number; // Maximum response length (default: 2000) systemPrompt?: string; // Custom system instructions memory?: boolean; // Enable persistent memory (default: false) knowledge?: boolean; // Enable knowledge base access (default: false) vision?: boolean; // Enable image processing (default: false) useTools?: boolean; // Enable tool/plugin usage (default: true) autoContextCompression?: boolean; // Enable smart context management (default: false) maxContextLength?: number; // Token limit before compression (default: 8000) preserveLastN?: number; // Recent messages to keep uncompressed (default: 3) compressionRatio?: number; // Target compression ratio (default: 0.3) compressionStrategy?: 'summarize' | 'selective' | 'hybrid'; // Algorithm (default: 'hybrid') debug?: boolean; // Enable debug logging (default: false) subAgents?: IAgent[]; // Sub-agents for delegation and coordination } ``` ### RunOptions Options for the `run()` method: ```typescript interface RunOptions { model?: string; // Override the agent's model temperature?: number; // Override temperature maxTokens?: number; // Override max tokens stream?: boolean; // Enable streaming response useTools?: boolean; // Enable/disable tools for this request onChunk?: (chunk: string) => void; // Callback for streaming chunks } ``` ### AskOptions Options for the `ask()` method (extends RunOptions with additional capabilities): ```typescript interface AskOptions { model?: string; // Override the agent's model temperature?: number; // Override temperature maxTokens?: number; // Override max tokens stream?: boolean; // Enable streaming response useTools?: boolean; // Enable/disable tools for this request onChunk?: (chunk: string) => void; // Callback for streaming chunks timeout?: number; // Timeout in milliseconds for sub-agent execution // Sub-agent options useSubAgents?: boolean; // Enable sub-agent delegation delegation?: 'auto' | 'manual' | 'sequential'; // Delegation strategy taskAssignment?: Record; // agentId -> task mapping coordination?: 'parallel' | 'sequential'; // Sub-agent coordination mode contextIsolation?: 'isolated' | 'shared' | 'merge'; // Context handling between agents // Attachments attachments?: Array<{ type: 'image' | 'pdf' | 'text' | 'markdown' | 'code' | 'json' | 'file'; path: string; name?: string; language?: string; // For code files }>; // Temporary MCP servers for this request mcpServers?: Array<{ name: string; command?: string; args?: string[]; url?: string; cwd?: string; }>; // Temporary plugins for this request plugins?: Array<{ plugin: { name: string; version: string; description?: string; tools?: Array<{ name: string; description: string; parameters: Record; handler: (params: Record) => Promise<{ success: boolean; data?: unknown; error?: string; }>; }>; }; config?: Record; }>; } ``` ### Example with All Attributes ```typescript // Create sub-agents first const researcher = await Agent.create({ name: 'ResearchAgent', systemPrompt: 'You are an expert researcher who gathers comprehensive information.' }); const writer = await Agent.create({ name: 'WriterAgent', systemPrompt: 'You create engaging, well-structured content.' }); const fullyConfiguredAgent = await Agent.create({ name: 'AdvancedAssistant', description: 'Multi-purpose AI assistant', model: 'gpt-4o', embeddingModel: 'text-embedding-3-small', // Optional: specific embedding model visionModel: 'gpt-4o', // Optional: specific vision model temperature: 0.7, maxTokens: 2000, systemPrompt: 'You are an expert software architect...', memory: true, knowledge: true, vision: true, useTools: true, autoContextCompression: true, maxContextLength: 6000, // Compress at 6000 tokens preserveLastN: 4, // Keep last 4 messages compressionRatio: 0.4, // 40% compression target compressionStrategy: 'hybrid', // Use hybrid strategy debug: true, // Enable debug logging subAgents: [researcher, writer] // Add sub-agents for delegation }); ``` ## Agent Methods ### Conversation Methods ```typescript // Simple conversation - returns response string const response = await agent.ask('What is TypeScript?'); // With options const response = await agent.ask('Analyze this image', { temperature: 0.5, attachments: [{ type: 'image', path: './screenshot.png' }], mcpServers: [{ name: 'search', command: 'npx', args: ['-y', '@anthropic/mcp-search'] }], useSubAgents: true, delegation: 'auto', coordination: 'sequential' }); // Alternative: run() method (simpler, no sub-agent support) const response = await agent.run('Hello world'); ``` ### Static Methods ```typescript // Find agent by ID const agent = await Agent.findById('550e8400-e29b-41d4-a716-446655440000'); // Find agent by name const agent = await Agent.findByName('MyAssistant'); // List all agents with pagination const agents = await Agent.list({ limit: 10, offset: 0, initialize: false // Whether to initialize agents (default: false for performance) }); ``` ### Lifecycle Methods ```typescript // Update agent configuration dynamically await agent.update({ temperature: 0.8, maxTokens: 3000 }); // Update model at runtime (synchronous) agent.updateModel('gpt-4o'); // Clear all memory and context const result = await agent.clearAll(); // Returns: { memoriesCleared: number, contextCleared: boolean } // Clear session messages (free memory) - synchronous agent.clearSessionMessages(); // Graceful cleanup and resource disposal await agent.destroy(); // Delete agent from database await agent.delete(); ``` ### Context Management Methods ```typescript // Get all context messages const messages = agent.getContext(); // Returns: ContextMessage[] // Get context messages (alternative) const messages = agent.getContextMessages(); // Returns: ContextMessage[] // Get context window information const window = agent.getContextWindow(); // Returns: ContextWindow { messages, totalTokens, maxTokens, utilizationPercent } // Analyze current context const analysis = agent.analyzeContext(); // Returns: ContextAnalysis { tokenCount, messageCount, roleDistribution, ... } // Manually compress context const result = await agent.compressContext(); // Returns: CompressionResult { originalMessageCount, compressedMessageCount, ... } // Clear context (with optional memory sync) await agent.clearContext({ syncWithMemory: true }); // Export context as JSON string const exported = agent.exportContext(); // Import context from JSON string agent.importContext(exported); // Generate context summary const summary = await agent.generateContextSummary(); // Returns: ContextSummary // Update context model (synchronous) agent.updateContextModel('gpt-4o'); // Search context messages with filters const results = agent.searchContext({ query: 'search term', graphId: 'graph-uuid', taskId: 'task-uuid', sessionId: 'session-uuid', role: 'user', // 'user' | 'assistant' | 'system' limit: 10 }); // Load graph-specific context from memory await agent.loadGraphContext( 'graph-uuid', // graphId 100, // limit (default: 100) false // isolated - if true, only graph-specific memories (default: false) ); ``` ### Utility Getters ```typescript agent.id // Agent UUID agent.name // Agent name agent.config // Full configuration object agent.hasMemory() // Check if memory is enabled agent.hasKnowledge() // Check if knowledge base is enabled agent.hasVision() // Check if vision is enabled agent.canUseTools() // Check if tools are enabled agent.getId() // Get agent ID agent.getName() // Get agent name agent.getDescription() // Get agent description (returns string | null) agent.getModel() // Get current model agent.getTemperature() // Get temperature setting agent.getMaxTokens() // Get max tokens setting agent.getSystemPrompt() // Get system prompt (returns string | null) ``` ## Response Types ### ask() Response ```typescript const response = await agent.ask('What is 2+2?'); // Returns: string - The agent's response text // Example: "2 + 2 equals 4" ``` ### Agent.list() Response ```typescript const agents = await Agent.list({ limit: 10 }); // Returns array of Agent objects: [ { id: "550e8400-e29b-41d4-a716-446655440000", name: "MyAssistant", description: "Helpful assistant", model: "gpt-4o", // ... other config properties } ] ``` ### clearAll() Response ```typescript const result = await agent.clearAll(); // Returns: { memoriesCleared: 25, // Number of memories deleted contextCleared: true // Whether context was cleared } ``` *** # Context URL: /docs/framework/context Source: /app/src/content/docs/framework/context.mdx import { DocImage } from '@/components/DocImage'; **Smart context management for long conversations with automatic compression** ## Overview Auto context compression in Astreus provides intelligent conversation management by automatically handling long conversation histories. The system compresses older messages while preserving important information, ensuring agents can maintain coherent long conversations without exceeding model token limits. ## Basic Usage Enable auto context compression to get automatic conversation management: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create an agent with auto context compression enabled const agent = await Agent.create({ name: 'ContextAwareAgent', model: 'gpt-4o', autoContextCompression: true // Enable smart context management }); // Long conversations are automatically managed for (let i = 1; i <= 50; i++) { const response = await agent.ask(`Tell me fact #${i} about TypeScript`); console.log(`Fact ${i}:`, response); } // Agent can still reference early conversation through compressed context const summary = await agent.ask('What was the first fact you told me?'); console.log(summary); // System retrieves from compressed context ``` ## Example with Tasks Auto context compression works with both direct conversations and tasks: ```typescript const agent = await Agent.create({ name: 'ResearchAgent', model: 'gpt-4o', autoContextCompression: true, memory: true // Often used together with memory }); // Create multiple related tasks const task1 = await agent.createTask({ prompt: "Research the latest trends in AI development" }); const result1 = await agent.executeTask(task1.id); const task2 = await agent.createTask({ prompt: "Based on the research, what are the key opportunities?" }); const result2 = await agent.executeTask(task2.id); // Task can reference previous context even if it was compressed ``` Auto context compression ensures agents can handle conversations and tasks of any length while maintaining coherence and staying within token limits. ## Configuration Options You can customize the auto context compression behavior with these parameters: ```typescript const agent = await Agent.create({ name: 'CustomContextAgent', model: 'gpt-4o', autoContextCompression: true, // Context compression configuration maxContextLength: 4000, // Trigger compression at 4000 tokens preserveLastN: 5, // Keep last 5 messages uncompressed compressionRatio: 0.4, // Target 40% size reduction compressionStrategy: 'hybrid', // Use hybrid compression strategy memory: true, }); ``` ### Configuration Parameters | Parameter | Type | Default | Description | | ------------------------ | --------- | ---------- | ---------------------------------------------- | | `autoContextCompression` | `boolean` | `false` | Enable automatic context compression | | `maxContextLength` | `number` | `8000` | Token limit before compression triggers | | `preserveLastN` | `number` | `3` | Number of recent messages to keep uncompressed | | `compressionRatio` | `number` | `0.3` | Target compression ratio (0.1 = 90% reduction) | | `compressionStrategy` | `string` | `'hybrid'` | Compression algorithm to use | ### Compression Mathematics The compression ratio determines how much the context is reduced: $\text{Compression Ratio} = \frac{\text{compressed tokens}}{\text{original tokens}}$ For example, with a ratio of 0.3: * Original: 1000 tokens * Compressed: 300 tokens * **Reduction: 70%** The token reduction percentage is calculated as: $\text{Reduction \%} = (1 - \text{ratio}) \times 100\%$ With `compressionRatio = 0.3`: $\text{Reduction} = (1 - 0.3) \times 100\% = 70\%$ ### Compression Strategies Choose the compression strategy that best fits your use case: #### `'summarize'` - Text Summarization * **Best for**: General conversations, Q\&A, discussions * **How it works**: Creates concise summaries of message groups * **Pros**: Maintains context flow, good for most use cases * **Cons**: May lose specific details ```typescript const agent = await Agent.create({ name: 'SummarizingAgent', autoContextCompression: true, compressionStrategy: 'summarize', preserveLastN: 4 }); ``` #### `'selective'` - Important Message Selection * **Best for**: Task-oriented conversations, technical discussions * **How it works**: Uses AI to identify and preserve important messages * **Pros**: Keeps crucial information intact * **Cons**: May be more resource intensive ```typescript const agent = await Agent.create({ name: 'SelectiveAgent', autoContextCompression: true, compressionStrategy: 'selective', preserveLastN: 3 }); ``` #### `'hybrid'` - Combined Approach (Recommended) * **Best for**: Most applications, balanced approach * **How it works**: Combines summarization and selective preservation * **Pros**: Balanced between context preservation and efficiency * **Cons**: None significant ```typescript const agent = await Agent.create({ name: 'HybridAgent', autoContextCompression: true, compressionStrategy: 'hybrid', // Default and recommended }); ``` ## Advanced Usage ### Custom Compression Settings by Use Case #### High-Frequency Conversations For chatbots or interactive agents with many short messages: ```typescript const chatbot = await Agent.create({ name: 'Chatbot', autoContextCompression: true, maxContextLength: 2000, // Compress more frequently preserveLastN: 8, // Keep more recent messages compressionRatio: 0.5, // More aggressive compression compressionStrategy: 'summarize' }); ``` #### Long-Form Content Creation For agents working with detailed content: ```typescript const writer = await Agent.create({ name: 'ContentWriter', autoContextCompression: true, maxContextLength: 12000, // Allow longer context preserveLastN: 3, // Keep recent context tight compressionRatio: 0.2, // Gentle compression compressionStrategy: 'selective' }); ``` #### Technical Documentation For agents handling complex technical discussions: ```typescript const techAgent = await Agent.create({ name: 'TechnicalAssistant', autoContextCompression: true, maxContextLength: 6000, preserveLastN: 5, compressionRatio: 0.3, compressionStrategy: 'hybrid' // Best for mixed content }); ``` ## How Context Compression Works ### Compression Process **Token Monitoring**: Agent continuously monitors total token count in conversation **Trigger Point**: When tokens exceed `maxContextLength`, compression is triggered **Message Preservation**: Recent `preserveLastN` messages are kept uncompressed **Content Analysis**: Older messages are analyzed based on chosen strategy **Compression**: Messages are compressed into summaries or selections **Context Update**: Compressed context replaces original messages ### What Gets Preserved * **System prompts**: Always preserved * **Recent messages**: Last N messages based on `preserveLastN` * **Important context**: Key information identified by the compression strategy * **Compressed summaries**: Condensed versions of older conversations ### Example Compression Flow ```typescript // Before compression (1200 tokens) [ { role: 'user', content: 'Tell me about TypeScript' }, { role: 'assistant', content: 'TypeScript is...' }, { role: 'user', content: 'What about interfaces?' }, { role: 'assistant', content: 'Interfaces in TypeScript...' }, { role: 'user', content: 'Show me an example' }, { role: 'assistant', content: 'Here\'s an example...' }, ] // After compression (400 tokens) [ { role: 'system', content: '[Compressed] User asked about TypeScript basics, interfaces, and examples. Assistant provided comprehensive explanations...' }, { role: 'user', content: 'Show me an example' }, { role: 'assistant', content: 'Here\'s an example...' }, ] ``` ## Monitoring and Debugging ### Context Window Information Get details about the current context state: ```typescript const contextWindow = agent.getContextWindow(); console.log({ messageCount: contextWindow.messages.length, totalTokens: contextWindow.totalTokens, maxTokens: contextWindow.maxTokens, utilization: `${contextWindow.utilizationPercentage.toFixed(1)}%` }); // Check if compression occurred const hasCompression = contextWindow.messages.some( msg => msg.metadata?.type === 'summary' ); console.log('Context compressed:', hasCompression); ``` ### Context Analysis Analyze context for optimization opportunities: ```typescript const analysis = agent.analyzeContext(); console.log({ compressionNeeded: analysis.compressionNeeded, averageTokensPerMessage: analysis.averageTokensPerMessage, suggestedCompressionRatio: analysis.suggestedCompressionRatio }); ``` ## Response Types Context management methods return detailed objects for monitoring and controlling conversation context. ### Context Window Response Get the current context window with utilization metrics: ```typescript const window = agent.getContextWindow(); // Response structure: { messages: [ { role: "user", content: "How do I use TypeScript?", timestamp: Date('2024-01-15T10:00:00Z'), tokens: 8 }, { role: "assistant", content: "TypeScript is a typed superset of JavaScript that compiles to plain JavaScript...", timestamp: Date('2024-01-15T10:00:05Z'), tokens: 50 } // ... more messages ], totalTokens: 3500, maxTokens: 8000, utilizationPercentage: 43.75 } ``` ### Context Analysis Response Analyze current context usage and compression needs: ```typescript const analysis = agent.analyzeContext(); // Response structure: { totalTokens: 6500, messageCount: 15, averageTokensPerMessage: 433, contextUtilization: 0.8125, // 81.25% of max context used compressionNeeded: true, suggestedCompressionRatio: 0.5 // Suggest 50% compression } ``` ### Compression Result Response Compress context and get detailed compression metrics: ```typescript const compression = await agent.compressContext(); // Response structure: { success: true, compressedMessages: [ { role: "system", content: "Summary: User asked about TypeScript features. Discussed types, interfaces, and generics...", timestamp: Date('2024-01-15T10:05:00Z'), tokens: 35 }, { role: "user", content: "Can you explain decorators?", timestamp: Date('2024-01-15T10:10:00Z'), tokens: 8 } // ... compressed messages (8 instead of 15) ], tokensReduced: 3250, // Tokens saved compressionRatio: 0.5, // 50% reduction achieved strategy: "summarize" // Strategy used } // On failure: { success: false, compressedMessages: [], tokensReduced: 0, compressionRatio: 0, error: "Compression failed: Minimum context threshold not reached" } ``` ### Context Summary Response Generate an AI-powered summary of the conversation: ```typescript const summary = await agent.generateContextSummary(); // Response structure: { mainTopics: [ "TypeScript development", "API design patterns", "Testing strategies" ], keyEntities: [ "Express.js", "Jest", "PostgreSQL", "Docker" ], conversationFlow: "Discussion started with TypeScript setup and configuration. Moved to API design patterns using Express.js. Covered database integration with PostgreSQL. Concluded with comprehensive testing strategies using Jest and continuous integration.", importantFacts: [ "User prefers functional programming style", "Project deadline is March 15th, 2024", "Must support Node.js 18+", "Team size is 5 developers" ], actionItems: [ "Set up Jest test framework with coverage reporting", "Create API documentation using OpenAPI/Swagger", "Configure Docker containers for development environment", "Implement CI/CD pipeline with GitHub Actions" ] } ``` ### Get Context Messages Response Retrieve all context messages as an array: ```typescript const messages = agent.getContext(); // OR const messages = agent.getContextMessages(); // Response structure: [ { role: "user", content: "How do I use async/await?", timestamp: Date('2024-01-15T09:30:00Z'), tokens: 10 }, { role: "assistant", content: "Async/await is syntactic sugar for promises...", timestamp: Date('2024-01-15T09:30:15Z'), tokens: 85 } // ... more messages ] ``` ### Export Context Response Export context returns a JSON string: ```typescript const exported = agent.exportContext(); // Response: JSON string '{"messages":[{"role":"user","content":"...","timestamp":"2024-01-15T10:00:00.000Z","tokens":10},...],"metadata":{"exportedAt":"2024-01-15T11:00:00.000Z","totalTokens":3500}}' ``` ### Import/Clear Context Response Import and clear operations return void: ```typescript // Import context agent.importContext(jsonString); // Returns: void // Clear context agent.clearContext(); // Returns: void ``` *** # Environment URL: /docs/framework/env-example Source: /app/src/content/docs/framework/env-example.mdx import { DocImage } from '@/components/DocImage'; **Environment configuration for Astreus AI applications** ## Complete Configuration ```bash # =========================================== # Astreus AI - Environment Variables Example # =========================================== # ===== DATABASE CONFIGURATION ===== # Main Application Database (Agents, Memory, Tasks, etc.) # SQLite (default for development) DB_URL=sqlite://./astreus.db # PostgreSQL (production recommended) # DB_URL=postgresql://username:password@localhost:5432/astreus_db # ===== KNOWLEDGE/RAG SYSTEM ===== # Knowledge Vector Database (PostgreSQL with pgvector extension required) # This is separate from the main database and stores vector embeddings KNOWLEDGE_DB_URL=postgresql://username:password@localhost:5432/knowledge_db # ===== LLM PROVIDERS API KEYS ===== # OpenAI OPENAI_API_KEY=sk-your-openai-api-key-here # Primary key (fallback for vision/embedding) OPENAI_VISION_API_KEY=sk-your-vision-api-key-here # Optional dedicated vision key OPENAI_EMBEDDING_API_KEY=sk-your-embedding-api-key-here # Optional dedicated embedding key OPENAI_BASE_URL=https://api.openai.com/v1 # Primary base URL (fallback for vision/embedding) OPENAI_VISION_BASE_URL=https://api.openai.com/v1 # Optional dedicated vision base URL OPENAI_EMBEDDING_BASE_URL=https://api.openai.com/v1 # Optional dedicated embedding base URL # Anthropic Claude ANTHROPIC_API_KEY=your-anthropic-api-key-here # Primary key (fallback for vision) ANTHROPIC_VISION_API_KEY=your-vision-api-key-here # Optional dedicated vision key ANTHROPIC_BASE_URL=https://api.anthropic.com # Primary base URL (fallback for vision) ANTHROPIC_VISION_BASE_URL=https://api.anthropic.com # Optional dedicated vision base URL # Google Gemini GEMINI_API_KEY=your-gemini-api-key-here # Primary key (replaces GOOGLE_API_KEY) GEMINI_VISION_API_KEY=your-vision-api-key-here # Optional dedicated vision key GEMINI_EMBEDDING_API_KEY=your-embedding-api-key-here # Optional dedicated embedding key GEMINI_BASE_URL=https://generativelanguage.googleapis.com # Primary base URL (fallback for vision/embedding) GEMINI_VISION_BASE_URL=https://generativelanguage.googleapis.com # Optional dedicated vision base URL GEMINI_EMBEDDING_BASE_URL=https://generativelanguage.googleapis.com # Optional dedicated embedding base URL # Ollama (for local models) OLLAMA_BASE_URL=http://localhost:11434 # Same as before # ===== APPLICATION SETTINGS ===== # Environment NODE_ENV=development # Options: 'development' | 'production' | 'test' # ===== DATABASE ENCRYPTION ===== # Enable/disable field-level encryption for sensitive data ENCRYPTION_ENABLED=true # Options: 'true' | 'false' # Master encryption key (required when ENCRYPTION_ENABLED=true) # IMPORTANT: Generate a strong 32+ character key and keep it secure! # You can generate one with: openssl rand -hex 32 ENCRYPTION_MASTER_KEY=your-256-bit-encryption-key-here-keep-it-safe-and-secure # Encryption algorithm (default: aes-256-gcm) ENCRYPTION_ALGORITHM=aes-256-gcm ``` *** # Graph URL: /docs/framework/graph Source: /app/src/content/docs/framework/graph.mdx import { DocImage } from '@/components/DocImage'; **Workflow orchestration with dependency management and parallel execution** ## Overview The Graph system enables you to create complex workflows by connecting tasks and agents with dependencies, conditions, and parallel execution capabilities. It provides a visual and programmatic way to orchestrate multi-step processes, handle branching logic, and coordinate multiple agents working together. ## Creating a Graph Graphs are composed of nodes (tasks or agents) and edges (connections between them): ```typescript import { Graph } from '@astreus-ai/astreus'; // Create a workflow graph with agent reference const agent = await Agent.create({ name: 'ContentAgent', model: 'gpt-4o' }); const graph = new Graph({ name: 'content-creation-pipeline', description: 'Research and write technical content' }, agent); // Pass agent as second parameter // Add task nodes const researchNodeId = graph.addTaskNode({ prompt: 'Research the latest TypeScript features and summarize key findings', model: 'gpt-4o', priority: 10, metadata: { type: 'research' } }); const writeNodeId = graph.addTaskNode({ prompt: 'Write a comprehensive blog post based on the research findings', model: 'gpt-4o', dependencies: [researchNodeId], // Depends on research completion priority: 5, metadata: { type: 'writing' } }); // Execute the graph const results = await graph.run(); console.log('Success:', results.success); console.log('Completed nodes:', results.completedNodes); console.log('Failed nodes:', results.failedNodes); console.log('Duration:', results.duration, 'ms'); console.log('Results:', results.results); ``` ## Graph Execution Flow ### Node Resolution Graph analyzes all nodes and their dependencies to determine execution order. ### Parallel Execution Independent nodes run simultaneously for optimal performance. ### Dependency Waiting Dependent nodes wait for their prerequisites to complete before starting. ### Result Collection All node outputs are collected and made available in the final result. ## Advanced Example Here's a complex workflow with dependencies, parallel execution, and error handling: ```typescript import { Graph } from '@astreus-ai/astreus'; // Create workflow graph with default agent const agent = await Agent.create({ name: 'OptimizationAgent', model: 'gpt-4o' }); const graph = new Graph({ name: 'code-optimization-pipeline', description: 'Analyze and optimize codebase', maxConcurrency: 3, // Allow 3 parallel nodes timeout: 300000, // 5 minute timeout retryAttempts: 2 // Retry failed nodes twice }, agent); // Pass agent as second parameter // Add task nodes with proper configuration const analysisNodeId = graph.addTaskNode({ prompt: 'Analyze the codebase for performance issues and categorize them by severity', model: 'gpt-4o', priority: 10, // High priority metadata: { step: 'analysis', category: 'review' } }); const optimizationNodeId = graph.addTaskNode({ prompt: 'Based on the analysis, implement performance optimizations', model: 'gpt-4o', dependencies: [analysisNodeId], // Depends on analysis priority: 8, metadata: { step: 'optimization', category: 'implementation' } }); const testNodeId = graph.addTaskNode({ prompt: 'Run performance tests and validate the optimizations', model: 'gpt-4o', dependencies: [optimizationNodeId], // Depends on optimization priority: 6, stream: true, // Enable streaming for real-time feedback metadata: { step: 'testing', category: 'validation' } }); const documentationNodeId = graph.addTaskNode({ prompt: 'Document all changes and performance improvements', model: 'gpt-4o', dependencies: [analysisNodeId], // Can run parallel to optimization priority: 5, // Lower priority metadata: { step: 'documentation', category: 'docs' } }); // Add edges (optional, as dependencies already create edges) graph.addEdge(analysisNodeId, optimizationNodeId); graph.addEdge(analysisNodeId, documentationNodeId); graph.addEdge(optimizationNodeId, testNodeId); // Execute the graph const results = await graph.run(); console.log('Pipeline results:', results); console.log('Completed nodes:', results.completedNodes); console.log('Failed nodes:', results.failedNodes); console.log('Duration:', results.duration, 'ms'); // Access individual node results Object.entries(results.results).forEach(([nodeId, result]) => { console.log(`Node ${nodeId}:`, result); }); // Check for errors if (results.errors && Object.keys(results.errors).length > 0) { console.log('Errors:', results.errors); } ``` ## Graph Configuration Graphs support various configuration options: ```typescript interface GraphConfig { id?: string; // Optional graph ID (UUID) name: string; // Graph name (required) description?: string; // Graph description maxConcurrency?: number; // Max parallel execution (default: 1) timeout?: number; // Execution timeout in ms retryAttempts?: number; // Retry attempts for failed nodes autoLink?: boolean; // Automatically link nodes based on dependencies maxContextTokens?: number; // Maximum context tokens for the graph contextWarningThreshold?: number; // Warning threshold for context usage (0-1, e.g., 0.8 = 80%) subAgentNodeTimeout?: number; // Extended timeout for sub-agent nodes (default: 5 minutes) metadata?: MetadataObject; // Custom metadata subAgentAware?: boolean; // Enable sub-agent awareness and optimization optimizeSubAgentUsage?: boolean; // Optimize sub-agent delegation patterns subAgentCoordination?: 'parallel' | 'sequential' | 'adaptive'; // Default sub-agent coordination } // Note: The default agent is passed as the second parameter to the constructor: // new Graph(config, agent) // The graph's defaultAgentId is automatically set from the agent's ID. // Example with full configuration including sub-agent support const graph = new Graph({ name: 'advanced-pipeline', description: 'Complex workflow with error handling and sub-agent coordination', maxConcurrency: 5, timeout: 600000, // 10 minutes retryAttempts: 3, subAgentAware: true, optimizeSubAgentUsage: true, subAgentCoordination: 'adaptive', metadata: { project: 'automation', version: '1.0' } }, agent); // Agent passed as second parameter ``` ## Node Types and Options ### Task Nodes ```typescript interface AddTaskNodeOptions { name?: string; // Node name for easy referencing prompt: string; // Task prompt (required) model?: string; // Override model for this task agentId?: string; // Override default agent (UUID) stream?: boolean; // Enable streaming for this task schedule?: string; // Simple schedule string (e.g., 'daily@09:00', 'after:5s') dependencies?: string[]; // Node IDs this task depends on dependsOn?: string[]; // Node names this task depends on (easier than IDs) priority?: number; // Execution priority (higher = earlier) metadata?: MetadataObject; // Custom metadata useSubAgents?: boolean; // Force enable/disable sub-agent usage for this task subAgentDelegation?: 'auto' | 'manual' | 'sequential'; // Sub-agent delegation strategy subAgentCoordination?: 'parallel' | 'sequential'; // Sub-agent coordination pattern } ``` ### Agent Nodes ```typescript interface AddAgentNodeOptions { agentId: string; // Agent ID (required, UUID) dependencies?: string[]; // Node IDs this agent depends on priority?: number; // Execution priority metadata?: MetadataObject; // Custom metadata } ``` ## Sub-Agent Configuration Options When configuring graphs with sub-agent support, you have comprehensive control over delegation and coordination: ### Graph-Level Sub-Agent Configuration * **subAgentAware**: Enables automatic detection and optimization of sub-agent opportunities across the graph * **optimizeSubAgentUsage**: Enables real-time performance monitoring and automatic strategy adjustment for better efficiency * **subAgentCoordination**: Sets the default coordination pattern: * `'parallel'`: Sub-agents work simultaneously across different nodes * `'sequential'`: Sub-agents work in dependency order, passing context between executions * `'adaptive'`: Dynamically chooses the best coordination pattern based on task complexity and dependencies ### Node-Level Sub-Agent Configuration Each task node can override graph-level settings with specific sub-agent behavior: * **useSubAgents**: Force enable or disable sub-agent delegation for specific nodes * **subAgentDelegation**: Control how tasks are distributed to sub-agents at the node level * **subAgentCoordination**: Override the graph's default coordination pattern for specific nodes ### Enhanced Graph Workflow with Sub-Agents ```typescript import { Graph, Agent } from '@astreus-ai/astreus'; // Create specialized sub-agents const researcher = await Agent.create({ name: 'DataResearcher', systemPrompt: 'You specialize in gathering and analyzing data from multiple sources.' }); const analyst = await Agent.create({ name: 'TechnicalAnalyst', systemPrompt: 'You provide technical insights and recommendations.' }); const writer = await Agent.create({ name: 'TechnicalWriter', systemPrompt: 'You create clear, comprehensive technical documentation.' }); // Main coordinator with sub-agents const coordinator = await Agent.create({ name: 'ProjectCoordinator', systemPrompt: 'You orchestrate complex projects using specialized team members.', subAgents: [researcher, analyst, writer] }); // Create sub-agent optimized graph // Note: defaultAgentId is automatically set from the coordinator agent passed as second parameter const projectGraph = new Graph({ name: 'Technical Documentation Pipeline', description: 'Automated technical documentation creation with specialized agents', maxConcurrency: 3, subAgentAware: true, optimizeSubAgentUsage: true, subAgentCoordination: 'adaptive' }, coordinator); // The coordinator's ID becomes the graph's defaultAgentId // Research phase with automatic sub-agent delegation const researchNode = projectGraph.addTaskNode({ name: 'Market Research', prompt: 'Research current trends in cloud computing and serverless architecture', useSubAgents: true, subAgentDelegation: 'auto', priority: 10, metadata: { phase: 'research', category: 'data-gathering' } }); // Analysis phase with sequential sub-agent coordination const analysisNode = projectGraph.addTaskNode({ name: 'Technical Analysis', prompt: 'Analyze research findings and identify key technical patterns', dependencies: [researchNode], useSubAgents: true, subAgentDelegation: 'auto', subAgentCoordination: 'sequential', priority: 8, metadata: { phase: 'analysis', category: 'insights' } }); // Documentation phase with parallel sub-agent work const docNode = projectGraph.addTaskNode({ name: 'Documentation Creation', prompt: 'Create comprehensive technical documentation and executive summary', dependencies: [analysisNode], useSubAgents: true, subAgentDelegation: 'manual', subAgentCoordination: 'parallel', priority: 6, metadata: { phase: 'documentation', category: 'deliverables' } }); // Execute the graph const result = await projectGraph.run(); console.log('Pipeline completed:', result.success); console.log('Node results:', result.results); ``` ## Response Types Graph execution returns comprehensive results including node outcomes, usage statistics, and performance metrics. ### Graph Execution Result The `graph.run()` method returns a detailed `GraphExecutionResult`: ```typescript const result = await graph.run({ timeout: 60000 }); // Response structure: { graph: { id: "graph-uuid-123", defaultAgentId: "agent-uuid", // Set from the agent passed to constructor config: { name: "code-optimization-pipeline", description: "Analyze and optimize codebase", maxConcurrency: 3, timeout: 300000, retryAttempts: 2 }, nodes: [ /* GraphNode[] */ ], edges: [ /* GraphEdge[] */ ], status: "completed", // 'idle' | 'running' | 'completed' | 'failed' | 'paused' startedAt: Date('2024-01-15T10:00:00Z'), completedAt: Date('2024-01-15T10:12:30Z'), executionLog: [ /* GraphExecutionLogEntry[] */ ], usage: { /* GraphUsage */ }, createdAt: Date('2024-01-15T09:55:00Z'), updatedAt: Date('2024-01-15T10:12:30Z') }, success: true, // Overall success status completedNodes: 5, // Number of successfully completed nodes failedNodes: 0, // Number of failed nodes duration: 12500, // Total execution time in milliseconds results: { "node_abc12345-...": "Analysis complete: Found 15 performance issues categorized by severity...", "node_def67890-...": "Optimization implemented: 40% performance improvement...", "node_ghi11111-...": "Tests passed: All optimizations validated...", "node_jkl22222-...": "Documentation updated with all changes...", "node_mno33333-...": "Final review completed..." }, errors: {}, // Empty if all nodes succeeded usage: { totalPromptTokens: 1500, totalCompletionTokens: 3000, totalTokens: 4500, totalContextTokens: 500, totalCost: 0.045, nodeUsages: { "node_abc12345-...": { promptTokens: 200, completionTokens: 400, totalTokens: 600, contextTokens: 100, model: "gpt-4", cost: 0.012 }, "node_def67890-...": { promptTokens: 300, completionTokens: 600, totalTokens: 900, contextTokens: 150, model: "gpt-4", cost: 0.018 } // ... more node usages }, modelsUsed: ["gpt-4", "gpt-3.5-turbo"] } } ``` ### Graph Execution with Errors When nodes fail, errors are included in the response: ```typescript const result = await graph.run(); // Response with failures: { graph: { /* ... */ }, success: false, completedNodes: 3, failedNodes: 2, duration: 8500, results: { "node_abc12345-...": "Successfully completed...", "node_def67890-...": "Partial completion...", "node_ghi11111-...": "Task completed..." }, errors: { "node_jkl22222-...": "Error: Timeout exceeded after 5000ms", "node_mno33333-...": "Error: Dependency node_jkl22222-... failed, skipping execution" }, usage: { /* ... */ } } ``` ### Add Node Response Adding nodes returns the node ID (format: `node_`): ```typescript const nodeId = graph.addTaskNode({ name: "Analyze Data", prompt: "Analyze the following data...", model: "gpt-4", priority: 10 }); // Response: "node_a1b2c3d4-e5f6-7890-abcd-ef1234567890" (node ID string) ``` ### Node Usage Details Each node's usage is tracked individually: ```typescript // Access individual node usage from result const nodeUsage = result.usage.nodeUsages["node_abc12345-..."]; // Structure: { promptTokens: 200, completionTokens: 400, totalTokens: 600, contextTokens: 100, // Optional: tokens from context/memory model: "gpt-4", cost: 0.012 // Optional: calculated cost } ``` ### Graph Usage Summary Total usage across all nodes: ```typescript const totalUsage = result.usage; // Structure: { totalPromptTokens: 1500, // Sum of all prompt tokens totalCompletionTokens: 3000, // Sum of all completion tokens totalTokens: 4500, // Total tokens used totalContextTokens: 500, // Total context tokens loaded totalCost: 0.045, // Total estimated cost nodeUsages: { /* ... */ }, // Per-node breakdown modelsUsed: ["gpt-4", "gpt-3.5-turbo"] // All models used in execution } ``` *** # Install URL: /docs/framework/install Source: /app/src/content/docs/framework/install.mdx import { DocImage } from '@/components/DocImage'; ## Node.js Version Requirements Astreus requires Node.js >=22.0.0. Here's how to check your version: ```bash node --version ``` If you need to update Node.js, visit [nodejs.org](https://nodejs.org/en/download) ## Installing Astreus ### 1. Install Astreus Install Astreus using npm or your preferred package manager: ```bash npm install @astreus-ai/astreus ``` Or with yarn: ```bash yarn add @astreus-ai/astreus ``` Or with pnpm: ```bash pnpm add @astreus-ai/astreus ``` Installation successful! You're ready to create your first AI agent. After installation, the package is ready to import into TypeScript projects, local prototypes, and production services. Most teams continue with the quickstart guide, create an agent instance, configure a provider, and then add memory, tools, or graph workflows as the application grows. Keeping this setup small at the beginning makes it easier to validate the runtime before adding more advanced orchestration. *** # Intro URL: /docs/framework/intro Source: /app/src/content/docs/framework/intro.mdx **Open-source AI agent framework for building autonomous systems that solve real-world tasks effectively.** Astreus is the developer-friendly AI agent framework that lets you build powerful, production-ready agents in minutes. Rapidly develop sophisticated AI systems with full control over capabilities while maintaining clean, maintainable code. ## Installation ```bash npm install @astreus-ai/astreus ``` ## Basic Usage ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'Assistant', model: 'gpt-4o', memory: true }); const response = await agent.ask('How can you help me?'); ``` ## Core Features } title="Sub-Agents"> Intelligent task delegation with specialized agent coordination, hierarchical workflows, and LLM-powered assignment. } title="Advanced Memory System"> Per-agent persistent memory with automatic context integration and vector search capabilities. } title="Task Orchestration"> Structured task execution with status tracking, dependency management, and streaming support. } title="Graph Workflows"> Complex workflow orchestration with conditional execution, parallel processing, and sub-agent integration. } title="MCP Integration"> Model Context Protocol support for seamless external tool and service connections. } title="Plugin System"> Extensible tool integration with JSON schema validation and automatic LLM function calling. } title="Vision Processing"> Built-in image analysis and document processing capabilities for multimodal interactions. } title="Knowledge Base"> RAG integration with document chunking, vector embeddings, and similarity search. *** # Knowledge URL: /docs/framework/knowledge Source: /app/src/content/docs/framework/knowledge.mdx import { DocImage } from '@/components/DocImage'; **RAG integration with document processing and vector search** ## Overview The Knowledge system provides retrieval-augmented generation (RAG) capabilities, allowing agents to access and utilize external documents in their responses. It automatically processes documents, creates vector embeddings, and enables semantic search for relevant information. Agents with knowledge can provide more accurate, contextual responses based on your documents. ## Enabling Knowledge Enable knowledge for an agent by setting the `knowledge` option to `true`: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'KnowledgeAgent', model: 'gpt-4o', knowledge: true, // Enable knowledge base access (default: false) embeddingModel: 'text-embedding-3-small' // Optional: specify embedding model }); ``` ## Adding Documents ### Add Text Content Add content directly as a string: ```typescript await agent.addKnowledge( 'Your important content here', 'Document Title', { category: 'documentation' } ); ``` ### Add from File Add content from supported file types: ```typescript // Add PDF file await agent.addKnowledgeFromFile( '/path/to/document.pdf', { source: 'manual', version: '1.0' } ); // Add text file await agent.addKnowledgeFromFile('/path/to/notes.txt'); ``` ### Add from Directory Process all supported files in a directory: ```typescript await agent.addKnowledgeFromDirectory( '/path/to/docs', { project: 'documentation' } ); ``` ## Supported File Types * **Text files**: `.txt`, `.md`, `.json` * **PDF files**: `.pdf` (with text extraction) ## How It Works The knowledge system follows a sophisticated processing pipeline: ### Document Processing Documents are stored and indexed in the knowledge database with metadata. ### Text Chunking Content is split into chunks (1500 characters with 300 character overlap) for optimal retrieval. The overlap ensures context continuity: $\text{overlap ratio} = \frac{300}{1500} = 0.2 = 20\%$ This prevents important information from being split across chunk boundaries. ### Vector Embeddings Each chunk is converted to vector embeddings using OpenAI, Gemini, or Ollama embedding models. Common embedding dimensions: * `text-embedding-3-small`: 1536 dimensions (OpenAI) * `text-embedding-3-large`: 3072 dimensions (OpenAI) * `text-embedding-ada-002`: 1536 dimensions (OpenAI) * `text-embedding-004`: 768 dimensions (Gemini) The Euclidean distance between vectors can also be used: $d(\vec{p}, \vec{q}) = \sqrt{\sum_{i=1}^{n}(p_i - q_i)^2}$ ### Semantic Search When agents receive queries, relevant chunks are retrieved using cosine similarity search. The similarity between query and document vectors is calculated using: $\text{cosine similarity} = \cos(\theta) = \frac{\vec{A} \cdot \vec{B}}{||\vec{A}|| \cdot ||\vec{B}||} = \frac{\sum_{i=1}^{n} A_i B_i}{\sqrt{\sum_{i=1}^{n} A_i^2} \cdot \sqrt{\sum_{i=1}^{n} B_i^2}}$ Where: * $\vec{A}$ is the query embedding vector * $\vec{B}$ is the document chunk embedding vector * Higher values (closer to 1) indicate greater similarity ### Context Integration Retrieved information is automatically added to the agent's context for enhanced responses. ## Example Usage Here's a complete example of using knowledge with an agent: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create agent with knowledge enabled const agent = await Agent.create({ name: 'DocumentAssistant', model: 'gpt-4o', knowledge: true, embeddingModel: 'text-embedding-3-small', // Optional: specify embedding model systemPrompt: 'You are a helpful assistant with access to company documentation.' }); // Add documentation await agent.addKnowledgeFromFile('./company-handbook.pdf', { type: 'handbook', department: 'hr' }); await agent.addKnowledge(` Our API uses REST principles with JSON responses. Authentication is done via Bearer tokens. Rate limiting is 1000 requests per hour. `, 'API Documentation', { type: 'api-docs', version: '2.0' }); // Query with automatic knowledge retrieval const response = await agent.ask('What is our API rate limit?'); console.log(response); // The agent will automatically search the knowledge base and include relevant context // Manual knowledge search const results = await agent.searchKnowledge('API authentication', 5, 0.7); results.forEach(result => { console.log(`Similarity: ${result.similarity}`); console.log(`Content: ${result.content}`); }); ``` ## Managing Knowledge ### Available Methods ```typescript // List all documents with metadata const documents = await agent.getKnowledgeDocuments(); // Returns: Array<{ id: string; title: string; created_at: string }> // Delete specific document by ID (documentId is UUID string) const success = await agent.deleteKnowledgeDocument(documentId); // Returns: boolean indicating success // Delete specific chunk by ID (chunkId is UUID string) const success = await agent.deleteKnowledgeChunk(chunkId); // Returns: boolean indicating success // Clear all knowledge for this agent await agent.clearKnowledge(); // Returns: void // Search with custom parameters const results = await agent.searchKnowledge( 'search query', 10, // limit: max results (default: 5) 0.8 // threshold: similarity threshold (0-1, default: 0.7) ); // Returns: Array<{ content: string; metadata: MetadataObject; similarity: number }> // Get relevant context for a query const context = await agent.getKnowledgeContext( 'query text', 5 // limit: max chunks to include (default: 5) ); // Returns: string with concatenated relevant content // Expand context around a specific chunk const expandedChunks = await agent.expandKnowledgeContext( documentId, // Document ID (UUID string) chunkIndex, // Chunk index within document 2, // expandBefore: chunks to include before (default: 1) 2 // expandAfter: chunks to include after (default: 1) ); // Returns: Array with expanded chunk content ``` ## Configuration ### Environment Variables ```bash # Database (required) KNOWLEDGE_DB_URL=postgresql://user:password@host:port/database # API key for embeddings OPENAI_API_KEY=your_openai_key # Or use dedicated embedding keys: OPENAI_EMBEDDING_API_KEY=your_embedding_key OPENAI_EMBEDDING_BASE_URL=https://api.openai.com/v1 # Optional: custom endpoint for embeddings GEMINI_API_KEY=your_gemini_key GEMINI_EMBEDDING_API_KEY=your_gemini_embedding_key # For Ollama embeddings (local) OLLAMA_BASE_URL=http://localhost:11434 ``` ### Embedding Model Configuration Specify the embedding model directly in the agent configuration: ```typescript const agent = await Agent.create({ name: 'KnowledgeAgent', model: 'gpt-4o', embeddingModel: 'text-embedding-3-small', // Specify embedding model here knowledge: true }); ``` ## Response Types Understanding knowledge method responses helps you work with the data effectively. ### Add Knowledge Response Adding knowledge returns the UUID of the created document: ```typescript const documentId = await agent.addKnowledge( "TypeScript is a typed superset of JavaScript...", "TypeScript Overview", { source: "documentation", version: "5.0" } ); // Response: "550e8400-e29b-41d4-a716-446655440000" (UUID string) ``` ### Search Knowledge Response Search returns an array of chunks with content, metadata, and similarity scores: ```typescript const results = await agent.searchKnowledge("TypeScript types", 5, 0.7); // Response structure: [ { content: "TypeScript provides static typing which helps catch errors at compile time...", metadata: { title: "TypeScript Overview", source: "documentation", version: "5.0" }, similarity: 0.95 }, { content: "Types in TypeScript include primitives like string, number, boolean...", metadata: { title: "Type System", source: "tutorial" }, similarity: 0.87 }, { content: "Advanced types like generics and conditional types provide powerful abstractions...", metadata: { title: "Advanced Types", source: "documentation" }, similarity: 0.79 } ] ``` ### Get Knowledge Context Response Context retrieval returns a concatenated string of relevant chunks: ```typescript const context = await agent.getKnowledgeContext("TypeScript", 3); // Response: concatenated string with separator "TypeScript is a typed superset of JavaScript...\n\n---\n\nTypes help catch errors at compile time...\n\n---\n\nAdvanced types provide powerful abstractions..." ``` ### Get Knowledge Documents Response Listing documents returns metadata for all stored documents: ```typescript const documents = await agent.getKnowledgeDocuments(); // Response structure: [ { id: "doc-uuid-1", // UUID string title: "TypeScript Overview", created_at: "2024-01-15T10:30:00Z" // ISO 8601 timestamp }, { id: "doc-uuid-2", title: "Advanced Types", created_at: "2024-01-16T14:20:00Z" }, { id: "doc-uuid-3", title: "Best Practices", created_at: "2024-01-17T09:15:00Z" } ] ``` ### Expand Knowledge Context Response Context expansion returns an array of chunk strings: ```typescript const chunks = await agent.expandKnowledgeContext("doc-uuid", 5, 2, 2); // Response structure (plain chunk content): [ "Earlier context before the target chunk...", "More context leading to the target...", "This is the target chunk with the main content...", "Following context after the target...", "Additional context for full understanding..." ] ``` ### Delete Responses Delete operations return booleans indicating success: ```typescript // Delete specific document const docDeleted = await agent.deleteKnowledgeDocument("doc-uuid"); // Returns: true or false // Delete specific chunk const chunkDeleted = await agent.deleteKnowledgeChunk("chunk-uuid"); // Returns: true or false ``` ### Clear Knowledge Response Clearing all knowledge returns void (no return value): ```typescript await agent.clearKnowledge(); // Returns: void (undefined) ``` ### File Operations Response File-based knowledge operations return void on success or throw on error: ```typescript // Add from file await agent.addKnowledgeFromFile('./document.pdf', { source: 'manual' }); // Returns: void // Add from directory await agent.addKnowledgeFromDirectory('./docs', { project: 'main' }); // Returns: void ``` *** # LLM URL: /docs/framework/llm Source: /app/src/content/docs/framework/llm.mdx import { DocImage } from '@/components/DocImage'; **Unified interface for multiple LLM providers with automatic routing** ## Overview The LLM abstraction layer provides seamless integration with multiple AI providers, allowing you to switch between OpenAI, Claude, Gemini, and Ollama without changing your code. It handles provider-specific implementations, message formatting, and streaming while providing a consistent API across all providers. ## Supported Providers Astreus supports four major LLM providers with automatic model routing: ### OpenAI **All 14 supported models:** * **Latest**: `gpt-4.5`, `gpt-4.1`, `gpt-4.1-mini`, `gpt-4.1-nano`, `o4-mini`, `o4-mini-high`, `o3` * **Stable**: `gpt-4o`, `gpt-4o-mini`, `gpt-4-turbo`, `gpt-4`, `gpt-3.5-turbo`, `gpt-3.5-turbo-16k`, `gpt-3.5-turbo-instruct` * **API Key**: Set `OPENAI_API_KEY` environment variable ### Anthropic Claude **All 9 supported models:** * **Latest**: `claude-sonnet-4-20250514`, `claude-opus-4-20250514`, `claude-3.7-sonnet-20250224` * **Stable**: `claude-3-5-sonnet-20241022`, `claude-3-5-sonnet-20240620`, `claude-3-5-haiku-20241022`, `claude-3-opus-20240229`, `claude-3-sonnet-20240229`, `claude-3-haiku-20240307` * **API Key**: Set `ANTHROPIC_API_KEY` environment variable ### Google Gemini **All 12 supported models:** * **Latest**: `gemini-2.5-pro`, `gemini-2.5-pro-deep-think`, `gemini-2.5-flash`, `gemini-2.5-flash-lite` * **Stable**: `gemini-2.0-flash`, `gemini-2.0-flash-thinking`, `gemini-2.0-flash-lite`, `gemini-2.0-pro-experimental`, `gemini-1.5-pro`, `gemini-1.5-flash`, `gemini-1.5-flash-8b`, `gemini-pro` * **API Key**: Set `GEMINI_API_KEY` environment variable ### Ollama (Local) **All 31 supported models:** * **Latest**: `deepseek-r1`, `deepseek-v3`, `deepseek-v2.5`, `deepseek-coder`, `deepseek-coder-v2`, `qwen3`, `qwen2.5-coder`, `llama3.3`, `gemma3`, `phi4` * **Popular**: `mistral-small`, `codellama`, `llama3.2`, `llama3.1`, `qwen2.5`, `gemma2`, `phi3`, `mistral`, `codegemma`, `wizardlm2` * **Additional**: `dolphin-mistral`, `openhermes`, `deepcoder`, `stable-code`, `wizardcoder`, `magicoder`, `solar`, `yi`, `zephyr`, `orca-mini`, `vicuna` * **Configuration**: Set `OLLAMA_BASE_URL` (default: `http://localhost:11434`) ## Configuration ### Environment Variables Set up your API keys and configuration: ```bash # OpenAI export OPENAI_API_KEY="your-openai-key" export OPENAI_BASE_URL="https://api.openai.com/v1" # Optional # Anthropic Claude export ANTHROPIC_API_KEY="your-anthropic-key" export ANTHROPIC_BASE_URL="https://api.anthropic.com" # Optional # Google Gemini export GEMINI_API_KEY="your-gemini-key" # Ollama (Local) export OLLAMA_BASE_URL="http://localhost:11434" # Optional ``` ### Agent Configuration Specify the model when creating agents: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'MyAgent', model: 'gpt-4.5', // Model automatically routes to correct provider temperature: 0.7, maxTokens: 2000 }); ``` ## Usage Examples ### Basic LLM Usage ```typescript import { getLLM } from '@astreus-ai/astreus'; const llm = getLLM(); // Generate response const response = await llm.generateResponse({ model: 'claude-sonnet-4-20250514', messages: [{ role: 'user', content: 'Explain quantum computing' }], temperature: 0.7, maxTokens: 1000 }); console.log(response.content); ``` ### Streaming Responses ```typescript // Stream response in real-time for await (const chunk of llm.generateStreamResponse({ model: 'gpt-4.5', messages: [{ role: 'user', content: 'Write a story about AI' }], stream: true })) { if (!chunk.done) { process.stdout.write(chunk.content); } } ``` ### Function Calling ```typescript const response = await llm.generateResponse({ model: 'gpt-4o', messages: [{ role: 'user', content: 'What\'s the weather in Tokyo?' }], tools: [{ type: 'function', function: { name: 'get_weather', description: 'Get current weather information', parameters: { type: 'object', properties: { location: { type: 'string', description: 'City name' } }, required: ['location'] } } }] }); // Handle tool calls if (response.toolCalls) { response.toolCalls.forEach(call => { console.log(`Tool: ${call.function.name}`); console.log(`Args: ${call.function.arguments}`); }); } ``` ## LLM Options Configure LLM behavior with these options: ```typescript interface LLMRequestOptions { model: string; // Required: Model identifier messages: LLMMessage[]; // Required: Conversation history temperature?: number; // Creativity level (0.0-1.0, default: 0.7) maxTokens?: number; // Max output tokens (default: 4096) stream?: boolean; // Enable streaming responses systemPrompt?: string; // System instructions tools?: Tool[]; // Function calling tools } ``` ### Parameter Details * **temperature**: Controls randomness (0.0 = deterministic, 1.0 = very creative) * **maxTokens**: Maximum tokens in the response (varies by model) * **stream**: Enable real-time streaming for long responses * **systemPrompt**: Sets behavior and context for the model * **tools**: Enable function calling capabilities ## Provider Features | Feature | OpenAI | Claude | Gemini | Ollama | | ---------------- | ------ | ------ | ------- | ------- | | Streaming | ✅ | ✅ | ✅ | ✅ | | Function Calling | ✅ | ✅ | Limited | Limited | | Vision | ✅ | ✅ | ✅ | ✅ | | Embeddings | ✅ | ❌ | ✅ | ✅ | | Token Usage | ✅ | ✅ | Limited | ✅ | | Custom Base URL | ✅ | ✅ | ❌ | ✅ | | Local Models | ❌ | ❌ | ❌ | ✅ | ## Vision Models Each provider supports specific models for image analysis: ### OpenAI Vision * `gpt-4o`, `gpt-4o-mini`, `gpt-4-turbo`, `gpt-4-vision-preview` * `gpt-4o-2024-08-06`, `gpt-4o-2024-05-13` ### Claude Vision * `claude-3-5-sonnet-20241022`, `claude-3-5-sonnet-20240620` * `claude-3-opus-20240229`, `claude-3-sonnet-20240229`, `claude-3-haiku-20240307` ### Gemini Vision * `gemini-1.5-pro`, `gemini-1.5-flash` * `gemini-1.0-pro-vision-latest`, `gemini-pro-vision` ### Ollama Vision * `llava`, `llava:7b`, `llava:13b`, `llava:34b` * `llava-llama3`, `llava-phi3`, `moondream` ## Embedding Models For knowledge base and semantic search: ### OpenAI Embeddings * `text-embedding-3-large` (3072 dimensions) * `text-embedding-3-small` (1536 dimensions) * `text-embedding-ada-002` (1536 dimensions) ### Gemini Embeddings * `text-embedding-004` * `embedding-001` ### Ollama Embeddings * `nomic-embed-text`, `mxbai-embed-large` * `all-minilm`, `snowflake-arctic-embed` > **Note**: Claude/Anthropic does not support embeddings. Use OpenAI or Gemini for embedding generation. ## Additional Environment Variables ```bash # Dedicated embedding API keys (optional) OPENAI_EMBEDDING_API_KEY="your-embedding-key" OPENAI_EMBEDDING_BASE_URL="https://api.openai.com/v1" GEMINI_EMBEDDING_API_KEY="your-gemini-embedding-key" # Dedicated vision API keys (optional) OPENAI_VISION_API_KEY="your-vision-key" OPENAI_VISION_BASE_URL="https://api.openai.com/v1" ANTHROPIC_VISION_API_KEY="your-anthropic-vision-key" ANTHROPIC_VISION_BASE_URL="https://api.anthropic.com" GEMINI_VISION_API_KEY="your-gemini-vision-key" ``` ## Model Selection Guide ### For Code Generation * **Best**: `gpt-4o`, `claude-3-5-sonnet-20241022`, `deepseek-coder` * **Fast**: `gpt-4o-mini`, `claude-3-5-haiku-20241022` ### For Reasoning Tasks * **Best**: `claude-opus-4-20250514`, `gpt-4.5`, `o3` * **Balanced**: `claude-sonnet-4-20250514`, `gpt-4o` ### For Creative Writing * **Best**: `gpt-4.5`, `claude-3-opus-20240229` * **Fast**: `gemini-2.5-pro`, `gpt-4o-mini` ### For Privacy/Local Use * **Best**: `deepseek-r1`, `llama3.3`, `qwen3` * **Code**: `deepseek-coder`, `codellama` *** # MCP URL: /docs/framework/mcp Source: /app/src/content/docs/framework/mcp.mdx import { DocImage } from '@/components/DocImage'; **Model Context Protocol integration for connecting agents with external tools and services** ## Overview MCP (Model Context Protocol) enables Astreus agents to connect with external tools and services seamlessly. Define MCP servers as simple objects with automatic environment variable loading and use them at different levels - agent, task, or conversation level. ## Type Definitions ### MCPServerDefinition ```typescript interface MCPServerDefinition { name: string; // Server name for identification (required) command?: string; // Command to execute (for stdio servers) args?: string[]; // Command arguments env?: Record; // Environment variable overrides url?: string; // URL for SSE servers cwd?: string; // Working directory } ``` ### MCPTool ```typescript interface MCPTool { name: string; description: string; inputSchema: MCPJsonSchema; } ``` ### MCPToolResult ```typescript interface MCPToolResult { content: Array<{ type: string; text?: string; }>; isError?: boolean; } ``` ### MCPValue ```typescript type MCPPrimitive = string | number | boolean | null; type MCPValue = MCPPrimitive | MCPPrimitive[] | { [key: string]: MCPValue }; ``` ## Creating MCP Servers Define MCP servers as array objects with automatic environment loading: ```typescript import { Agent } from '@astreus-ai/astreus'; // Define MCP servers array const mcpServers = [ { name: 'github', command: "npx", args: ["-y", "@modelcontextprotocol/server-github"] // GITHUB_PERSONAL_ACCESS_TOKEN loaded from .env automatically }, { name: 'filesystem', command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/Documents"] } ]; const agent = await Agent.create({ name: 'DevAgent', model: 'gpt-4' }); // Add MCP servers to agent await agent.addMCPServers(mcpServers); // Use automatically in conversations const response = await agent.ask("List my repositories and save to repos.txt"); ``` ## Example Here's a complete example showing MCP integration: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create agent const agent = await Agent.create({ name: 'DevAssistant', model: 'gpt-4', systemPrompt: 'You are a helpful development assistant with access to various tools.' }); // Add MCP servers await agent.addMCPServers([ { name: 'github', command: "npx", args: ["-y", "@modelcontextprotocol/server-github"] }, { name: 'filesystem', command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/project"] }, { name: 'search', command: "npx", args: ["-y", "@modelcontextprotocol/server-brave-search"] } ]); // Agent now has access to GitHub, filesystem, and search tools const response = await agent.ask(` Check my latest repositories, create a summary file in my project directory, and search for TypeScript best practices `); console.log(response); ``` ## Environment Variables MCP servers automatically load environment variables from your `.env` file: ```bash # .env GITHUB_PERSONAL_ACCESS_TOKEN=ghp_xxxxxxxxxxxx BRAVE_API_KEY=your_brave_api_key GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json ``` No need to specify environment variables in code - they're loaded automatically and securely. ## Server Types ### Local Servers (stdio) For servers that run as local processes: ```typescript const localServers = [ { name: 'sqlite', command: "npx", args: ["-y", "@modelcontextprotocol/server-sqlite", "--db-path", "/path/to/db.sqlite"], cwd: "/working/directory" } ]; ``` ### Remote Servers (SSE) For servers that connect via HTTP/SSE: ```typescript const remoteServers = [ { name: 'api-server', url: "https://api.example.com/mcp/events" } ]; ``` ## Multi-Level Usage ### Agent Level Available for all tasks and conversations: ```typescript // Agent-level: Available everywhere await agent.addMCPServers([ { name: 'filesystem', command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/Documents"] } ]); ``` ### Task Level Available for specific tasks: ```typescript // Task-level: Available for this task only const task = await agent.createTask({ prompt: "Analyze my GitHub repositories", mcpServers: [ { name: 'github', command: "npx", args: ["-y", "@modelcontextprotocol/server-github"] } ] }); ``` ### Conversation Level Available for single conversations: ```typescript // Conversation-level: Available for this conversation only const response = await agent.ask("Search for TypeScript news", { mcpServers: [ { name: 'search', command: "npx", args: ["-y", "@modelcontextprotocol/server-brave-search"] } ] }); ``` ## Manual Tool Access Access MCP tools programmatically: ```typescript // List available MCP tools const tools: MCPTool[] = agent.getMCPTools(); console.log('Available MCP tools:', tools.map(t => t.name)); // Call specific MCP tool // Tool name format: "server:tool_name" or just "tool_name" (auto-resolves server) const result: MCPToolResult = await agent.callMCPTool('github:list_repos', { owner: 'username' }); // Remove an MCP server by name (synchronous) agent.removeMCPServer('github'); ``` ## Response Types ### callMCPTool Response ```typescript const result: MCPToolResult = await agent.callMCPTool('github:list_repos', { owner: 'username' }); // Response structure (MCPToolResult): { content: [ { type: 'text', text: 'Repository list...' } ], isError?: boolean // Optional error flag } ``` ### getMCPTools Response ```typescript const tools: MCPTool[] = agent.getMCPTools(); // Response structure (MCPTool[]): [ { name: 'list_repos', // Tool name without server prefix description: 'List repositories for a user', inputSchema: { // MCPJsonSchema type: 'object', properties: { owner: { type: 'string', description: 'Repository owner' } }, required: ['owner'] } } ] ``` ## API Reference ### Agent MCP Methods ```typescript // Add a single MCP server (async) async addMCPServer(serverDef: MCPServerDefinition): Promise // Add multiple MCP servers (async) async addMCPServers(servers: MCPServerDefinition[]): Promise // Remove an MCP server by name (sync) removeMCPServer(name: string): void // Call an MCP tool (async) async callMCPTool( toolName: string, // "server:tool" or just "tool" args: Record // Tool arguments ): Promise // Get all available MCP tools (sync) getMCPTools(): MCPTool[] ``` MCP integration provides powerful external tool access while maintaining security and simplicity. *** # Memory URL: /docs/framework/memory Source: /app/src/content/docs/framework/memory.mdx import { DocImage } from '@/components/DocImage'; **Persistent conversation memory with vector search and automatic context integration** ## Overview The Memory system provides agents with long-term memory capabilities, enabling them to remember past conversations, learn from interactions, and maintain context across sessions. When memory is enabled, agents automatically store and retrieve relevant information from previous conversations, creating a more personalized and context-aware experience. ## Enabling Memory Enable memory for an agent by setting the `memory` option to `true`: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'MemoryAgent', model: 'gpt-4o', memory: true // Enable persistent memory }); ``` ## Basic Usage Here's a complete example showing how memory works across conversations: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create an agent with memory const agent = await Agent.create({ name: 'PersonalAssistant', model: 'gpt-4o', memory: true, systemPrompt: 'You are a helpful personal assistant who remembers user preferences.' }); // First conversation const response1 = await agent.ask('My name is John and I love TypeScript'); console.log(response1); // Output: "Nice to meet you, John! It's great that you love TypeScript..." // Later conversation - agent remembers const response2 = await agent.ask('What programming language do I like?'); console.log(response2); // Output: "You mentioned that you love TypeScript, John!" // Memory persists even after restarting const sameAgent = await Agent.create({ name: 'PersonalAssistant', // Same name retrieves existing memories model: 'gpt-4o', memory: true }); const response3 = await sameAgent.ask('Do you remember my name?'); console.log(response3); // Output: "Yes, your name is John!" ``` ## Memory Methods When memory is enabled, agents have access to these memory management methods: ```typescript // Add a memory manually const memory = await agent.addMemory( 'Important project information: Budget is $50k', { type: 'project', category: 'budget' }, // Optional metadata { graphId: 'project-123', taskId: 'task-456', sessionId: 'session-789' } // Optional context for memory isolation ); // Remember conversation with role context const userMemory = await agent.rememberConversation( 'I prefer TypeScript over JavaScript', 'user' ); // Get a specific memory by ID const existingMemory = await agent.getMemory(memory.id); // Search memories by content (semantic search with embeddings) const budgetMemories = await agent.searchMemories('budget', { limit: 5, startDate: new Date('2024-01-01') }); // Vector similarity search for semantic matching const happyMemories = await agent.searchMemoriesBySimilarity('joyful moments', { similarityThreshold: 0.7, // Minimum similarity score limit: 10 }); // List all memories with options const allMemories = await agent.listMemories({ limit: 20, orderBy: 'createdAt', order: 'desc' }); // Update a memory const updatedMemory = await agent.updateMemory(memory.id, { content: 'Updated budget: $75k', metadata: { type: 'project', category: 'budget', updated: true } }); // Delete a specific memory const deleted = await agent.deleteMemory(memory.id); // Generate embedding for existing memory (migration/repair) const result = await agent.generateEmbeddingForMemory(memory.id); if (result.success) { console.log('✅ Embedding generated successfully'); } // Clear all memories const deletedCount = await agent.clearMemories(); // Clear memories with options const deletedCount = await agent.clearMemories({ syncWithContext: false // Prevent context synchronization (default: true) }); ``` ## Similarity Search Mathematics When searching memories using vector similarity, the system calculates similarity scores between query and memory embeddings: ### Cosine Similarity Score $\text{similarity} = \frac{\vec{q} \cdot \vec{m}}{||\vec{q}|| \cdot ||\vec{m}||} \in [0, 1]$ Where: * $\vec{q}$ is the query embedding vector * $\vec{m}$ is the memory embedding vector * Result ranges from 0 (completely different) to 1 (identical) ### Distance-Based Score For distance metrics, the similarity score is calculated as: $\text{score} = \frac{1}{1 + d(\vec{q}, \vec{m})}$ Where $d$ is the Euclidean distance between vectors. ### Threshold Filtering Memories are returned only if: $\text{similarity} \geq \theta$ Where $\theta$ is the `similarityThreshold` parameter (default: 0.7). ## Memory Object Structure ```typescript interface Memory { id: string; // Unique memory identifier (UUID) agentId: string; // ID of the owning agent (UUID) graphId?: string; // Graph context (for memory isolation) taskId?: string; // Task context (for memory isolation) sessionId?: string; // Session context (for memory isolation) content: string; // Memory content embedding?: number[]; // Vector embedding (auto-generated) metadata?: MetadataObject; // Custom metadata createdAt: Date; // When memory was created updatedAt: Date; // Last update time } interface MemorySearchOptions { limit?: number; // Max results (default: 10 for search, 100 for list) offset?: number; // Skip results (default: 0) pageSize?: number; // Pagination size for large result sets graphId?: string; // Filter by graph context taskId?: string; // Filter by task context sessionId?: string; // Filter by session context orderBy?: 'createdAt' | 'updatedAt' | 'relevance'; // Sort field order?: 'asc' | 'desc'; // Sort order (default: 'desc') startDate?: Date; // Filter from date endDate?: Date; // Filter to date similarityThreshold?: number; // Similarity threshold (0-1, default: 0.7) useEmbedding?: boolean; // Use embedding search (default: true) } ``` ## Response Types Understanding what each memory method returns helps you handle responses correctly in your code. ### Memory Object Response When creating or retrieving memories, you receive a complete `Memory` object: ```typescript const memory = await agent.addMemory("User prefers dark mode", { type: "preference", importance: "high" }); // Response structure: { id: "550e8400-e29b-41d4-a716-446655440000", // UUID string agentId: "agent-uuid-123", // UUID string content: "User prefers dark mode", embedding: [0.1, 0.2, 0.3, ..., 0.768], // 1536 dimensions array metadata: { type: "preference", importance: "high" }, createdAt: Date('2024-01-15T10:30:00Z'), updatedAt: Date('2024-01-15T10:30:00Z') } ``` ### Memory List Response Search and list methods return an array of `Memory` objects: ```typescript const memories = await agent.searchMemories("preferences", { limit: 5, similarityThreshold: 0.7 }); // Response structure: [ { id: "memory-uuid-1", agentId: "agent-uuid", content: "User prefers dark mode", embedding: [0.1, 0.2, ...], metadata: { type: "preference" }, createdAt: Date(...), updatedAt: Date(...) }, { id: "memory-uuid-2", agentId: "agent-uuid", content: "User timezone is PST", embedding: [0.15, 0.25, ...], metadata: { type: "preference" }, createdAt: Date(...), updatedAt: Date(...) } ] ``` ### Generate Embedding Response Embedding generation returns a detailed success/failure object: ```typescript const result = await agent.generateEmbeddingForMemory(memory.id); // Response structure: { success: true, message: "Embedding generated successfully", embedding: [0.1, 0.2, 0.3, ..., 0.768] // Optional: included on success } // On failure (possible messages): { success: false, message: "Memory not found" // or "Memory already has embedding", "Failed to generate embedding", etc. } ``` ### Delete Response Delete operations return a boolean indicating success: ```typescript const deleted = await agent.deleteMemory(memory.id); // Returns: true or false ``` ### Clear Memories Response Clearing all memories returns the count of deleted items: ```typescript const deletedCount = await agent.clearMemories(); // Returns: 15 (number of memories deleted) ``` *** # Plugin URL: /docs/framework/plugin Source: /app/src/content/docs/framework/plugin.mdx import { DocImage } from '@/components/DocImage'; **Extensible tool system with JSON schema validation and automatic function calling** ## Overview Plugins extend agent capabilities by providing tools that can be called during conversations. The plugin system is built around a decorator pattern that enhances agents with tool execution capabilities. It provides automatic parameter validation, error handling, and seamless LLM integration with function calling. ## Built-in Tools Astreus comes with several built-in tools available to all agents: ### Knowledge Tools * **search\_knowledge**: Search through the agent's knowledge base for relevant information * `query` (string, required): Search query * `limit` (number, optional): Maximum results (default: 5) * `threshold` (number, optional): Similarity threshold (default: 0.7) ### Vision Tools * **analyze\_image**: General image analysis with custom prompts * **describe\_image**: Generate accessibility-friendly descriptions * **extract\_text\_from\_image**: OCR capabilities for text extraction ## Creating Custom Plugins ### Define Your Tool Create a tool definition with handler function: ```typescript import { ToolDefinition, ToolContext, ToolParameterValue } from '@astreus-ai/astreus'; const weatherTool: ToolDefinition = { name: 'get_weather', description: 'Get current weather information for a location', parameters: { location: { name: 'location', type: 'string', description: 'City name or location', required: true }, units: { name: 'units', type: 'string', description: 'Temperature units (celsius or fahrenheit)', required: false } }, handler: async (params: Record, context?: ToolContext) => { try { // Your tool implementation const weather = await fetchWeather(params.location as string, params.units as string); return { success: true, data: { temperature: weather.temp, conditions: weather.conditions, location: params.location } }; } catch (error) { return { success: false, error: error instanceof Error ? error.message : 'Unknown error' }; } } }; ``` ### Create the Plugin Bundle your tools into a plugin: ```typescript import { Plugin, ToolParameterValue } from '@astreus-ai/astreus'; const weatherPlugin: Plugin = { name: 'weather-plugin', version: '1.0.0', description: 'Weather information tools', tools: [weatherTool], // Optional: Plugin initialization initialize: async (config?: Record) => { console.log('Weather plugin initialized'); }, // Optional: Plugin cleanup cleanup: async () => { console.log('Weather plugin cleaned up'); } }; ``` ### Register with Agent Register your plugin with an agent: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'WeatherAgent', model: 'gpt-4o' }); // Register the plugin await agent.registerPlugin(weatherPlugin); ``` ## Tool Parameter Types The plugin system supports comprehensive parameter validation: ```typescript // Parameter type definitions interface ToolParameter { name: string; // Parameter name type: 'string' | 'number' | 'boolean' | 'object' | 'array'; description: string; // Parameter description required?: boolean; // Whether parameter is required (optional, defaults to false) enum?: Array; // Allowed values (supports both string and number) properties?: Record; // For object types (nested properties) items?: ToolParameter; // For array types (item type definition) } ``` ### Parameter Examples ```typescript const advancedTool: ToolDefinition = { name: 'process_data', description: 'Process data with various options', parameters: { // String with enum values format: { name: 'format', type: 'string', description: 'Output format', required: true, enum: ['json', 'csv', 'xml'] }, // Number parameter (optional) limit: { name: 'limit', type: 'number', description: 'Maximum records to process', required: false }, // Object with nested properties options: { name: 'options', type: 'object', description: 'Processing options', required: false, properties: { includeHeaders: { name: 'includeHeaders', type: 'boolean', description: 'Include column headers', required: false } } }, // Array of strings fields: { name: 'fields', type: 'array', description: 'Fields to include', required: false, items: { name: 'field', type: 'string', description: 'Field name' } } }, handler: async (params) => { // Tool implementation return { success: true, data: params }; } }; ``` ## Using Tools in Conversations ### Automatic Tool Usage Agents with registered plugins can automatically use tools during conversations: ```typescript const agent = await Agent.create({ name: 'AssistantAgent', model: 'gpt-4o' }); await agent.registerPlugin(weatherPlugin); // Agent can automatically call tools based on conversation const response = await agent.ask("What's the weather like in Tokyo?"); // Agent will automatically call get_weather tool and incorporate results console.log(response); // "The current weather in Tokyo is 22°C with clear skies..." ``` ### Manual Tool Execution You can also execute tools manually: ```typescript // Execute single tool const result = await agent.executeTool({ id: 'call-123', name: 'get_weather', parameters: { location: 'New York', units: 'celsius' } }); console.log(result.result.success ? result.result.data : result.result.error); // Execute multiple tools sequentially const results = await Promise.all([ agent.executeTool({ id: 'call-1', name: 'get_weather', parameters: { location: 'Tokyo' } }), agent.executeTool({ id: 'call-2', name: 'get_weather', parameters: { location: 'London' } }) ]); ``` ### Tool-Enhanced Tasks Use tools in structured tasks via the Task module: ```typescript const task = await agent.createTask({ prompt: "Compare the weather in Tokyo, London, and New York", useTools: true }); const result = await agent.executeTask(task.id, { stream: true, onChunk: (chunk) => { console.log(chunk); } }); ``` ## Tool Context and Metadata Tools receive execution context with useful information: ```typescript const contextAwareTool: ToolDefinition = { name: 'log_action', description: 'Log an action with context', parameters: { action: { name: 'action', type: 'string', description: 'Action to log', required: true } }, handler: async (params, context) => { // Access execution context console.log(`Agent ${context?.agentId} performed: ${params.action}`); console.log(`Task ID: ${context?.taskId}`); console.log(`User ID: ${context?.userId}`); console.log(`Metadata:`, context?.metadata); return { success: true, data: { logged: true, timestamp: new Date().toISOString() } }; } }; ``` ## Response Types Understanding tool execution responses helps you handle results and errors properly. ### Tool Execution Response Executing a tool returns a `ToolCallResult` with execution details: ```typescript const result = await agent.executeTool({ id: "call-123", name: "get_weather", parameters: { location: "Tokyo", units: "celsius" } }); // Response structure: { id: "call-123", name: "get_weather", result: { success: true, data: { temperature: 22, conditions: "clear skies", location: "Tokyo", humidity: 65, wind: "5 km/h" } }, executionTime: 250 // Execution time in milliseconds } ``` ### Tool Execution with Error When a tool fails, the error is included in the result: ```typescript const result = await agent.executeTool({ id: "call-456", name: "get_weather", parameters: { location: "InvalidCity" } }); // Response with error: { id: "call-456", name: "get_weather", result: { success: false, error: "Location 'InvalidCity' not found" }, executionTime: 150 } ``` ### Multiple Tool Execution Response Executing multiple tools using `Promise.all` returns an array of results: ```typescript const results = await Promise.all([ agent.executeTool({ id: "call-1", name: "get_weather", parameters: { location: "Tokyo" } }), agent.executeTool({ id: "call-2", name: "get_weather", parameters: { location: "London" } }), agent.executeTool({ id: "call-3", name: "search_knowledge", parameters: { query: "climate" } }) ]); // Response structure: [ { id: "call-1", name: "get_weather", result: { success: true, data: { temperature: 22, conditions: "clear" } }, executionTime: 200 }, { id: "call-2", name: "get_weather", result: { success: true, data: { temperature: 15, conditions: "cloudy" } }, executionTime: 220 }, { id: "call-3", name: "search_knowledge", result: { success: true, data: [ { content: "Climate patterns...", similarity: 0.92 }, { content: "Global warming...", similarity: 0.85 } ] }, executionTime: 180 } ] ``` ### Tool List Response Retrieving available tools returns an array of tool definitions: ```typescript const tools = agent.getTools(); // Response structure: [ { name: "get_weather", description: "Get current weather information for a location", parameters: { location: { name: "location", type: "string", description: "City name or location", required: true }, units: { name: "units", type: "string", description: "Temperature units", required: false } }, handler: [Function] }, { name: "search_knowledge", description: "Search through the agent's knowledge base", parameters: { /* ... */ }, handler: [Function] } ] ``` ### Plugin List Response Listing registered plugins: ```typescript const plugins = agent.listPlugins(); // Response structure: [ { name: "weather-plugin", version: "1.0.0", description: "Weather information tools", tools: [ /* ToolDefinition[] */ ], initialize: [Function], cleanup: [Function] }, { name: "data-plugin", version: "2.1.0", description: "Data processing utilities", tools: [ /* ToolDefinition[] */ ] } ] ``` *** # Quickstart URL: /docs/framework/quickstart Source: /app/src/content/docs/framework/quickstart.mdx import { DocImage } from '@/components/DocImage'; **Build your first AI agent with Astreus in under 2 minutes** Let's create a simple agent that can execute tasks and respond intelligently. Before we proceed, make sure you have Astreus installed. If you haven't installed it yet, follow the [installation guide](/docs/framework/install). ## Build your first agent ### Create Environment File Create a `.env` file in your project root and add your OpenAI API key: ```bash touch .env ``` Add your API key to the `.env` file: ```bash OPENAI_API_KEY=sk-your-openai-api-key-here ``` ### Create your First Agent Create an agent with memory and system prompt: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create agent const agent = await Agent.create({ name: 'ResearchAgent', model: 'gpt-4o', memory: true, systemPrompt: 'You are an expert research assistant.' }); ``` ### Create and Execute Task Create a task and execute it with your agent: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create agent const agent = await Agent.create({ name: 'ResearchAgent', model: 'gpt-4o', memory: true, systemPrompt: 'You are an expert research assistant.' }); // Create a task const task = await agent.createTask({ prompt: "Research latest news in Anthropic and OpenAI" }); // Execute the task const result = await agent.executeTask(task.id); console.log(result.response); ``` ### Build a Graph Workflow Create a workflow graph with multiple tasks: ```typescript import { Agent, Graph } from '@astreus-ai/astreus'; // Create agent const agent = await Agent.create({ name: 'ResearchAgent', model: 'gpt-4o', memory: true, systemPrompt: 'You are an expert research assistant.' }); // Create a graph for complex workflows const graph = new Graph({ name: 'Research Pipeline', defaultAgentId: agent.id }); // Add task nodes const researchNode = graph.addTaskNode({ prompt: 'Research the latest AI developments' }); const analysisNode = graph.addTaskNode({ prompt: 'Analyze the research findings', dependencies: [researchNode] }); const summaryNode = graph.addTaskNode({ prompt: 'Create a summary report', dependencies: [analysisNode] }); // Run the graph const graphResult = await graph.run(); console.log(graphResult.results[summaryNode]); ``` Congratulations! You've created your first AI agent with Astreus. *** # Scheduler URL: /docs/framework/scheduler Source: /app/src/content/docs/framework/scheduler.mdx import { DocImage } from '@/components/DocImage'; **Simple time-based execution with minimal setup** ## Overview The Astreus scheduler provides simple time-based execution for tasks and graphs using intuitive schedule strings. No complex configuration needed - just add a `schedule` field and you're done! ## Basic Task Scheduling Schedule individual tasks with simple syntax: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'SchedulerAgent', model: 'gpt-4o' }); // Create a scheduled task - scheduler starts automatically when needed const scheduledTask = await agent.createTask({ prompt: 'Generate monthly report for December', schedule: 'once@2024-12-25@09:00' }); // Create a recurring task const dailyTask = await agent.createTask({ prompt: 'Daily health check and status report', schedule: 'daily@08:00' }); // Execute the task - scheduler will handle the scheduling automatically await agent.executeTask(scheduledTask.id); ``` ## Schedule Configuration Use simple schedule strings for easy configuration: ```typescript // Supported schedule formats: 'daily@07:00' // Daily at 7 AM 'weekly@monday@09:00' // Weekly on Monday at 9 AM 'monthly@1@10:00' // Monthly on 1st day at 10 AM 'hourly' // Every hour (default time) '@15:30' // Once today at 3:30 PM 'once@2024-12-25@10:00' // Once on specific date and time // Delay-based schedules: 'after:5s' // Run after 5 seconds 'after:30m' // Run after 30 minutes 'after:2h' // Run after 2 hours // Examples: await agent.createTask({ prompt: 'Morning briefing', schedule: 'daily@08:00' }); await agent.createTask({ prompt: 'Weekly report', schedule: 'weekly@friday@17:00' }); ``` ## Graph Scheduling with Dependencies Schedule graphs with intelligent dependency resolution: ```typescript import { Graph } from '@astreus-ai/astreus'; const graph = new Graph({ name: 'Morning Workflow', defaultAgentId: agent.id }, agent); // Node A: Data collection at 6 AM const nodeA = graph.addTaskNode({ name: 'Data Collection', prompt: 'Collect overnight data from all sources', schedule: 'once@2024-12-20@06:00' }); // Node B: Processing (depends on A completing first) const nodeB = graph.addTaskNode({ name: 'Data Processing', prompt: 'Process collected data and generate insights', schedule: 'once@2024-12-20@07:00', dependsOn: ['Data Collection'] // Must wait for A }); // Node C: Report generation at 8 AM const nodeC = graph.addTaskNode({ name: 'Report Generation', prompt: 'Generate morning executive report', schedule: 'once@2024-12-20@08:00', dependsOn: ['Data Processing'] }); // Execute - scheduler starts automatically for scheduled nodes await graph.run(); // Result: A runs at 06:00, B waits and runs after A (~06:05), C runs at 08:00 ``` ## Recurring Patterns Create sophisticated recurring schedules: ### Daily Schedules ```typescript // Every day at 8 AM { type: 'recurring', executeAt: new Date('2024-12-20T08:00:00Z'), recurrence: { pattern: 'daily', interval: 1, maxExecutions: 365 // Stop after 1 year } } // Every 3 days { type: 'recurring', executeAt: new Date('2024-12-20T08:00:00Z'), recurrence: { pattern: 'daily', interval: 3 } } ``` ### Weekly Schedules ```typescript // Every Monday at 9 AM { type: 'recurring', executeAt: new Date('2024-12-23T09:00:00Z'), // Monday recurrence: { pattern: 'weekly', interval: 1, daysOfWeek: [1] // Monday } } // Every Monday and Friday { type: 'recurring', executeAt: new Date('2024-12-23T09:00:00Z'), recurrence: { pattern: 'weekly', interval: 1, daysOfWeek: [1, 5] // Monday and Friday } } ``` ### Monthly and Yearly ```typescript // 15th of every month { type: 'recurring', executeAt: new Date('2024-12-15T10:00:00Z'), recurrence: { pattern: 'monthly', interval: 1, dayOfMonth: 15 } } // Every January 1st { type: 'recurring', executeAt: new Date('2025-01-01T00:00:00Z'), recurrence: { pattern: 'yearly', interval: 1, monthOfYear: 1 } } ``` ## Dependency Resolution Logic The scheduler intelligently resolves conflicts between schedules and dependencies: | Scenario | Behavior | | -------------------------------- | ------------------------------------ | | Node scheduled before dependency | **Waits for dependency to complete** | | Node scheduled after dependency | **Runs at scheduled time** | | Multiple dependencies | **Waits for ALL dependencies** | | Circular dependencies | **Error thrown during validation** | | Mixed scheduled/immediate nodes | **Works seamlessly together** | The scheduler provides a robust foundation for building automated, time-based AI workflows that respect dependencies and scale with your needs. *** # Security URL: /docs/framework/security Source: /app/src/content/docs/framework/security.mdx import { DocImage } from '@/components/DocImage'; **Field-level encryption for protecting sensitive data in your Astreus agents** ## Overview Astreus includes built-in **AES-256-GCM encryption** to protect sensitive data stored in your database. This feature provides transparent field-level encryption for conversations, system prompts, task data, and knowledge base content. ## Quick Setup ### 1. Generate Encryption Key ```bash # Generate a cryptographically secure 256-bit key openssl rand -hex 32 ``` ### 2. Configure Environment ```bash # Enable encryption ENCRYPTION_ENABLED=true # Your secure master key (keep this secret!) ENCRYPTION_MASTER_KEY=your-256-bit-encryption-key-here # Optional: specify algorithm (default: aes-256-gcm) ENCRYPTION_ALGORITHM=aes-256-gcm ``` ### 3. Use Normally ```javascript import { Agent } from '@astreus-ai/astreus'; // Create agent with sensitive system prompt const agent = await Agent.create({ name: 'SecureAgent', systemPrompt: 'Your confidential business logic here', // ← Automatically encrypted memory: true, knowledge: true }); // All interactions automatically encrypted const response = await agent.ask('Sensitive question here'); // Knowledge uploads automatically encrypted await agent.knowledge.addDocument( 'Confidential Document', 'Sensitive content here' // ← Automatically encrypted ); ``` ## Key Management ### Master Key Requirements * **Minimum Length**: 32 characters (256 bits) * **Generation**: Use cryptographically secure random generators * **Storage**: Store securely outside of codebase * **Rotation**: Plan for periodic key rotation *** # Sub-Agents URL: /docs/framework/sub-agents Source: /app/src/content/docs/framework/sub-agents.mdx import { DocImage } from '@/components/DocImage'; **Intelligent task delegation with specialized agents working in coordination** ## Overview Sub-Agents enable sophisticated multi-agent coordination where a main agent intelligently delegates tasks to specialized sub-agents. Each sub-agent has its own expertise, capabilities, and role, working together to complete complex workflows that would be challenging for a single agent. **New**: Sub-Agents now integrate seamlessly with Graph workflows, enabling hierarchical task distribution across complex workflow orchestration systems. ## Creating Sub-Agents Sub-agents are created independently and then attached to a main coordinator agent: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create specialized sub-agents const researcher = await Agent.create({ name: 'ResearcherBot', model: 'gpt-4o', systemPrompt: 'You are an expert researcher who gathers and analyzes information thoroughly.', memory: true, knowledge: true }); const writer = await Agent.create({ name: 'WriterBot', model: 'gpt-4o', systemPrompt: 'You are a skilled content writer who creates engaging, well-structured content.', vision: true }); const analyst = await Agent.create({ name: 'AnalystBot', model: 'gpt-4o', systemPrompt: 'You are a data analyst who provides insights and recommendations.', useTools: true }); // Create main agent with sub-agents const mainAgent = await Agent.create({ name: 'CoordinatorAgent', model: 'gpt-4o', systemPrompt: 'You coordinate complex tasks between specialized sub-agents.', subAgents: [researcher, writer, analyst] }); ``` ## Delegation Strategies ### Auto Delegation The main agent uses LLM intelligence to analyze tasks and assign them optimally: ```typescript const result = await mainAgent.ask( 'Research AI market trends, analyze the data, and write an executive summary', { useSubAgents: true, delegation: 'auto' // AI-powered task distribution } ); ``` ### Task Analysis Main agent analyzes the complex task using LLM reasoning. ### Agent Matching Evaluates each sub-agent's capabilities and specializations. ### Optimal Assignment Creates specific subtasks for the most appropriate agents. ### Coordinated Execution Manages execution flow and result aggregation. ### Manual Delegation Explicitly assign specific tasks to specific agents using their IDs: ```typescript const result = await mainAgent.ask( 'Complex multi-step project', { useSubAgents: true, delegation: 'manual', taskAssignment: { [researcher.id]: 'Research market opportunities in healthcare AI', [analyst.id]: 'Analyze market size and growth potential', [writer.id]: 'Create executive summary with recommendations' } } ); ``` ### Sequential Delegation Sub-agents work in sequence, building on previous results: ```typescript const result = await mainAgent.ask( 'Create a comprehensive business plan for an AI startup', { useSubAgents: true, delegation: 'sequential' // Each agent builds on the previous work } ); ``` ## Coordination Patterns ```mermaid graph TD A[Main Coordinator Agent] --> B{Task Analysis} B -->|Research Tasks| C[ResearcherBot] B -->|Analysis Tasks| D[AnalystBot] B -->|Content Tasks| E[WriterBot] C --> F[Research Results] D --> G[Analysis Results] E --> H[Written Content] F --> I[Result Aggregation] G --> I H --> I I --> J[Final Output] style A fill:#333,stroke:#333,stroke-width:4px style C fill:#333,stroke:#333,stroke-width:2px style D fill:#333,stroke:#333,stroke-width:2px style E fill:#333,stroke:#333,stroke-width:2px ``` ### Parallel Execution Sub-agents work simultaneously for maximum efficiency: ```typescript const result = await mainAgent.ask( 'Multi-faceted analysis task', { useSubAgents: true, delegation: 'auto', coordination: 'parallel' // All agents work concurrently } ); ``` ### Sequential Execution Sub-agents work in order with context passing: ```typescript const result = await mainAgent.ask( 'Research → Analyze → Report workflow', { useSubAgents: true, delegation: 'auto', coordination: 'sequential' // Agents work in dependency order } ); ``` ## Sub-Agent Configuration ### Specialized Roles Configure sub-agents for specific expertise areas: ```typescript // Research Specialist const researcher = await Agent.create({ name: 'ResearchSpecialist', systemPrompt: 'You conduct thorough research using multiple sources and methodologies.', knowledge: true, // Access to knowledge base memory: true, // Remember research context useTools: true // Use research tools }); // Content Creator const creator = await Agent.create({ name: 'ContentCreator', systemPrompt: 'You create compelling content across different formats and audiences.', vision: true, // Process visual content useTools: true // Use content creation tools }); // Technical Analyst const analyst = await Agent.create({ name: 'TechnicalAnalyst', systemPrompt: 'You analyze technical data and provide actionable insights.', useTools: true // Use analysis tools }); ``` ## Graph Integration Sub-Agents work seamlessly with Graph workflows for complex orchestration: ```typescript import { Agent, Graph } from '@astreus-ai/astreus'; // Create specialized sub-agents const researcher = await Agent.create({ name: 'ResearchBot', systemPrompt: 'You conduct thorough research and analysis.', knowledge: true }); const writer = await Agent.create({ name: 'WriterBot', systemPrompt: 'You create compelling content and reports.', vision: true }); // Main coordinator with sub-agents const coordinator = await Agent.create({ name: 'ProjectCoordinator', systemPrompt: 'You coordinate complex projects using specialized teams.', subAgents: [researcher, writer] }); // Create sub-agent aware graph const projectGraph = new Graph({ name: 'Market Analysis Project', defaultAgentId: coordinator.id, subAgentAware: true, optimizeSubAgentUsage: true }, coordinator); // Add tasks with intelligent sub-agent delegation const researchTask = projectGraph.addTaskNode({ name: 'Market Research', prompt: 'Research AI healthcare market trends and opportunities', useSubAgents: true, subAgentDelegation: 'auto' }); const reportTask = projectGraph.addTaskNode({ name: 'Executive Report', prompt: 'Create comprehensive executive report based on research', dependencies: [researchTask], useSubAgents: true, subAgentCoordination: 'sequential' }); // Execute the graph const result = await projectGraph.run(); ``` ### Graph Sub-Agent Features * **Automatic Detection**: Graph nodes automatically use sub-agents when beneficial * **Context Passing**: Workflow context flows to sub-agents for better coordination * **Performance Optimization**: Real-time monitoring and automatic strategy adjustment * **Flexible Configuration**: Per-node sub-agent settings with inheritance from graph config ## Advanced Examples ### Content Production Pipeline ```typescript const contentPipeline = await Agent.create({ name: 'ContentPipeline', model: 'gpt-4o', subAgents: [researcher, writer, analyst] }); const blogPost = await contentPipeline.ask( 'Create a comprehensive blog post about quantum computing applications in finance', { useSubAgents: true, delegation: 'auto', coordination: 'sequential' } ); ``` ### Market Research Workflow ```typescript const marketResearch = await Agent.create({ name: 'MarketResearchTeam', model: 'gpt-4o', subAgents: [researcher, analyst, writer] }); const report = await marketResearch.ask( 'Analyze the fintech market and create investor presentation', { useSubAgents: true, delegation: 'manual', coordination: 'parallel', taskAssignment: { [researcher.id]: 'Research fintech market trends and competitors', [analyst.id]: 'Analyze market data and financial projections', [writer.id]: 'Create compelling investor presentation' } } ); ``` ## Response Types Sub-agent methods return different response formats depending on the operation. ### Execute With Sub-Agents Response Basic sub-agent execution returns the final combined result as a string: ```typescript const result = await mainAgent.executeWithSubAgents( "Research renewable energy and create comprehensive report", [researchAgent, writerAgent], { coordination: 'sequential' } ); // Response: string "Research complete: Solar and wind energy show 23% growth year-over-year. Report includes market analysis, technology trends, and investment opportunities across 15 regions." ``` ### Delegate Task Response Task delegation returns the sub-agent's response as a string: ```typescript const result = await mainAgent.delegateTask( "Translate this document to Spanish", translatorAgent ); // Response: string "Documento traducido exitosamente. El contenido ha sido adaptado para audiencia hispanohablante manteniendo el tono profesional original." ``` ### Coordinate Agents Response Coordinating multiple agents returns an array of task-result pairs: ```typescript const results = await mainAgent.coordinateAgents([ { agent: analyzerAgent, prompt: "Analyze Q4 sales data" }, { agent: reportAgent, prompt: "Create executive summary" }, { agent: visualizerAgent, prompt: "Generate performance charts" } ], 'sequential'); // Response structure: [ { task: { agent: analyzerAgent, // IAgent object prompt: "Analyze Q4 sales data" }, result: "Q4 analysis complete: Revenue increased 18%, top products identified, seasonal trends mapped." }, { task: { agent: reportAgent, prompt: "Create executive summary" }, result: "Executive summary created with key findings: 18% growth driven by product line expansion..." }, { task: { agent: visualizerAgent, prompt: "Generate performance charts" }, result: "Performance visualizations generated: 5 charts showing revenue trends, product mix, and regional distribution." } ] ``` ### Agent.ask() with Sub-Agents Response Using `agent.ask()` with sub-agent options returns the final response string: ```typescript const result = await mainAgent.ask( "Create market analysis presentation", { useSubAgents: true, delegation: 'auto', coordination: 'parallel' } ); // Response: string "Market analysis presentation completed with 3 specialized teams: Research team gathered competitor data, Analysis team processed financial metrics (showing 12% market growth), and Content team created 25-slide deck with executive summary." ``` ### Manual Task Assignment Response Manual assignment also returns a string with combined results: ```typescript const result = await coordinatorAgent.ask( "Develop comprehensive product launch strategy", { useSubAgents: true, delegation: 'manual', coordination: 'sequential', taskAssignment: { [marketResearcher.id]: "Research target market and competitors", [strategyAnalyst.id]: "Develop go-to-market strategy", [contentCreator.id]: "Create launch materials and messaging" } } ); // Response: string "Product launch strategy complete: Target market identified (tech-savvy professionals 25-40), competitive positioning defined (premium quality, mid-tier pricing), go-to-market plan created with 3-phase rollout, and launch materials prepared including website, social media, and press kit." ``` *** # Task URL: /docs/framework/task Source: /app/src/content/docs/framework/task.mdx import { DocImage } from '@/components/DocImage'; **Structured task execution with status tracking and tool integration** ## Overview Tasks provide a way to organize and execute complex operations with your agents. They support status tracking, tool usage, and can be composed into larger workflows. Each task can have dependencies, execute specific actions, and maintain its own state throughout execution. ## Creating Tasks Tasks are created through agents using a simple prompt-based approach: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'TaskAgent', model: 'gpt-4o' }); // Create a task const task = await agent.createTask({ prompt: 'Analyze the TypeScript code and suggest performance improvements' }); // Execute the task const result = await agent.executeTask(task.id); console.log(result.response); ``` ## Task Attributes Tasks can be configured with the following attributes: ```typescript interface TaskRequest { prompt: string; // The task instruction or query graphId?: string; // UUID - Graph this task belongs to graphNodeId?: string; // UUID - Graph node creating this task useTools?: boolean; // Enable/disable tool usage (default: true) mcpServers?: MCPServerDefinition[]; // Task-level MCP servers plugins?: Array<{ // Task-level plugins plugin: Plugin; config?: PluginConfig; }>; attachments?: Array<{ // Files to attach to the task type: 'image' | 'pdf' | 'text' | 'markdown' | 'code' | 'json' | 'file'; path: string; // File path name?: string; // Display name language?: string; // Programming language (for code files) }>; schedule?: string; // Simple schedule string (e.g., 'daily@07:00', 'weekly@monday@09:00') metadata?: MetadataObject; // Custom metadata for tracking executionContext?: Record; // Additional execution metadata useSubAgents?: boolean; // Enable sub-agent delegation for this task subAgentDelegation?: 'auto' | 'manual' | 'sequential'; // Delegation strategy subAgentCoordination?: 'parallel' | 'sequential'; // How sub-agents coordinate taskAssignment?: Record; // Manual task assignment (agentId UUID -> task) } ``` ### Attribute Details * **prompt**: The main instruction or query for the task. This is the only required field. * **graphId**: UUID of the graph this task belongs to. Used when tasks are part of a graph workflow. * **graphNodeId**: UUID of the graph node that created this task. Used for tracking task origin in graph workflows. * **useTools**: Controls whether the task can use tools/plugins. Defaults to `true` (inherits from agent if not specified). * **mcpServers**: Task-specific MCP (Model Context Protocol) servers to enable for this task. * **plugins**: Task-specific plugins to register for this task execution. * **attachments**: Array of files to attach to the task. Supports images, PDFs, text files, code files, and more. * **schedule**: Simple schedule string for time-based execution (e.g., `'daily@07:00'`, `'weekly@monday@09:00'`). Optional field that enables automatic scheduling when used with graphs. * **metadata**: Custom key-value pairs for organizing and tracking tasks (e.g., category, priority, tags). * **executionContext**: Additional execution metadata as a record of key-value pairs. Useful for passing runtime context information. #### Sub-Agent Integration * **useSubAgents**: Enable sub-agent delegation for this specific task. When `true`, the main agent will intelligently delegate portions of the task to its registered sub-agents. * **subAgentDelegation**: Strategy for task delegation: * `'auto'`: AI-powered intelligent task distribution based on sub-agent capabilities * `'manual'`: Explicit task assignment using `taskAssignment` mapping * `'sequential'`: Sub-agents work in sequence, building on previous results * **subAgentCoordination**: Coordination pattern for sub-agent execution: * `'parallel'`: Sub-agents work simultaneously for maximum efficiency * `'sequential'`: Sub-agents work in order with context passing between them * **taskAssignment**: Manual task assignment mapping (only used with `subAgentDelegation: 'manual'`). Maps agent IDs to specific task instructions. ## Task Lifecycle Tasks go through several states during execution: ```typescript type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'failed'; ``` ### Pending Task is created but not yet started. Waiting for execution or dependencies. ### In Progress Task is actively being executed by the agent. Tools may be used during this phase. ### Completed Task has finished successfully with results available. ### Failed Task encountered an error during execution. Error details are available. ## Example with Attachments and Tools Here's a complete example showing tasks with file attachments and tool integration: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create an agent const agent = await Agent.create({ name: 'CodeReviewAssistant', model: 'gpt-4o', vision: true // Enable vision for screenshots }); // Code review task with multiple file types const codeReviewTask = await agent.createTask({ prompt: `Please perform a comprehensive code review: 1. Check for security vulnerabilities 2. Identify performance issues 3. Suggest improvements for code quality 4. Review the UI mockup for usability issues`, attachments: [ { type: 'code', path: './src/auth/login.ts', name: 'Login Controller', language: 'typescript' }, { type: 'code', path: './src/middleware/security.js', name: 'Security Middleware', language: 'javascript' }, { type: 'json', path: './package.json', name: 'Package Dependencies' }, { type: 'image', path: './designs/login-mockup.png', name: 'Login UI Mockup' }, { type: 'markdown', path: './docs/security-requirements.md', name: 'Security Requirements' } ], metadata: { type: 'code-review', priority: 'high', reviewer: 'ai-assistant' } }); // Execute task with streaming const result = await agent.executeTask(codeReviewTask.id, { model: 'gpt-4o', // Override model for this task stream: true // Enable streaming response }); console.log('Code review completed:', result.response); // Documentation task with text files const docTask = await agent.createTask({ prompt: 'Update the API documentation based on the latest code changes', attachments: [ { type: 'text', path: '/api/routes.txt', name: 'API Routes' }, { type: 'markdown', path: '/README.md', name: 'Current Documentation' } ] }); // List tasks with attachments const tasksWithFiles = await agent.listTasks({ orderBy: 'createdAt', order: 'desc' }); tasksWithFiles.forEach(task => { console.log(`Task ${task.id}: ${task.status}`); if (task.metadata?.attachments) { console.log(` - Has attachments`); } if (task.completedAt) { console.log(` - Completed: ${task.completedAt.toISOString()}`); } }); ``` ## Sub-Agent Task Delegation Tasks now support sub-agent delegation directly through task creation and execution: ```typescript import { Agent } from '@astreus-ai/astreus'; // Create specialized sub-agents const researcher = await Agent.create({ name: 'ResearchBot', systemPrompt: 'You are an expert researcher who gathers comprehensive information.' }); const writer = await Agent.create({ name: 'WriterBot', systemPrompt: 'You create engaging, well-structured content.' }); const mainAgent = await Agent.create({ name: 'ContentCoordinator', subAgents: [researcher, writer] }); // Create task with automatic sub-agent delegation const autoTask = await mainAgent.createTask({ prompt: 'Research renewable energy trends and write a comprehensive report', useSubAgents: true, subAgentDelegation: 'auto', subAgentCoordination: 'sequential', metadata: { type: 'research-report', priority: 'high' } }); // Create task with manual sub-agent assignment const manualTask = await mainAgent.createTask({ prompt: 'Create market analysis presentation', useSubAgents: true, subAgentDelegation: 'manual', subAgentCoordination: 'parallel', taskAssignment: { [researcher.id]: 'Research market data and competitor analysis', [writer.id]: 'Create presentation slides and executive summary' }, metadata: { type: 'presentation', deadline: '2024-12-01' } }); // Execute tasks - sub-agent coordination happens automatically const autoResult = await mainAgent.executeTask(autoTask.id); const manualResult = await mainAgent.executeTask(manualTask.id); console.log('Auto-delegated result:', autoResult.response); console.log('Manually-assigned result:', manualResult.response); ``` ### Alternative: Agent Methods for Sub-Agent Execution You can also leverage sub-agents through agent methods for immediate execution: ```typescript // Direct execution with sub-agent delegation via agent.ask() const result = await mainAgent.ask('Research renewable energy trends and write report', { useSubAgents: true, delegation: 'auto', coordination: 'sequential' }); // Manual delegation with specific task assignments const manualResult = await mainAgent.ask('Create market analysis presentation', { useSubAgents: true, delegation: 'manual', coordination: 'parallel', taskAssignment: { [researcher.id]: 'Research market data and competitor analysis', [writer.id]: 'Create presentation slides and executive summary' } }); ``` ### Benefits of Task-Level Sub-Agent Delegation * **Persistent Configuration**: Sub-agent settings are stored with the task and persist across sessions * **Reproducible Workflows**: Task definitions can be reused with consistent sub-agent behavior * **Flexible Execution**: Tasks can be executed immediately or scheduled for later with same sub-agent coordination * **Audit Trail**: Task metadata includes sub-agent delegation history for tracking and debugging ## Managing Tasks Tasks can be managed and tracked throughout their lifecycle: ```typescript // Update task with additional metadata await agent.updateTask(task.id, { metadata: { ...task.metadata, progress: 50, estimatedCompletion: new Date() } }); // Delete a specific task await agent.deleteTask(task.id); // Clear all tasks for an agent const deletedCount = await agent.clearTasks(); console.log(`Deleted ${deletedCount} tasks`); // Search tasks with filters const pendingTasks = await agent.listTasks({ status: 'pending', limit: 5 }); const recentTasks = await agent.listTasks({ orderBy: 'completedAt', order: 'desc', limit: 10 }); // Filter tasks by graph const graphTasks = await agent.listTasks({ graphId: 'graph-uuid-123', orderBy: 'createdAt', order: 'asc' }); ``` ## Response Types Understanding task responses helps you handle execution results and track task lifecycle. ### Task Object Response Creating or retrieving a task returns a complete `Task` object: ```typescript const task = await agent.createTask({ prompt: "Analyze this data", useTools: true, metadata: { priority: "high" } }); // Response structure (Task interface): { id: "550e8400-e29b-41d4-a716-446655440000", // UUID string agentId: "agent-uuid-123", // UUID string graphId?: "graph-uuid-456", // UUID string if part of a graph graphNodeId?: "node-uuid-789", // UUID string if created by graph node prompt: "Analyze this data", response?: "Analysis result...", // Filled after execution status: "pending", // 'pending' | 'in_progress' | 'completed' | 'failed' metadata?: { priority: "high" }, executionContext?: {}, // Additional execution metadata createdAt: Date('2024-01-15T10:30:00Z'), updatedAt: Date('2024-01-15T10:30:00Z'), completedAt?: Date('2024-01-15T10:35:00Z') // Filled after completion } ``` ### Task Execution Response Executing a task returns a `TaskResponse` with execution details: ```typescript const result = await agent.executeTask("task-uuid-123", { model: "gpt-4", stream: false }); // Response structure (TaskResponse interface): { task: { id: "task-uuid-123", agentId: "agent-uuid", graphId?: "graph-uuid", // If part of a graph graphNodeId?: "node-uuid", // If created by graph node prompt: "Analyze this data", response: "Analysis complete: The data shows a 15% increase...", status: "completed", metadata?: { priority: "high" }, executionContext?: {}, // Additional execution metadata createdAt: Date('2024-01-15T10:30:00Z'), updatedAt: Date('2024-01-15T10:35:00Z'), completedAt: Date('2024-01-15T10:35:00Z') }, response: "Analysis complete: The data shows a 15% increase in user engagement...", model?: "gpt-4", usage?: { promptTokens: 150, completionTokens: 300, totalTokens: 450 } } ``` ### Task List Response Listing tasks returns an array of `Task` objects: ```typescript const tasks = await agent.listTasks({ status: 'completed', orderBy: 'completedAt', order: 'desc', limit: 10, offset: 0, // Pagination offset graphId: 'optional' // Filter by graph ID (UUID) }); // Response structure (Task[] array): [ { id: "task-uuid-1", agentId: "agent-uuid", graphId?: "graph-uuid", // If part of a graph graphNodeId?: "node-uuid", // If created by graph node prompt: "First task", response?: "First task completed", status: "completed", metadata?: {}, executionContext?: {}, createdAt: Date(...), updatedAt: Date(...), completedAt?: Date(...) }, { id: "task-uuid-2", agentId: "agent-uuid", graphId?: "graph-uuid", graphNodeId?: "node-uuid", prompt: "Second task", response?: "Second task completed", status: "completed", metadata?: {}, executionContext?: {}, createdAt: Date(...), updatedAt: Date(...), completedAt?: Date(...) } ] ``` ### Update Task Response Updating a task returns the updated `Task` object or null if not found: ```typescript const updated = await agent.updateTask("task-uuid", { metadata: { progress: 50, estimatedCompletion: new Date() } }); // Response: Task object with updated fields or null { id: "task-uuid", agentId: "agent-uuid", prompt: "Original prompt", status: "in_progress", metadata: { priority: "high", progress: 50, estimatedCompletion: Date('2024-01-15T12:00:00Z') }, updatedAt: Date('2024-01-15T10:40:00Z'), ... } ``` ### Get Task Response Retrieving a specific task returns the `Task` object or null: ```typescript const task = await agent.getTask("task-uuid"); // Returns: Task object or null if not found ``` ### Delete Task Response Deleting a task returns a boolean indicating success: ```typescript const deleted = await agent.deleteTask("task-uuid"); // Returns: true or false ``` ### Clear Tasks Response Clearing all tasks returns the count of deleted tasks: ```typescript const deletedCount = await agent.clearTasks(); // Returns: 25 (number of tasks deleted) ``` *** # Vision URL: /docs/framework/vision Source: /app/src/content/docs/framework/vision.mdx import { DocImage } from '@/components/DocImage'; **Image analysis and document processing for multimodal interactions** ## Overview The Vision system enables agents to process and analyze images, providing multimodal AI capabilities for richer interactions. It supports multiple image formats, offers various analysis modes, and integrates seamlessly with OpenAI, Claude, Gemini, and local Ollama providers for flexible deployment options. ## Enabling Vision Enable vision capabilities for an agent by setting the `vision` option to `true`: ```typescript import { Agent } from '@astreus-ai/astreus'; const agent = await Agent.create({ name: 'VisionAgent', model: 'gpt-4o', // Vision-capable model vision: true // Enable vision capabilities (default: false) }); ``` ## Attachment System Astreus supports an intuitive attachment system for working with images: ```typescript // Clean, modern attachment API const response = await agent.ask("What do you see in this image?", { attachments: [ { type: 'image', path: '/path/to/image.jpg', name: 'My Photo' } ] }); ``` The attachment system automatically: * Detects the file type and selects appropriate tools * Enhances the prompt with attachment information * Enables tool usage when attachments are present ## Vision Capabilities The vision system provides three core capabilities through built-in tools: ### 1. General Image Analysis Analyze images with custom prompts and configurable detail levels: ```typescript // Using attachments (recommended approach) const response = await agent.ask("Please analyze this screenshot and describe the UI elements", { attachments: [ { type: 'image', path: '/path/to/screenshot.png', name: 'UI Screenshot' } ] }); // Using the analyze_image tool through conversation const response2 = await agent.ask("Please analyze the image at /path/to/screenshot.png and describe the UI elements"); // Direct method call const analysis = await agent.analyzeImage('/path/to/image.jpg', { prompt: 'What UI elements are visible in this interface?', detail: 'high', maxTokens: 1500 }); ``` ### 2. Image Description Generate structured descriptions for different use cases: ```typescript // Accessibility-friendly description const description = await agent.describeImage('/path/to/image.jpg', 'accessibility'); // Available styles: // - 'detailed': Comprehensive description of all visual elements // - 'concise': Brief description of main elements // - 'accessibility': Screen reader-friendly descriptions // - 'technical': Technical analysis including composition and lighting ``` ### 3. Text Extraction (OCR) Extract and transcribe text from images: ```typescript // Extract text with language hint const text = await agent.extractTextFromImage('/path/to/document.jpg', 'english'); // The system maintains original formatting and structure console.log(text); ``` ## Supported Formats The vision system supports these image formats: * **JPEG** (`.jpg`, `.jpeg`) * **PNG** (`.png`) * **GIF** (`.gif`) * **BMP** (`.bmp`) * **WebP** (`.webp`) ### Input Sources ### File Paths Analyze images from local file system: ```typescript const result = await agent.analyzeImage('/path/to/image.jpg'); ``` ### Base64 Data Analyze images from base64-encoded data: ```typescript const base64Image = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ...'; const result = await agent.analyzeImageFromBase64(base64Image); ``` ## Configuration ### Vision Model Configuration Specify the vision model directly in the agent configuration: ```typescript const agent = await Agent.create({ name: 'VisionAgent', model: 'gpt-4o', visionModel: 'gpt-4o', // Specify vision model here vision: true }); ``` ### Environment Variables ```bash # API keys (auto-detected based on model) OPENAI_API_KEY=your_openai_key # For OpenAI models OPENAI_VISION_API_KEY=your_openai_key # Dedicated vision API key (takes priority) ANTHROPIC_API_KEY=your_anthropic_key # For Claude models ANTHROPIC_VISION_API_KEY=your_anthropic_key # Dedicated vision API key (takes priority) GEMINI_API_KEY=your_gemini_key # For Gemini models GEMINI_VISION_API_KEY=your_gemini_key # Dedicated vision API key (takes priority) # Ollama configuration (local) OLLAMA_BASE_URL=http://localhost:11434 # Default if not set ``` The vision system automatically selects the appropriate provider based on the `visionModel` specified in the agent configuration. ### Analysis Options Configure analysis behavior with these options: ```typescript interface AnalysisOptions { prompt?: string; // Custom analysis prompt maxTokens?: number; // Response length limit (default: 1000) detail?: 'low' | 'high' | 'auto'; // Analysis detail level (OpenAI only) } ``` ## Usage Examples ### Screenshot Analysis ```typescript const agent = await Agent.create({ name: 'UIAnalyzer', model: 'gpt-4o', vision: true }); // Analyze a UI screenshot const analysis = await agent.analyzeImage('/path/to/app-screenshot.png', { prompt: 'Analyze this mobile app interface. Identify key UI components, layout structure, and potential usability issues.', detail: 'high' }); console.log(analysis); ``` ### Document Processing ```typescript // Extract text from scanned documents const documentText = await agent.extractTextFromImage('/path/to/scanned-invoice.jpg', 'english'); // Generate accessible descriptions const accessibleDesc = await agent.describeImage('/path/to/chart.png', 'accessibility'); ``` ### Multimodal Conversations ```typescript // Using attachments for cleaner API const response = await agent.ask("I'm getting an error. Can you analyze this screenshot and help me fix it?", { attachments: [ { type: 'image', path: '/Users/john/Desktop/error.png', name: 'Error Screenshot' } ] }); // Multiple attachments const response2 = await agent.ask("Compare these UI mockups and suggest improvements", { attachments: [ { type: 'image', path: '/designs/mockup1.png', name: 'Design A' }, { type: 'image', path: '/designs/mockup2.png', name: 'Design B' } ] }); // Traditional approach (still works) const response3 = await agent.ask( "Please analyze the error screenshot at /Users/john/Desktop/error.png and suggest how to fix the issue" ); ``` ## Provider Comparison | Feature | OpenAI (gpt-4o) | Claude (claude-3-5-sonnet) | Gemini (gemini-1.5-pro) | Ollama (llava) | | ---------------- | --------------- | -------------------------- | ----------------------- | ---------------- | | Analysis Quality | Excellent | Excellent | Excellent | Good | | Processing Speed | Fast | Fast | Fast | Variable | | Cost | Pay-per-use | Pay-per-use | Pay-per-use | Free (local) | | Privacy | Cloud-based | Cloud-based | Cloud-based | Local processing | | Detail Levels | Low/High/Auto | Standard | Standard | Standard | | Language Support | Extensive | Extensive | Extensive | Good | ### OpenAI Provider * **Best for**: Production applications requiring high accuracy * **Default Model**: `gpt-4o` * **Features**: Detail level control, excellent text recognition ### Claude Provider * **Best for**: Nuanced analysis and detailed descriptions * **Default Model**: `claude-3-5-sonnet-20241022` * **Features**: Strong reasoning, excellent context understanding ### Gemini Provider * **Best for**: Multimodal tasks and document analysis * **Default Model**: `gemini-1.5-pro` * **Features**: Long context support, good for complex images ### Ollama Provider (Local) * **Best for**: Privacy-sensitive applications or development * **Default Model**: `llava` * **Features**: Local processing, no API costs, offline capability ## Batch Processing Process multiple images efficiently: ```typescript const images = [ '/path/to/image1.jpg', '/path/to/image2.png', '/path/to/image3.gif' ]; // Process all images in parallel const results = await Promise.all( images.map(imagePath => agent.describeImage(imagePath, 'concise') ) ); console.log('Analysis results:', results); // Or use task attachments for batch processing const batchTask = await agent.createTask({ prompt: 'Analyze all these images and provide a comparative report', attachments: images.map(path => ({ type: 'image', path, name: path.split('/').pop() })) }); const batchResult = await agent.executeTask(batchTask.id); ``` ## Built-in Vision Tools When vision is enabled, these tools are automatically available: ### analyze\_image * **Parameters**: * `image_path` (string, required): Path to image file * `prompt` (string, optional): Custom analysis prompt * `detail` (string, optional): 'low' or 'high' detail level ### describe\_image * **Parameters**: * `image_path` (string, required): Path to image file * `style` (string, optional): Description style ('detailed', 'concise', 'accessibility', 'technical') ### extract\_text\_from\_image * **Parameters**: * `image_path` (string, required): Path to image file * `language` (string, optional): Language hint for better OCR accuracy ## Response Types Vision methods return string responses containing the analysis results. ### Analyze Image Response Image analysis returns a descriptive string based on your prompt: ```typescript const analysis = await agent.analyzeImage('/path/to/office.jpg', { prompt: "What objects are in this image and how is the space organized?", detail: "high" }); // Response: string "The image shows a modern office workspace with a MacBook Pro laptop, wireless keyboard, and mouse on a wooden desk. To the left is a coffee mug and a notebook. The desk is positioned near a window with natural lighting. The space features a minimalist organization with cable management and a small potted plant." ``` ### Describe Image Response Describeimage returns a formatted description string: ```typescript const description = await agent.describeImage('/path/to/product.jpg'); // Response: string "A professional product photograph featuring a stainless steel water bottle with a matte black finish. The bottle has a wide mouth opening and is photographed against a white background with soft studio lighting creating subtle highlights along the curved surfaces." ``` ### Extract Text from Image Response OCR returns the extracted text as a string: ```typescript const text = await agent.extractTextFromImage('/path/to/document.png', { language: 'en' }); // Response: string "INVOICE\nDate: January 15, 2024\nInvoice #: INV-2024-001\n\nBill To:\nAcme Corporation\n123 Main Street\nNew York, NY 10001\n\nDescription Quantity Price Total\nProfessional Services 8 hrs $150 $1,200\nConsulting Fee 1 $500 $500\n\nSubtotal: $1,700\nTax (8%): $136\nTotal: $1,836" ``` ### Analyze Image from Base64 Response Base64 image analysis also returns a string: ```typescript const base64Image = "data:image/png;base64,iVBORw0KG..."; const result = await agent.analyzeImageFromBase64(base64Image, { prompt: "Identify the main subject and mood of this image" }); // Response: string "The main subject is a sunset landscape with mountains in the background. The mood is serene and peaceful, with warm orange and pink tones dominating the sky. The composition creates a sense of tranquility and natural beauty." ```