# AgentDock Documentation LLMs-full.txt ## Agent Templates Agent Templates are the core configuration mechanism in AgentDock, allowing you to define an agent's identity, capabilities, and behavior in a declarative JSON format. ## Overview Each agent in the `/agents` directory has a `template.json` file. This file defines: * Basic identity (ID, name, description) * LLM provider and model selection, including model parameters * System prompt and personality traits * Available tools * Orchestration rules (steps, conditions, sequences) This templating system makes it easy to create, share, and modify agents without writing extensive code. See [Contributing Community Agents](./rfa/add-agent.md) for information on how to add your own agent templates to the public repository. ## Template Structure (`template.json`) The `template.json` file follows this general structure: ```json { "version": "1.0", // Optional: Version of the template format "agentId": "unique-agent-id", // Required: Unique identifier "name": "Display Name", // Required: Name shown in UI "description": "Brief description of the agent.", // Required: Description for UI "tags": ["Example", "Research"], // Optional: Tags for categorization "priority": 10, // Optional: Lower numbers appear higher in lists "personality": [ // Required: System prompt broken into lines/paragraphs "Personality trait 1", "Personality trait 2" ], "nodes": [ // Required: List of node types used by the agent "llm.openai", // Example: Specify the LLM node provider "search" // Example: Include necessary tool nodes ], "nodeConfigurations": { // Required: Configuration for specific nodes "llm.openai": { // Key matches the node type from the "nodes" list "model": "YOUR_CHOSEN_MODEL", // Required: Specify the model ID "temperature": 0.7, // Optional: Controls randomness (0=deterministic, >0=more random). Range varies by provider. "maxTokens": 4096, // Optional: Max tokens for the response. "topP": 0.9, // Optional: Nucleus sampling (0-1). Consider only top P% probability mass. Use temperature OR topP. "topK": 50, // Optional: Consider only the top K most likely tokens. "frequencyPenalty": 0.2, // Optional: Penalizes frequently used tokens (0=no penalty). Range varies. "presencePenalty": 0.1, // Optional: Penalizes tokens already present in prompt/response (0=no penalty). Range varies. "stopSequences": ["\nUser:"], // Optional: Sequences that stop generation. "seed": 12345, // Optional: Integer for deterministic results (if supported). "useCustomApiKey": false // Optional: If true, requires user to provide API key in settings. }, "search": { // Example: Configuration for a tool node (if needed) "maxResults": 5 } }, "chatSettings": { // Required: Settings for the chat interface "historyPolicy": "lastN", // Optional: 'none', 'lastN', 'all' (default: 'lastN') "historyLength": 20, // Optional: Number of messages if policy is 'lastN' (default: 50) "initialMessages": [ // Optional: Messages shown when chat starts "Hello! How can I help?" ], "chatPrompts": [ // Optional: Suggested prompts shown in UI "What can you do?" ] }, "options": { // Optional: Additional agent-level options "maxSteps": 10 // Example: Max tool execution steps per turn } } ``` ### Key Configuration Fields * **`agentId`, `name`, `description`**: Basic identification. * **`personality`**: Defines the system prompt and core behavior. Crucial for guiding the LLM. * **`nodes`**: Lists all capabilities (LLM provider node, tool nodes) the agent requires. * **`nodeConfigurations`**: Allows setting specific parameters for each node listed in `nodes`. * For LLM nodes (e.g., `llm.openai`), you **must** specify the `model`. * You can optionally override default LLM behavior by setting parameters like `temperature`, `maxTokens`, `topP`, `topK`, `frequencyPenalty`, `presencePenalty`, `stopSequences`, and `seed`. The exact behavior and valid ranges for these settings can vary between different LLM providers. * **`chatSettings`**: Controls the user interface behavior, initial state, and prompt suggestions. For detailed explanations of the common LLM settings (`temperature`, `topP`, `maxTokens`, etc.) and their effects, refer to the [Vercel AI SDK Settings Documentation](https://sdk.vercel.ai/docs/ai-sdk-core/settings). ## Featured Agents | Agent | Description | GitHub | | :------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :-------------------------------------------------------------------------------------------- | | [Cognitive Reasoner](/chat?agent=cognitive-reasoner) | Tackles complex problems using a suite of cognitive enhancement tools and structured reasoning. Features different operational modes including Research, Problem-Solving, Evaluation, Comparison, Ideation, and Debate. Uses the think tool for step-by-step reasoning. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/cognitive-reasoner) | | [Dr. House](/chat?agent=dr-house) | Medical diagnostician inspired by the TV character, specializing in advanced medical diagnostics and rare disease identification. Leverages comprehensive medical knowledge and medical databases. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/dr-house) | | [Science Translator](/chat?agent=science-translator) | Makes complex scientific papers accessible by finding and translating them into simple language without sacrificing accuracy. Utilizes PubMed access and multi-database scientific research capabilities. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/science-translator) | | [Calorie Vision](/chat?agent=calorie-vision) | Analyzes food images to provide precise calorie and nutrient breakdowns using visual recognition technology. Integrates with visual analysis tools to process and evaluate food content from photos. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/calorie-vision) | | [Harvey Specter](/chat?agent=harvey-specter) | Legal strategist and negotiator inspired by the Suits character, specializing in contract review, case strategy, and negotiation tactics. Accesses legal databases to provide accurate and actionable legal insights. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/harvey-specter) | | [Orchestrated Agent](/chat?agent=orchestrated-agent) | Demonstrates advanced agent orchestration by combining multiple specialized agents and tools in a cohesive workflow with dynamic branching. Shows how different agents can be combined and orchestrated. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/orchestrated-agent) | | [Agent Planner](/chat?agent=agent-planner) | Specialized agent for designing and implementing AI agents using the AgentDock framework and RFA system. Provides agent ideation, architecture design, implementation guidance, and RFA system integration. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/agent-planner) | | [Tenant Rights Advisor](/chat?agent=tenant-rights) | Guides renters through housing issues like repairs, evictions, and deposit disputes based on general housing regulations. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/tenant-rights) | | [Consumer Rights Defender](/chat?agent=consumer-rights) | Helps consumers navigate issues with refunds, warranties, defective products, and unfair billing practices. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/consumer-rights) | | [Small Claims Court Guide](/chat?agent=small-claims) | Assists with small claims court navigation including filing paperwork, preparing evidence, and collecting judgments. | [View Code](https://github.com/agentdock/agentdock/tree/main/agents/small-claims) | ## Agent File Structure For detailed implementation examples, clone the AgentDock repository and explore the `agents/` directory. ``` agents/ └── agent-name/ ├── template.json # Core configuration (required) ├── README.md # Documentation (recommended) └── assets/ # Optional assets (e.g., avatar.png) ``` ## Usage These templates can be: 1. **Tested directly**: Try them out via the chat interface by clicking the agent links above (if running the client). 2. **Examined for patterns**: Study their implementations to learn configuration techniques. 3. **Used as starting points**: Copy and modify them to create your own specialized agents. ## AgentDock Pro AgentDock Pro extends our open-source framework with enterprise-grade features, simplified agent creation, and powerful workflow orchestration. ## What is AgentDock Pro? AgentDock Pro is our cloud platform that enhances the open-source AgentDock framework with improved stability, scalability, and advanced capabilities. It's built for teams that need to deploy AI agents and sophisticated workflows at scale. ```mermaid graph LR A[AgentDock Open Source] --> B[AgentDock Pro] B --> C[Enterprise Ready] B --> D[Natural Language Agent Creation] B --> E[Workflow Orchestration] B --> F[Advanced Scalability] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style A fill:#f9f9f9,stroke:#cccccc style C fill:#f5f5f5,stroke:#333333 style D fill:#f5f5f5,stroke:#333333 style E fill:#f5f5f5,stroke:#333333 style F fill:#f5f5f5,stroke:#333333 ``` ## Key Benefits ### Natural Language Agent Creation Build AI agents by describing what you want them to do in plain language, without coding. - **Describe your agent**: "I need an agent that monitors market data and executes trades" - **Automatic tool selection**: The system configures the right tools based on your description - **Instant prototyping**: Test your agent immediately after creating it [Learn more about Natural Language AI Agent Builder →](/docs/roadmap/nl-agent-builder) ### Workflow Orchestration Connect agents and tools into automated workflows for complex tasks. ```mermaid graph LR A[Event Trigger] --> B[Data Collection] B --> C[AI Processing] C --> D[Decision Logic] D -->|Scenario 1| E[Voice Response] D -->|Scenario 2| F[Email Notification] D -->|Scenario 3| G[Database Update] E --> H[User Feedback] F --> H G --> H H --> I[Analytics] style C fill:#0066cc,color:#ffffff,stroke:#0033cc style D fill:#0066cc,color:#ffffff,stroke:#0033cc ``` - **Visual workflow builder**: Drag-and-drop interface for complex workflows - **Conditional branching**: Create decision paths based on data or agent outputs - **Event triggers**: Start workflows from messages, schedules, or API calls - **Third-party integrations**: Connect to popular services and APIs ### Persistent Memory & Knowledge Agents maintain conversation history and knowledge across sessions. - **Per-user memory**: Each end-user gets their own conversation history - **Knowledge integration**: Connect external data sources and documents - **Contextual awareness**: Agents understand and remember previous interactions ### Advanced Scalability Deploy agents to handle large user loads while maintaining performance. - **Horizontal scaling**: Handle high volume without performance degradation - **Resource optimization**: Automatic scaling based on demand - **Enterprise stability**: Consistent performance under load - **Multi-region support**: Low-latency for global deployments ### Unified Cost Management Simplify your AI budget with our credit-based system. - **Save 80-90%** with our discounted API access compared to direct provider pricing - **Consolidated billing** across LLM providers and third-party services - **Predictable pricing** with transparent usage tracking - **Lower barriers** to premium models and services ## Who Benefits from AgentDock Pro? AgentDock Pro can transform virtually any industry where human expertise, routine tasks, or customer interactions are involved. If it can be described in natural language, it can likely be automated or augmented with our AI agents. Here are just some of the ways organizations and professionals are leveraging our platform: ### Enterprise Workforce Transformation Replace repetitive jobs with AI agents for customer service, research, and administrative tasks. **Example**: Automate 80% of your HR support tickets with a specialized agent that handles employee onboarding, benefits questions, and request processing, saving $150,000 annually in operational costs. ```mermaid graph LR A[Employees] --> B[HR Support Agent] B --> C{Request Type} C -->|Onboarding| D[Document Collection] C -->|Benefits| E[Benefits Database] C -->|Requests| F[Automated Processing] D --> G[HR Dashboard] E --> G F --> G style B fill:#f5f5f5,stroke:#333333 style C fill:#f5f5f5,stroke:#333333 ``` ### AI Agents for Trading & Automation Create sophisticated trading and monitoring agents that execute based on real-time conditions. **Example**: "When S&P 500 opens positively, buy $500 of Bitcoin from my Coinbase account and notify me via Telegram" ```mermaid graph LR A[Market Data] --> B{Trading Agent} B -->|Condition Met| C[Coinbase API] B -->|Transaction Complete| D[Telegram Notification] style B fill:#f5f5f5,stroke:#333333 ``` ### Education & Tutoring Develop personalized learning agents that adapt to each student's needs, providing 24/7 education support. **Example**: Launch a subscription-based math tutoring service where your AI agent provides unlimited practice problems, step-by-step explanations, and personalized learning paths – scaling to thousands of students while maintaining individual progress tracking. ```mermaid graph LR A[Student] --> B[Math Tutor Agent] B --> C{Learning Path} C -->|Problems| D[Problem Generation] C -->|Help| E[Explanations] C -->|Analytics| F[Progress Tracking] D --> G[Student Dashboard] E --> G F --> G style B fill:#f5f5f5,stroke:#333333 style C fill:#f5f5f5,stroke:#333333 ``` ### Healthcare Services Deploy compliant agents for patient intake, follow-up, and routine care management that integrate with existing systems. **Example**: Create a HIPAA-compliant pre-appointment screening agent that collects patient information, verifies insurance coverage, and sends required forms – reducing administrative costs by 40% while improving patient satisfaction. ```mermaid graph LR A[Patient] --> B[Screening Agent] B -->|Collect| C[Patient Information] B -->|Verify| D[Insurance Verification] B -->|Send| E[Forms Distribution] C --> F[EHR Integration] D --> F E --> F style B fill:#f5f5f5,stroke:#333333 ``` ### Legal & Compliance Automate document review, client intake, and routine legal processes while maintaining security and confidentiality. **Example**: Build a GDPR-compliant contract review agent that analyzes agreements in seconds, highlights potential issues, and suggests revisions – turning a time-intensive process into a scalable, high-margin service. ```mermaid graph LR A[Contract] --> B[Review Agent] B --> C[Issue Detection] B --> D[GDPR Compliance] B --> E[Revision Suggestions] C --> F[Attorney Dashboard] D --> F E --> F style B fill:#f5f5f5,stroke:#333333 ``` ### Insurance & Financial Services Streamline claims processing, policy recommendations, and customer service with automated workflows. **Example**: Deploy an SOC 2 compliant insurance claims agent that processes routine claims 5x faster than human agents, validating documentation, calculating payouts, and updating customer records while maintaining full audit trails. ```mermaid graph LR A[Claim Submission] --> B[Claims Agent] B -->|Validate| C[Documentation Validation] B -->|Calculate| D[Payout Calculation] B -->|Update| E[Record Updates] C --> F[Audit Trail] D --> F E --> F style B fill:#f5f5f5,stroke:#333333 ``` ### Voice Agent Developers Create voice assistants and conversational interfaces that handle concurrent conversations. **Example**: Build a restaurant reservation system that handles 200+ concurrent calls during peak hours, confirming bookings, answering questions, and upselling premium options – all without hiring additional staff. ```mermaid graph LR A[Caller] --> B[Voice Agent] B --> C{Interaction Type} C -->|Reservation| D[Booking System] C -->|Questions| E[Knowledge Base] C -->|Upsell| F[Premium Options] style B fill:#f5f5f5,stroke:#333333 style C fill:#f5f5f5,stroke:#333333 ``` ### AI Agencies & Consultancies Build custom AI agents for clients with rapid deployment and minimal overhead. **Example**: Create AI-powered assistants and automation solutions for your clients, generating recurring revenue while leveraging AgentDock Pro's infrastructure instead of building everything from scratch. ```mermaid graph LR A[Client Needs] --> B[Agency] B --> C[Custom Agent Creation] C -->|Deploy| D[Client 1] C -->|Deploy| E[Client 2] C -->|Deploy| F[Client 3] style B fill:#f5f5f5,stroke:#333333 style C fill:#f5f5f5,stroke:#333333 ``` ### Service Professionals Scale your expertise - whether you're a coach, concierge, or consultant - to serve more clients simultaneously. **Example**: Create a personal fitness coach agent that provides 24/7 guidance to hundreds of clients at once, delivering personalized workout plans, nutrition advice, and motivation – transforming your limited-scale service into a subscription business. ```mermaid graph LR A[Fitness Coach] --> B[Coach Agent] B --> C{Client Services} C -->|Fitness| D[Workout Plans] C -->|Diet| E[Nutrition Advice] C -->|Support| F[Motivation] D --> G[Many Clients] E --> G F --> G style B fill:#f5f5f5,stroke:#333333 style C fill:#f5f5f5,stroke:#333333 ``` ## Migration from Open Source AgentDock Pro builds on our open-source framework, making it easy to upgrade when you're ready. ```mermaid graph TB subgraph "Your AgentDock Journey" A[Start with
Open Source] --> B[Build First
Agents] B --> C[Deploy to
AgentDock Pro] end subgraph "Open Source Features" direction LR OS1[Node-based
Architecture] --- OS2[Tool System] --- OS3[Provider
Independence] --- OS4[BYOK Support] end subgraph "Pro Features" direction TB P1[Natural Language
Agent Creation] P2[Workflow
Orchestration] P3[Advanced
Scalability] P4[Enterprise
Integrations] end A --- OS1 B --- OS3 C --- P1 C --- P2 C --- P3 C --- P4 style C fill:#0066cc,color:#ffffff,stroke:#0033cc style P1 fill:#f5f5f5,stroke:#333333 style P2 fill:#f5f5f5,stroke:#333333 style P3 fill:#f5f5f5,stroke:#333333 style P4 fill:#f5f5f5,stroke:#333333 ``` - **Simple migration**: Transfer your open source agents to Pro with minimal changes - **Familiar concepts**: All core concepts from open source remain the same in Pro - **Enhanced capabilities**: Add Pro features to your existing agents without rebuilding - **Flexible deployment**: Use open source for development and Pro for production ## Join the Ecosystem AgentDock Pro is transforming how businesses build and deploy AI. **Receive $100 in free credits when you sign up.** [Sign Up at agentdock.ai →](https://agentdock.ai) ## Analytics Integration using PostHog This document outlines how analytics, specifically using PostHog, is integrated into the AgentDock Starter Kit. The primary goal is to gather usage data when deployed (e.g., on AgentDock Hub) to understand application performance and user interaction patterns, while ensuring compatibility with core features like Vercel AI SDK tool calling. ## Implementation Overview The integration uses both client-side and server-side PostHog libraries: 1. **Client-Side (`posthog-js`):** Handles automatic event capture (autocapture) for general UI interactions and manual pageview tracking. Setup via `src/components/providers/posthog-provider.tsx`. 2. **Server-Side (`posthog-node`):** Handles specific, critical events triggered by backend processes, such as successful chat completions. Setup via `src/lib/analytics.ts`. This dual approach allows capturing broad UI interactions without interfering with sensitive backend operations, while still capturing key server-side events. ## Client-Side Integration * **Provider Component:** The `src/components/providers/posthog-provider.tsx` component initializes `posthog-js` and wraps the main application layout (`src/components/layout/layout-content.tsx`). * **Configuration for Compatibility:** The `posthog-js` client is initialized with specific options carefully chosen to prevent interference with the Vercel AI SDK's tool calling mechanisms: * `capture_pageview: false`: Default pageview tracking is disabled. Pageviews are tracked manually after a delay (`useEffect` in `posthog-provider.tsx`) to avoid race conditions during initial load. * `autocapture: true`: Standard UI interactions (clicks, form submissions, etc.) are captured automatically. * `capture_pageleave: false`: Disabled. * `disable_session_recording: true`: Session recording is disabled to minimize performance impact and potential conflicts. * **Context & Hook:** The provider exposes a `usePostHog` hook and a `capture` function for triggering custom client-side events if needed. ## Server-Side Integration * **Utility Module:** The `src/lib/analytics.ts` file initializes a singleton instance of the `posthog-node` client. * **Non-Blocking Capture:** It provides a `captureEvent` function that captures events asynchronously (`Promise.resolve().then(...)`) to ensure analytics calls never block the main execution thread (e.g., API responses). * **Functions:** Exports `captureEvent`, `identifyUser`, and `flushAnalytics` for server-side use. ## Tracked Events Currently, the following key events are confirmed to be tracked: 1. **`$pageview` (Client-Side):** Manually captured by `src/components/providers/posthog-provider.tsx` after a 1-second delay upon route changes to avoid conflicts during initial load. 2. **Autocaptured Events (Client-Side):** Standard UI interactions captured automatically by `posthog-js` (e.g., button clicks, form submissions), as configured in `src/components/providers/posthog-provider.tsx`. 3. **`Chat Completion Success` (Server-Side):** Captured in `src/app/api/chat/[agentId]/route.ts` after a successful response is generated by the agent. Includes the following confirmed properties: * `agentId`: The ID of the agent used. * `sessionId`: A masked version of the user's session ID. * `durationMs`: Time taken for the API request/response cycle. * `provider`: The LLM provider used (e.g., 'openai', 'groq'). * `model`: The specific LLM model used. * `environment`: Node environment (e.g., 'development', 'production'). * `timestamp`: Event timestamp. * *(Note: Token usage properties are not currently captured in this event.)* ## Configuration Analytics integration is controlled by environment variables: * `NEXT_PUBLIC_POSTHOG_API_KEY`: Your PostHog Project API Key. **Required** to enable tracking. * `NEXT_PUBLIC_POSTHOG_HOST`: The PostHog instance host (e.g., `https://us.i.posthog.com` or your self-hosted URL). Defaults to PostHog Cloud US. * `NEXT_PUBLIC_ANALYTICS_ENABLED`: Set to `true` to enable analytics. Defaults to `true` only if `NODE_ENV` is `production`. ## Future Considerations & Customization Users deploying this starter kit might want to: * **Add More Custom Events:** Track specific tool usage (client or server-side), settings changes, agent creation/selection, or errors. * **Enable Session Recording:** If compatibility is confirmed or tool usage is minimal, session recording could be enabled for deeper UX insights (carefully monitor performance). * **User Identification:** Implement `identifyUser` calls (e.g., upon login if authentication is added) to associate events with specific users rather than just anonymous sessions. * **Feature Flags:** Leverage PostHog's feature flags for A/B testing or rolling out features. *No other standard server-side events (like `api_chat_request`, `api_chat_error`, `api_tool_execution_started`) are currently tracked by default.* ## Debugging When running in development mode (`NODE_ENV=development`): 1. Client-side PostHog instance is available at `window.posthog` for debugging 2. Server-side events are logged to the server console ## Best Practices 1. **Personal Information**: Avoid tracking personally identifiable information (PII) in events 2. **Error Information**: Include error types and general messages, but not stack traces or sensitive error details 3. **User IDs**: Use anonymous IDs where possible, especially for public-facing applications 4. **Property Naming**: Use snake_case for event names and property keys ## Additional Resources - [PostHog Documentation](https://posthog.com/docs) - [Client API Reference](https://posthog.com/docs/api/js) - [Node.js API Reference](https://posthog.com/docs/api/nodejs) ## Adding a New LLM Provider This guide explains how to add a new LLM provider to the AgentDock Core framework. ## Overview AgentDock Core uses a unified LLM implementation that integrates with the Vercel AI SDK (version 4.2.0). The framework provides standardized interfaces and conversion utilities to maintain compatibility between internal message formats and the AI SDK. Adding a new provider involves: 1. Adding provider-specific configuration types 2. Creating a provider-specific model creation function 3. Updating the provider registry 4. Updating the `createLLM` function 5. Testing the new provider integration ## Step 1: Add Provider Configuration Types First, add the provider-specific configuration types to `src/llm/types.ts`: ```typescript // Add a new provider to the LLMProvider type export type LLMProvider = 'anthropic' | 'openai' | 'gemini' | 'deepseek' | 'groq' | 'your-provider'; // Add provider-specific configuration export interface YourProviderConfig extends LLMConfig { // Add provider-specific properties here someProviderSpecificOption?: boolean; } // Update the ProviderConfig type export type ProviderConfig = AnthropicConfig | OpenAIConfig | GeminiConfig | DeepSeekConfig | GroqConfig | YourProviderConfig; ``` ## Step 2: Add Provider SDK Dependency Add the provider's SDK to the project's dependencies in `package.json`. If the provider has an official AI SDK integration, use that; otherwise, you'll need to use the provider's native SDK and create an adapter. ```json { "dependencies": { // Existing dependencies "@ai-sdk/anthropic": "^1.0.7", "@ai-sdk/google": "^1.1.26", "@ai-sdk/openai": "^1.0.14", "@ai-sdk/groq": "^1.0.0", // Add your provider's SDK "@ai-sdk/your-provider": "^1.0.0", // Or the native SDK if no AI SDK integration exists "your-provider-sdk": "^1.0.0" } } ``` Note: Some providers like DeepSeek use OpenAI-compatible APIs, so they can utilize the OpenAI SDK with a custom base URL. ## Step 3: Create a Model Creation Function Next, create a model creation function in `src/llm/model-utils.ts`. This function should use the AI SDK's integration for the provider if available: ```typescript import { YourProvider } from '@ai-sdk/your-provider'; // Or import the native SDK // import { YourProviderClient } from 'your-provider-sdk'; /** * Create a YourProvider model */ export function createYourProviderModel(config: LLMConfig): LanguageModel { // Validate API key if (!config.apiKey) { throw createError('llm', 'API key is required', ErrorCode.LLM_API_KEY); } // Add any provider-specific validation here if (!config.apiKey.startsWith('your-prefix-')) { throw createError('llm', 'Invalid API key format for Your Provider', ErrorCode.LLM_API_KEY); } // Create the provider using the AI SDK integration const provider = YourProvider({ apiKey: config.apiKey, // Any other provider-specific initialization options }); // Create model options const modelOptions: any = {}; // Add provider-specific options if needed const yourProviderConfig = config as YourProviderConfig; if (yourProviderConfig.someProviderSpecificOption !== undefined) { modelOptions.someOption = yourProviderConfig.someProviderSpecificOption; } // Create and return the model with options return provider.LanguageModel({ model: config.model, ...modelOptions }); } ``` ### Alternative: Creating a Custom Adapter If the provider doesn't have an AI SDK integration, you'll need to create a custom adapter that implements the `LanguageModel` interface: ```typescript import { LanguageModel } from 'ai'; import { YourProviderClient } from 'your-provider-sdk'; export function createYourProviderModel(config: LLMConfig): LanguageModel { // Initialize the native client const client = new YourProviderClient({ apiKey: config.apiKey, // Other initialization options }); // Create a custom adapter that implements the LanguageModel interface return { generate: async (options) => { // Convert messages from CoreMessage format to provider format const providerMessages = options.messages.map(message => { // Implement conversion logic here return { role: message.role === 'data' ? 'tool' : message.role, content: message.content, // Other provider-specific fields }; }); // Call the provider's API const response = await client.createCompletion({ model: config.model, messages: providerMessages, temperature: options.temperature, // Map other options }); // Return formatted response return { choices: [{ message: { role: 'assistant', content: response.text } }] }; }, // Implement streaming support if the provider supports it generateStream: async (options) => { // Similar to generate, but return a ReadableStream // See the AI SDK documentation for details } }; } ``` ## Step 4: Update the Provider Registry Update the provider registry in `src/llm/provider-registry.ts`: ```typescript // Add your provider to the DEFAULT_PROVIDERS object const DEFAULT_PROVIDERS: Record = { // ... existing providers ... 'your-provider': { id: 'your-provider', displayName: 'Your Provider', description: 'Description of your provider', defaultModel: 'default-model-id', validateApiKey: (key: string) => key.startsWith('your-prefix-'), // Add proper validation logic // Add function to fetch models if supported fetchModels: async (apiKey: string) => { try { // Initialize client with API key const client = new YourProviderClient({ apiKey }); // Fetch models from the provider const models = await client.listModels(); // Convert to standardized format return models.map(model => ({ id: model.id, name: model.name, contextLength: model.contextLength || 4096, pricingInfo: { inputPrice: model.inputPrice || 0, outputPrice: model.outputPrice || 0, unit: model.pricingUnit || '1M tokens' } })); } catch (error) { logger.error(LogCategory.LLM, 'fetchModels', `Error fetching models for your-provider: ${error.message}`); return []; } } } }; ``` ## Step 5: Update the createLLM Function Next, update the `createLLM` function in `src/llm/create-llm.ts`: ```typescript // Import your model creation function import { createAnthropicModel, createOpenAIModel, createGeminiModel, createDeepSeekModel, createGroqModel, createYourProviderModel } from './model-utils'; export function createLLM(config: LLMConfig): CoreLLM { logger.debug( LogCategory.LLM, 'createLLM', 'Creating LLM instance', { provider: config.provider, model: config.model } ); // Create the appropriate model based on the provider let model; switch (config.provider) { case 'anthropic': model = createAnthropicModel(config); break; case 'openai': model = createOpenAIModel(config); break; case 'gemini': model = createGeminiModel(config); break; case 'deepseek': model = createDeepSeekModel(config); break; case 'groq': model = createGroqModel(config); break; case 'your-provider': model = createYourProviderModel(config); break; default: throw createError('llm', `Unsupported provider: ${config.provider}`, ErrorCode.LLM_EXECUTION); } // Create and return the CoreLLM instance return new CoreLLM({ model, config }); } ``` ## Step 6: Update Exports Update the exports in `src/llm/index.ts` to include your new provider: ```typescript // Export your model creation function export { createAnthropicModel, createOpenAIModel, createGeminiModel, createDeepSeekModel, createGroqModel, createYourProviderModel } from './model-utils'; ``` If needed, also update the main exports in `src/index.ts` to include any provider-specific types or classes that should be accessible to clients: ```typescript //============================================================================= // Provider-specific imports for re-export //============================================================================= /** * Re-export provider-specific classes and types */ import { GoogleGenerativeAI } from '@google/generative-ai'; import { GroqAPI } from '@ai-sdk/groq'; import { YourProviderClient } from 'your-provider-sdk'; // If needed export { GoogleGenerativeAI, GroqAPI, YourProviderClient }; ``` ## Step 7: Message Format Compatibility The AgentDock Core framework already provides utilities for converting between internal message formats and the AI SDK's format in `src/types/messages.ts`: - `toAIMessage`: Converts from AgentDock's internal `Message` format to the AI SDK's `AIMessage` format - `fromAIMessage`: Converts from AI SDK's `AIMessage` format to AgentDock's internal `Message` format If your provider requires special message handling, you may need to update these functions or create provider-specific utilities. ## Step 8: Provider-Specific Features (Optional) If your provider has specific features that aren't covered by the standard LLM interface, you can add them to the provider-specific configuration and handle them in the model creation function. For example, if your provider supports a special "creativity" setting: ```typescript // In types.ts export interface YourProviderConfig extends LLMConfig { creativity?: number; } // In model-utils.ts export function createYourProviderModel(config: LLMConfig): LanguageModel { const yourProviderConfig = config as YourProviderConfig; // Create model options const modelOptions: any = {}; // Add provider-specific options if (yourProviderConfig.creativity !== undefined) { modelOptions.creativity = yourProviderConfig.creativity; } // Create and return the model with options return YourProvider({ apiKey: config.apiKey }).LanguageModel({ model: config.model, ...modelOptions }); } ``` ## Step 9: Testing Create tests for your new provider implementation in `src/llm/__tests__/your-provider.test.ts`: ```typescript import { createLLM } from '../create-llm'; import { CoreLLM } from '../core-llm'; // Consider using Jest's mock system to avoid actual API calls jest.mock('your-provider-sdk', () => { return { YourProviderClient: jest.fn().mockImplementation(() => { return { createCompletion: jest.fn().mockResolvedValue({ text: 'Mock response' }), // Mock other methods }; }) }; }); describe('YourProvider integration', () => { it('creates a YourProvider LLM instance', () => { const llm = createLLM({ provider: 'your-provider', apiKey: 'your-test-api-key', model: 'your-test-model' }); expect(llm).toBeInstanceOf(CoreLLM); expect(llm.config.provider).toBe('your-provider'); }); it('generates text correctly', async () => { const llm = createLLM({ provider: 'your-provider', apiKey: 'your-test-api-key', model: 'your-test-model' }); const result = await llm.generateText({ messages: [{ role: 'user', content: 'Hello' }] }); expect(result.text).toBeDefined(); }); // Test streaming and other features }); ``` You should also manually test your provider with a real API key to ensure it works correctly with the actual service: ```typescript const llm = createLLM({ provider: 'your-provider', apiKey: process.env.YOUR_PROVIDER_API_KEY, model: 'your-provider-model', // Provider-specific options someProviderSpecificOption: true }); // Test text generation const result = await llm.generateText({ messages: [{ role: 'user', content: 'Hello' }] }); console.log(result.text); // Test streaming const stream = await llm.streamText({ messages: [{ role: 'user', content: 'Tell me a story' }], onFinish: (text) => console.log('Finished:', text) }); for await (const chunk of stream) { console.log('Chunk:', chunk.text); } ``` ## Embedding Support When adding a new LLM provider, consider whether it supports embeddings for memory connections: ### **Providers with Embedding Support** - ✅ **OpenAI** - `text-embedding-3-small`, `text-embedding-3-large` - ✅ **Google** - `text-embedding-004` - ✅ **Mistral** - `mistral-embed` (when AI SDK package available) ### **Providers without Embedding Support** - ❌ **Anthropic, Groq, Cerebras, DeepSeek** - No embedding models available ### **Implementation Notes** - Embedding support is **optional** - agents work perfectly without memory connections - Missing embedding support gracefully disables memory connection features - The LLM layer handles provider validation and throws clear error messages - Update the provider list in `createEmbedding()` when new embedding providers are added ### **Adding Embedding Support** If your provider supports embeddings, add it to `src/llm/create-embedding.ts`: ```typescript export function createEmbedding(config: EmbeddingConfig): EmbeddingModel { switch (config.provider) { case 'openai': // OpenAI implementation break; case 'google': // Google implementation break; case 'your-provider': if (!config.apiKey) { throw createError('llm', 'Your Provider API key is required for embeddings', ErrorCode.LLM_API_KEY); } const provider = createYourProvider({ apiKey: config.apiKey }); return provider.embedding(config.model || 'your-embedding-model'); case 'your-provider-without-embeddings': throw createError('llm', 'Your Provider does not currently support embeddings', ErrorCode.LLM_EXECUTION); default: throw createError('llm', `Provider ${config.provider} does not support embeddings`, ErrorCode.LLM_EXECUTION); } } ``` ## Conclusion By following these steps, you can add a new LLM provider to the AgentDock Core framework. The unified implementation makes it easy to add new providers while maintaining a consistent interface for all LLM operations. The framework's architecture separates the AI SDK integration from client applications, allowing them to use a consistent interface regardless of the underlying provider. This design makes it easy to switch providers or update the AI SDK version without changing client code. When implementing a new provider, focus on: 1. **Compatibility**: Ensure your implementation aligns with the existing message and model interfaces 2. **Error handling**: Implement proper error handling and validation 3. **Performance**: Consider caching and efficiency in your implementation 4. **Testing**: Create comprehensive tests for your provider ## Tool Integration The AgentDock Core framework provides a mechanism for tools to access the agent's LLM instance. This allows tools to leverage the LLM capabilities without having to create their own LLM instances. When an agent calls a tool, it passes its LLM instance via the `options.llmContext` parameter. Tools can check for this parameter and use it if available. Key best practices for tool integration: 1. **Always check if LLM is available**: Use `if (options.llmContext?.llm)` to check if the LLM instance is available. 2. **Implement fallbacks**: Always have a fallback mechanism in case the LLM is not available or encounters an error. 3. **Use proper error handling**: Wrap LLM calls in try/catch blocks to handle errors gracefully. 4. **Keep messages focused**: Create clear system and user messages that focus on the specific task. 5. **Use appropriate temperature**: Set the temperature based on the task requirements (lower for factual tasks, higher for creative tasks). ## Agent Node (`AgentNode`) The `AgentNode` class (`agentdock-core/src/nodes/agent-node.ts`) is the primary orchestrator for conversational agent interactions within AgentDock Core. It leverages the Vercel AI SDK for efficient streaming and multi-step tool execution. ## Core Responsibilities - **Message Processing:** Handles incoming message arrays via its primary `handleMessage` method. - **LLM Interaction:** Manages communication with language models via `CoreLLM`, utilizing the Vercel AI SDK's `streamText` function for generation, streaming, and tool execution. - **Tool Integration:** Determines available tools based on the agent template and orchestration state, then prepares them for execution through the LLM. - **State Management:** Updates orchestration state (token usage, recently used tools) through callbacks. - **Configuration:** Reads agent behavior rules from the `AgentConfig` object and accepts runtime overrides. - **Context Injection:** Adds current time and other relevant context to the LLM prompt. - **Provider Fallbacks:** Supports fallback providers for enhanced reliability. ## Key Interactions ```mermaid graph TD A[API Endpoint / Client] --> B(AgentNode) B --> C(Orchestration Logic) C --> D(OrchestrationStateManager) B --> E(CoreLLM) E --> F[LLM Provider API] F --> E B --> G{Tool Execution} G --> H[Specific Tool] H --> G G --> B E --> B D --> C style B fill:#0066cc,color:#ffffff,stroke:#0033cc ``` 1. Receives request with messages and session ID. 2. Consults Orchestration logic to determine active step and load relevant state. 3. Filters available tools based on active step and sequence rules. 4. Constructs the prompt using message history, system prompt, and context. 5. Calls `CoreLLM.streamText`, passing messages, prompt, and filtered tools. 6. Handles tool calls by executing them and returning results to the LLM. 7. Streams the final text response back to the caller. 8. Updates token usage and state information after the interaction completes. ## Configuration The `AgentNode`'s behavior is configured through the agent template (`template.json`), which specifies: ```typescript // Example of AgentNode configuration { "type": "AgentNode", "config": { "provider": "anthropic", "apiKey": "YOUR_API_KEY", "fallbackApiKey": "BACKUP_API_KEY", // Optional "fallbackProvider": "openai", // Optional "agentConfig": { "personality": "You are a helpful assistant.", "nodes": ["search", "deep_research"], "nodeConfigurations": { "anthropic": { "model": "claude-3-5-sonnet-20240620" } } } } } ``` ## Response Streaming The `AgentNode` returns an `AgentDockStreamResult` from its `handleMessage` method, which provides: - **State Tracking**: Automatically updates token usage and tool usage in session state - **Error Handling**: Better error propagation from LLM providers - **Tool Management**: Handles tool execution and tracking in session state For detailed implementation, see [`agentdock-core/src/nodes/agent-node.ts`](../../agentdock-core/src/nodes/agent-node.ts). For more about streaming capabilities, see [Response Streaming Documentation](./core/response-streaming.md). ## AgentDock: Build Anything with AI Agents AgentDock is an open-source, backend-first framework for building and deploying sophisticated AI agents. It's designed to be framework-agnostic and provider-independent, giving you complete control over your agent's implementation. ## Core Architecture The framework is built around a powerful node-based system: - **AgentNode**: The primary abstraction for agent functionality, encapsulating LLM interaction and tool integration - **BaseNode**: The foundation for all nodes, providing core functionality and a consistent interface - **Node Registry**: Central system for registering and retrieving all node types, including both regular nodes and tools - **Tool Registry**: Focused abstraction for managing tool availability for agents, working with the Node Registry - **Custom Tools**: Specialized nodes that can be called by LLMs to perform specific tasks - **Configuration**: Simple JSON-based agent definitions - **Orchestration Framework**: Dynamic control of agent behavior based on conversation context - **Session Management**: Isolated state management for concurrent conversations ### Advanced Subsystems #### Session Management The [session management system](./sessions/README.md) provides isolation between concurrent conversations and maintains state across multiple requests. Key capabilities include: - **Stateful Conversations**: Maintain conversation context and history - **Tool Context Persistence**: Enable tools to store and access stateful information - **Memory Efficiency**: Optimized storage with automatic cleanup - **Single Source of Truth**: Consistent session state across components For more details, see the [Session Management Overview](./sessions/session-overview.md). #### Orchestration Framework The [orchestration framework](./orchestration/README.md) enables dynamic control of agent behavior and tool availability based on conversation context: - **Context-Aware Steps**: Transition between different modes based on conversation content - **Dynamic Tool Availability**: Control which tools are available in different steps - **Conditional Logic**: Activate steps based on message content or previous tool usage - **Tool Sequences**: Define specific tool ordering for complex workflows For more details, see the [Orchestration Framework Overview](./orchestration/orchestration-overview.md). ### Registry Relationship The Node Registry and Tool Registry work together to provide a comprehensive system for managing nodes and tools: - **Node Registry**: Handles the broader node ecosystem, including registration, creation, metadata, and versioning - **Tool Registry**: Provides a focused interface specifically for making tools available to agents - **Tools as Nodes**: Tools are registered in the Node Registry with the `isTool` flag set to `true` - **Dual Purpose**: This architecture supports both the current OSS implementation and the future Pro implementation ## What You Can Build 1. **AI-Powered Applications** - Custom chatbots with any frontend - Command-line AI assistants - Automated data processing pipelines - Backend service integrations 2. **Integration Capabilities** - Any AI provider (OpenAI, Anthropic, etc.) - Any frontend framework - Any backend service - Custom data sources and APIs 3. **Automation Systems** - Data processing workflows - Document analysis pipelines - Automated reporting systems - Task automation agents ## Key Features - 🔌 **Framework Agnostic**: Use with any tech stack - 🧩 **Modular Design**: Build complex systems from simple nodes - 🛠️ **Extensible**: Create custom nodes for any functionality - 🔒 **Secure**: Built-in security features for API keys and data - 📦 **Self-Contained**: Core framework has minimal dependencies - 🔄 **Orchestration**: Control agent behavior dynamically - 💾 **Session Management**: Support concurrent conversations ## Architecture Documentation For more detailed documentation on specific architecture components: | Component | Documentation | |-----------|---------------| | Agent Node | [Agent Node Architecture](./agent_node.md) | | Error Handling | [Core Error Handling](./core-error-handling.md) | | Provider Abstraction | [Provider-Agnostic API](./provider-agnostic-api.md) | | Orchestration | [Orchestration Framework](./orchestration/README.md) | | Sessions | [Session Management](./sessions/README.md) | ## Getting Started 1. Install the framework 2. Create your first agent configuration 3. Add custom nodes for your specific needs 4. Deploy anywhere ## Future Possibilities - Visual agent builders - Natural language agent creation - Advanced agent templates - Enhanced execution systems - Managed integrations AgentDock provides the foundation for building sophisticated AI agent systems while maintaining complete control over your implementation and infrastructure. ## Core Architecture Overview **AgentDock Core** provides the foundational libraries and systems for building stateful, tool-using AI agents. It emphasizes modularity, type safety, and extensibility. ## Guiding Principles - **Modularity:** Key concerns (LLM interaction, state, storage, orchestration) are handled by distinct, often replaceable components. - **Extensibility:** Designed to easily incorporate new LLM providers, storage backends, custom tools, and agent logic. - **Type Safety:** Leverages TypeScript for robust typing throughout the core library. - **Provider Agnosticism:** Aims to abstract common functionalities across different LLM providers and storage systems. - **State Management:** Central focus on reliably managing conversational state across multiple interactions. ## Key Subsystems & Components AgentDock Core comprises several interacting subsystems: 1. **LLM Abstraction (`/llm`):** - `CoreLLM`: Central class providing a unified interface to interact with various LLM providers (via Vercel AI SDK). - Handles streaming, function/tool calling API translation, and basic token usage reporting. 2. **Node System (`/nodes`):** - `AgentNode`: The primary node type responsible for orchestrating agent interactions, integrating LLM calls, tool execution, and state management. - Defines the main processing logic for conversational agents. 3. **Storage Abstraction (`/storage`):** - Provides interfaces (`StorageProvider`) and implementations (Memory, Redis, Vercel KV) for persistent Key-Value storage. - `StorageFactory`: Manages provider instantiation based on configuration. - `SecureStorage`: Client-side encrypted storage for browsers. - Foundation for planned Vector and Relational storage. 4. **Session Management (`/session`):** - `SessionManager`: Manages session state lifecycle (creation, retrieval, update, TTL cleanup) using the Storage Abstraction layer. - Ensures conversational context is maintained and isolated between different sessions. 5. **Orchestration Framework (`/orchestration`):** - `OrchestrationStateManager`: Manages session-specific orchestration state (active step, tool history, sequence progress) using `SessionManager`. - `StepSequencer`: Enforces defined tool execution order within steps. - Condition Logic: Evaluates configured conditions to control transitions between steps. - Controls tool availability based on the active step and sequence. 6. **Tool System (`/tools`, integrated in `/nodes`, `/llm`):** - Defines tool structures and execution logic. - Integrates with `CoreLLM` for function/tool calling. - `AgentNode` handles tool loading, filtering (via Orchestration), and execution. 7. **Configuration System (`/config`, `/templates`):** - Loads agent definitions from template files (`template.json`). - Manages environment variables for API keys and storage configuration. 8. **Error Handling (`/errors`):** - Provides standardized error types and a factory for consistent error reporting. 9. **Evaluation Framework (`/evaluation`):** - Provides tools for systematic evaluation of agent performance. - Includes `EvaluationRunner`, various `Evaluators` (RuleBased, LLMJudge, NLP, Lexical, ToolUsage), `EvaluationCriteria` definition, and `EvaluationStorageProvider` for results persistence. ## Core Components AgentDock Core consists of several key components: - **Node System** - A flexible, modular framework for building AI agents - **LLM Providers** - Unified interfaces to multiple LLM providers - **Tool Framework** - Standardized way to define and use tools with agents - **Orchestration** - Manages multi-step agent workflows - **Response Streaming** - Enhanced streaming capabilities built on Vercel AI SDK - **LLM Orchestration Service** - Bridges AgentNode and CoreLLM with orchestration capabilities For more details on specific components: - [Request Flow](./request-flow.md) - [Technology Stack](./technology-stack.md) - [Response Streaming](./response-streaming.md) ## Core Interaction Summary The subsystems work in concert: An `AgentNode` uses `CoreLLM` for language tasks, relies on `SessionManager` and `OrchestrationStateManager` (backed by `Storage`) to maintain context and control flow, and executes `Tools` as directed by the LLM and permitted by Orchestration rules defined in the agent's `Configuration`. See [Architecture Overview](../README.md) for links to detailed documentation on each subsystem. ## Request Flow in AgentDock Core This document outlines the typical sequence of events when a request is processed by AgentDock Core. ## Request Flow Diagram ```mermaid sequenceDiagram participant Client participant API participant Agent participant LLM participant Tool Client->>+API: Send Message (with SessionId) API->>+Agent: Process Request Agent->>+LLM: Generate Response (incl. History, Filtered Tools) alt Tool Call Needed LLM-->>Agent: Request Tool Execution Agent->>+Tool: Execute Tool Tool-->>-Agent: Return Result Agent->>LLM: Provide Tool Result LLM->>Agent: Continue Response Generation end LLM-->>-Agent: Stream/Complete Response Text Agent->>-API: Stream Response Chunks API-->>-Client: Stream Response ``` ## Detailed Steps 1. **Request Initiation:** A client sends a request (e.g., a user message, potentially including a `sessionId`) to an API endpoint. 2. **API Endpoint Handling:** Extracts the `sessionId` and message payload, determining the target `agentId`. 3. **Agent Instantiation (`AgentNode`):** Creates an instance of `AgentNode`, passing the agent configuration, API keys, and core managers. 4. **State Retrieval / Initialization:** Loads or creates orchestration state for the session. 5. **Orchestration & Tool Filtering:** Evaluates conditions to determine the `activeStep` and filters available tools. 6. **LLM Interaction (`CoreLLM.streamText`):** Prepares the prompt, sets callbacks, and calls the LLM with filtered tools. 7. **Response Streaming & Tool Handling:** - LLM streams response (text chunks or tool call requests) - Tool calls are executed and results returned to the LLM - Text chunks are streamed back to the client 8. **State Updates:** Update token usage, tool history, sequence index, and timestamps. 9. **Response Completion:** Stream ends and response is finalized. 10. **Cleanup:** `AgentNode` instance is discarded while session state persists. For implementation details, see [`agentdock-core/src/nodes/agent-node.ts`](../../../agentdock-core/src/nodes/agent-node.ts). ## Enhanced Streaming Flow AgentDock extends standard streaming with `AgentDockStreamResult`: ```mermaid sequenceDiagram participant Client participant Adapter participant AgentNode participant LLMService as LLMOrchestrationService participant CoreLLM participant LLM as LLM Provider Client->>Adapter: Request Adapter->>AgentNode: handleMessage() AgentNode->>LLMService: streamWithOrchestration() LLMService->>CoreLLM: streamText() CoreLLM->>LLM: API Call with Streaming loop For each token/chunk LLM-->>CoreLLM: Token/Chunk CoreLLM-->>LLMService: Enhanced Stream LLMService-->>Adapter: AgentDockStreamResult Adapter-->>Client: Streaming Response end LLM-->>CoreLLM: onFinish() CoreLLM-->>LLMService: Update state LLMService-->>Adapter: Stream completion ``` This enhanced flow provides: 1. **Automatic State Management**: Updates token usage and tracks tools used 2. **Error Handling**: Propagates errors from LLM providers with better context 3. **Tool Orchestration**: Manages tool execution and updates session state For details on streaming implementation, see [Response Streaming](./response-streaming.md). ## Response Streaming in AgentDock AgentDock's response streaming system extends the Vercel AI SDK to provide enhanced functionality for orchestration, error handling, and state management. ## AgentDockStreamResult The core of AgentDock's streaming capabilities is the `AgentDockStreamResult` interface, which extends Vercel AI SDK's `StreamTextResult`: ```typescript export interface AgentDockStreamResult extends VercelStreamTextResult { _orchestrationState?: { recentlyUsedTools?: string[]; cumulativeTokenUsage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; [key: string]: unknown; } | null; _hasStreamingError?: boolean; _streamingErrorMessage?: string; } ``` ### Key Enhancements 1. **Orchestration State Tracking** - Maintains a record of recently used tools - Tracks cumulative token usage across multiple requests - Supports arbitrary state properties for extensibility 2. **Enhanced Error Handling** - Includes flags to indicate streaming errors - Preserves error messages for client-side handling - Overrides `toDataStreamResponse` to properly include error information 3. **Backward Compatibility** - Provides a type alias (`StreamTextResult`) for backward compatibility - Maintains the same streaming interface as Vercel AI SDK ## Integration with LLMOrchestrationService The `AgentDockStreamResult` is primarily returned by the `LLMOrchestrationService.streamWithOrchestration` method, which: 1. Wraps the CoreLLM's `streamText` method 2. Injects orchestration-specific callbacks 3. Updates token usage in session state 4. Tracks tool usage for subsequent requests ## Usage in AgentNode The `AgentNode` returns the `AgentDockStreamResult` from its `handleMessage` method, allowing: 1. Clients to consume the stream directly 2. Error handling at the adapter/route level 3. Access to orchestration state for complex flows ## Benefits - **Enhanced Reliability**: Better error propagation and handling - **Improved State Management**: Automatic tracking of tokens and tools - **Seamless Integration**: Works with the existing Vercel AI SDK patterns For more information about the AgentNode implementation, see [Agent Node Documentation](../agent-node.md). ## Technology Stack This document outlines the core technologies used in AgentDock Core and its reference implementation. ## Core Framework - **TypeScript**: Primary language, providing type safety and modern JavaScript features - **Node.js**: Server-side runtime (>= 20.11.0) - **Vercel AI SDK**: For LLM provider integrations ## State Management - **Zod**: Schema validation and runtime type checking - **Zustand**: UI state management in the reference implementation ## Development Environment - **pnpm**: Package manager (>= 9.15.0) - **ESLint & TypeScript-ESLint**: Code quality and type checking - **Jest**: Testing framework - **Husky**: Git hooks for code quality ## Reference Implementation For details about the open source client implementation built with Next.js, see [Next.js Implementation](../../oss-client/nextjs-implementation.md). ### Key Technologies - **Next.js**: React framework with App Router - **React**: UI library (^18.2.0) - **Shadcn/ui & Radix UI**: Component primitives - **Tailwind CSS**: Utility-first styling - **React Hook Form**: Form handling - **React Markdown**: Documentation rendering ## AgentDock Core - **Language:** TypeScript - Provides strong typing, compile-time checks, and improved maintainability for the core library. - **Runtime:** Node.js (LTS versions recommended) - The primary execution environment for the core logic when run server-side. - **LLM Interaction:** Vercel AI SDK (`ai` package) - Provides a unified, stream-first interface to interact with various LLM providers (OpenAI, Anthropic, Google Gemini, Groq, etc.). - Handles the complexities of different provider APIs for text generation, streaming, and function/tool calling. - **Storage (Defaults & Included):** - In-Memory: Default key-value store for sessions/orchestration if no external provider is configured. - Redis (`@upstash/redis`): Included provider for persistent key-value storage, often used with Docker for development. - Vercel KV (`@vercel/kv`): Included provider for Vercel's key-value store. - **Schema Validation (for Tools):** Zod - Used within tool definitions to define and validate input parameters expected from the LLM, ensuring type safety and providing clear error messages. - **Logging:** Custom logger utilities (`agentdock-core/src/logging`) - Provides structured logging capabilities within the core library. - **Package Manager:** pnpm - Used for managing dependencies and ensuring efficient installation. AgentDock Core will be released as a separate NPM package when it's ready for release. ## Open Source Client (Reference Implementation) This web application demonstrates how to use AgentDock Core. - **Framework:** Next.js (App Router) - Provides the foundation for the web application, including routing, server components, client components, and API routes. - **UI Components:** Shadcn/ui & Radix UI - Used for building the user interface components (buttons, inputs, layout, etc.). Built on top of Tailwind CSS. - **Styling:** Tailwind CSS - A utility-first CSS framework for styling the application. - **State Management (UI):** Primarily React state/context, potentially Zustand for more complex global state if needed. - **Client-Side Storage:** `localStorage` (potentially secured via `SecureStorage` from Core for sensitive items like API keys). ## Development & Build Tools - **Package Management:** pnpm - Manages dependencies with efficient node_modules structure and consistent installs. - **Task Running/Scripting:** pnpm scripts (defined in `package.json`) - Used for build, test, dev, linting, and other development tasks. - **Testing:** Vitest - Used for running unit and integration tests. - **Linting/Formatting:** ESLint & Prettier - Ensures code quality and consistent formatting. ## Optional Backend Services (for Development) - **Redis:** (As mentioned in Core) Typically run via Docker Compose (`docker-compose.yaml`) for persistent session/orchestration state during development. - **Redis Commander:** A simple web UI (included in `docker-compose.yaml`) for inspecting data stored in the development Redis instance. ### Extended Vercel AI SDK Capabilities AgentDock extends the Vercel AI SDK with enhanced capabilities: - **AgentDockStreamResult**: Extends the standard `StreamTextResult` with: - Orchestration state tracking - Enhanced error handling - Custom response transformations - **LLMOrchestrationService**: Bridges the SDK's streaming capabilities with orchestration: - Automatically updates token usage in session state - Tracks tools used during conversations - Provides this state to orchestration rules For more details, see: - [Response Streaming](./response-streaming.md) - [LLM Orchestration](../orchestration/llm-orchestration.md) ## Model Architecture This document explains the model architecture in the AgentDock reference implementation. ## Overview The model architecture follows a clean, consistent pattern that separates concerns and avoids redundancy: 1. **API Routes**: Handle provider-specific model fetching and validation 2. **Model Registry**: Stores model metadata in memory 3. **Model Service**: Provides a centralized way to interact with models ## Directory Structure ``` src/ ├── app/ │ └── api/ │ └── providers/ │ ├── models/ # Generic models endpoint │ ├── anthropic/ │ │ └── models/ # Anthropic-specific models endpoint │ ├── openai/ │ │ └── models/ # OpenAI-specific models endpoint │ ├── gemini/ │ │ └── models/ # Gemini-specific models endpoint │ └── deepseek/ │ └── models/ # DeepSeek-specific models endpoint └── lib/ ├── models/ │ └── registry.ts # Central model registry └── services/ └── model-service.ts # Model service for interacting with models ``` ## Components ### API Routes 1. **Provider-Specific Routes** (`/api/providers/{provider}/models`): - Fetch models from the provider's API - Validate API keys - Register models with the ModelRegistry 2. **Generic Models Route** (`/api/providers/models`): - Return models from the registry - Do not fetch models from provider APIs ### Model Registry The `ModelRegistry` class in `src/lib/models/registry.ts`: - Stores model metadata in memory - Organizes models by provider - Provides methods to register, get, and reset models ### Model Service The `ModelService` class in `src/lib/services/model-service.ts`: - Provides a centralized way to interact with models - Handles API calls to fetch and register models - Manages model registration and retrieval ## Flow 1. **Initialization**: - The application starts with an empty model registry 2. **API Key Configuration**: - User provides an API key for a provider - Application validates the API key using the provider-specific endpoint - If valid, the endpoint fetches models from the provider's API and registers them with the registry 3. **Model Usage**: - Application retrieves models from the registry using the ModelService - No additional API calls are made unless the models need to be refreshed ## Integration with agentdock-core The reference implementation consumes the agentdock-core package, which provides: - Provider types (`anthropic`, `openai`, `gemini`, `deepseek`) - A `ProviderRegistry` class for provider metadata - Model creation functions for each provider - A unified `CoreLLM` class that works with any provider The reference implementation extends this with: - A dynamic model registry for runtime model registration - API routes for fetching models from provider APIs - A service layer for simplified model interaction ## Best Practices 1. **Single Source of Truth**: - The ModelRegistry is the single source of truth for model metadata - Provider-specific API routes are the only place where models are fetched from provider APIs 2. **Separation of Concerns**: - API routes handle HTTP requests and responses - ModelRegistry handles model storage - ModelService provides a clean interface for model operations 3. **DRY (Don't Repeat Yourself)**: - Common functionality is centralized in the ModelService - Provider-specific logic is isolated to provider-specific routes 4. **KISS (Keep It Simple, Stupid)**: - The architecture is simple and easy to understand - Each component has a clear, single responsibility - All provider-related endpoints are organized under a common path ## Conditional Transitions This document explains how AgentDock manages transitions between different orchestration steps based on defined conditions. ## Core Concept Conditional transitions allow the agent's behavior (specifically, the active orchestration step and thus the available tools) to change dynamically based on the agent's past actions within the current session. ## Configuration Conditions are defined within each step in the agent's orchestration configuration (`template.json`): ```json { "name": "post_analysis_step", "description": "Activate after the 'think' tool has been used.", "conditions": [ { "type": "tool_used", "value": "think" } ], "availableTools": { "allowed": ["summarize", "save_result"] } } ``` - Each step can have a `conditions` array. - A step becomes active only if **all** conditions within its array are met simultaneously (logical AND). - Each condition object has a `type` and a `value`. ## Implemented Condition Types Currently, the following condition types are implemented in `agentdock-core`: - **`tool_used`**: Checks if the specified tool name (`value`) exists *anywhere* in the session's `recentlyUsedTools` list. - Example: `{ "type": "tool_used", "value": "search" }` - **`sequence_match`**: Checks if the *end* of the session's `recentlyUsedTools` list exactly matches the `sequence` array defined for the step being evaluated. This is useful for activating steps only after a specific series of tools has been used in order. - Does *not* use the `value` field. - Example: `{ "type": "sequence_match" }` (used on a step that has a `sequence` array defined). ## Implementation (`OrchestrationManager`) The logic for evaluating conditions resides within the `OrchestrationManager` (`agentdock-core/src/orchestration/index.ts`). ### Key Logic: - **Access to State:** The condition evaluation logic needs access to the current `OrchestrationState` for the session (from `OrchestrationStateManager`), specifically the `recentlyUsedTools` list. - **Evaluation Flow:** 1. Triggered typically at the beginning of processing a new user message (before determining available tools for the LLM call). 2. **Additionally**, evaluation is now triggered immediately *after* a tool usage event is processed (`processToolUsage`). This ensures that step transitions based on completed sequences happen within the same turn. 3. Iterates through all defined orchestration steps in the configuration. 4. For each step, evaluates **all** of its defined `conditions` (e.g., `tool_used`, `sequence_match`) against the current state. 5. If **all** conditions for a step pass, that step is considered a candidate for activation. - **Step Activation:** - If one or more steps meet their conditions, a strategy selects the active step (typically the first matching step in the configuration order). - The `OrchestrationStateManager.setActiveStep` method updates the session's state with the name of the newly activated step. - If no step's conditions are met, the system might fall back to a default step or maintain the current `activeStep`. ## How it Works (Example Flow) 1. **Initial State:** Session starts, maybe in a default "general" step. `recentlyUsedTools` is empty. 2. **User Action / LLM Response:** The agent uses the `think` tool. 3. **State Update:** `OrchestrationStateManager.addUsedTool(sessionId, "think")` is called. `recentlyUsedTools` now contains `["think"]`. 4. **Next Interaction - Condition Check:** Before the next LLM call, the `OrchestrationManager` evaluates conditions: - Step "general" (Default) -> May remain candidate. - Step "post_analysis_step" (`tool_used`: "think") -> Condition is checked against `recentlyUsedTools`. It passes. 5. **Step Activation:** Since conditions for "post_analysis_step" passed, it becomes the active step. `OrchestrationStateManager.setActiveStep(sessionId, "post_analysis_step")` is called. 6. **Tool Availability:** On the next turn, when the LLM asks for tools, the system provides only those allowed in "post_analysis_step" (e.g., `summarize`, `save_result`). ## Multi-Agent Relevance In the planned [Orchestration-Driven Personas](./../roadmap/multi-agent-collaboration.md) model for multi-agent collaboration: - The `tool_used` condition could trigger transitions between different agent personas/steps. - For example, after a "Researcher" persona (step) uses `web_search` and `summarize`, a `tool_used: summarize` condition could activate a "Planner" persona (step) to process the summary. ## Considerations - **Limited Conditions:** The current implementation only supports `tool_used`. Expanding condition types (e.g., based on message content, state values) would require adding more cases to the `checkCondition` logic in `OrchestrationManager`. - **Condition Order:** The order of steps in the configuration matters if multiple steps depend on the same `tool_used` condition. - **Statefulness:** Conditions rely heavily on accurate session state (`recentlyUsedTools`). - **Relying on Model Intelligence:** As frontier LLMs become increasingly capable of understanding context and following complex instructions, overly rigid constraints (like numerous, complex condition types or strict sequences) might become less necessary or even counterproductive. Future development may explore balancing explicit orchestration rules with leveraging the model's inherent planning and reasoning abilities, potentially simplifying configuration while maintaining reliable task execution. 1. **Initial State:** Session starts, no specific step active (or a default step). 2. **User Message:** User sends a message: "Okay, let's plan the project structure." 3. **Condition Check:** The orchestration system evaluates conditions for all steps: - Step "research" (`message_contains`: "research") -> Fails. - Step "planning_mode" (`message_contains`: "plan") -> Passes. - Step "planning_mode" (`not_recently_used`: "web_search", `window`: 3) -> Passes (assuming `web_search` wasn't just used). 4. **Step Activation:** Since both conditions for "planning_mode" passed, it becomes the active step. `OrchestrationStateManager.setActiveStep(sessionId, "planning_mode")` is called. 5. **Tool Availability:** On the next turn, when the LLM asks for tools, the system provides only those allowed in "planning_mode" (e.g., `think`, `list_generation`). 6. **Further Interaction:** If the user later says "research caching strategies", the conditions might re-evaluate, potentially activating the "research" step and changing the available tools. ## Considerations - **Condition Order:** The order of steps in the configuration can matter if multiple steps' conditions might be met simultaneously (first match usually wins). - **Specificity:** Conditions should be specific enough to avoid unintended step changes but general enough to capture user intent. - **Complexity:** Overly complex conditions or numerous steps can make agent behavior hard to predict or debug. - **Statefulness:** Conditions rely heavily on accurate session state (`activeStep`, `recentlyUsedTools`). ## LLM Orchestration Service The `LLMOrchestrationService` serves as a bridge between the `AgentNode` and `CoreLLM`, adding orchestration-specific functionality to LLM interactions. ## Core Responsibilities - **Stream Management**: Wraps CoreLLM's streaming capabilities with orchestration state - **Token Usage Tracking**: Updates token usage in session state - **Tool Tracking**: Monitors and records tools used during interactions - **Callback Injection**: Provides orchestration-aware callbacks for stream events ## Architecture Position ```mermaid graph TD A[AgentNode] --> B[LLMOrchestrationService] B --> C[CoreLLM] C --> D[Vercel AI SDK] D --> E[LLM Provider APIs] B <--> F[OrchestrationManager] F <--> G[State Storage] style B fill:#0066cc,color:#ffffff,stroke:#0033cc ``` ## Key Methods ### streamWithOrchestration The primary method that wraps `CoreLLM.streamText` with orchestration capabilities: ```typescript async streamWithOrchestration( options: StreamWithOrchestrationOptions ): Promise, any>> ``` This method: 1. Prepares orchestration-aware callbacks for `onFinish` and `onStepFinish` 2. Calls `CoreLLM.streamText` with these callbacks 3. Returns an enhanced stream result with orchestration state ### updateTokenUsage A private method that updates the token usage in the session state: ```typescript private async updateTokenUsage(usage?: TokenUsage): Promise ``` This method: 1. Fetches the current state from the `OrchestrationManager` 2. Updates the cumulative token usage with the new usage information 3. Stores the updated state back in the session ## Integration with Tool Tracking The service also tracks tools used during the conversation: - Monitors tool calls in the `onStepFinish` callback - Updates the `recentlyUsedTools` array in session state - Provides this information to orchestration rules for conditional transitions ## Constructor ```typescript constructor( private llm: CoreLLM, private orchestrationManager: OrchestrationManager, private sessionId: SessionId ) ``` The service requires: - A `CoreLLM` instance for LLM interactions - An `OrchestrationManager` for state management - A `sessionId` to identify the session context ## Related Documentation - [Orchestration Overview](./orchestration-overview.md) - General orchestration concepts - [State Management](./state-management.md) - How state is managed in orchestration - [Response Streaming](../core/response-streaming.md) - Details on streaming capabilities ## Step Activation - **Step Activation:** Based on conditions met (e.g., a specific tool was used), the active step can change, altering the agent's behavior and available tools for the next turn. - The system now re-evaluates conditions immediately after a tool is used, allowing for step transitions within the same turn a defining sequence is completed. ## Example Scenario: Cognitive Reasoner Agent Let's illustrate with the [Cognitive Reasoner agent](https://github.com/AgentDock/AgentDock/tree/main/agents/cognitive-reasoner), specifically its `EvaluationMode`. **Agent Configuration (`template.json` excerpt):** ```json { "name": "EvaluationMode", "description": "Critical evaluation sequence", "sequence": [ "critique", "debate", "reflect" ], "conditions": [ { "type": "sequence_match" } ], "availableTools": { "allowed": ["critique", "debate", "reflect", "search"] } } ``` **Flow:** 1. **Initial State:** Session starts, `activeStep` is `DefaultMode`, `recentlyUsedTools` is `[]`. 2. **User Request:** "Critique the argument that remote work improves productivity." 3. **LLM Action (Turn 1 - Critique):** The agent, likely in `DefaultMode`, uses the `critique` tool. `processToolUsage` is called. - `recentlyUsedTools` becomes `["critique"]`. - `getActiveStep` runs immediately. No sequence matches yet. `activeStep` remains `DefaultMode`. 4. **LLM Action (Turn 2 - Debate):** Following the critique, the agent uses the `debate` tool (perhaps prompted internally or by user). `processToolUsage` is called. - `recentlyUsedTools` becomes `["critique", "debate"]`. - `getActiveStep` runs. No sequence matches yet. `activeStep` remains `DefaultMode`. 5. **LLM Action (Turn 3 - Reflect):** The agent uses the `reflect` tool. `processToolUsage` is called. - `recentlyUsedTools` becomes `["critique", "debate", "reflect"]`. - `getActiveStep` runs. It checks `EvaluationMode`: - Condition `type: "sequence_match"` is evaluated. - The end of `recentlyUsedTools` `["critique", "debate", "reflect"]` matches the step's `sequence` `["critique", "debate", "reflect"]`. - The condition passes. - `EvaluationMode` becomes the new `activeStep`. The `sequenceIndex` is reset to `0` for this newly activated step. 6. **Next Turn:** When the next interaction begins, the agent is now in `EvaluationMode`. If the active step involved sequence enforcement via the `StepSequencer`, only the tool at `sequenceIndex: 0` (`critique`) would be initially allowed, although this specific example focuses on the *transition* via `sequence_match` rather than sequence *enforcement* during the step. ## Orchestration Configuration This document details how to configure orchestration behavior for AgentDock agents using the agent template (`template.json` or similar). ## Structure Orchestration is defined within the main agent configuration under the top-level `orchestration` key: ```json { "id": "research-planner", "name": "Research and Planning Agent", "description": "An agent that performs research and planning.", "llm": { "provider": "openai", "model": "gpt-4-turbo" }, "tools": ["web_search", "think", "list_generation"], "orchestration": { "description": "Manages transitions between research and planning modes.", "defaultStep": "idle", "steps": [ // Step definitions go here... ] } } ``` - `orchestration`: The main object containing all orchestration settings. - `description`: Optional description of the orchestration workflow. - `defaultStep`: (Optional) The name of the step to activate if no other step's conditions are met. If omitted, the agent might operate without a specific step active initially or fall back to allowing all configured tools. - `steps`: An array of orchestration step objects. ## Step Definition Each object in the `steps` array defines an orchestration step: ```json { "name": "research_mode", "description": "Step for active research using web search.", "conditions": [ { "type": "tool_used", "value": "search" }, { "type": "sequence_match" } ], "availableTools": { "allowed": ["web_search", "think", "*cognitive*"], "denied": [] }, "sequence": [ "web_search", "think" ], "resetSequenceOn": ["message_contains"] } ``` ### Core Step Properties: - `name` (Required): A unique identifier string for the step (e.g., `research_mode`, `planning`, `code_review`). - `description` (Optional): A human-readable description of the step's purpose. ### `conditions` (Array, Optional) An array of condition objects that must *all* be met for this step to become active. - Each object in the array represents a single condition. - If this array is omitted or empty, the step has no activation conditions (other than potentially being the `isDefault` step). #### Condition Object ```json { "type": "tool_used" | "sequence_match", "value": "string (required for type='tool_used', unused for type='sequence_match')", "description": "string (optional)" } ``` - `type` (String, Required): The type of condition to check. Valid types: - `tool_used`: Checks if the tool specified in `value` exists in the session's `recentlyUsedTools` history. - `sequence_match`: Checks if the end of the `recentlyUsedTools` history matches the `sequence` defined for this step. - `value` (String, Conditional): The value associated with the condition. - **Required** if `type` is `tool_used` (specifies the tool name). - **Not used** (and should be omitted) if `type` is `sequence_match`. - `description` (String, Optional): A human-readable description of the condition's purpose. ### `availableTools` - (Optional) An object controlling which tools are accessible when this step is active. - `allowed`: An array of tool names or wildcards (e.g., `*cognitive*`) that are permitted. - `denied`: An array of tool names or wildcards that are explicitly forbidden, even if matched by `allowed`. - **Behavior:** - If `availableTools` is omitted, all tools configured for the agent are implicitly allowed. - If only `allowed` is present, only those tools are available. - If only `denied` is present, all tools *except* those denied are available. - If both are present, tools are allowed if they match `allowed` AND do not match `denied`. ### `sequence` (Array, Optional) - An array of tool name strings defining a required order of execution for this step. - When a step with a sequence is active, the `StepSequencer` typically restricts available tools to only the *next* tool required in the sequence. - Tools listed here should generally also be permitted by the `availableTools` configuration for this step. - See [Step Sequencing](./step-sequencing.md) for more details. ## Orchestration Framework Overview Orchestration in AgentDock provides a structured way to control agent behavior, manage tool availability across different states (steps), and define sequences for complex tasks. It enables more guided, reliable, and focused agent interactions compared to allowing unrestricted tool use. ## Core Concepts - **Steps (or Modes):** Discrete states within an agent's workflow (e.g., `research`, `planning`, `code_generation`). Each step defines specific behaviors. - **Conditions:** Rules that trigger transitions *between* steps based on context (user messages, tool usage). See [Conditional Transitions](./conditional-transitions.md). - **Tool Availability:** Each step configuration dictates which tools are allowed or denied when that step is active. - **Sequencing:** Within a step, a specific order of tool execution can be enforced. See [Step Sequencing](./step-sequencing.md). - **Session State:** Orchestration relies heavily on session-specific state (`OrchestrationState`) to track the active step, tool usage history, and sequence progress. See [State Management](./state-management.md). ## Architecture & Implementation Key components work together, managed primarily within the `agentdock-core/src/orchestration` directory: 1. **Configuration:** Defined in the agent template (`template.json`), specifying steps, conditions, tool availability, and sequences. See [Orchestration Configuration](./orchestration-config.md). 2. **`OrchestrationStateManager`:** Manages the `OrchestrationState` for each session, using the core `SessionManager` and configured storage provider. 3. **`StepSequencer`:** Enforces tool sequences defined within steps, interacting with the `OrchestrationStateManager` to track progress (`sequenceIndex`). 4. **Condition Evaluation Logic:** Determines which step should be active based on configured conditions and current context (message content, `OrchestrationState`). This logic coordinates reading state and triggering state updates. 5. **Tool Filtering:** Combines the `availableTools` configuration from the active step and the `StepSequencer`'s filtering to determine the exact set of tools available to the LLM at any given moment. ## Flow of Operation 1. **Initialization:** An agent instance loads its orchestration configuration. 2. **Interaction Received (e.g., User Message):** a. The system retrieves or creates the `OrchestrationState` for the session using `OrchestrationStateManager`. b. Condition evaluation logic checks the message content and current state against the conditions defined for all steps. c. If conditions for a new step are met, `OrchestrationStateManager.setActiveStep` updates the state. 3. **Tool Availability Determination:** a. The system identifies the `activeStep` from the `OrchestrationState`. b. It retrieves the `availableTools` (allowed/denied lists) from the active step's configuration. c. It applies initial filtering based on `availableTools`. d. It calls `StepSequencer.filterToolsBySequence` with the filtered list. If a sequence is active, this further restricts the list, often to a single tool. e. The final, filtered list of tools is provided to the LLM. 4. **Tool Execution:** a. The LLM selects and invokes a tool from the provided list. b. The tool executes. 5. **Post-Tool Processing:** a. `OrchestrationStateManager.addUsedTool` records the tool usage. b. If a sequence was active, `StepSequencer.processTool` is called to potentially advance the `sequenceIndex`. c. Condition evaluation logic *may* run again to check if the tool usage triggers a step transition. ## Benefits - **Guided Workflows:** Ensures agents follow specific processes for complex tasks. - **Improved Reliability:** Prevents agents from using inappropriate tools or getting stuck. - **Focused Interactions:** Limits the LLM's choices, potentially improving response quality and reducing hallucination. - **Stateful Control:** Enables dynamic behavior changes based on conversation history and context. ## Integration Points - **Session Management:** Relies fundamentally on session state isolation and management. - **Agent Configuration:** Defined via agent templates. - **LLM Interaction:** Controls the tools presented to the LLM. ## Orchestration Framework This directory contains documentation about AgentDock's orchestration framework. ## Overview Orchestration in AgentDock controls the flow of agent interactions and tool availability based on the conversation context. It provides a structured way to define complex agent behaviors through: - Step-based workflows - Conditional tool access - Context-aware transitions - Tool sequence enforcement - Memory-efficient state management ## Documentation - [Orchestration Overview](./orchestration-overview.md) - [Orchestration Configuration](./orchestration-config.md) - [State Management](./state-management.md) - [Step Sequencing](./step-sequencing.md) - [Conditional Transitions](./conditional-transitions.md) - [LLM Orchestration](./llm-orchestration.md) ## Documentation Files - [orchestration-overview.md](./orchestration-overview.md) - Core concepts and architecture of the orchestration system - [orchestration-config.md](./orchestration-config.md) - Configuration format and options - [step-sequencing.md](./step-sequencing.md) - Tool sequence enforcement and next-step prediction - [state-management.md](./state-management.md) - Optimized state management for orchestration - [conditional-transitions.md](./conditional-transitions.md) - How conditions work for transitioning between steps ## Orchestration State Management This document details the implementation of orchestration state management within AgentDock, focusing on how session-specific state is handled for controlling agent behavior and tool usage. ## Core Concepts - **Session-Scoped State:** All orchestration state (active step, tool sequence progress, recently used tools) is tied to a specific `SessionId` and managed separately for each conversation. - **State Interface (`OrchestrationState`):** Defined in `agentdock-core/src/orchestration/state.ts`, this interface extends the base `SessionState` and includes: - `activeStep?: string`: The name of the currently active orchestration step. - `recentlyUsedTools: string[]`: A list of tool names used within the session. - `sequenceIndex?: number`: The current index within a defined tool sequence for the `activeStep`. - `cumulativeTokenUsage?`: Tracks token counts for the session. - `lastAccessed: number`: Timestamp for TTL calculation. - `ttl: number`: Time-to-live for the state. ## Implementation (`OrchestrationStateManager`) The `OrchestrationStateManager` class (`agentdock-core/src/orchestration/state.ts`) is the central component for managing `OrchestrationState`. ### Key Features: - **Uses `SessionManager`:** Internally, it leverages the core `SessionManager` specifically configured to handle `OrchestrationState`. It passes a `createDefaultState` function to initialize new orchestration states. - **Storage Integration:** Inherits storage capabilities from `SessionManager`, allowing `OrchestrationState` to be persisted using the configured storage provider (Memory, Redis, Vercel KV, etc.) under a specific namespace (default: `orchestration-state`). - **Factory Function:** The recommended way to get an instance is via the factory function `createOrchestrationStateManager(options)`, allowing configuration of storage and cleanup. - **State Accessors/Mutators:** Provides methods to interact with the state: - `getState(sessionId)`: Retrieves the full `OrchestrationState`. - `getOrCreateState(sessionId, config?)`: Retrieves existing state or creates a new default state if needed (and if orchestration is configured). - `updateState(sessionId, updates)`: Performs a partial, immutable update to the state. - `setActiveStep(sessionId, stepName)`: Updates the `activeStep` field. - `addUsedTool(sessionId, toolName)`: Appends a tool name to `recentlyUsedTools`. - `advanceSequence(sessionId)`: Increments the `sequenceIndex`. - `resetState(sessionId)`: Resets the state back to its default values. - **Conditional Creation:** The `getOrCreateState` method checks if an agent configuration includes orchestration steps before creating state, optimizing for agents without orchestration. - **TTL & Cleanup:** The Time-To-Live for orchestration state (and thus the underlying session key in storage) is configurable. - **Default:** If not explicitly configured, the default TTL is 24 hours of inactivity (defined in `agentdock-core`). - **Configuration:** The TTL can be overridden by setting the `SESSION_TTL_SECONDS` environment variable in the main application (e.g., `agentdock_cursor_starter`). This value (in seconds) is passed down during initialization. - **Mechanism:** The underlying `SessionManager` uses this configured TTL to set the expiration time on the storage key (e.g., via Redis `EXPIRE`). The state is automatically removed from storage after the TTL expires since the last access. ### Relationship with `StepSequencer` The `StepSequencer` relies heavily on the `OrchestrationStateManager` to: - Get the current `sequenceIndex` for a session (`getState`). - Update the `sequenceIndex` when a sequence step is completed (`advanceSequence`). - Track which tools have been used (`addUsedTool`). ## State Lifecycle 1. **Initialization:** State is typically created lazily via `getOrCreateState` when the orchestration system first needs to access or modify state for a session, provided the agent has orchestration configured. 2. **Updates:** State fields (`activeStep`, `recentlyUsedTools`, `sequenceIndex`, `lastAccessed`) are updated throughout the agent's interaction via specific `OrchestrationStateManager` methods. 3. **Retrieval:** Components needing orchestration context (like the `StepSequencer` or condition checkers) use `getState`. 4. **Cleanup:** Expired state is automatically removed based on the `ttl` and `lastAccessed` timestamps by the underlying `SessionManager`'s cleanup process. ## Session Persistence & Long-Lived Agents The TTL mechanism is designed for typical web session expiry. For agents intended to persist indefinitely (like a personal assistant): 1. **Set a Very Long TTL:** Configure `SESSION_TTL_SECONDS` to a very large value (e.g., years in seconds). 2. **Regular Interaction:** Ensure the agent's session is accessed periodically (e.g., through a scheduled task or user interaction). Each access updates the `lastAccessed` timestamp, effectively resetting the TTL countdown. 3. **Disable TTL (Use with Caution):** While possible to modify the core code to disable TTL (`ttlSeconds = undefined` in `SessionManager`), this is generally discouraged as it can lead to orphaned state accumulating in the storage provider if sessions are never explicitly deleted. ```mermaid sequenceDiagram participant App as Application participant OSM as OrchestrationStateManager participant SM as SessionManager participant StoreP as Storage Provider participant Store as Redis/KV Store App->>+OSM: Initialize (Reads SESSION_TTL_SECONDS) OSM->>+SM: Initialize (Passes TTL in ms) Note over SM,Store: Session Activity Occurs... SM->>+StoreP: storage.set(key, data, {ttlSeconds}) StoreP->>+Store: SET key data EX ttlSeconds Store-->>-StoreP: OK StoreP-->>-SM: OK SM-->>-OSM: Returns OSM-->>-App: Ready/Returns ``` ## Configuration The `OrchestrationStateManager` can be configured during instantiation using `createOrchestrationStateManager(options)`: - `storageProvider`: Provide a specific storage instance (e.g., a configured `RedisStorageProvider`). - `storageNamespace`: Change the namespace used in the storage backend. - `cleanup`: Configure the cleanup *check* interval and enable/disable the automatic cleanup timer. Note: The actual session **TTL** is primarily controlled by `SESSION_TTL_SECONDS` passed during initialization. ## Best Practices - Use the factory `createOrchestrationStateManager(options)` for proper configuration. - Leverage conditional state creation logic where applicable. - Ensure the underlying storage provider is configured correctly for the deployment environment. ## Step Sequencing This document explains how AgentDock enforces tool sequences within orchestration steps, ensuring tools are used in the intended order for structured tasks. ## Core Concept Some orchestration steps require tools to be executed in a specific order. For example, a research task might require: 1. `web_search` 2. `think` (to analyze results) 3. `summarize` (to condense findings) The sequencing feature ensures the agent follows this prescribed order. ## Configuration Sequences are defined within an orchestration step's configuration in the agent template: ```json { "name": "structured_research", "description": "Perform research following a specific sequence.", "availableTools": { "allowed": ["web_search", "think", "summarize", "*cognitive*"] }, "sequence": [ "web_search", "think", "summarize" ] } ``` - The `sequence` array lists the tool names in the required order. - Tools listed in the sequence must also be included in `availableTools` (directly or via wildcard). ## Implementation (`StepSequencer`) The `StepSequencer` class (`agentdock-core/src/orchestration/sequencer.ts`) manages sequence logic. ### Key Features: - **State Dependency:** Relies on the `OrchestrationStateManager` to read and write the `sequenceIndex` within the `OrchestrationState` for the current session. - **Sequence Tracking:** - `hasActiveSequence(step, sessionId)`: Checks if a step has a sequence and if the current `sequenceIndex` is within the bounds of that sequence. - `getCurrentSequenceTool(step, sessionId)`: Returns the name of the tool expected at the current `sequenceIndex`. - `advanceSequence(step, sessionId)`: Increments the `sequenceIndex` in the session's `OrchestrationState`. - **Tool Processing:** - `processTool(step, sessionId, usedTool)`: Called when a tool is used. It checks if the `usedTool` matches the `getCurrentSequenceTool`. If it matches, it calls `advanceSequence`. If not, it logs a warning. - **Tool Filtering:** - `filterToolsBySequence(step, sessionId, allToolIds)`: This is the core enforcement mechanism. If a sequence is active for the step, this method checks the `getCurrentSequenceTool`. If that tool exists in the `allToolIds` list (tools generally available for the step), it returns *only* that tool name. Otherwise (sequence finished, expected tool not available), it may return all tools or an empty list depending on the exact logic (currently returns `[]` if the expected tool isn't available, effectively blocking progress if the configuration is inconsistent). ## How it Works 1. **Step Activation:** When an orchestration step with a `sequence` becomes active, the `OrchestrationStateManager` ensures the `sequenceIndex` in the session's state is initialized (usually to 0). 2. **Tool Availability Request:** When the core system (e.g., `AgentNode`) asks for available tools for the LLM: a. It determines the active step. b. It gets the generally allowed tools for that step (based on `availableTools` config). c. It calls `StepSequencer.filterToolsBySequence` passing the step, session ID, and allowed tools. d. If a sequence is active and the expected tool is available, `filterToolsBySequence` returns *only* that tool's name. e. The LLM is only presented with the single allowed tool for the current sequence step. 3. **Tool Execution:** The LLM invokes the required tool. 4. **Sequence Advancement:** After the tool executes, the system calls `StepSequencer.processTool`: a. If the executed tool matches the expected sequence tool, `processTool` calls `advanceSequence` to increment the `sequenceIndex` in the session state. b. If the tool doesn't match (which shouldn't happen if filtering works correctly, but handled defensively), a warning is logged. 5. **Next Step:** On the next interaction, the process repeats. `filterToolsBySequence` will now look for the tool at the *new* `sequenceIndex`. 6. **Sequence Completion:** Once the `sequenceIndex` reaches the length of the `sequence` array, `getCurrentSequenceTool` returns `null`, and `filterToolsBySequence` allows all tools generally available for the step (or falls back to default step behavior). ## Considerations - **Configuration Consistency:** Tools in the `sequence` must be available in the step's `availableTools` definition. - **Error Handling:** The current implementation logs warnings if the sequence is violated or the expected tool isn't available. More robust error handling or alternative behaviors (like resetting the sequence) could be added. - **LLM Compliance:** This relies on the LLM correctly using only the single tool provided to it when a sequence is active. ## Sequence Concepts ### What is a Tool Sequence? A tool sequence defines an ordered list of tools that must be used in a specific order. This creates a guided workflow that helps agents complete complex tasks methodically. Sequences can be used to: - Enforce methodical problem-solving approaches - Guide agents through complex workflows - Ensure critical steps are not skipped - Create structured reasoning patterns ### Sequence Representation Sequences are represented in step configurations as arrays: ```json "sequence": [ "think", "web_search", "summarize" ] ``` This sequence requires the agent to: 1. First use the "think" tool 2. Then use the "web_search" tool 3. Finally use the "summarize" tool ### Flexible Sequences For more flexibility, sequences can include groups of tools at each position: ```json "sequence": [ ["think", "reflect"], // First position: either think OR reflect "web_search", // Second position: web_search ["summarize", "save"] // Third position: either summarize OR save ] ``` This allows multiple valid paths through the sequence while maintaining the overall structure. ## Sequence Enforcement Across Environments One key improvement in our system is that sequence enforcement works consistently across all environments, including serverless deployments. ### Always Enforced Previously, sequence enforcement was conditionally applied: ```typescript // Old approach - sequences were only enforced under certain conditions if (!this.lightweight && activeStep.sequence?.length) { return this.sequencer.filterToolsBySequence(activeStep, sessionId, allToolIds); } ``` Now, sequences are always enforced: ```typescript // New approach - sequences are always enforced if (activeStep.sequence?.length) { return this.sequencer.filterToolsBySequence(activeStep, sessionId, allToolIds); } ``` ### Why This Matters This change ensures that: 1. **Consistent Agent Behavior**: Agents behave the same way in all environments 2. **Structured Thinking**: Steps like "critique → debate → reflect" are properly enforced 3. **Reliable Sequences**: Users can count on sequences working as designed 4. **Without Performance Penalty**: Sequence enforcement has minimal overhead ### Implementation Details The key method that filters tools based on sequences: ```typescript public filterToolsBySequence( step: OrchestrationStep, sessionId: SessionId, allToolIds: string[] ): string[] { // If no active sequence, return all tools if (!this.hasActiveSequence(step, sessionId)) return allToolIds; const currentTool = this.getCurrentSequenceTool(step, sessionId); if (!currentTool) return allToolIds; // If current tool is available, only allow that tool if (allToolIds.includes(currentTool)) { return [currentTool]; } // Current tool not available logger.warn( LogCategory.ORCHESTRATION, 'StepSequencer', 'Current sequence tool not available', { sessionId, step: step.name, currentTool } ); return allToolIds; } ``` This ensures that only the current tool in the sequence is available to the agent until the sequence advances. ## Integration with Tool Filtering The orchestration manager provides a method to get allowed tools, which integrates sequence filtering with other filtering mechanisms: ```typescript public getAllowedTools( orchestration: OrchestrationConfig, messages: LLMMessage[], sessionId: SessionId, allToolIds: string[] ): string[] { // If no orchestration, return all tools if (!orchestration?.steps?.length) return allToolIds; // Get active step const activeStep = this.getActiveStep(orchestration, messages, sessionId); // If no active step, return all tools if (!activeStep) return allToolIds; // Apply sequence filtering regardless of environment if (activeStep.sequence?.length) { return this.sequencer.filterToolsBySequence(activeStep, sessionId, allToolIds); } // If step has explicitly allowed tools, filter by those if (activeStep.availableTools?.allowed && activeStep.availableTools.allowed.length > 0) { return allToolIds.filter(toolId => { return activeStep.availableTools?.allowed?.includes(toolId) || false; }); } // If step has explicitly denied tools, filter those out if (activeStep.availableTools?.denied && activeStep.availableTools.denied.length > 0) { return allToolIds.filter(toolId => { return !activeStep.availableTools?.denied?.includes(toolId); }); } // Default - return all tools return allToolIds; } ``` ## Sequence Processing When tools are used, the sequence advances accordingly: ```typescript public processToolUsage( orchestration: OrchestrationConfig, messages: LLMMessage[], sessionId: SessionId, toolName: string ): void { // Get active step const activeStep = this.getActiveStep(orchestration, messages, sessionId); // Skip if no active step if (!activeStep) return; // Skip if no sequence defined if (!activeStep.sequence?.length) return; // Always process tool usage through the sequencer this.sequencer.processTool(activeStep, sessionId, toolName); } ``` ## User Experience The sequence enforcement system creates a guided experience for users: 1. **Clarity**: The agent clearly communicates which tool it's using in the sequence 2. **Structure**: Complex reasoning processes follow a consistent pattern 3. **Methodical**: Steps like evaluation follow a "critique → debate → reflect" pattern 4. **Thoroughness**: Ensures agents don't skip important steps in a reasoning process ## Example: Evaluation Mode Sequence A practical example of sequence enforcement is the Evaluation Mode in our cognitive reasoning agents: ```json { "name": "EvaluationMode", "description": "Critical evaluation sequence", "conditions": [ { "type": "message_regex", "value": "critique|evaluate|assess|review|analyze|opinion" } ], "sequence": [ "critique", "debate", "reflect" ], "availableTools": { "allowed": ["critique", "debate", "reflect", "search"] } } ``` This enforces a three-step evaluation process: 1. First critically analyze the subject (critique) 2. Then present multiple perspectives (debate) 3. Finally extract insights and principles (reflect) This structured approach ensures thorough evaluation regardless of deployment environment. ## Deployment Considerations ### Serverless/Edge In serverless and Edge deployments: - Sequence enforcement works consistently - Session state must be properly rehydrated between requests - Response headers contain minimal state information ### Long-Running Servers In long-running server deployments: - Full state persistence provides seamless sequence tracking - Memory management prevents sequence state from growing unbounded - Cleanup mechanisms prevent leaked states ## Best Practices 1. **Keep Sequences Short**: Aim for 3-5 steps maximum 2. **Provide Context**: Explain to users that a structured sequence is being followed 3. **Allow Flexibility**: When appropriate, include multiple tools in sequence positions 4. **Test Thoroughly**: Ensure sequences work properly across all deployment environments ## Provider-Agnostic API Architecture This document explains how AgentDock works with multiple LLM providers through a unified API layer. ## What This Means For Users AgentDock supports a variety of LLM providers (OpenAI, Anthropic, Gemini, DeepSeek, Groq, etc.) through a single, consistent interface. This means: 1. **Consistent Experience** - The same chat interface works across all providers 2. **Easy Provider Switching** - Change providers without changing your application code 3. **Unified Error Handling** - Clear, consistent error messages regardless of provider 4. **Simple API Key Management** - Manage all provider keys in one place ## Benefits ### For Developers 1. **Simplified Integration** - Connect to any supported provider using the same API 2. **No Provider-Specific Code** - Write code once that works with all providers 3. **Future-Proof** - New providers are added to the core library without requiring changes to your application 4. **Type Safety** - Full TypeScript support for all providers ### For End Users 1. **Provider Flexibility** - Use preferred providers without learning new interfaces 2. **Graceful Error Handling** - Receive clear, actionable error messages 3. **Consistent Model Selection** - Choose models through a standardized interface 4. **Smooth Failover** - Automatic retries and provider fallbacks when configured ## Supported Providers AgentDock currently supports these LLM providers: - **OpenAI** - GPT models (3.5, 4, etc.) - **Anthropic** - Claude models - **Google** - Gemini models - **DeepSeek** - DeepSeek models - **Groq** - Fast inference for various models - **Cerebras** - LLaMA and other open source models ## Error Handling The provider-agnostic design includes standardized error handling: 1. **Normalized Errors** - Technical provider errors are translated to user-friendly messages 2. **Clear API Key Guidance** - Specific instructions when API keys are missing or invalid 3. **Appropriate Recovery Options** - Context-aware options for resolving different error types ## How It Works Behind the scenes, AgentDock: 1. Accepts a standard message format for all providers 2. Translates requests to provider-specific formats 3. Manages streaming connections appropriately for each provider 4. Normalizes responses and errors back to a standard format This abstraction layer means that applications using AgentDock don't need to know the details of each provider's API. ## AgentDock Architecture This section provides an overview of the architecture of AgentDock Core, the foundation library that powers all AgentDock functionality. ## Core Philosophy AgentDock Core is designed with the following principles: - **Modularity:** Components like LLM interaction, session management, storage, and orchestration are distinct and replaceable. - **Extensibility:** Easy to add new LLM providers, storage backends, tools, or custom agent logic. - **Type Safety:** Comprehensive TypeScript types ensure developer confidence and reduce runtime errors. - **Provider Agnosticism:** Abstracting away differences between LLM providers and storage systems where possible. - **State Management Focus:** Robust mechanisms for managing conversational state across interactions. ## Key Subsystems AgentDock Core is composed of several interconnected subsystems: 1. **LLM Abstraction (`/llm`):** Provides a consistent interface (`CoreLLM`) for interacting with different LLM providers (OpenAI, Anthropic, Gemini via Vercel AI SDK). Handles API calls, streaming, and basic token usage reporting. 2. **Storage Abstraction Layer (`/storage`):** Offers a pluggable system for Key-Value storage (Memory, Redis, Vercel KV implemented) with plans for Vector and Relational storage. See [Storage Overview](../storage/README.md). 3. **Session Management (`/session`):** Manages isolated conversational state using the Storage Abstraction Layer. Ensures context preservation and handles state lifecycle (creation, updates, TTL-based cleanup). See [Session Management](./sessions/session-management.md). 4. **Orchestration Framework (`/orchestration`):** Controls agent behavior by managing steps (modes), conditional transitions, tool availability, and optional tool sequencing based on session state. See [Orchestration Overview](./orchestration/orchestration-overview.md). 5. **Node System (`/nodes`):** Defines the core execution units and modular architecture. Based on `BaseNode`, it includes the primary `AgentNode` (integrating LLM, tools, session, orchestration), tool nodes, and potentially custom nodes. Managed by `NodeRegistry` (for types) and `ToolRegistry` (for runtime availability). See [Node System Overview](../nodes/README.md). 6. **Tool System (Integrated within `/nodes`):** Tools are implemented as specialized nodes. Their definition, registration (`NodeRegistry`), runtime availability (`ToolRegistry`), and execution (triggered by `AgentNode` via LLM function/tool calling) are integral parts of the Node System. 7. **Error Handling (`/errors`):** Standardized error types and handling mechanisms. 8. **Configuration (`/config`, Agent Templates):** Agent behavior is defined via template files (`template.json`) specifying LLM, tools, prompts, orchestration rules, etc. ## High-Level Interaction Flow A typical interaction involves: 1. **Request:** An incoming request (e.g., from the Open Source Client) hits an API endpoint. 2. **Session Handling:** The endpoint retrieves or establishes a `SessionId`. 3. **Agent Instantiation:** An `AgentNode` instance is created based on the agent template configuration. 4. **State Retrieval:** Relevant session state (e.g., `OrchestrationState`) is loaded via `SessionManager` / `OrchestrationStateManager`. 5. **Orchestration Check:** The orchestration logic determines the active step and filters available tools based on conditions and sequences. 6. **LLM Call:** `AgentNode` uses `CoreLLM` to interact with the LLM provider, passing the message history, system prompt, and filtered tools. 7. **Tool Execution (if needed):** If the LLM requests a tool, `AgentNode` executes it, potentially updating session state. 8. **Response Streaming:** The LLM response (text or tool calls) is streamed back. 9. **State Update:** Session state (message history, token usage, orchestration state) is updated via the respective managers. 10. **Response Completion:** The stream ends, and the final state is persisted. See [Request Flow](./core/request-flow.md) for more details. ## Directory Structure (`agentdock-core/src`) ``` /src ├── client/ # (Primarily for Open Source Client integration) ├── config/ # Configuration loading utilities ├── errors/ # Custom error types and factory ├── evaluation/ # Agent evaluation framework (runner, evaluators, storage) ├── llm/ # CoreLLM abstraction, provider specifics ├── logging/ # Logging utilities ├── nodes/ # AgentNode, tool execution logic ├── orchestration/ # State management, sequencing, conditions ├── session/ # SessionManager implementation ├── storage/ # Storage abstraction, providers (KV, Secure) ├── tools/ # Base tool definitions and specific tool implementations ├── types/ # Core TypeScript type definitions └── utils/ # General utility functions ``` ## Further Reading - [Core Architecture Overview](./core/overview.md) - [Node System Overview](../nodes/README.md) - [Technology Stack](./core/technology-stack.md) ## Evaluation Framework A crucial component of AgentDock is its **Evaluation Framework**, designed to systematically measure, analyze, and improve agent quality. This framework resides within `agentdock-core` and provides a comprehensive suite of tools for assessing various aspects of agent performance. Key aspects include: * **Modular Evaluators**: A collection of diverse evaluators (e.g., `RuleBasedEvaluator`, `LLMJudgeEvaluator`, `NLPAccuracyEvaluator`, Lexical Suite, `ToolUsageEvaluator`) allow for targeted assessment of different quality dimensions. * **`EvaluationRunner`**: Orchestrates the execution of evaluation runs based on defined criteria and configurations. * **Configurable Criteria**: Enables developers to define specific `EvaluationCriteria` (name, description, scale, weight) against which agents are assessed. * **Result Aggregation & Storage**: Provides mechanisms for aggregating results (e.g., weighted scoring) and persisting them via `EvaluationStorageProvider` implementations. * **Extensibility**: Designed with interfaces like `Evaluator` and `EvaluationStorageProvider` to allow for easy custom extensions. The Evaluation Framework is integral to maintaining high standards of agent reliability and performance, facilitating data-driven development and iterative improvement. For more details, see the [Evaluation Framework Documentation](../evaluations/README.md). ## NextJS Session Integration This document explains how AgentDock's session management integrates with Next.js applications, focusing on API routes, client-side handling, and runtime considerations. ## Orchestration Adapter (`src/lib/orchestration-adapter.ts`) The core integration logic connecting the Next.js application to `agentdock-core`'s orchestration capabilities resides in `src/lib/orchestration-adapter.ts`. This adapter handles initializing the core `OrchestrationManager` with the correct environment configuration (storage provider, session TTL) and provides helper functions for interacting with it from API routes. ```typescript // Simplified structure from src/lib/orchestration-adapter.ts import { createOrchestrationManager, OrchestrationManager, // ... other agentdock-core imports } from 'agentdock-core'; // Singleton pattern using globalThis for Node/Serverless environments declare global { var __orchestrationManagerInstance: OrchestrationManager | null | undefined; } export function getOrchestrationManagerInstance(): OrchestrationManager { if (globalThis.__orchestrationManagerInstance) { return globalThis.__orchestrationManagerInstance; } // Determine storage provider (using getConfiguredStorageProvider helper) const storageProvider = getConfiguredStorageProvider(); // Determine TTL from environment (SESSION_TTL_SECONDS) const sessionTtlMs = /* ... logic to parse env var ... */; // Create and store the single instance const newInstance = createOrchestrationManager({ storageProvider: storageProvider, cleanup: { enabled: false, ttlMs: sessionTtlMs } }); globalThis.__orchestrationManagerInstance = newInstance; return newInstance; } ``` Key aspects of this adapter: 1. **Singleton Instance:** Uses `globalThis` to ensure only one `OrchestrationManager` instance is created per server process. This is crucial for serverless/edge environments to reuse the manager instance across invocations where possible. 2. **Environment Configuration:** Reads environment variables (`KV_STORE_PROVIDER`, `SESSION_TTL_SECONDS`, etc.) to dynamically configure the storage provider and session TTL when creating the singleton instance. 3. **Standard Core Components:** Uses the standard `createOrchestrationManager` function and other components imported directly from `agentdock-core`. ### Environment-Based TTL Configuration The `getOrchestrationManagerInstance` function within `src/lib/orchestration-adapter.ts` handles reading the `SESSION_TTL_SECONDS` environment variable. ```typescript // Simplified logic from src/lib/orchestration-adapter.ts import { createOrchestrationManager, getStorageFactory, OrchestrationManager, // ... other imports } from 'agentdock-core'; declare global { var __orchestrationManagerInstance: OrchestrationManager | null | undefined; } export function getOrchestrationManagerInstance() { // Use global singleton if (globalThis.__orchestrationManagerInstance) { return globalThis.__orchestrationManagerInstance; } // Determine storage provider based on ENV (KV_STORE_PROVIDER, etc.) const storageProvider = getConfiguredStorageProvider(); // Internal helper function // Read and calculate TTL from ENV const sessionTtlSeconds = process.env.SESSION_TTL_SECONDS ? parseInt(process.env.SESSION_TTL_SECONDS, 10) : undefined; let sessionTtlMs: number | undefined = undefined; if (sessionTtlSeconds && sessionTtlSeconds > 0) { sessionTtlMs = sessionTtlSeconds * 1000; // Convert to ms } // Create the manager instance const newInstance = createOrchestrationManager({ storageProvider: storageProvider, // Pass configured TTL (undefined lets core use its 24h default) cleanup: { enabled: false, // Cleanup timer managed within core if needed ttlMs: sessionTtlMs } }); // Store globally and return globalThis.__orchestrationManagerInstance = newInstance; return newInstance; } ``` This ensures that the session TTL configured in the environment dictates the actual session lifespan managed by `agentdock-core`. ## API Route Integration ### Lazy Initialization The `OrchestrationManager` instance itself is initialized lazily on the first call to `getOrchestrationManagerInstance()` within a server process. However, the decision to *use* orchestration features (like getting state) typically happens within the API route handler based on the specific agent's configuration: ```typescript // Example check within an API Route Handler (e.g., /api/chat/[agentId]/route.ts) if (template && 'orchestration' in template && template.orchestration) { logger.debug( LogCategory.API, 'ChatRoute', 'Initializing orchestration for agent with orchestration', { agentId } ); // Get the manager instance (initializes on first call) const manager = getOrchestrationManagerInstance(); // Ensure orchestration state exists if (finalSessionId) { await getOrchestrationState(finalSessionId, template); } } ``` This ensures that orchestration state operations (`getOrchestrationState`) are only performed for agents configured to use orchestration, even though the manager instance might have already been created by a previous request in the same process. Benefits: 1. Orchestration logic is only engaged for relevant agents. 2. No resources are wasted on non-orchestrated agents 3. Cold starts are faster for simple agents ### Session ID Management Session ID creation and management happens at the route handler level: ```typescript // Get session ID from various sources with priority const headerSessionId = request.headers.get('x-session-id'); const requestSessionId = requestJson.sessionId; // Use existing session ID or create a new one const finalSessionId = headerSessionId || requestSessionId || `session-${agentId}-${Date.now()}-${crypto.randomUUID()}`; ``` The session ID is then passed to the agent adapter: ```typescript // Process the message using the adapter const result = await processAgentMessage({ agentId, messages, sessionId: finalSessionId, // Always provide a valid session ID apiKey, fallbackApiKey, provider: llmInfo.provider, system, config }); ``` ### Response Headers Session state is included in response headers for client tracking: ```typescript // Create and return the response with proper headers return createAgentResponse(result, finalSessionId); // Implementation of createAgentResponse function createAgentResponse(result: any, sessionId: string): Response { // Convert the result to a stream const stream = streamText(() => result); const response = toDataStreamResponse(stream); // Add orchestration state to response - required for session continuity const orchestrationState = result._orchestrationState; if (orchestrationState) { response.headers.set('x-orchestration-state', JSON.stringify(orchestrationState)); } // Always ensure the session ID is present in the response headers response.headers.set('x-session-id', sessionId); return response; } ``` This approach: - Ensures clients can maintain session continuity - Provides access to orchestration state when needed - Follows HTTP standards for custom headers ## Client-Side State Management On the client side, we use a simple cache to maintain state between requests: ```typescript // Cache to store user session information const sessionCache = new Map(); /** * Update orchestration state in the cache */ export function updateOrchestrationCache( sessionId: string, state: OrchestrationState | Partial ): void { if (!sessionId) return; // Update the cache with the new state const existing = sessionCache.get(sessionId); if (existing) { sessionCache.set(sessionId, { ...existing, ...state }); } else { sessionCache.set(sessionId, state as OrchestrationState); } } ``` The client component then handles this state: ```typescript // In the chat component useEffect(() => { // Extract orchestration state from headers const orchestrationStateHeader = response.headers.get('x-orchestration-state'); if (orchestrationStateHeader) { try { const stateData = JSON.parse(orchestrationStateHeader); updateOrchestrationCache(stateData.sessionId, stateData); } catch (e) { console.error('Failed to parse orchestration state:', e); } } }, [response]); ``` ## Agent Adapter Integration The agent adapter in Next.js uses the orchestration wrapper: ```typescript // Import helper functions directly from the adapter import { getOrchestrationState } from '@/lib/orchestration-adapter'; // ... export async function processAgentMessage(options: { agentId: string; messages: CoreMessage[]; sessionId: string; // ... }) { // ... // Get orchestration state if needed if (config.orchestration) { const orchestrationState = await getOrchestrationState( sessionId, config ); if (orchestrationState) { logger.debug( LogCategory.ADAPTER, 'AgentAdapter', 'Using orchestration', { sessionId, activeStep: orchestrationState.activeStep } ); } } // ... } ``` ## Edge Runtime Considerations The suitability and performance in Edge Runtime environments depend on: - The inherent efficiency of the core `OrchestrationManager` and `SessionManager`. - The chosen **Storage Provider**: Using providers compatible with the Edge runtime (like Vercel KV via `@vercel/kv`, or potentially Redis via `@upstash/redis`) is crucial. In-memory storage will not persist between Edge function invocations. Key optimizations: - Minimized dependency loading - Efficient state structures - No cleanup timers in Edge mode - Simplified operations ## Deployment Considerations Different deployment environments have different requirements: ### Vercel and Edge Functions For Vercel and other serverless/Edge environments: 1. **Configure Appropriate Cleanup Options** ```typescript // Configure manager with cleanup disabled for edge environments orchestrationManager = createOrchestrationManager({ cleanup: { enabled: false } }); ``` 2. **Rely on Client Caching** ```typescript // Client-side: Use cache for state if (typeof window !== 'undefined') { return sessionCache.get(sessionId) || null; } ``` 3. **Minimize State Transfer** - Send only essential state in headers - Parse and store on client ### Multi-Region Deployments For multi-region deployments: 1. **Consider External State Store** - Redis or similar for shared state - Keep state minimal for performance 2. **Proper Session Routing** - Use sticky sessions if possible - Include region info in session IDs ## Debugging Support ### Debugging Tools For debugging session and orchestration state: ```tsx function ChatDebug({ sessionId, orchestrationState }: { sessionId: string; orchestrationState: OrchestrationState | null; }) { if (!orchestrationState) return null; return (

Session Debug

Session ID: {sessionId}
Active Step: {orchestrationState.activeStep || 'None'}
Tools Used: {orchestrationState.recentlyUsedTools.join(', ')}
Sequence Position: {orchestrationState.sequenceIndex}
); } ``` This helps with: - Verifying state persistence - Checking sequence progression - Identifying orchestration issues ## Best Practices 1. **Initialize Only When Needed** - Check `template.orchestration` before calling orchestration-specific functions like `getOrchestrationState`. 2. **Configure for Environment** - Set appropriate cleanup options based on your deployment environment - Disable cleanup timers in serverless environments 3. **Client-Side Caching** - Store state in client-side cache - Update from response headers - Handle expired or invalid state gracefully 4. **Clean Session IDs** - Use a consistent format with sufficient entropy - Never expose sensitive information in session IDs - Include timestamps for debugging 5. **Error Handling** - Have fallbacks for orchestration failures - Parse state carefully with try/catch - Log orchestration errors but continue if possible ### Environment-Based TTL Configuration The `src/lib/orchestration-adapter.ts` file handles reading environment variables to configure the `agentdock-core` `OrchestrationManager` instance. It ensures a single instance (singleton) is used per server process. ```typescript // Simplified logic from src/lib/orchestration-adapter.ts import { createOrchestrationManager, getStorageFactory, OrchestrationManager, // ... other imports } from 'agentdock-core'; declare global { var __orchestrationManagerInstance: OrchestrationManager | null | undefined; } export function getOrchestrationManagerInstance() { // Use global singleton if (globalThis.__orchestrationManagerInstance) { return globalThis.__orchestrationManagerInstance; } // Determine storage provider based on ENV (KV_STORE_PROVIDER, etc.) const storageProvider = getConfiguredStorageProvider(); // Internal helper function // Read and calculate TTL from ENV const sessionTtlSeconds = process.env.SESSION_TTL_SECONDS ? parseInt(process.env.SESSION_TTL_SECONDS, 10) : undefined; let sessionTtlMs: number | undefined = undefined; if (sessionTtlSeconds && sessionTtlSeconds > 0) { sessionTtlMs = sessionTtlSeconds * 1000; // Convert to ms } // Create the manager instance const newInstance = createOrchestrationManager({ storageProvider: storageProvider, // Pass configured TTL (undefined lets core use its 24h default) cleanup: { enabled: false, // Cleanup timer managed within core if needed ttlMs: sessionTtlMs } }); // Store globally and return globalThis.__orchestrationManagerInstance = newInstance; return newInstance; } ``` This ensures that the session TTL configured in the environment dictates the actual session lifespan managed by `agentdock-core`. ## Session Management This directory contains documentation about AgentDock's session management system. ## Overview Sessions in AgentDock provide isolation between concurrent conversations and maintain state across multiple requests. They are a critical part of the architecture that enables: - Stateful conversations with LLM agents - Tool context persistence - Orchestration state management - Memory efficiency and resource optimization ## Documentation Files - [session-overview.md](./session-overview.md) - Core concepts and architecture of the session system - [session-implementation.md](./session-implementation.md) - Technical implementation details and API - [session-optimization.md](./session-optimization.md) - Performance optimizations and memory management - [nextjs-integration.md](./nextjs-integration.md) - How sessions integrate with Next.js applications ## Session Management Sessions in AgentDock provide the foundation for stateful, continuous interactions between users and AI agents. This document covers the core concepts, architecture, implementation details, and optimization strategies for the session management system. ## Core Concepts - **Session:** Represents a single conversation, identified by a unique `SessionId`. It maintains state across multiple interactions (messages, tool calls) to preserve context. - **Session Isolation:** Ensures that concurrent conversations do not interfere with each other. Critical for multi-user environments. - **Single Source of Truth:** Session IDs are generated centrally (typically by the entry point, like an API route handler), and state is managed through a single `SessionManager` instance for a given state type, ensuring consistency. ## Architecture & Implementation The session system revolves around the generic `SessionManager` class found in `agentdock-core/src/session/index.ts`. ### `SessionManager` - **Generic:** Can manage different types of session state (e.g., base state, orchestration state, tool state) by extending the base `SessionState` interface. - **Storage-Backed:** Uses the [Storage Abstraction Layer](./storage-abstraction.md) for persistence. It defaults to an in-memory provider but can be configured (via constructor options) to use Redis, Vercel KV, or other providers. - **Namespace:** Uses a storage namespace (e.g., `sessions`, `orchestration-state`) to keep different types of session data separate in the storage backend. - **State Factory:** Requires a `defaultStateGenerator` function during instantiation to define how the initial state (`T`) for a new session should be created. ### Key Operations - `createSession(options)`: Creates a new session (if one doesn't exist for the given or generated `SessionId`) using the `defaultStateGenerator` and stores it. Returns a `SessionResult`. - `getSession(sessionId)`: Retrieves the current state for a session ID from storage. Returns `SessionResult`. - `updateSession(sessionId, updateFn)`: Updates session state immutably. It retrieves the current state, applies the `updateFn` to generate a new state object, and stores the new state atomically. Returns `SessionResult`. - `deleteSession(sessionId)`: Removes a session from storage. ### Session ID Generation Session IDs are typically generated by the application entry point (e.g., API route handler) to maintain the single source of truth. While the core library can generate a UUID (`generateSessionId`), passing a predetermined ID is preferred. Format often includes prefixes for traceability. ### Session Lifecycle & Cleanup 1. **Creation:** Handled by `createSession`, often triggered by the first interaction if no `SessionId` is provided. 2. **Access & Update:** `getSession` and `updateSession` are used throughout the agent's processing logic. 3. **Expiration (TTL):** Each session state includes `lastAccessed` (timestamp) and `ttl` (milliseconds) properties. The TTL is configurable (default: 30 minutes). - **Default:** The default TTL is **24 hours** of inactivity, defined in `agentdock-core`. - **Configuration:** This default can be overridden globally for the application by setting the `SESSION_TTL_SECONDS` environment variable (value in seconds). This configured TTL is used when creating or updating session keys in the storage provider. 4. **Automatic Cleanup:** The `SessionManager` includes an optional, periodic cleanup mechanism (`setupCleanupInterval`, `cleanupExpiredSessions`) that checks `lastAccessed + ttl` against the current time and automatically calls `deleteSession` for expired entries. This timer uses `unref()` in Node.js to avoid blocking process exit. ### Persistence & Long-Lived Sessions For sessions needing longer persistence than typical web interactions (e.g., persistent personal assistants): 1. **Configure Long TTL:** Set `SESSION_TTL_SECONDS` in the application's environment to a large value (e.g., `31536000` for one year). 2. **Ensure Activity:** As long as the session is accessed (via `getSession` or `updateSession`), the `lastAccessed` timestamp is updated, resetting the TTL timer for the storage key. 3. **No TTL:** Setting `SESSION_TTL_SECONDS` to `0` or a negative value will likely result in the storage provider *not* setting an expiration time, making the session persist indefinitely until explicitly deleted. Use this cautiously to avoid accumulating orphaned data. ```mermaid sequenceDiagram participant App as Application participant SM as SessionManager participant StoreP as Storage Provider participant Store as Redis/KV Store App->>+SM: Initialize (Reads SESSION_TTL_SECONDS, passes TTL ms) Note over SM: Session Created/Exists App->>SM: getSession(sessionId) SM->>+StoreP: storage.get(key) StoreP->>+Store: GET key Store-->>-StoreP: Returns data (incl. old ttlMs) StoreP-->>SM: Returns data Note over SM: Updates lastAccessed in data SM->>+StoreP: storage.set(key, updatedData, {ttlSeconds from Configured TTL}) StoreP->>+Store: SET key updatedData EX configuredTtlSeconds Store-->>-StoreP: OK StoreP-->>-SM: OK SM->>App: Returns session data loop TTL Check (Conceptual - Handled by Store) Store->>Store: Is key expired? alt Key Expired Store->>Store: Delete Key end end ``` ## Optimization Techniques - **Conditional State Creation:** Components or managers (like `OrchestrationStateManager`) should check if session state is truly needed before calling `createSession` or `getSession`. For example, an agent without orchestration configured doesn't need orchestration state. - **Minimalist State Design:** Session state interfaces (`T extends SessionState`) should only include essential data, avoiding large objects or duplication. - **Lazy Loading:** Components retrieve session state only when required for an operation. - **Efficient Updates:** The immutable update pattern (`updateSession`) with partial updates (`{ ...state, ...updates }`) is efficient and prevents race conditions. - **Last Accessed Tracking:** Updating `lastAccessed` on `getSession` or `updateSession` keeps active sessions alive while allowing inactive ones to expire naturally via TTL. - **Storage Provider Choice:** Selecting an appropriate storage provider (Memory for development, Redis/Vercel KV for production) significantly impacts performance and scalability. - **Leverage Configurable TTL:** Set `SESSION_TTL_SECONDS` appropriately for your application's needs (e.g., shorter for web sessions, longer for persistent agents) for automatic cleanup. ## Integration - **LLM:** Session state (especially message history) provides context for LLM calls. - **Tools:** Tools can access session state (via specific managers if needed) to maintain context or share data across invocations. - **Orchestration:** The `OrchestrationStateManager` uses the `SessionManager` to store its specific `OrchestrationState` per session, enabling step tracking, sequence management, etc. - **Next.js:** See [Next.js Integration](./nextjs-integration.md) for details on managing session IDs in API routes and client components. ## Best Practices 1. **Single Source of Truth:** Generate/manage session IDs at the entry point (API route). 2. **Pass, Don't Create:** Components receive session IDs; they don't generate them. 3. **Configure Storage:** Choose the appropriate storage provider for your environment. 4. **Minimize State:** Only store necessary data in session state objects. 5. **Leverage TTL:** Use TTL effectively for automatic cleanup. 6. **Handle Errors:** Check `SessionResult.success` and handle potential errors (e.g., session not found). ## Session Management Overview Sessions in AgentDock provide a foundation for stateful interactions between users and AI agents. This document outlines the core concepts, architecture, and design principles of the session management system. ## Core Concepts ### What is a Session? A session represents a single conversation between a user and an agent. It maintains state across multiple interactions, ensuring continuity and context preservation. Each session is identified by a unique ID (SessionId) and contains all the state necessary for the conversation to progress. ### Session Isolation Session isolation is a critical feature that prevents different conversations from interfering with each other. This is especially important in multi-user environments where multiple conversations may be happening concurrently. ### Single Source of Truth AgentDock follows a "single source of truth" principle for session management, where: 1. Session IDs are generated at a single point in the system 2. Session state is managed centrally 3. All components access the same session state This design eliminates issues with duplicate sessions or inconsistent state. ## Architecture The session management system consists of several key components: ### SessionManager The `SessionManager` is a generic class that provides core session creation, retrieval, and update capabilities. It is designed to be extended for different types of session state. ### Session State Types AgentDock uses several types of session state: 1. **Base Session State** - Core session data including the session ID 2. **AgentSession** - Extended state for agent interactions 3. **OrchestrationState** - State specific to orchestration workflows 4. **Tool-specific State** - Some tools maintain their own session state ### Session Lifecycle 1. **Creation** - Sessions are created when a user starts a new conversation 2. **Access** - Components access session state to perform operations 3. **Updates** - State is updated as the conversation progresses 4. **Cleanup** - Sessions are eventually deleted when they expire ## Implementation Principles ### Immutability Session states are treated as immutable objects. Updates create new state objects rather than modifying existing ones, preventing race conditions in concurrent access. ### Lazy Loading Sessions are loaded only when needed, improving performance by avoiding unnecessary state creation. ### TTL (Time-to-Live) Sessions have a configurable TTL, after which they are automatically cleaned up to prevent memory leaks. ### Conditional Creation Session state is only created for components that need it, reducing memory usage. ## Integration Points ### LLM Integration Sessions provide context for LLM interactions, including: - Conversation history - System prompts - Tool usage patterns ### Tool System Integration Tools access session state to: - Maintain tool-specific context - Track previous tool invocations - Share data between invocations ### Orchestration Integration The orchestration system relies on sessions to: - Track active steps - Manage tool availability - Store transition conditions - Record tool sequences ## Conclusion The session management system forms a critical foundation for AgentDock's stateful agent capabilities. By providing consistent, isolated, and efficient state management, it enables complex conversational interactions while maintaining performance and reliability. ## AgentDock Core Error Handling This document describes the error handling architecture in the agentdock-core library. ## Error Categories AgentDock Core defines standard error categories that help organize and handle errors consistently: - **API Errors** - Issues with provider API communication - **Authentication Errors** - Problems with API keys or credentials - **Validation Errors** - Invalid inputs or parameters - **Resource Errors** - Issues with resource availability or limitations - **System Errors** - Internal failures within the core library ## Core Error Classes The library provides a set of standardized error classes: ```typescript // Example of the error types (conceptual, not actual implementation) class AgentError extends Error { /* Base error class */ } class APIError extends AgentError { /* API-related errors */ } class ValidationError extends AgentError { /* Input validation errors */ } ``` ## Provider Error Handling A key feature of agentdock-core is consistent error handling across different LLM providers: 1. **Provider Pattern Detection** - Each provider returns errors in different formats - Core library maps these to standardized patterns - Pattern detection uses string matching and error codes 2. **Error Normalization** - All provider errors are normalized to a consistent format - Error messages are made user-friendly - Status codes and error types are standardized 3. **Error Context Preservation** - Original error details are preserved when needed for debugging - Error stack traces are maintained - Provider-specific details are available when required ## Error Response Format Normalized errors follow this structure: ```typescript { error: string; // Human-readable error message code: string; // Standard error code (e.g., "LLM_API_KEY_ERROR") status: number; // HTTP status code equivalent provider?: string; // Provider that generated the error (if applicable) details?: unknown; // Additional error details (if available) } ``` ## Using Error Handling in Applications Applications that use agentdock-core can leverage this error system: 1. **Detecting Error Types** ```typescript try { // Use agentdock-core functionality } catch (error) { if (error instanceof APIError && error.code === "LLM_API_KEY_ERROR") { // Handle API key errors } } ``` 2. **Error Events** - The library emits error events that applications can listen to - Provides hooks for logging, monitoring, and user feedback ## Logging Integration Error handling is integrated with the core logging system: 1. Errors are automatically logged at appropriate levels 2. Sensitive information in errors is automatically redacted 3. Contextual information is included with error logs ## LLM Error Handling How we handle errors from LLM providers and present them to users. ## Overview Our error handling system captures and normalizes errors across all LLM providers, converting technical API errors into clear, actionable messages. ## Error Flow Architecture Error handling follows this layered architecture: ### 1. CoreLLM (Detection Layer) - Detects errors during streaming in `agentdock-core/src/llm/core-llm.ts` - Sets error flags: `_hasStreamingError` and `_streamingErrorMessage` - Adds metadata like error code to the stream result ### 2. Agent Adapter (Conversion Layer) - Located in `src/lib/agent-adapter.ts` - Enhances the stream result with Vercel AI SDK's error handling - Provides `getErrorMessage` implementation to extract detailed errors from CoreLLM - Properly formats errors for client-side presentation ### 3. API Route (Transport Layer) - Simple pass-through of the already-enhanced results - Handles non-streaming errors using standard error response formats ### 4. Client Components (Presentation Layer) - Display user-friendly error messages from the error handling pipeline - Provide appropriate actions based on error types ## Implementation Details ### CoreLLM Error Detection ```typescript // In agentdock-core/src/llm/core-llm.ts const enhancedResult: StreamTextResult = { ...streamResult, _hasStreamingError: false, _streamingErrorMessage: '', // When streaming errors are detected if (part.type === 'error') { enhancedResult._hasStreamingError = true; enhancedResult._streamingErrorMessage = parsedError.message; } }; ``` ### Agent Adapter Error Conversion ```typescript // In src/lib/agent-adapter.ts const enhancedResult = { ...result, toDataStreamResponse(options = {}) { return result.toDataStreamResponse({ ...options, getErrorMessage: (error: unknown) => { // Extract streaming error message from CoreLLM if (error && typeof error === 'object' && '_hasStreamingError' in error) { const streamError = error as any; if (streamError._streamingErrorMessage) { return streamError._streamingErrorMessage; } } // Standard error handling if (error instanceof Error) { return error.message; } return typeof error === 'string' ? error : 'Unknown error occurred'; } }); } }; ``` ## Error Categories Errors are categorized into these types: | Category | Description | Examples | |----------|-------------|----------| | API Key Errors | Missing or invalid API keys | No API key provided, invalid key format | | Rate Limit Errors | Provider throttling | Too many requests, usage limits exceeded | | Context Window Errors | Input size limitations | Message too long for model context window | | Service Availability | Provider downtime | API service unavailable, maintenance | | Network Errors | Connectivity issues | Connection timeout, network failure | | Quota Errors | Usage quotas exceeded | "You exceeded your current quota" | ## User Experience When errors occur, users see: 1. **Clear error messages** - Technical details translated into understandable language 2. **Actionable guidance** - Instructions on how to resolve the issue 3. **Relevant options** - UI provides appropriate actions based on error type ### API Key Errors For API key issues, the system: - Clearly indicates that an API key is required - Provides a direct link to settings where keys can be added - Explains which environment variables are needed if applicable ### Rate Limit Errors When rate limits are hit, users are: - Informed that usage limits have been reached - Advised to wait before making additional requests - Provided retry options when appropriate ### Service and Network Errors For connectivity issues: - The system distinguishes between temporary and persistent problems - Provides retry options for transient failures - Offers troubleshooting guidance for persistent issues ## BYOK Mode Considerations In Bring Your Own Keys (BYOK) mode: - Error messages emphasize that users must provide their own API keys - The system checks for API keys when the window regains focus - Clear guidance directs users to the settings page for key management ## Error Handling in AgentDock This document outlines our approach to error handling in the AgentDock application using React ErrorBoundary components and specialized error handlers. ## Core Components ### ErrorBoundary We use a comprehensive ErrorBoundary component located at `src/components/error-boundary.tsx` that provides robust error handling throughout the application. This component: 1. Catches and handles errors in React component trees 2. Provides a consistent error UI experience throughout the application 3. Includes special handling for different error types (NetworkError, SecurityError, ValidationError, StorageError) 4. Shows detailed error information in development mode 5. Provides retry functionality to recover from errors when possible ### ChatErrorOverlay For handling runtime errors in the chat interface, we use the `ChatErrorOverlay` component located at `src/components/chat/chat-error-overlay.tsx`. This component: 1. Displays user-friendly error messages for chat-specific errors 2. Categorizes errors according to our standard error types (Security, Network, Validation, Storage) 3. Provides appropriate recovery actions based on error type 4. Integrates with the core error handling architecture ## Vercel AI SDK Integration We integrate with Vercel AI SDK's error handling system to ensure proper error propagation from LLM providers to the UI: ### Agent Adapter Error Handling The agent adapter in `src/lib/agent-adapter.ts` enhances the stream result to properly handle errors: ```typescript // In agent-adapter.ts const enhancedResult = { ...result, toDataStreamResponse(options = {}) { return result.toDataStreamResponse({ ...options, getErrorMessage: (error: unknown) => { // Extract streaming error message if (error && typeof error === 'object' && '_hasStreamingError' in error) { const streamError = error as any; if (streamError._streamingErrorMessage) { return streamError._streamingErrorMessage; } } // Standard error handling if (error instanceof Error) { return error.message; } return typeof error === 'string' ? error : 'Unknown error occurred'; } }); } }; ``` This approach: 1. Uses Vercel's recommended `getErrorMessage` pattern 2. Extracts detailed error information from CoreLLM 3. Ensures consistent error display in the UI ### Error Flow Architecture Our error handling follows a layered architecture: 1. **CoreLLM** - Detects streaming errors and sets error flags 2. **Agent Adapter** - Converts errors to Vercel AI SDK format 3. **API Route** - Passes enhanced results without modification 4. **Client Components** - Displays user-friendly error messages See the detailed documentation in [LLM Error Handling](./llm-error-handling.md). ## Error Categories All errors in AgentDock are categorized into these standard types: | Category | Description | Examples | |----------|-------------|----------| | Security | Permission and authentication issues | Missing API keys, invalid credentials | | Network | API and connectivity problems | Rate limits, service unavailable | | Validation | Input validation failures | Invalid inputs, context window exceeded | | Storage | Local storage access issues | Failed to access secure storage | | Unknown | Fallback for other errors | Unexpected exceptions | | LLM | Model-specific errors | Quota exceeded, model unavailable | ## Using the ErrorBoundary When implementing new features that need error handling: ```tsx import { ErrorBoundary } from "@/components/error-boundary"; // Basic usage // With custom fallback UI } > // With error callback { // Log or handle the error console.error("Component error:", error); }} resetOnPropsChange={true} > ``` ## Using the ChatErrorOverlay For handling API errors in chat interfaces: ```tsx import { ChatErrorOverlay } from "@/components/chat/chat-error-overlay"; // Basic usage within chat components ``` ## Best Practices 1. Wrap top-level feature components with ErrorBoundary 2. Use specific error types when throwing errors to enable specialized handling 3. Consider using resetOnPropsChange for components that should retry on prop changes 4. Provide meaningful error messages to help users understand what went wrong 5. Use ChatErrorOverlay for runtime API errors in chat interfaces 6. Follow the established error categories when classifying errors 7. Ensure all error messages are user-friendly and actionable 8. Use Vercel AI SDK's error handling pattern for LLM errors 9. Keep error handling logic in the appropriate layer (adapter, not API route) ## Specialized Error Handling The ErrorBoundary component provides specialized handling for different types of errors: ### Network Errors - Displays connectivity-related information - Provides reload options - Shows troubleshooting tips ### Security Errors - Handles permission-related issues - Provides clear guidance on fixing permissions ### Validation Errors - Shows detailed information about data validation failures - Provides guidance on fixing input data ### Storage Errors - Handles issues with browser storage - Suggests clearing cache or using a different browser ### LLM Errors - Shows detailed information from the LLM provider - Differentiates between quota issues, rate limits, and other errors - Provides relevant recovery actions ## API Error Handling For API errors, particularly in chat interfaces: 1. Backend uses a normalized error system (`parseProviderError` and `normalizeError` functions) 2. Chat components display errors using the ChatErrorOverlay 3. Errors are categorized and displayed with appropriate actions 4. Streaming errors are handled through the Vercel AI SDK framework 5. Development mode shows additional error details for debugging ## Future Roadmap ### 1. Error Tracking and Analytics - Implement integration with error tracking services - Add anonymous error reporting to improve the application - Create an error dashboard for administrators ### 2. Enhanced Recovery Strategies - Implement more sophisticated retry mechanisms - Add circuit breaker patterns for external services - Provide user-controlled recovery options ### 3. Context-Aware Error Boundaries - Create specialized error boundaries for different parts of the application - Implement context-aware error handling based on component type - Add custom recovery strategies for specific errors ## Creating Custom Evaluators The AgentDock Evaluation Framework is designed for extensibility. While the built-in evaluators cover many common use cases, you will inevitably encounter scenarios requiring bespoke evaluation logic specific to your agent's tasks, data, or business rules. A core design philosophy is that a framework's true power lies in its adaptability. The core of this extensibility is the `Evaluator` interface. By implementing this interface, you can seamlessly integrate your custom evaluation logic into the `EvaluationRunner` and leverage the broader framework features. ## The `Evaluator` Interface To create a custom evaluator, you need to define a class that implements the `Evaluator` interface. This interface is defined as follows (conceptually): ```typescript // Conceptual representation (refer to actual types in agentdock-core) interface Evaluator { /** * A unique string identifier for this evaluator type. * This is used in EvaluationRunConfig to specify which evaluator to use. */ type: string; /** * The core evaluation logic. * @param input The full EvaluationInput for the current run. * @param criteria The specific EvaluationCriteria this evaluator should assess. * @param config The specific configuration for this instance of the evaluator, taken from EvaluationRunConfig. * @returns A Promise resolving to an array of EvaluationResult objects. */ evaluate( input: EvaluationInput, criteria: EvaluationCriteria[], config: ConfigType ): Promise[]>; } ``` Key aspects: * **`type` (string):** This is a crucial static or instance property. It must be a unique string that identifies your custom evaluator. This `type` string is what users will specify in the `EvaluationRunConfig` to select your evaluator. * **`evaluate(input, criteria, config)` (method):** This asynchronous method contains your core evaluation logic. It receives: * `input: EvaluationInput`: The complete input data for the evaluation (agent response, prompt, history, context, etc.). * `criteria: EvaluationCriteria[]`: An array of criteria that this evaluator instance is responsible for assessing. Your evaluator should iterate through these and produce a result for each one it's configured to handle. * `config: ConfigType`: The specific configuration object for this evaluator, as provided in the `evaluatorConfigs` array in `EvaluationRunConfig`. This allows you to parameterize your evaluator. * It must return a `Promise` that resolves to an array of `EvaluationResult` objects. ## Core Workflow of a Custom Evaluator The following diagram illustrates the general workflow when a custom evaluator is invoked by the `EvaluationRunner`: ```mermaid graph TD ERC[EvaluationRunConfig] -- "Specifies 'CustomType' & Config" --> ER[EvaluationRunner] subgraph CustomLogic CE[YourCustomEvaluator] -- "Implements" --> EIface[Evaluator Interface] EIface -.-> EvalMethod["evaluate(input, criteria, config)"] CE -- "Uses" --> CEC["Custom Evaluator Config (from ERC)"] CE -- "Processes" --> EIn["EvaluationInput"] CE -- "Produces" --> EVR["EvaluationResult(s)"] end ER -- "Instantiates/Uses" --> CE EVR --> ER style ER fill:#f9f,stroke:#333,stroke-width:2px style CE fill:#ccf,stroke:#333,stroke-width:2px style EIface fill:#e6e6fa,stroke:#333 style EVR fill:#9f9,stroke:#333,stroke-width:2px ``` ## Example: A Simple Custom Length Checker Let's imagine a custom evaluator that checks if a response length is *exactly* a specific value, different from the min/max range check of the built-in `RuleBasedEvaluator`. ```typescript // my-custom-evaluators.ts import type { Evaluator, EvaluationInput, EvaluationCriteria, EvaluationResult } from 'agentdock-core'; // Adjust path as necessary // Assuming getInputText is exported from agentdock-core or a known utils path // For example: import { getInputText } from 'agentdock-core/evaluation/utils'; // Or if getInputText becomes part of the main agentdock-core exports: // import { getInputText } from 'agentdock-core'; // Import the utility function from the framework import { getInputText } from 'agentdock-core/evaluation/utils'; // Configuration type for our custom evaluator interface ExactLengthConfig { expectedLength: number; sourceField?: string; // e.g., 'response', 'context.someField' } class ExactLengthEvaluator implements Evaluator { public readonly type = 'ExactLengthCheck'; // Unique type identifier async evaluate( input: EvaluationInput, criteria: EvaluationCriteria[], config: ExactLengthConfig ): Promise { const results: EvaluationResult[] = []; // Use the utility function to extract text const textToEvaluate = getInputText(input, config.sourceField); // Original logic for iterating criteria and checking length follows for (const criterion of criteria) { if (textToEvaluate === undefined) { results.push({ criterionName: criterion.name, score: false, reasoning: `Source field '${config.sourceField || 'response'}' not found, not a string, or not extractable.`, evaluatorType: this.type, }); continue; } const actualLength = textToEvaluate.length; const passed = actualLength === config.expectedLength; results.push({ criterionName: criterion.name, score: passed, reasoning: passed ? `Response length is exactly ${config.expectedLength}.` : `Expected length ${config.expectedLength}, got ${actualLength}.`, evaluatorType: this.type, }); } return results; } } // To make it available, you might export it or register it with a central registry if your app has one. export { ExactLengthEvaluator }; // Testing custom evaluators // -------------------------- // It's important to thoroughly test your custom evaluators. Here's a basic example of how you might // write tests for the `ExactLengthEvaluator` using a testing framework like Jest. /* import { ExactLengthEvaluator } from './my-custom-evaluators'; import type { EvaluationInput, EvaluationCriteria, ExactLengthConfig } from './my-custom-evaluators'; // Assuming types are also exported or defined locally for test describe('ExactLengthEvaluator', () => { let evaluator: ExactLengthEvaluator; const mockCriteria: EvaluationCriteria[] = [{ name: 'ExactLength', description: 'Test', scale: 'binary' }]; const mockConfig: ExactLengthConfig = { expectedLength: 10 }; beforeEach(() => { evaluator = new ExactLengthEvaluator(); // Assuming constructor takes no args, or adjust as needed }); it('should pass when text length matches expected length', async () => { const input: EvaluationInput = { response: '1234567890', // exactly 10 characters criteria: mockCriteria }; const results = await evaluator.evaluate(input, mockCriteria, mockConfig); expect(results.length).toBe(1); expect(results[0].score).toBe(true); expect(results[0].reasoning).toContain('Response length is exactly 10.'); }); it('should fail when text length differs from expected length', async () => { const input: EvaluationInput = { response: '12345', // only 5 characters criteria: mockCriteria }; const results = await evaluator.evaluate(input, mockCriteria, mockConfig); expect(results.length).toBe(1); expect(results[0].score).toBe(false); expect(results[0].reasoning).toContain('Expected length 10, got 5.'); }); it('should handle undefined textToEvaluate gracefully', async () => { const input: EvaluationInput = { response: { complex: 'object' }, // Not a string, and getInputText might return undefined criteria: mockCriteria }; // Assuming config.sourceField is not set, so getInputText defaults to 'response' const results = await evaluator.evaluate(input, mockCriteria, mockConfig); expect(results.length).toBe(1); expect(results[0].score).toBe(false); expect(results[0].reasoning).toContain('Source field \'response\' not found, not a string, or not extractable.'); }); }); */ ## Using Your Custom Evaluator Once defined, you would use your custom evaluator in an `EvaluationRunConfig` by providing its `type` and any necessary configuration: ```typescript // in your evaluation script // import { ExactLengthEvaluator } from './my-custom-evaluators'; // Assuming local file // import { EvaluationRunner, type EvaluationRunConfig ... } from 'agentdock-core'; // If your custom evaluator isn't automatically discoverable by EvaluationRunner via its type, // you might need to pass an instance directly if the runner supports it, // or ensure your bundler includes it if type-based instantiation is used. // The current EvaluationRunner instantiates evaluators based on their 'type' string matching // a known set of built-in evaluators. For true custom external evaluators, the runner // would need a mechanism to register or receive instantiated custom evaluators. // For now, let's assume it can be configured if EvaluationRunner is adapted or if it's used within the same project scope. const runConfig: EvaluationRunConfig = { evaluatorConfigs: [ // ... other built-in evaluator configs { type: 'ExactLengthCheck', // The unique type string of your custom evaluator // criteriaNames: ['MustBeSpecificLength'], // Link to specific criteria names config: { // The ExactLengthConfig for this instance expectedLength: 50, sourceField: 'response' } } ], // ... other run config properties }; // const results = await runEvaluation(myInput, runConfig); ``` Building custom evaluators empowers you to tailor the AgentDock Evaluation Framework precisely to your needs, ensuring that your agent's quality is measured against the metrics that matter most for your application. ## Keyword Coverage Evaluator The `KeywordCoverageEvaluator` checks for the presence, frequency, or coverage of specified keywords or phrases within a given text. This is a straightforward but highly effective way to ensure that essential information is included in an agent's response, or conversely, that undesirable terms are absent. Experience finds this useful for quick checks on information inclusion or policy adherence. ## Core Workflow The `KeywordCoverageEvaluator` takes an input text (typically the agent's response) and a configuration specifying a list of keywords and matching rules (e.g., case sensitivity, expected outcome). It then scans the input text to determine the presence, frequency, or coverage of these keywords, producing a score that reflects this, which is included in the `EvaluationResult`. ```mermaid graph TD subgraph Inputs InputText["Input Text (e.g., Agent Response)"] KWConfig["Keyword List & Matching Rules (Config)"] end KCEval[KeywordCoverageEvaluator] InputText --> KCEval KWConfig --> KCEval KCEval -- "Scans Text" --> ScanResult["Keyword Scan (Presence/Frequency)"] ScanResult --> CoverageScore["Coverage Score"] CoverageScore --> ER[EvaluationResult] style KCEval fill:#ccf,stroke:#333,stroke-width:2px style ScanResult fill:#f0ad4e,stroke:#333 style ER fill:#9f9,stroke:#333,stroke-width:2px ``` ## Use Cases The `KeywordCoverageEvaluator` is valuable for: * Ensuring product names, disclaimers, or specific instructions are mentioned. * Verifying that all topics from a checklist are addressed. * Basic checking for forbidden words (though `ToxicityEvaluator` might be more specialized). * Counting occurrences of specific terms for analytical purposes. ## Configuration Configuration involves defining the keywords and the matching logic: * `keywords`: An array of strings or patterns to search for. * `caseSensitive`: Boolean, defaults to `false`. * `expectedOutcome`: Defines what constitutes a pass (e.g., 'any' keyword found, 'all' keywords found, 'none' found, or a specific count/frequency). * `sourceField`: Specifies which field from `EvaluationInput` to check (defaults to 'response'). ```typescript // Example configuration structure (to be detailed) // { // type: 'KeywordCoverage', // keywords: ['important disclaimer', 'AgentDock Core'], // caseSensitive: false, // expectedOutcome: 'all', // e.g., requires both to be present // sourceField: 'response.textBlock' // } ``` ## Output (`EvaluationResult`) The `KeywordCoverageEvaluator` produces an `EvaluationResult`: * **`criterionName`**: Reflects the keyword check being performed (e.g., "IncludesMandatoryTerms"). * **`score`**: Typically boolean (`true`/`false`) or a numeric score (e.g., percentage of keywords found, count of occurrences). * **`reasoning`**: Details about which keywords were found/missing, or counts. * **`evaluatorType`**: `'KeywordCoverage'`. * **`error`**: For configuration errors or issues accessing the text. This evaluator offers a simple way to enforce content requirements based on keyword presence. ## Lexical Evaluator Suite The AgentDock Evaluation Framework includes a suite of **Lexical Evaluators** designed for fast, deterministic, and cost-effective analysis of textual content. These evaluators operate directly on the text of agent responses or other inputs, without relying on complex NLP models or LLMs. Practical experience shows that these kinds of checks are invaluable for quick feedback loops and for validating basic textual properties before engaging more resource-intensive evaluations. They are particularly useful for: * Quick sanity checks on output format and content. * Identifying the presence or absence of specific terms. * Basic sentiment and toxicity screening. * Measuring superficial textual similarity. While they don't capture deep semantic meaning, they provide a crucial layer of assessment for many common requirements. ## Evaluators in this Suite This suite currently comprises the following evaluators. Each has its own detailed documentation page: * [Lexical Similarity Evaluator](./lexical-similarity.md): * Compares string similarity using various algorithms (e.g., Levenshtein, Jaro-Winkler). * Useful for checking how closely a response matches an expected template or a piece of known text, without requiring exact matches. * [Keyword Coverage Evaluator](./keyword-coverage.md): * Checks for the presence, frequency, or coverage of specified keywords or phrases within the text. * Helpful for ensuring key information is included or for flagging forbidden terms (though `ToxicityEvaluator` is more specialized for the latter). * [Sentiment Evaluator](./sentiment.md): * Analyzes the sentiment of the text, typically classifying it as positive, negative, or neutral. * Useful for gauging the emotional tone of an agent's response. * [Toxicity Evaluator](./toxicity.md): * Scans text for predefined toxic terms or patterns from a blocklist. * A basic but important check for safety and appropriateness. These evaluators can be used individually or in combination to build a comprehensive picture of an agent's textual output characteristics. ## Lexical Similarity Evaluator The `LexicalSimilarityEvaluator` compares two strings and calculates a score representing their textual similarity. This is distinct from semantic similarity (handled by `NLPAccuracyEvaluator`) as it focuses on the character-level or token-level makeup of the strings. Experience suggests this is useful for cases where specific phrasing or structure is expected, but minor variations are tolerable, or for comparing against known textual patterns. It typically employs various string comparison algorithms like Levenshtein distance, Jaro-Winkler, or others available through libraries. ## Core Workflow The `LexicalSimilarityEvaluator` takes two text inputs (e.g., an agent's response and a ground truth reference) and a selected similarity algorithm (specified in its configuration). It applies the algorithm to compare the two texts and calculates a numerical similarity score, which is then reported in the `EvaluationResult`. ```mermaid graph TD subgraph Inputs TextA["Text A (e.g., Agent Response)"] TextB["Text B (e.g., Ground Truth)"] Algo["Similarity Algorithm (Config)"] end LSEval[LexicalSimilarityEvaluator] TextA --> LSEval TextB --> LSEval Algo --> LSEval LSEval -- "Calculates" --> SimScore["Similarity Score"] SimScore --> ER[EvaluationResult] style LSEval fill:#ccf,stroke:#333,stroke-width:2px style SimScore fill:#f0ad4e,stroke:#333 style ER fill:#9f9,stroke:#333,stroke-width:2px ``` ## Use Cases The `LexicalSimilarityEvaluator` is useful for: * Checking how closely an agent's response matches an expected template or a known answer, allowing for some flexibility. * Assessing adherence to specific phrasing guidelines. * Identifying minor typos or variations in user input when comparing against a knowledge base. * Measuring the difference between two versions of a text. ## Configuration Configuration primarily involves selecting the algorithm and specifying the source of the texts to compare from the `EvaluationInput`: * `sourceField`: A string (e.g., 'response', 'context.someData') indicating which field from `EvaluationInput` provides the primary text. * `referenceField`: A string (e.g., 'groundTruth', 'context.expectedAnswer') indicating which field from `EvaluationInput` provides the reference text. * `algorithm`: The string similarity algorithm to use (e.g., 'levenshtein', 'jaroWinkler', 'sorensenDice'). * Potentially, algorithm-specific parameters like `caseSensitive` or `normalizeWhitespace`. ```typescript // Example configuration structure (to be detailed) // { // type: 'LexicalSimilarity', // algorithm: 'jaroWinkler', // Or other supported algorithm // sourceField: 'response', // referenceField: 'groundTruth.answer', // Example path to a nested field // caseSensitive: false // } ``` ## Output (`EvaluationResult`) The `LexicalSimilarityEvaluator` produces an `EvaluationResult`: * **`criterionName`**: A name reflecting the comparison being made (e.g., "ResponseTemplateSimilarity"). * **`score`**: A numeric value representing the similarity, often normalized (e.g., 0 to 1, where 1 is a perfect match). * **`reasoning`**: May include the raw score from the algorithm if different from the normalized score, or the algorithm used. * **`evaluatorType`**: `'LexicalSimilarity'`. * **`error`**: For issues like an unsupported algorithm or problems accessing the source/target texts. This evaluator provides a quantitative measure of textual closeness, useful when exact matches are too strict but semantic understanding is not required. ## LLM-as-Judge Evaluator The `LLMJudgeEvaluator` leverages the power of a large language model (LLM) to perform nuanced, qualitative assessments of agent outputs. Unlike rule-based systems that check for specific, deterministic patterns, an LLM judge can evaluate responses based on broader criteria like coherence, relevance, helpfulness, safety, or adherence to complex instructions. Practical experience shows that for many sophisticated agent behaviors, an LLM judge is an indispensable tool for capturing the subtleties of quality. ## Core Workflow The `LLMJudgeEvaluator` takes the agent's response and the evaluation criteria as input. It then typically formats these into a prompt for a specified Language Model (LLM), instructing the LLM to assess the response against each criterion and provide a score and reasoning. The evaluator parses the LLM's structured output to generate the final `EvaluationResult` objects. ```mermaid graph TD subgraph Input direction LR EI_Response["Agent Response"] EI_Criteria["Evaluation Criteria"] end LLMEval[LLMJudgeEvaluator] --> LLM["Language Model (LLM)"] EI_Response --> LLMEval EI_Criteria --> LLMEval LLM -- "Assesses based on Criteria" --> LLMEval LLMEval --> ER[EvaluationResult] style LLMEval fill:#ccf,stroke:#333,stroke-width:2px style LLM fill:#f9f,stroke:#333,stroke-width:2px style ER fill:#9f9,stroke:#333,stroke-width:2px ``` ## Use Cases The `LLMJudgeEvaluator` is particularly well-suited for: * Assessing the overall quality of free-form text responses. * Evaluating adherence to complex or nuanced instructions. * Checking for specific stylistic elements (e.g., tone, formality). * Identifying potential safety issues or harmful content that might be missed by simpler checks. * Comparing agent responses against a gold standard or ground truth in a semantic way. ## Configuration Details on how to configure the `LLMJudgeEvaluator` will go here. This typically involves specifying: * The LLM to use (e.g., model name, provider). * The system prompt or template to guide the LLM's judgment. * How criteria are presented to the LLM. ```typescript // Example configuration structure (to be detailed) // { // type: 'LLMJudge', // llmConfig: { /* ... CoreLLM configuration ... */ }, // judgePromptTemplate?: string, // Optional: Custom prompt template // // ... other LLM judge specific settings // } ``` ## Output (`EvaluationResult`) The `LLMJudgeEvaluator` produces an `EvaluationResult` for each criterion it assesses. * **`criterionName`**: The name of the criterion being evaluated. * **`score`**: The score assigned by the LLM, often on a predefined scale (e.g., numeric, Likert). * **`reasoning`**: The justification provided by the LLM for its score. This is often the most valuable part of the output. * **`evaluatorType`**: `'LLMJudge'`. * **`error`**: Populated if there was an issue with the LLM call or processing its response. This evaluator allows for a much richer and more human-like assessment of agent performance, complementing more deterministic methods. ## NLP Accuracy Evaluator The `NLPAccuracyEvaluator` measures the semantic similarity between an agent's response and a provided ground truth. This is crucial for tasks where the exact wording isn't as important as the meaning or intent conveyed. Experience indicates that for question answering, summarization, or any task requiring semantic understanding, this kind of evaluation is far more insightful than simple lexical matches. It typically works by generating embeddings (vector representations) for both the agent's response and the ground truth, and then calculating the cosine similarity between these embeddings. A higher cosine similarity indicates greater semantic closeness. ## Core Workflow The `NLPAccuracyEvaluator` takes an agent's response and a ground truth text as input. Both texts are then processed by a specified embedding model to generate their respective vector embeddings. The cosine similarity between these two embeddings is calculated, yielding a score that quantifies their semantic closeness. This score forms the core of the `EvaluationResult`. ```mermaid graph TD subgraph Inputs AR["Agent Response"] GT["Ground Truth"] end subgraph Processing EM[Embedding Model] AR --> EM GT --> EM EM --> ARE[Response Embedding] EM --> GTE[Ground Truth Embedding] ARE --> CS[Cosine Similarity] GTE --> CS CS --> Score["Similarity Score"] end NLPAEval[NLPAccuracyEvaluator] -.-> Score Score --> ER[EvaluationResult] style NLPAEval fill:#ccf,stroke:#333,stroke-width:2px style EM fill:#f9f,stroke:#333,stroke-width:2px style CS fill:#f0ad4e,stroke:#333,stroke-width:2px style ER fill:#9f9,stroke:#333,stroke-width:2px ``` ## Use Cases The `NLPAccuracyEvaluator` is ideal for: * Evaluating the relevance and accuracy of answers in question-answering systems. * Assessing the quality of summaries against reference summaries. * Measuring how well an agent's response captures the meaning of a target text. * Comparing different phrasings of a concept for semantic equivalence. ## Configuration Configuring this evaluator primarily involves specifying how embeddings are generated: * The embedding model to use (via `CoreLLM` or a dedicated embedding service configuration). * Potentially, parameters for the embedding generation. ```typescript // Example configuration // NOTE: The `embeddingAdapter` needs to be an instance of a class // that implements the `EmbeddingAdapter` interface. // The instantiation below is conceptual. // You would typically import and configure a specific adapter (e.g., for OpenAI, Google, etc.). // Conceptual: const myOpenAIAdapter = new OpenAIEmbeddingAdapter({ apiKey: 'YOUR_API_KEY', model: 'text-embedding-ada-002' }); // Conceptual: const myGoogleAdapter = new GoogleEmbeddingAdapter({ apiKey: 'YOUR_API_KEY', model: 'embedding-001' }); // Example using a conceptual adapter instance: { type: 'NLPAccuracy', criterionName: 'SemanticClosenessToAnswer', // embeddingAdapter: myOpenAIAdapter, // Pass the instantiated adapter embeddingAdapter: {} as any, // Placeholder for a real adapter instance in a real setup sourceTextField: 'response', // Text to evaluate (e.g., agent's answer) referenceTextField: 'groundTruth', // Text to compare against (e.g., ideal answer) similarityThreshold: 0.75 // Optional: score >= this is considered a pass } ``` ## Output (`EvaluationResult`) The `NLPAccuracyEvaluator` produces an `EvaluationResult`: * **`criterionName`**: Typically a name like "SemanticSimilarity" or "NLPAccuracy". * **`score`**: A numeric value (usually between 0 and 1, or -1 and 1 for cosine similarity) representing the semantic similarity. Higher is generally better. * **`reasoning`**: May include details like the actual cosine similarity score if the scaled score is different, or notes about the embedding process. * **`evaluatorType`**: `'NLPAccuracy'`. * **`error`**: Populated if there were issues generating embeddings or calculating similarity. This evaluator helps quantify how well an agent understands and reproduces meaning, a key aspect of advanced agent performance. ## Rule-Based Evaluator The `RuleBasedEvaluator` provides essential, low-cost checks for agent outputs. Its purpose is straightforward: enforce deterministic constraints and basic validations without incurring the latency or cost of LLM calls. Experience shows that establishing these kinds of guardrails early is fundamental for building any semblance of predictable agent behavior. Think of it as the first line of defense: Does the response meet minimum length? Does it contain required keywords? Is the generated structure valid? These aren't complex semantic judgments, but they are critical for filtering out basic failures quickly. ## Use Cases This evaluator excels at checks like: * **Format Validation:** Ensuring output is valid JSON, respects length constraints (min/max characters), or matches a specific regular expression. * **Keyword Enforcement:** Verifying the presence (or absence) of specific required terms, product names, or identifiers. * **Basic Safety/Compliance:** Flagging responses containing blacklisted terms (though the dedicated `ToxicityEvaluator` is often better suited for more nuanced checks). * **Instruction Adherence (Simple):** Checking if simple instructions, like including a specific phrase, were followed. It's fast, cheap, and deterministic—essential characteristics for checks you might run frequently, perhaps even in CI/CD pipelines. ## Configuration To use the `RuleBasedEvaluator`, you include its configuration in the `evaluatorConfigs` array within your `EvaluationRunConfig`. ```typescript // In your EvaluationRunConfig { // ... other evaluator configs { type: 'RuleBased'; rules: EvaluationRule[]; // Array of rules to apply }, // ... other evaluator configs } ``` The core of the configuration lies in the `rules` array, which contains `EvaluationRule` objects. ### `EvaluationRule` Interface Each rule links a specific check to a defined evaluation criterion: ```typescript interface EvaluationRule { /** The name of the criterion this rule evaluates (must match a name in EvaluationInput.criteria). */ criterionName: string; /** The specific configuration defining the check to perform. */ config: RuleConfig; } ``` ### `RuleConfig` Union Type The `config` field within an `EvaluationRule` specifies the actual check. It's a discriminated union based on the `type` property. ```mermaid graph TD RuleConfig --> Length RuleConfig --> Regex RuleConfig --> Includes RuleConfig --> JSON_Parse ``` **Common Optional Property:** * `sourceField?: 'response' | 'prompt' | 'groundTruth' | string;` * Specifies which field from the `EvaluationInput` the rule should check. * Defaults to `'response'`. * Use dot notation for nested context fields, e.g., `'context.extractedData'`. If the field doesn't exist or isn't a string when one is expected, the rule will typically fail. **Supported Rule Types:** 1. **`length`**: Checks the string length of the `sourceField`. ```typescript type LengthRuleConfig = { type: 'length'; min?: number; // Minimum allowed length (inclusive) max?: number; // Maximum allowed length (inclusive) sourceField?: string; }; ``` *Example:* `{ type: 'length', min: 10, max: 150, sourceField: 'response' }` 2. **`regex`**: Checks if the `sourceField` matches a given regular expression. ```typescript type RegexRuleConfig = { type: 'regex'; pattern: string; // The regex pattern (as a string) flags?: string; // Optional regex flags (e.g., 'i' for case-insensitive) sourceField?: string; }; ``` *Example:* `{ type: 'regex', pattern: '^\{.*\}$', flags: 's', sourceField: 'response' }` (Checks if response is a JSON object) 3. **`includes`**: Checks for the presence of keywords in the `sourceField`. ```typescript type IncludesRuleConfig = { type: 'includes'; keywords: string[]; // Array of keywords to check for caseSensitive?: boolean; // Defaults to false expectedOutcome: 'any' | 'all' | 'none'; // 'any': at least one keyword present, 'all': all keywords present, 'none': no keywords present sourceField?: string; }; ``` *Example:* `{ type: 'includes', keywords: ['AgentDock', 'API key'], caseSensitive: true, expectedOutcome: 'all', sourceField: 'response' }` 4. **`json_parse`**: Checks if the `sourceField` contains a valid JSON string. ```typescript type JsonParseRuleConfig = { type: 'json_parse'; sourceField?: string; }; ``` *Example:* `{ type: 'json_parse', sourceField: 'response' }` ### Configuration Example Here's how you might configure the `RuleBasedEvaluator` for two criteria: `IsConcise` and `MentionsProductName`. ```typescript import type { EvaluationRunConfig, EvaluationRule, RuleConfig } from 'agentdock-core'; // Assume EvaluationInput.criteria includes criteria named 'IsConcise' and 'MentionsProductName' const ruleBasedRules: EvaluationRule[] = [ { criterionName: 'IsConcise', config: { type: 'length', max: 200, // sourceField defaults to 'response' } as RuleConfig, // Type assertion sometimes helpful }, { criterionName: 'MentionsProductName', config: { type: 'includes', keywords: ['AgentDock Framework'], caseSensitive: false, expectedOutcome: 'any' } as RuleConfig, }, ]; const runConfig: EvaluationRunConfig = { evaluatorConfigs: [ // ... other evaluators { type: 'RuleBased', rules: ruleBasedRules, }, ], // ... other config properties }; ``` ## Output (`EvaluationResult`) The `RuleBasedEvaluator` produces an `EvaluationResult` for each `EvaluationRule` whose `criterionName` matches a criterion defined in the `EvaluationInput`. * **`criterionName`**: Matches the name from the `EvaluationRule`. * **`score`**: `true` if the rule check passed, `false` otherwise. * **`reasoning`**: A simple string indicating which rule type passed or failed (e.g., "Rule length passed", "Rule regex failed"). * **`evaluatorType`**: `'RuleBased'`. * **`error`**: Populated only if there was an unexpected issue processing the rule itself (e.g., invalid regex pattern provided in config), not for simple rule failures. This evaluator is foundational. While it doesn't assess semantic meaning or complex reasoning, it provides essential, cost-effective guardrails that are indispensable for operational stability. ## Sentiment Evaluator The `SentimentEvaluator` analyzes the emotional tone of a given text, typically classifying it as positive, negative, or neutral. It can also provide a numerical score indicating the intensity of the sentiment. This is useful for ensuring agents maintain an appropriate tone or for flagging overly negative or positive responses. Experience shows this is a good first-pass check for agent demeanor. It usually relies on pre-trained sentiment analysis models or libraries (like VADER, AFINN, or others). ## Core Workflow The `SentimentEvaluator` processes an input text (e.g., an agent's response) using an underlying sentiment analysis engine or library. This analysis typically yields a categorical classification (like positive, negative, or neutral) and/or a numerical sentiment score. These findings are then reported in the `EvaluationResult`. ```mermaid graph TD InputText["Input Text (e.g., Agent Response)"] --> SEval[SentimentEvaluator] SEval --> SAE["Sentiment Analysis Engine/Library"] SAE --> SentClass["Sentiment Classification (e.g., Positive, Negative, Neutral)"] SAE --> SentScore["Sentiment Score (Numeric)"] SentClass --> ER[EvaluationResult] SentScore -- Optional --> ER style SEval fill:#ccf,stroke:#333,stroke-width:2px style SAE fill:#f9f,stroke:#333 style ER fill:#9f9,stroke:#333,stroke-width:2px ``` ## Use Cases The `SentimentEvaluator` is helpful for: * Monitoring the overall tone of agent responses (e.g., ensuring helpfulness, avoiding aggression). * Flagging customer interactions that may require human review due to strong negative sentiment. * Analyzing user feedback for emotional content. * Ensuring marketing copy or agent personas align with desired sentiment profiles. ## Configuration Configuration might involve: * `sourceField`: Specifies which field from `EvaluationInput` to analyze (defaults to 'response'). * Potentially, selecting a specific sentiment analysis model or library if multiple are supported, or passing parameters to the underlying library. ```typescript // Example configuration structure (to be detailed) // { // type: 'Sentiment', // sourceField: 'response.text', // // modelConfig: { /* optional: specify model or library params */ } // } ``` ## Output (`EvaluationResult`) The `SentimentEvaluator` produces an `EvaluationResult`: * **`criterionName`**: Reflects the sentiment check (e.g., "ResponseSentiment"). * **`score`**: Can be a categorical label (e.g., "positive", "negative", "neutral") or a numeric score (e.g., a value from -1 to 1). * **`reasoning`**: Might include the raw numeric score if the main score is categorical, or a list of words that most influenced the sentiment. * **`evaluatorType`**: `'Sentiment'`. * **`error`**: For issues accessing the text or problems with the sentiment analysis engine. This evaluator provides a quick way to gauge the emotional tone of text, an important factor in human-agent interaction. ## Tool Usage Evaluator The `ToolUsageEvaluator` is designed to assess the correctness of an agent's tool invocations. In modern agent systems, the ability to reliably and accurately use tools is paramount. This evaluator checks if the agent called the right tools, with the right arguments, and in the expected manner. Deploying agents has shown that tool use is a frequent point of failure, making robust evaluation in this area critical. It typically examines the `messageHistory` within the `EvaluationInput` to find tool call messages and compares them against predefined expectations. ## Core Workflow The `ToolUsageEvaluator` processes the agent's message history (from `EvaluationInput`) to identify any tool calls made by the agent. These actual tool calls are then compared against a set of predefined 'Expected Tool Call Rules' provided in the evaluator's configuration. This comparison typically involves validating the tool name, checking the arguments passed to the tool, and ensuring adherence to rules about whether a tool call was required or optional. The outcomes of these checks form the `EvaluationResult` objects. ```mermaid graph TD subgraph Input AMH["Agent Message History"] ETCR["Expected Tool Call Rules (Config)"] end TUEval[ToolUsageEvaluator] AMH --> TUEval ETCR --> TUEval TUEval -- "Extracts" --> ATC["Actual Tool Calls"] subgraph ComparisonLogic direction LR ATC --> CheckName[Tool Name Check] ETCR --> CheckName ATC --> CheckArgs[Argument Validation] ETCR --> CheckArgs ETCR --> CheckRequired[Required/Optional Check] end CheckName --> ER[EvaluationResult] CheckArgs --> ER CheckRequired --> ER style TUEval fill:#ccf,stroke:#333,stroke-width:2px style ATC fill:#f0ad4e,stroke:#333 style ER fill:#9f9,stroke:#333,stroke-width:2px ``` ## Use Cases The `ToolUsageEvaluator` is essential for: * Verifying that an agent calls a specific required tool. * Ensuring that all arguments passed to a tool call are valid (e.g., correct type, within expected ranges, matching a pattern). * Checking if a tool was called when it shouldn't have been. * Validating the sequence or number of tool calls. * Confirming that data returned by a tool is processed correctly by the agent in subsequent steps (though this might sometimes require a more complex evaluator). ## Configuration Configuration involves defining the expectations for tool usage: * A list of expected tool calls, including the tool `name`. * For each expected tool call, validation rules for its `arguments`. * Rules for whether a tool call is `required` or `optional`. * Potentially, checks for the `order` or `frequency` of calls. ```typescript // Example configuration { type: 'ToolUsage', criterionName: 'CorrectToolUse', expectedToolCalls: [ { toolName: 'search_knowledge_base', required: true, argumentChecks: { 'query': (value: any) => typeof value === 'string' && value.length > 0, 'max_results': (value: any) => typeof value === 'number' && value > 0 && value <= 10 } }, { toolName: 'send_email', required: false, argumentChecks: { 'recipient': (value: any) => typeof value === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value), 'subject': (value: any) => typeof value === 'string' && value.length > 0 } } ] } ``` ## Output (`EvaluationResult`) The `ToolUsageEvaluator` produces `EvaluationResult` objects for criteria related to tool usage: * **`criterionName`**: Could be specific to a tool (e.g., "CorrectlyCalled_example_tool") or more general ("ValidToolArguments"). * **`score`**: Typically boolean (`true` if the check passes, `false` otherwise) or a numeric score representing the degree of correctness. * **`reasoning`**: Details about why a tool usage check passed or failed (e.g., "Tool 'example_tool' not called", "Argument 'arg2' for tool 'example_tool' was not positive"). * **`evaluatorType`**: `'ToolUsage'`. * **`error`**: For unexpected issues during evaluation, not for failed tool usage checks themselves. Correct tool usage is a cornerstone of effective agent behavior, and this evaluator provides the means to systematically verify it. ## Toxicity Evaluator The `ToxicityEvaluator` scans text for the presence of predefined toxic terms, offensive language, or other undesirable content based on a blocklist. This is a fundamental safety check to help ensure agents do not produce harmful or inappropriate responses. Experience underscores that even basic blocklist checks are a necessary first line of defense for responsible agent deployment. ## Core Workflow The `ToxicityEvaluator` compares an input text (e.g., an agent's response) against a configured blocklist of toxic terms or patterns. It scans the text for any matches, and based on these findings, determines a toxicity status (e.g., whether toxic terms were detected, or a count of detected terms). This status forms the basis of the `EvaluationResult`. ```mermaid graph TD subgraph Inputs InputText["Input Text (e.g., Agent Response)"] Blocklist["Toxicity Term Blocklist (Config)"] end TEval[ToxicityEvaluator] InputText --> TEval Blocklist --> TEval TEval -- "Scans Text for Matches" --> ScanResult["Blocklist Scan Results (Detected Terms)"] ScanResult --> ToxicityStatus["Toxicity Status (e.g., Detected/Clear, Count)"] ToxicityStatus --> ER[EvaluationResult] style TEval fill:#ccf,stroke:#333,stroke-width:2px style ScanResult fill:#f0ad4e,stroke:#333 style ER fill:#9f9,stroke:#333,stroke-width:2px ``` ## Use Cases The `ToxicityEvaluator` is primarily used for: * Flagging agent responses that contain offensive or inappropriate language. * Ensuring compliance with content policies that forbid certain terms. * Basic safety screening of user inputs if the agent is designed to process them in sensitive ways (though this is less common for the evaluator's direct use). ## Configuration Configuration typically involves defining the list of toxic terms and matching behavior: * `blockList`: An array of strings or regular expressions representing toxic terms/patterns. * `caseSensitive`: Boolean, defaults to `false`. * `matchWholeWord`: Boolean, to avoid flagging substrings within non-toxic words. * `sourceField`: Specifies which field from `EvaluationInput` to check (defaults to 'response'). ```typescript // Example configuration structure (to be detailed) // { // type: 'Toxicity', // blockList: ['offensive_word1', 'another_bad_phrase', '^regex_pattern_for_toxicity$'], // caseSensitive: false, // matchWholeWord: true, // sourceField: 'response' // } ``` ## Output (`EvaluationResult`) The `ToxicityEvaluator` produces an `EvaluationResult`: * **`criterionName`**: Reflects the toxicity check (e.g., "IsNonToxic"). * **`score`**: Typically boolean (`true` if no toxic terms found, `false` if toxic terms are present) or a count of toxic terms found. * **`reasoning`**: Details about which toxic terms were found, if any. * **`evaluatorType`**: `'Toxicity'`. * **`error`**: For configuration errors or issues accessing the text. This provides a direct mechanism for identifying and flagging potentially harmful content based on a defined set of rules. ## AgentDock Evaluation Framework: Measuring What Matters The capability to build AI agents is rapidly becoming commoditized. The real differentiator lies in the ability to systematically and reliably measure agent quality. Without robust evaluation, "improvement" is guesswork, and "reliability" is a marketing slogan. Experience in deploying these systems has consistently shown that what isn't measured, isn't managed, and certainly isn't improved in a way that stands up to real-world demands. AgentDock Core now includes a foundational, extensible **Evaluation Framework** designed to address this critical need. This isn't about chasing every possible academic metric; it's about providing a practical, adaptable toolkit for developers to define what quality means for *their* agents and to measure it consistently. ## Core Philosophy: Practicality and Extensibility The framework is built on two core tenets: 1. **Practicality:** The framework provides a suite of common-sense evaluators out-of-the-box--from simple rule-based checks and lexical analysis to sophisticated LLM-as-judge capabilities. These are tools designed for immediate utility in typical development and CI/CD workflows. The focus is on actionable insights, not just scores. 2. **Extensibility:** No framework can anticipate every evaluation need. The AgentDock Evaluation Framework is architected around a clear `Evaluator` interface. This allows developers to seamlessly integrate custom evaluation logic, whether it's proprietary business rules, specialized NLP models, or wrappers around third-party evaluation services, without needing to modify the core framework. This isn't just about running tests; it's about building a continuous feedback loop that drives genuine improvement in agent performance, safety, and reliability. ## Key Components & Concepts Understanding the framework starts with a few core components: ```mermaid graph TD A[EvaluationInput] --> ER[EvaluationRunner] ARC[EvaluationRunConfig] --> ER subgraph EvaluationInput Components direction LR A_crit[EvaluationCriteria] A_resp[Agent Response] A_prom[Prompt] A_hist[Message History] A_cont[Context] A_conf[Agent Config] A_crit --> A A_resp --> A A_prom --> A A_hist --> A A_cont --> A A_conf --> A end subgraph EvaluationRunConfig Components direction LR ARC_eval_configs[Evaluator Configurations] ARC_storage["storageProvider (optional)"] ARC_eval_configs --> ARC ARC_storage --> ARC end ER -- uses --> E[Evaluator Interface] E -- processes w/ --> A_crit E -- produces --> RES[EvaluationResult] ER -- aggregates --> AGG[AggregatedEvaluationResult] RES --> AGG style ER fill:#f9f,stroke:#333,stroke-width:2px style E fill:#ccf,stroke:#333,stroke-width:2px style AGG fill:#9f9,stroke:#333,stroke-width:2px style A fill:#lightgrey,stroke:#333 style ARC fill:#lightgrey,stroke:#333 ``` * **`EvaluationInput`**: This is the data packet for an evaluation. It's a rich structure containing not just the agent's `response`, but also the `prompt`, `groundTruth` (if available), `messageHistory`, `context`, `agentConfig`, and the `criteria` to be assessed. Providing comprehensive input enables more nuanced and context-aware evaluations. * **`EvaluationCriteria`**: Defines *what* you're measuring. Each criterion has a `name`, `description`, and an `EvaluationScale` (e.g., `binary`, `likert5`, `numeric`, `pass/fail`). This allows for both quantitative and qualitative assessments. * **`Evaluator` Interface**: The heart of the system's extensibility. Any class implementing this interface can be plugged into the framework. It defines a `type` identifier and an `evaluate` method that takes an `EvaluationInput` and `EvaluationCriteria[]`, returning `EvaluationResult[]`. * **`EvaluationResult`**: The output from a single evaluator for a single criterion. It includes the `criterionName`, the `score` (which can be a number, boolean, or string), optional `reasoning`, and the `evaluatorType`. * **`EvaluationRunConfig`**: Configures an evaluation run. It specifies the `evaluatorConfigs` (which evaluators to use and their specific settings), includes the optional `storageProvider (optional)`, and can include run-level `metadata`. * **`EvaluationRunner`**: The orchestrator. The `runEvaluation(input: EvaluationInput, config: EvaluationRunConfig)` function takes the input and configuration, instantiates the necessary evaluators, executes them, and aggregates their findings. * **`AggregatedEvaluationResult`**: The final output of `runEvaluation`. It contains an optional `overallScore` (if applicable through normalization and weighting of criteria), a list of all individual `EvaluationResult` objects, a snapshot of the input and configuration, and metadata for the run. ## Getting Started: The `runEvaluation` Function The primary entry point is the `runEvaluation` function. Developers provide the `EvaluationInput` (what to test and how) and the `EvaluationRunConfig` (which evaluators to use). The function returns a promise resolving to the `AggregatedEvaluationResult`. ```typescript // Conceptual Example: import { runEvaluation, type EvaluationInput, type EvaluationRunConfig } from 'agentdock-core'; // ... import specific evaluator configs ... async function performMyEvaluation() { const input: EvaluationInput = { /* ... your agent's output, criteria, etc. ... */ }; const config: EvaluationRunConfig = { evaluatorConfigs: [ { type: 'RuleBased', rules: [/* ... your rules ... */] }, { type: 'LLMJudge', config: { /* ... your LLM judge setup ... */ } }, // ... other evaluator configurations ], // For server-side scripts wanting to persist results, a storage mechanism can be provided: // storageProvider: new JsonFileStorageProvider({ filePath: './my_eval_results.log' }) }; const aggregatedResult = await runEvaluation(input, config); console.log(JSON.stringify(aggregatedResult, null, 2)); // Further process or store aggregatedResult as needed } ``` And here's a visual representation of that flow: ```mermaid sequenceDiagram participant D as Developer/System participant RFE as runEvaluation() participant ER as EvaluationRunner (Internal) participant EV as Evaluator(s) participant SP as StorageProvider (Optional) D->>RFE: Calls with EvaluationInput & EvaluationRunConfig RFE->>ER: Processes input & config ER->>EV: Instantiates & calls evaluate() EV-->>ER: Returns EvaluationResult(s) alt storageProvider is provided ER->>SP: saveResult(AggregatedEvaluationResult) SP-->>ER: Confirmation end ER-->>RFE: Provides AggregatedEvaluationResult RFE-->>D: Returns AggregatedEvaluationResult ``` ## Result Persistence The `EvaluationRunner` returns the `AggregatedEvaluationResult` in memory. For server-side scenarios (like CI runs or dedicated evaluation scripts), persisting these results is often necessary. The `EvaluationRunConfig` accepts an optional `storageProvider` parameter. Server-side scripts can instantiate a logger, such as the `JsonFileStorageProvider` (imported directly via its file path: `agentdock-core/src/evaluation/storage/json_file_storage.ts`), and pass it to the runner. This provider will append each `AggregatedEvaluationResult` as a JSON line to the specified file. ```typescript // Example of using JsonFileStorageProvider in a server-side script: import { JsonFileStorageProvider } from '../agentdock-core/src/evaluation/storage/json_file_storage'; // Direct path import // ... const myFileLogger = new JsonFileStorageProvider({ filePath: './evaluation_run_output.jsonl' }); const config: EvaluationRunConfig = { // ... other configs storageProvider: myFileLogger, }; // ... ``` While this direct file logging is practical for many use cases, the long-term vision is for evaluation result persistence to integrate more deeply with AgentDock Core's broader [Storage Abstraction Layer (SAL)](../storage/README.md). This would allow evaluation results to be seamlessly routed to various configurable backends (e.g., databases, cloud storage) managed by the SAL, offering greater flexibility and consistency with how other AgentDock data is handled. For now, direct instantiation of specific loggers like `JsonFileStorageProvider` provides a robust server-side solution. ## Available Evaluators The framework ships with a versatile set of built-in evaluators: * [**Rule-Based Evaluator**](./evaluators/rule-based.md): For fast, deterministic checks based on predefined rules (length, regex, keywords, JSON parsing). * [**LLM-as-Judge Evaluator**](./evaluators/llm-judge.md): Leverages a language model to provide nuanced, qualitative assessments. * [**NLP Accuracy Evaluator**](./evaluators/nlp-accuracy.md): Measures semantic similarity between a response and ground truth using embeddings. * [**Tool Usage Evaluator**](./evaluators/tool-usage.md): Assesses the correctness of an agent's tool invocations and argument handling. * **Lexical Evaluators**: A suite of fast, non-LLM evaluators for common textual checks: * [**Lexical Similarity Evaluator**](./evaluators/lexical-similarity.md): Compares string similarity using various algorithms. * [**Keyword Coverage Evaluator**](./evaluators/keyword-coverage.md): Checks for the presence and coverage of specified keywords. * [**Sentiment Evaluator**](./evaluators/sentiment.md): Analyzes the sentiment (positive, negative, neutral) of the text. * [**Toxicity Evaluator**](./evaluators/toxicity.md): Scans text for predefined toxic terms. ## Next Steps Dive deeper into the specifics of each evaluator, learn how to create custom evaluators, and explore the example script (`scripts/examples/run_evaluation_example.ts`) in the repository to see the framework in action. This framework is a living system. The expectation is that it will evolve as new patterns and requirements are identified from real-world agent deployments. The current foundation, however, provides the necessary tools to move beyond subjective assessments and start building a culture of measurable quality. ## Example Evaluation Outputs This section provides examples of the `AggregatedEvaluationResult` objects that the `EvaluationRunner` produces. These are typically written to a log file (e.g., `evaluation_results.log` if using the `JsonFileStorageProvider`) or can be processed directly if no storage provider is used. ### Comprehensive Evaluation Run The following is an example output from a run that includes multiple types of evaluators (RuleBased, LLMJudge, NLPAccuracy, ToolUsage, and the Lexical Suite). This demonstrates the typical structure of a complete evaluation result. ```json { "overallScore": 0.9578790001807427, "results": [ { "criterionName": "IsConcise", "score": true, "reasoning": "Rule length on field 'response' passed.", "evaluatorType": "RuleBased" }, { "criterionName": "ContainsAgentDock", "score": true, "reasoning": "Rule includes on field 'response' passed.", "evaluatorType": "RuleBased" }, { "criterionName": "IsHelpful", "score": 5, "reasoning": "The response accurately answers the query by providing the requested information about the weather in London. It is clear, concise, and directly addresses the user's request.", "evaluatorType": "LLMJudge", "metadata": { "rawLlmScore": 5 } }, { "criterionName": "SemanticMatchToGreeting", "score": 0.8556048791777057, "reasoning": "Cosine similarity: 0.8556.", "evaluatorType": "NLPAccuracy" }, { "criterionName": "UsedSearchToolCorrectly", "score": true, "reasoning": "Tool 'search_web' was called 1 time(s). Argument check passed for the first call.", "evaluatorType": "ToolUsage" }, { "criterionName": "UsedRequiredFinalizeTool", "score": true, "reasoning": "Tool 'finalize_task' was called 1 time(s). Argument check passed for the first call.", "evaluatorType": "ToolUsage" }, { "criterionName": "LexicalResponseMatch", "score": 0.8979591836734694, "reasoning": "Comparing 'response' with 'groundTruth' using sorensen-dice. Case-insensitive comparison. Whitespace normalized. Sørensen-Dice similarity: 0.8980. Processed source: \"i am an agentdock assistant. i found the weather for you. the weather in london is 15c and cloudy. i...\", Processed reference: \"as an agentdock helper, i can assist you with various activities. the weather in london is currently...\".", "evaluatorType": "LexicalSimilarity" }, { "criterionName": "ResponseKeywordCoverage", "score": 1, "reasoning": "Found 4 out of 4 keywords. Coverage: 100.00%. Found: [weather, london, assistant, task]. Missed: []. Source text (processed): \"i am an agentdock assistant. i found the weather for you. the weather in london is 15c and cloudy. i have finalized the task.\".", "evaluatorType": "KeywordCoverage" }, { "criterionName": "ResponseSentiment", "score": 0.5, "reasoning": "Sentiment analysis of 'response'. Raw score: 0, Comparative: 0.0000. Output type: comparativeNormalized -> 0.5000.", "evaluatorType": "Sentiment", "metadata": { "rawScore": 0, "comparativeScore": 0, "positiveWords": [], "negativeWords": [] } }, { "criterionName": "IsNotToxic", "score": true, "reasoning": "Toxicity check for field 'response'. No configured toxic terms found. Configured terms: [hate, stupid, terrible, awful, idiot]. Case sensitive: false, Match whole word: true.", "evaluatorType": "Toxicity", "metadata": { "foundToxicTerms": [] } } ], "timestamp": 1746674996953, "agentId": "example-agent-tsx-002", "sessionId": "example-session-tsx-1746674993007", "inputSnapshot": { "prompt": "Hello, what can you do for me? And find weather in London.", "response": "I am an AgentDock assistant. I found the weather for you. The weather in London is 15C and Cloudy. I have finalized the task.", "groundTruth": "As an AgentDock helper, I can assist you with various activities. The weather in London is currently 15C and cloudy.", "criteria": "[... criteria definitions truncated for README example ...]", "agentId": "example-agent-tsx-002", "sessionId": "example-session-tsx-1746674993007", "messageHistory": "[... message history truncated for README example ...]" }, "evaluationConfigSnapshot": { "evaluatorTypes": [ "RuleBased", "LLMJudge:IsHelpful", "NLPAccuracy:SemanticMatchToGreeting", "ToolUsage", "LexicalSimilarity:LexicalResponseMatch", "KeywordCoverage:ResponseKeywordCoverage", "Sentiment:ResponseSentiment", "Toxicity:IsNotToxic" ], "criteriaNames": [ "IsConcise", "IsHelpful", "ContainsAgentDock", "SemanticMatchToGreeting", "UsedSearchToolCorrectly", "UsedRequiredFinalizeTool", "LexicalResponseMatch", "ResponseKeywordCoverage", "ResponseSentiment", "IsNotToxic" ], "storageProviderType": "external", "metadataKeys": [ "testSuite" ] }, "metadata": { "testSuite": "example_tsx_explicit_dotenv_local_script_with_nlp", "errors": [], "durationMs": 3946 } } ``` ### Negative Sentiment Test This example shows the output when specifically testing the `SentimentEvaluator` with a configuration designed to categorize a clearly negative response. Note that `overallScore` might be absent if only non-numeric scores (like string categories) are produced and no aggregation is performed or possible. ```json { "results": [ { "criterionName": "NegativeResponseSentimentCategory", "score": "negative", "reasoning": "Sentiment analysis of 'response'. Raw score: -11, Comparative: -0.8462. Output type: category -> negative. (PosThreshold: 0.2, NegThreshold: -0.2).", "evaluatorType": "Sentiment", "metadata": { "rawScore": -11, "comparativeScore": -0.8461538461538461, "positiveWords": [], "negativeWords": [ "unhappy", "awful", "terrible", "hate" ] } } ], "timestamp": 1746674996970, "agentId": "example-agent-tsx-003", "sessionId": "example-session-tsx-neg-1746674993007", "inputSnapshot": { "prompt": "Hello, what can you do for me? And find weather in London.", "response": "I hate this. This is terrible and awful and I am very unhappy.", "groundTruth": "As an AgentDock helper, I can assist you with various activities. The weather in London is currently 15C and cloudy.", "criteria": "[... criteria definitions truncated for README example ...]", "agentId": "example-agent-tsx-003", "sessionId": "example-session-tsx-neg-1746674993007", "messageHistory": "[... message history truncated for README example ...]" }, "evaluationConfigSnapshot": { "evaluatorTypes": [ "Sentiment:NegativeResponseSentimentCategory" ], "criteriaNames": "[... criteria names truncated for README example ...]", "storageProviderType": "external", "metadataKeys": [ "testSuite" ] }, "metadata": { "testSuite": "negative_sentiment_category_test", "errors": [], "durationMs": 3 } } ``` ### Toxic Response Test This example shows the output when specifically testing the `ToxicityEvaluator`. The response contains terms from the blocklist, resulting in a `false` score for the `IsNotToxic` criterion and an `overallScore` of 0 (as this was the only criterion weighted for this run in the example script). ```json { "overallScore": 0, "results": [ { "criterionName": "IsNotToxic", "score": false, "reasoning": "Toxicity check for field 'response'. Found toxic terms: [hate, stupid, terrible, idiot]. Configured terms: [hate, stupid, terrible, awful, idiot]. Case sensitive: false, Match whole word: true.", "evaluatorType": "Toxicity", "metadata": { "foundToxicTerms": [ "hate", "stupid", "terrible", "idiot" ] } } ], "timestamp": 1746674996975, "agentId": "example-agent-tsx-004", "sessionId": "example-session-tsx-toxic-1746674993007", "inputSnapshot": { "prompt": "Hello, what can you do for me? And find weather in London.", "response": "You are a stupid idiot and I hate this terrible service.", "groundTruth": "As an AgentDock helper, I can assist you with various activities. The weather in London is currently 15C and cloudy.", "criteria": "[... criteria definitions truncated for README example ...]", "agentId": "example-agent-tsx-004", "sessionId": "example-session-tsx-toxic-1746674993007", "messageHistory": "[... message history truncated for README example ...]" }, "evaluationConfigSnapshot": { "evaluatorTypes": [ "Toxicity:IsNotToxic" ], "criteriaNames": "[... criteria names truncated for README example ...]", "storageProviderType": "external", "metadataKeys": [ "testSuite" ] }, "metadata": { "testSuite": "toxic_response_test", "errors": [], "durationMs": 0 } } ## Getting Started with AgentDock This guide will help you set up and run AgentDock on your local machine for development and testing purposes. ## Components AgentDock consists of two main components: 1. **AgentDock Core** - The foundation library that powers agent functionality 2. **Open Source Client** - A complete reference implementation built with Next.js that provides a web interface for interacting with agents This repository includes both components, allowing you to use them together or separately. ## Requirements - Node.js ≥ 20.11.0 (LTS) - pnpm ≥ 9.15.0 (Required) - Docker and Docker Compose (Recommended for stateful features) - API keys for at least one LLM provider (Anthropic, OpenAI, Gemini, etc.) ## Installation & Setup 1. **Clone the Repository**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Install pnpm** (if not already installed): ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Install Dependencies**: ```bash pnpm install ``` 4. **(Recommended) Start Backend Services (Redis via Docker)** For features requiring persistent state across interactions (like session management, orchestration state, and cumulative token usage tracking), running a Redis instance via Docker is highly recommended. - **Why Docker/Redis?** AgentDock Core uses a configurable storage layer. By default (without Docker), it uses **in-memory storage**. This means session state, orchestration progress, and cumulative token counts **will be lost** between server restarts or even potentially between requests in some deployment models. While the app might run, stateful features won't work reliably. - Using Redis provides a persistent backend store for this data during development. - **Using Docker Desktop:** If you're new to Docker, using [Docker Desktop](https://www.docker.com/products/docker-desktop/) provides a graphical interface to easily manage your containers (start, stop, view logs, etc.). - **Start Services:** Navigate to the root of the cloned repository where `docker-compose.yaml` is located and run: ```bash docker compose up -d ``` This command starts Redis (and related services like Redis Commander for viewing data) in the background. - **Stopping Redis:** When you're done developing, you can stop the services: ```bash docker compose down ``` 5. **Configure environment variables**: Create an environment file (`.env` or `.env.local`) in the root directory: ```bash # Option 1: Create .env.local cp .env.example .env.local # Option 2: Create .env cp .env.example .env ``` Edit your environment file: - Add your LLM provider API keys (at least one is required). - **(If using Docker/Redis from step 4)** Choose ONE storage configuration option below: **Option A: Direct Redis Connection (Recommended for most local development)** ```dotenv # --- Key-Value Storage --- # Connect directly to the Redis container KV_STORE_PROVIDER=redis REDIS_URL="redis://localhost:6380" # REDIS_TOKEN=... (Leave commented out unless you set a password in docker-compose.yaml) ``` **Option B: Redis HTTP Proxy Connection (For simulating edge/serverless environments locally)** The `docker-compose.yaml` also starts `redis-http-proxy` (on port 8079), which provides an HTTP interface to Redis, similar to services like Upstash used in production/edge deployments. Use this if you specifically need to test interaction via an HTTP proxy. ```dotenv # --- Key-Value Storage --- # Connect via the local Redis HTTP Proxy container KV_STORE_PROVIDER=redis REDIS_URL="http://localhost:8079" # Note: Using HTTP URL for the proxy REDIS_TOKEN="test_token" # Use the token defined for the proxy in docker-compose.yaml ``` - **(If NOT using Docker/Redis)** The application will default to `KV_STORE_PROVIDER=memory`. Ensure this variable is either set to `memory` or omitted entirely. Example snippet for `.env.local` (using Option A - Direct Redis): ```dotenv # LLM Provider API Keys OPENAI_API_KEY=sk-xxxxxxx OPENAI_API_KEY=sk-xxxxxxx # ... other keys ... # Storage Configuration (Using Dockerized Redis) KV_STORE_PROVIDER=redis REDIS_URL="redis://localhost:6380" ``` 6. **Start the development server**: ```bash pnpm dev ``` 7. **Access the application**: Open your browser and navigate to [http://localhost:3000](http://localhost:3000) ## Creating Your First Agent AgentDock uses agent templates to define agent behavior. Here's how to create your own agent: ### 1. Create Agent Template Create a new directory in the `agents` folder for your agent: ``` agents/my-first-agent/ ``` Create a `template.json` file in this directory with your agent configuration: ```json { "version": "1.0", "agentId": "my-first-agent", "name": "My First Agent", "description": "A simple example agent", "personality": [ "You are a helpful assistant that provides concise answers.", "You are designed to be helpful and informative.", "You can help users with weather information and web searches.", "Use the weather tool to get current conditions and forecasts for any location worldwide.", "Use the search tool to find information on any topic. The tool will return relevant web search results that you can use to answer user questions.", ], "nodes": [ "llm.anthropic", "weather", "search" ], "nodeConfigurations": { "llm.anthropic": { "model": "gpt-4.1-mini", "temperature": 0.7, "maxTokens": 4096, "useCustomApiKey": false }, "weather": { "maxResults": 5 }, "search": { "maxResults": 8 } }, "chatSettings": { "historyPolicy": "lastN", "historyLength": 50, "initialMessages": [ "Hello! I'm your new agent. I can help you with weather information and web searches. How can I assist you today?" ], "chatPrompts": [ "What's the weather like in New York?", "Search for information about climate change" ] }, "tags": ["Personal", "Weather", "Research"] } ``` ### 2. Start the Development Server Simply run the development server which will automatically bundle your templates: ```bash pnpm dev ``` The `predev` script will automatically run before starting the server, bundling all templates in the `agents` directory. ### 3. Test Your Agent Navigate to [http://localhost:3000/chat?agentId=my-first-agent](http://localhost:3000/chat?agentId=my-first-agent) to interact with your agent. Your agent will also appear in the agent selection page. ## Customizing Your Agent Agent customization is done entirely through the `template.json` file. The file supports the following key fields: - `version`: Template version (optional) - `agentId`: Unique identifier for your agent - `name`: Display name for your agent - `description`: Brief description of what your agent does - `personality`: Array of personality traits that guide your agent's behavior - `nodes`: Array of node types used by the agent. Each node represents a capability: - LLM nodes (e.g., "llm.anthropic", "llm.openai", "llm.gemini") - Provide language model capabilities - Tool nodes - Provide specific functionality: - "weather" - Get weather forecasts for locations - "search" - Search the web for information - "stock-price" - Get stock market data - "crypto-price" - Get cryptocurrency prices - "image-generation" - Generate images - "deep-research" - Perform in-depth research - "science" - Access scientific papers and data - "cognitive-tools" - Advanced cognitive capabilities - `nodeConfigurations`: Configuration for specific nodes - For LLM nodes, specify the model and parameters (temperature, maxTokens, etc.) - For tool nodes, configure their specific settings (e.g., maxResults for search) - Each node type may have its own configuration options - `chatSettings`: Controls chat behavior - `historyPolicy`: How chat history is managed ("none", "lastN", "all") - `historyLength`: Number of messages to keep if using "lastN" - `initialMessages`: Messages shown when chat starts - `chatPrompts`: Suggested prompts shown in UI - `tags`: Categories for your agent ## About the Open Source Client The Open Source Client is the complete web application in this repository that provides a reference implementation of the AgentDock Core. It includes: - A chat interface for interacting with agents - Agent selection and management - Documentation site - API routes for agent communication - Image generation capabilities - Settings management - And more The client demonstrates how to build a full-featured application using the AgentDock Core framework. ## Building for Production To create a production build: ```bash pnpm build ``` This will create an optimized production build in the `.next` directory. To preview the production build locally: ```bash pnpm start ``` ## Using AgentDock Core Standalone If you want to use just the AgentDock Core library in your own project: 1. **Install the package**: ```bash pnpm add agentdock-core ``` 2. **Import and use in your code**: ```typescript import { AgentNode } from 'agentdock-core'; async function createAgent() { // Create an agent configuration const config = { id: "my-agent", name: "My Agent", systemPrompt: "You are a helpful assistant.", tools: ["search"] }; // Create an agent const agent = new AgentNode('my-agent', { agentConfig: config, apiKey: process.env.OPENAI_API_KEY, provider: 'openai' }); // Handle a message const result = await agent.handleMessage({ messages: [{ role: 'user', content: 'Hello, how can you help me?' }] }); console.log(result.text); } ``` ## Next Steps Now that you have AgentDock running, you can explore: - [Agent Templates](agent-templates.md) - Learn more about agent templates and available options - [Architecture Overview](architecture/README.md) - Understand the system architecture - [Node System](nodes/README.md) - Learn about the node-based architecture - [Custom Tool Development](nodes/custom-tool-development.md) - Create your own custom tools - [Open Source Client](oss-client/image-generation.md) - Explore features in the reference implementation ## Troubleshooting ### Common Issues 1. **"Cannot find module 'pnpm'"** - Make sure you have pnpm installed globally or via corepack 2. **API Key Errors** - Verify that you've added the correct API keys to your `.env.local` file - Check that the API key format is correct for the provider you're using 3. **Agent not appearing after creation** - Make sure you restart the development server after creating a new agent - Check that your template.json file is valid JSON with all required fields 4. **Dependency Issues** - Try running `pnpm clean && pnpm install` to clean and reinstall all dependencies ### Getting Help If you encounter problems not covered here, please: - Check existing issues in the GitHub repository - Open a new issue with detailed information about your problem ### Start Development Server ```bash pnpm dev ``` This will start the Next.js reference client application. ### Using AgentDock Core in Other Backends While this guide focuses on the reference Next.js client, `agentdock-core` is designed as a standalone library for Node.js environments. You can integrate it into any Node.js backend framework (like Express, Fastify, Hono, NestJS, etc.): 1. **Install:** Add `@agentdock/core` (once published) or link the local `agentdock-core` package to your backend project. 2. **Import:** Import necessary classes and functions (e.g., `AgentNode`, `NodeRegistry`, `registerCoreNodes`, configuration loaders). 3. **Initialize:** Register core nodes (`registerCoreNodes()`) and any custom nodes/tools. 4. **Integrate:** Create API endpoints (e.g., `/api/chat/:agentId`) in your chosen framework. 5. **Handle Requests:** Within your endpoint handlers, instantiate `AgentNode`, manage sessions (using core session/storage managers or your own), handle message processing via `agentNode.handleMessage`, and stream responses back to the client. ### Using AgentDock from Other Languages (Python, Rust, etc.) You cannot directly use the `agentdock-core` TypeScript library in non-JavaScript/TypeScript environments. However, you can interact with AgentDock agents from *any* language or platform: 1. **Build an API:** Create a backend service using Node.js and `agentdock-core` (as described above) that exposes an HTTP API (e.g., REST). 2. **Consume the API:** From your Python, Rust, Java, frontend application, or any other client, make standard HTTP requests to your AgentDock backend API endpoints to interact with your agents. This API-centric approach allows AgentDock's core capabilities to be leveraged across diverse technology stacks. ## Next Steps - Explore the [Agent Templates](agent-templates.md) to understand configuration. - Learn about the [Node System](../nodes/README.md) in detail. - Dive into the [Core Architecture](../architecture/README.md). ## AgentDock: ابنِ أي مشروع باستخدام وكلاء الذكاء الاصطناعي

AgentDock Logo

## 🌐 ترجمات README [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock هو إطار عمل لبناء وكلاء ذكاء اصطناعي متطورين يقومون بمهام معقدة مع **حتمية قابلة للتكوين**. يتكون من مكونين رئيسيين: 1. **AgentDock Core**: إطار عمل مفتوح المصدر، يركز على الواجهة الخلفية، لبناء ونشر وكلاء الذكاء الاصطناعي. تم تصميمه ليكون *غير مرتبط بإطار عمل محدد* و*غير مرتبط بمزود محدد*، مما يمنحك تحكمًا كاملاً في تنفيذ وكيلك. 2. **Open Source Client**: تطبيق Next.js كامل الميزات يعمل كتطبيق مرجعي ومستهلك لإطار عمل AgentDock Core. يمكنك رؤيته قيد التشغيل على [https://hub.agentdock.ai](https://hub.agentdock.ai) تم بناء AgentDock باستخدام TypeScript، وهو يركز على *البساطة*، *قابلية التوسع*، و***الحتمية القابلة للتكوين***، مما يجعله مثاليًا لبناء أنظمة ذكاء اصطناعي موثوقة ويمكن التنبؤ بها يمكنها العمل بأقل قدر من الإشراف. ## 🧠 مبادئ التصميم يعتمد AgentDock على هذه المبادئ الأساسية: - **البساطة أولاً**: الحد الأدنى من التعليمات البرمجية المطلوبة لإنشاء وكلاء وظيفيين - **بنية قائمة على العقد (Nodes)**: يتم تنفيذ جميع القدرات كعقد - **الأدوات كعقد متخصصة**: توسع الأدوات نظام العقد لقدرات الوكيل - **الحتمية القابلة للتكوين**: التحكم في قابلية التنبؤ بسلوك الوكيل - **سلامة الأنواع (Type Safety)**: أنواع TypeScript كاملة في جميع الأنحاء ### الحتمية القابلة للتكوين ***الحتمية القابلة للتكوين*** هي حجر الزاوية في فلسفة تصميم AgentDock، مما يتيح لك الموازنة بين القدرات الإبداعية للذكاء الاصطناعي وسلوك النظام المتوقع: - `AgentNode` غير حتمية بطبيعتها حيث يمكن لنماذج اللغة الكبيرة (LLMs) إنشاء استجابات مختلفة في كل مرة - يمكن جعل مسارات العمل (Workflows) أكثر حتمية من خلال *مسارات تنفيذ أدوات محددة* - يمكن للمطورين **التحكم في مستوى الحتمية** عن طريق تكوين أجزاء النظام التي تستخدم استدلال LLM - حتى مع مكونات LLM، يظل سلوك النظام العام **متوقعًا** من خلال تفاعلات الأدوات المهيكلة - يتيح هذا النهج المتوازن كلاً من *الإبداع* و**الموثوقية** في تطبيقات الذكاء الاصطناعي الخاصة بك #### مسارات العمل الحتمية يدعم AgentDock بشكل كامل مسارات العمل الحتمية التي تعرفها من بناة مسارات العمل النموذجية. تتوفر جميع مسارات التنفيذ المتوقعة والنتائج الموثوقة التي تتوقعها، مع أو بدون استدلال LLM: ```mermaid flowchart LR Input[مدخل] --> Process[معالجة] Process --> Database[(قاعدة بيانات)] Process --> Output[مخرج] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### سلوك الوكيل غير الحتمي مع AgentDock، يمكنك أيضًا الاستفادة من `AgentNode` مع LLMs عندما تحتاج إلى مزيد من القدرة على التكيف. يمكن أن تختلف المخرجات الإبداعية بناءً على احتياجاتك، مع الحفاظ على أنماط التفاعل المهيكلة: ```mermaid flowchart TD Input[استعلام المستخدم] --> Agent[AgentNode] Agent -->|"استدلال LLM (غير حتمي)"| ToolChoice{اختيار الأداة} ToolChoice -->|"الخيار أ"| ToolA[أداة البحث العميق] ToolChoice -->|"الخيار ب"| ToolB[أداة تحليل البيانات] ToolChoice -->|"الخيار ج"| ToolC[استجابة مباشرة] ToolA --> Response[الاستجابة النهائية] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### وكلاء غير حتميين مع مسارات عمل فرعية حتمية يقدم لك AgentDock ***أفضل ما في العالمين*** من خلال الجمع بين ذكاء الوكيل غير الحتمي وتنفيذ مسار العمل الحتمي: ```mermaid flowchart TD Input[استعلام المستخدم] --> Agent[AgentNode] Agent -->|"استدلال LLM (غير حتمي)"| FlowChoice{اختيار مسار العمل الفرعي} FlowChoice -->|"القرار أ"| Flow1[مسار العمل الحتمي 1] FlowChoice -->|"القرار ب"| Flow2[مسار العمل الحتمي 2] FlowChoice -->|"القرار ج"| DirectResponse[إنشاء استجابة] Flow1 --> |"الخطوة 1 → 2 → 3 → ... → 200"| Flow1Result[نتيجة مسار العمل 1] Flow2 --> |"الخطوة 1 → 2 → 3 → ... → 100"| Flow2Result[نتيجة مسار العمل 2] Flow1Result --> Response[الاستجابة النهائية] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` يتيح هذا النهج استدعاء مسارات عمل معقدة متعددة الخطوات (قد تتضمن مئات الخطوات الحتمية المنفذة داخل الأدوات أو كتسلسلات من العقد المتصلة) بواسطة قرارات وكيل ذكية. يتم تنفيذ كل مسار عمل بشكل متوقع على الرغم من تشغيله بواسطة استدلال وكيل غير حتمي. لمسارات عمل وكلاء الذكاء الاصطناعي الأكثر تقدمًا وخطوط أنابيب المعالجة متعددة المراحل، نقوم ببناء [AgentDock Pro](../../agentdock-pro.md) - منصة قوية لإنشاء وتصور وتنفيذ أنظمة وكلاء معقدة. #### باختصار: الحتمية القابلة للتكوين فكر في الأمر مثل القيادة. أحيانًا تحتاج إلى إبداع الذكاء الاصطناعي (مثل التنقل في شوارع المدينة - غير حتمي)، وأحيانًا تحتاج إلى عمليات موثوقة خطوة بخطوة (مثل اتباع لافتات الطرق السريعة - حتمي). يتيح لك AgentDock بناء أنظمة تستخدم *كليهما*، واختيار النهج الصحيح لكل جزء من المهمة. تحصل على ذكاء الذكاء الاصطناعي *و* نتائج متوقعة عند الحاجة. ## 🏗️ البنية المعمارية الأساسية يعتمد إطار العمل على نظام قوي ونمطي قائم على العقد (Nodes)، والذي يعمل كأساس لجميع وظائف الوكيل. تستخدم هذه البنية أنواعًا مميزة من العقد كوحدات بناء: - **`BaseNode`**: الفئة الأساسية التي تحدد الواجهة والقدرات الأساسية لجميع العقد. - **`AgentNode`**: عقدة أساسية متخصصة تنسق تفاعلات LLM واستخدام الأدوات ومنطق الوكيل. - **الأدوات والعقد المخصصة**: ينفذ المطورون قدرات الوكيل والمنطق المخصص كعقد توسع `BaseNode`. تتفاعل هذه العقد من خلال سجلات مُدارة ويمكن توصيلها (الاستفادة من منافذ البنية الأساسية وحافلة رسائل محتملة) لتمكين سلوكيات ومسارات عمل وكلاء معقدة وقابلة للتكوين وربما حتمية. للحصول على شرح مفصل لمكونات وقدرات نظام العقد، راجع [وثائق نظام العقد](../../nodes/README.md). ## 🚀 البدء للحصول على دليل شامل، راجع [دليل البدء](../../getting-started.md). ### المتطلبات * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (مطلوب) * مفاتيح API لموفري LLM (Anthropic، OpenAI، إلخ) ### التثبيت 1. **استنساخ المستودع**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **تثبيت pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **تثبيت التبعيات**: ```bash pnpm install ``` لإعادة تثبيت نظيفة (عندما تحتاج إلى إعادة البناء من البداية): ```bash pnpm run clean-install ``` يزيل هذا البرنامج النصي جميع `node_modules` وملفات القفل ويعيد تثبيت التبعيات بشكل صحيح. 4. **تكوين البيئة**: قم بإنشاء ملف بيئة (`.env` أو `.env.local`) بناءً على ملف `.env.example` المقدم: ```bash # الخيار 1: إنشاء .env.local cp .env.example .env.local # الخيار 2: إنشاء .env cp .env.example .env ``` ثم أضف مفاتيح API الخاصة بك إلى ملف البيئة. 5. **بدء خادم التطوير**: ```bash pnpm dev ``` ### القدرات المتقدمة | القدرة | الوصف | الوثائق | | :---------------------- | :------------------------------------------------------------------------------------------ | :---------------------------------------------------------------------------------- | | **إدارة الجلسات** | إدارة حالة معزولة وعالية الأداء للمحادثات | [وثائق الجلسات](../../architecture/sessions/README.md) | | **إطار عمل التنسيق** | التحكم في سلوك الوكيل وتوافر الأدوات بناءً على السياق | [وثائق التنسيق](../../architecture/orchestration/README.md) | | **تجريد التخزين** | نظام تخزين مرن مع موفرين قابلين للتوصيل لـ KV و Vector والتخزين الآمن | [وثائق التخزين](../../storage/README.md) | يتطور نظام التخزين حاليًا مع تخزين المفتاح والقيمة (موفرو Memory، Redis، Vercel KV) والتخزين الآمن من جانب العميل، بينما يتم تطوير تخزين المتجهات والواجهات الخلفية الإضافية. ## 📕 الوثائق تتوفر وثائق إطار عمل AgentDock على [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) وفي مجلد `/docs/` في هذا المستودع. تتضمن الوثائق: - أدلة البدء - مراجع API - دروس إنشاء العقد - أمثلة التكامل ## 📂 بنية المستودع يحتوي هذا المستودع على: 1. **AgentDock Core**: إطار العمل الأساسي الموجود في `agentdock-core/` 2. **Open Source Client**: تطبيق مرجعي كامل الميزات مبني باستخدام Next.js، يعمل كمستهلك لإطار عمل AgentDock Core. 3. **وكلاء مثال**: تكوينات وكلاء جاهزة للاستخدام في دليل `agents/` يمكنك استخدام AgentDock Core بشكل مستقل في تطبيقاتك الخاصة، أو استخدام هذا المستودع كنقطة انطلاق لبناء تطبيقاتك الخاصة التي تعمل بالوكلاء. ## 📝 قوالب الوكلاء يتضمن AgentDock العديد من قوالب الوكلاء المعدة مسبقًا. استكشفها في دليل `agents/` أو اقرأ [وثائق قوالب الوكلاء](../../agent-templates.md) للحصول على تفاصيل التكوين. ## 🔧 تطبيقات مثال توضح تطبيقات المثال حالات استخدام متخصصة ووظائف متقدمة: | التطبيق | الوصف | الحالة | | :----------------------------- | :------------------------------------------------------------------------------------------------- | :----------- | | **الوكيل المنسق** | وكيل مثال يستخدم التنسيق لتكييف السلوك بناءً على السياق | متوفر | | **المفكر المعرفي** | يعالج المشكلات المعقدة باستخدام التفكير المنظم والأدوات المعرفية | متوفر | | **مخطط الوكلاء** | وكيل متخصص لتصميم وتنفيذ وكلاء ذكاء اصطناعي آخرين | متوفر | | [**Code Playground**](../../roadmap/code-playground.md) | إنشاء وتنفيذ تعليمات برمجية في بيئة معزولة مع قدرات تصور غنية | مخطط له | ## 🔐 تفاصيل تكوين البيئة يتطلب AgentDock Open Source Client مفاتيح API لموفري LLM ليعمل. يتم تكوينها في ملف بيئة (`.env` أو `.env.local`) تقوم بإنشائه بناءً على ملف `.env.example` المقدم. ### مفاتيح API لموفري LLM أضف مفاتيح API لموفري LLM (مطلوب واحد على الأقل): ```bash # مفاتيح API لموفري LLM - مطلوب واحد على الأقل ANTHROPIC_API_KEY=sk-ant-xxxxxxx # مفتاح API Anthropic OPENAI_API_KEY=sk-xxxxxxx # مفتاح API OpenAI GEMINI_API_KEY=xxxxxxx # مفتاح API Google Gemini DEEPSEEK_API_KEY=xxxxxxx # مفتاح API DeepSeek GROQ_API_KEY=xxxxxxx # مفتاح API Groq ``` ### تحديد مفتاح API يتبع AgentDock Open Source Client ترتيب أولوية عند تحديد مفتاح API الذي يجب استخدامه: 1. **مفتاح API مخصص لكل وكيل** (يتم تعيينه من خلال إعدادات الوكيل في واجهة المستخدم) 2. **مفتاح API للإعدادات العامة** (يتم تعيينه من خلال صفحة الإعدادات في واجهة المستخدم) 3. **متغير البيئة** (من `.env.local` أو منصة النشر) ### مفاتيح API خاصة بالأدوات تتطلب بعض الأدوات أيضًا مفاتيح API الخاصة بها: ```bash # مفاتيح API خاصة بالأدوات SERPER_API_KEY= # مطلوب لوظيفة البحث FIRECRAWL_API_KEY= # مطلوب لتصفح الويب بشكل أعمق ``` لمزيد من التفاصيل حول تكوين البيئة، راجع التنفيذ في [`src/types/env.ts`](../../../../src/types/env.ts). ### استخدام مفاتيح API الخاصة بك (BYOK) يتبع AgentDock نموذج BYOK (أحضر مفتاحك الخاص): 1. أضف مفاتيح API الخاصة بك في صفحة إعدادات التطبيق 2. بدلاً من ذلك، قم بتوفير المفاتيح عبر رؤوس الطلب للاستخدام المباشر لواجهة برمجة التطبيقات 3. يتم تخزين المفاتيح بشكل آمن باستخدام نظام التشفير المدمج 4. لا تتم مشاركة أو تخزين أي مفاتيح API على خوادمنا ## 📦 مدير الحزم يتطلب هذا المشروع استخدام `pnpm` لإدارة التبعيات بشكل متسق. `npm` و `yarn` غير مدعومين. ## 💡 ما يمكنك بناؤه 1. **التطبيقات التي تعمل بالذكاء الاصطناعي** - روبوتات محادثة مخصصة مع أي واجهة أمامية - مساعدو الذكاء الاصطناعي لسطر الأوامر - خطوط أنابيب معالجة البيانات الآلية - تكاملات خدمات الواجهة الخلفية 2. **قدرات التكامل** - أي مزود ذكاء اصطناعي (OpenAI، Anthropic، إلخ) - أي إطار عمل للواجهة الأمامية - أي خدمة واجهة خلفية - مصادر بيانات وواجهات برمجة تطبيقات مخصصة 3. **أنظمة الأتمتة** - مسارات عمل معالجة البيانات - خطوط أنابيب تحليل المستندات - أنظمة التقارير الآلية - وكلاء أتمتة المهام ## الميزات الرئيسية | الميزة | الوصف | | :----------------------------- | :------------------------------------------------------------------------------------------------- | | 🔌 **غير مرتبط بإطار عمل (Node.js Backend)** | تتكامل المكتبة الأساسية مع مكدسات الواجهة الخلفية لـ Node.js. | | 🧩 **تصميم نمطي** | بناء أنظمة معقدة من عقد بسيطة | | 🛠️ **قابل للتوسيع** | إنشاء عقد مخصصة لأي وظيفة | | 🔒 **آمن** | ميزات أمان مدمجة لمفاتيح API والبيانات | | 🔑 **BYOK** | استخدم *مفاتيح API الخاصة بك* لموفري LLM | | 📦 **مكتفي ذاتيًا** | يحتوي إطار العمل الأساسي على الحد الأدنى من التبعيات | | ⚙️ **استدعاءات أدوات متسلسلة متعددة الخطوات** | دعم *لسلاسل التفكير المعقدة* | | 📊 **Structured Logging** | رؤى مفصلة حول تنفيذ الوكيل | | 🛡️ **Robust Error Handling**| سلوك متوقع وتصحيح أخطاء مبسط | | 📝 **TypeScript أولاً** | سلامة الأنواع وتجربة مطور محسنة | | 🌐 **Open Source Client** | يتضمن تطبيق مرجعي كامل الميزات لـ Next.js | | 🔄 **التنسيق** | *تحكم ديناميكي* في سلوك الوكيل بناءً على السياق | | 💾 **إدارة الجلسات** | حالة معزولة للمحادثات المتزامنة | | 🎮 **الحتمية القابلة للتكوين** | وازن بين إبداع الذكاء الاصطناعي والقدرة على التنبؤ من خلال منطق العقدة/مسار العمل. | ## 🧰 المكونات تعتمد البنية النمطية لـ AgentDock على هذه المكونات الرئيسية: * **BaseNode**: الأساس لجميع العقد في النظام * **AgentNode**: التجريد الرئيسي لوظائف الوكيل * **الأدوات والعقد المخصصة**: قدرات قابلة للاستدعاء ومنطق مخصص يتم تنفيذه كعقد. * **سجل العقد**: يدير تسجيل واسترجاع جميع أنواع العقد * **سجل الأدوات**: يدير توافر الأدوات للوكلاء * **CoreLLM**: واجهة موحدة للتفاعل مع موفري LLM * **سجل الموفرين**: يدير تكوينات موفري LLM * **معالجة الأخطاء**: نظام لإدارة الأخطاء وضمان سلوك متوقع * **التسجيل (Logging)**: نظام تسجيل منظم للمراقبة وتصحيح الأخطاء * **التنسيق**: يتحكم في توافر الأدوات والسلوك بناءً على سياق المحادثة * **الجلسات**: تدير عزل الحالة بين المحادثات المتزامنة للحصول على وثائق فنية مفصلة حول هذه المكونات، راجع [نظرة عامة على البنية](../../architecture/README.md). ## 🗺️ خارطة الطريق فيما يلي خارطة طريق التطوير الخاصة بنا لـ AgentDock. ترتبط معظم التحسينات المدرجة هنا بإطار عمل AgentDock الأساسي (`agentdock-core`)، والذي يتم تطويره حاليًا محليًا وسيتم إصداره كحزمة NPM ذات إصدار عند الوصول إلى إصدار مستقر. قد تتضمن بعض عناصر خارطة الطريق أيضًا تحسينات على تطبيق العميل مفتوح المصدر. | الميزة | الوصف | الفئة | | :-------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------- | :-------------- | | [**طبقة تجريد التخزين**](../../roadmap/storage-abstraction.md) | نظام تخزين مرن مع موفرين قابلين للتوصيل | **قيد التقدم** | | [**أنظمة الذاكرة المتقدمة**](../../roadmap/advanced-memory.md) | إدارة السياق طويلة الأجل | **قيد التقدم** | | [**تكامل تخزين المتجهات**](../../roadmap/vector-storage.md) | استرجاع قائم على التضمين للمستندات والذاكرة | **قيد التقدم** | | [**إطار تقييم وكلاء الذكاء الاصطناعي**](../../roadmap/evaluation-framework.md) | إطار عمل اختبار وتقييم شامل | **قيد التقدم** | | [**تكامل المنصات**](../../roadmap/platform-integration.md) | دعم Telegram و WhatsApp ومنصات المراسلة الأخرى | **مخطط له** | | [**تعاون متعدد الوكلاء**](../../roadmap/multi-agent-collaboration.md) | السماح للوكلاء بالعمل معًا | **مخطط له** | | [**تكامل بروتوكول سياق النموذج (MCP)**](../../roadmap/mcp-integration.md) | دعم اكتشاف واستخدام الأدوات الخارجية عبر MCP | **مخطط له** | | [**وكلاء الذكاء الاصطناعي الصوتيون**](../../roadmap/voice-agents.md) | وكلاء ذكاء اصطناعي يستخدمون واجهات صوتية وأرقام هواتف عبر AgentNode | **مخطط له** | | [**القياس عن بعد والتتبع**](../../roadmap/telemetry.md) | تسجيل متقدم وتتبع الأداء | **مخطط له** | | [**Workflow Runtime & Node أنواع**](../../roadmap/workflow-nodes.md) | وقت التشغيل الأساسي وأنواع العقد ومنطق التنسيق للتشغيل الآلي المعقد | **مخطط له** | | [**AgentDock Pro**](../../agentdock-pro.md) | منصة سحابية شاملة للمؤسسات لتوسيع نطاق وكلاء الذكاء الاصطناعي وسير العمل | **سحابة** | | [**منشئ وكلاء الذكاء الاصطناعي باللغة الطبيعية**](../../roadmap/nl-agent-builder.md) | منشئ مرئي + بناء وكلاء ومسارات عمل باللغة الطبيعية | **سحابي** | | [**سوق الوكلاء**](../../roadmap/agent-marketplace.md) | قوالب وكلاء قابلة للتسييل | **سحابي** | ## 👥 المساهمة نرحب بالمساهمات في AgentDock! راجع [CONTRIBUTING.md](../../../CONTRIBUTING.md) للحصول على إرشادات مفصلة للمساهمة. ## 📜 الترخيص تم إصدار AgentDock بموجب [ترخيص MIT](../../../LICENSE). ## ✨ ابنِ أي شيء! يوفر AgentDock الأساس لبناء أي تطبيق أو أتمتة تعمل بالذكاء الاصطناعي يمكنك تخيلها تقريبًا. نشجعك على استكشاف إطار العمل، وبناء وكلاء مبتكرين، والمساهمة مرة أخرى في المجتمع. لنبني مستقبل تفاعل الذكاء الاصطناعي معًا! --- [العودة إلى فهرس الترجمات](/docs/i18n/README.md) ## AgentDock: 用 AI Agent 构建无限可能

AgentDock Logo

## 🌐 README 翻译 [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock 是一个用于构建复杂 AI Agent 的框架,这些 Agent 通过**可配置的确定性**来完成复杂任务。它由两个主要组件构成: 1. **AgentDock Core**:一个开源的、后端优先的框架,用于构建和部署 AI Agent。它被设计为*框架无关*和*提供商无关*,让您完全控制 Agent 的实现。 2. **开源客户端**:一个完整的 Next.js 应用程序,作为 AgentDock Core 框架的参考实现和消费者。您可以在 [https://hub.agentdock.ai](https://hub.agentdock.ai) 看到它的实际运行情况。 AgentDock 使用 TypeScript 构建,强调*简单性*、*可扩展性*和***可配置的确定性***,使其成为构建可靠且可预测的 AI 系统的理想选择,这些系统可以在最少的监督下运行。 ## 🧠 设计原则 AgentDock 建立在以下核心原则之上: - **简单优先**:创建功能性 Agent 所需的最少代码 - **基于节点的架构**:所有功能都实现为节点 - **作为专用节点的工具**:工具扩展了节点系统以实现 Agent 功能 - **可配置的确定性**:控制 Agent 行为的可预测性 - **类型安全**:贯穿始终的全面 TypeScript 类型 ### 可配置的确定性 ***可配置的确定性***是 AgentDock 设计理念的基石,使您能够在创造性的 AI 能力和可预测的系统行为之间取得平衡: - 由于 LLM 每次可能生成不同的响应,AgentNode 本质上是非确定性的 - 可以通过*定义的工具执行路径*使工作流更具确定性 - 开发人员可以通过配置系统的哪些部分使用 LLM 推理来**控制确定性的级别** - 即使有 LLM 组件,通过结构化的工具交互,整个系统的行为仍然**可预测** - 这种平衡的方法使您的 AI 应用程序兼具*创造性*和**可靠性** #### 确定性工作流 AgentDock 完全支持您在典型工作流构建器中熟悉的确定性工作流。无论是否有 LLM 推理,您期望的所有可预测执行路径和可靠结果都可用: ```mermaid flowchart LR Input[输入] --> Process[处理] Process --> Database[(数据库)] Process --> Output[输出] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### 非确定性 Agent 行为 使用 AgentDock,当您需要更高的适应性时,也可以利用带有 LLM 的 AgentNode。创造性的输出可能会根据您的需求而变化,同时保持结构化的交互模式: ```mermaid flowchart TD Input[用户查询] --> Agent[AgentNode] Agent -->|"LLM 推理 (非确定性)"| ToolChoice{工具选择} ToolChoice -->|"选项 A"| ToolA[深度研究工具] ToolChoice -->|"选项 B"| ToolB[数据分析工具] ToolChoice -->|"选项 C"| ToolC[直接响应] ToolA --> Response[最终响应] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### 具有确定性子工作流的非确定性 Agent AgentDock 通过将非确定性 Agent 智能与确定性工作流执行相结合,为您提供了***两全其美***的方案: ```mermaid flowchart TD Input[用户查询] --> Agent[AgentNode] Agent -->|"LLM 推理 (非确定性)"| FlowChoice{子工作流选择} FlowChoice -->|"决策 A"| Flow1[确定性工作流 1] FlowChoice -->|"决策 B"| Flow2[确定性工作流 2] FlowChoice -->|"决策 C"| DirectResponse[生成响应] Flow1 --> |"步骤 1 → 2 → 3 → ... → 200"| Flow1Result[工作流 1 结果] Flow2 --> |"步骤 1 → 2 → 3 → ... → 100"| Flow2Result[工作流 2 结果] Flow1Result --> Response[最终响应] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` 这种方法使得复杂的多步骤工作流(可能涉及在工具内或作为连接的节点序列实现的数百个确定性步骤)能够由智能 Agent 决策调用。尽管由非确定性 Agent 推理触发,每个工作流仍能可预测地执行。 对于更高级的 AI Agent 工作流和多阶段处理流水线,我们正在构建 [AgentDock Pro](../../docs/agentdock-pro.md) - 一个用于创建、可视化和运行复杂 Agent 系统的强大平台。 #### 关于可配置确定性的简而言之 把它想象成开车。有时您需要 AI 的创造力(比如在城市街道中导航 - 非确定性),有时您需要可靠的、按部就班的流程(比如遵循高速公路标志 - 确定性)。AgentDock 让您能够构建同时兼顾*两方面优势*的系统,为任务的每个部分选择正确的方法。您既能获得 AI 的智能,又能在需要时获得可预测的结果。 ## 🏗️ 核心架构 该框架围绕一个强大的、模块化的基于节点的系统构建,作为所有 Agent 功能的基础。该架构使用不同的节点类型作为构建块: - **`BaseNode`**:为所有节点建立核心接口和功能的基本类。 - **`AgentNode`**:协调 LLM 交互、工具使用和 Agent 逻辑的专用核心节点。 - **工具和自定义节点**:开发人员将 Agent 功能和自定义逻辑实现为扩展 `BaseNode` 的节点。 这些节点通过托管注册表进行交互,并且可以连接(利用核心架构的端口和潜在的消息总线)以实现复杂、可配置且可能具有确定性的 Agent 行为和工作流。 有关节点系统的组件和功能的详细说明,请参阅[节点系统文档](../../docs/nodes/README.md)。 ## 🚀 开始使用 有关全面的指南,请参阅[开始使用指南](../../docs/getting-started.md)。 ### 要求 * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (必需) * LLM 提供商(Anthropic、OpenAI 等)的 API 密钥 ### 安装 1. **克隆存储库**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **安装 pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **安装依赖项**: ```bash pnpm install ``` 进行干净的重新安装(当您需要从头开始重新构建时): ```bash pnpm run clean-install ``` 此脚本会删除所有 node_modules、锁定文件,并正确重新安装依赖项。 4. **配置环境**: 根据提供的 `.env.example` 文件创建一个环境文件(`.env` 或 `.env.local`): ```bash # 选项 1:创建 .env.local cp .env.example .env.local # 选项 2:创建 .env cp .env.example .env ``` 然后将您的 API 密钥添加到环境文件中。 5. **启动开发服务器**: ```bash pnpm dev ``` ### 高级功能 | 功能 | 描述 | 文档 | | :------------------- | :-------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------- | | **会话管理** | 对话的隔离、高性能状态管理 | [会话文档](../../docs/architecture/sessions/README.md) | | **编排框架** | 根据上下文控制 Agent 行为和工具可用性 | [编排文档](../../docs/architecture/orchestration/README.md) | | **存储抽象** | 灵活的存储系统,为 KV、Vector 和 Secure 存储提供可插拔的提供商 | [存储文档](../../docs/storage/README.md) | 存储系统目前正在通过键值存储(Memory、Redis、Vercel KV 提供商)和安全的客户端存储进行演进,而向量存储和其他后端正在开发中。 ## 📕 文档 AgentDock 框架的文档可在 [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) 和此存储库的 `/docs/` 文件夹中找到。文档包括: - 开始使用指南 - API 参考 - 节点创建教程 - 集成示例 ## 📂 存储库结构 此存储库包含: 1. **AgentDock Core**:位于 `agentdock-core/` 中的核心框架 2. **开源客户端**:使用 Next.js 构建的完整参考实现,作为 AgentDock Core 框架的消费者。 3. **示例 Agent**:`agents/` 目录中即用型 Agent 配置 您可以在自己的应用程序中独立使用 AgentDock Core,或将此存储库用作构建自己的 Agent 驱动应用程序的起点。 ## 📝 Agent 模板 AgentDock 包含几个预配置的 Agent 模板。在 `agents/` 目录中浏览它们,或阅读[Agent 模板文档](../../docs/agent-templates.md)了解配置详细信息。 ## 🔧 示例实现 示例实现展示了专门的用例和高级功能: | 实现 | 描述 | 状态 | | :-------------------- | :----------------------------------------------------------------------------- | :------- | | **编排的 Agent** | 使用编排根据上下文调整行为的示例 Agent | 可用 | | **认知推理器** | 使用结构化推理和认知工具解决复杂问题 | 可用 | | **Agent 规划器** | 用于设计和实现其他 AI Agent 的专用 Agent | 可用 | | [**代码演练场**](../../docs/roadmap/code-playground.md) | 具有丰富可视化功能的沙盒化代码生成和执行 | 计划中 | ## 🔐 环境配置详细信息 AgentDock 开源客户端需要 LLM 提供商的 API 密钥才能运行。这些密钥在您根据提供的 `.env.example` 文件创建的环境文件(`.env` 或 `.env.local`)中配置。 ### LLM 提供商 API 密钥 添加您的 LLM 提供商 API 密钥(至少需要一个): ```bash # LLM 提供商 API 密钥 - 至少需要一个 ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Anthropic API 密钥 OPENAI_API_KEY=sk-xxxxxxx # OpenAI API 密钥 GEMINI_API_KEY=xxxxxxx # Google Gemini API 密钥 DEEPSEEK_API_KEY=xxxxxxx # DeepSeek API 密钥 GROQ_API_KEY=xxxxxxx # Groq API 密钥 ``` ### API 密钥解析 AgentDock 开源客户端在解析要使用的 API 密钥时遵循优先级顺序: 1. **每个 Agent 的自定义 API 密钥**(通过 UI 中的 Agent 设置进行设置) 2. **全局设置 API 密钥**(通过 UI 中的设置页面进行设置) 3. **环境变量**(来自 .env.local 或部署平台) ### 工具特定的 API 密钥 某些工具还需要自己的 API 密钥: ```bash # 工具特定的 API 密钥 SERPER_API_KEY= # 搜索功能所需 FIRECRAWL_API_KEY= # 更深入的网络搜索所需 ``` 有关环境配置的更多详细信息,请参阅 [`src/types/env.ts`](../../src/types/env.ts) 中的实现。 ### 使用您自己的 API 密钥 (BYOK) 模型 AgentDock 遵循 BYOK (Bring Your Own Key / 自带密钥) 模型: 1. 在应用程序的设置页面中添加您的 API 密钥 2. 或者,通过请求头提供密钥以直接使用 API 3. 密钥使用内置的加密系统安全存储 4. 不会在我们的服务器上共享或存储任何 API 密钥 ## 📦 包管理器 此项目*需要*使用 `pnpm` 进行一致的依赖项管理。不支持 `npm` 和 `yarn`。 ## 💡 您可以构建什么 1. **AI 驱动的应用程序** - 带有任何前端的自定义聊天机器人 - 命令行 AI 助手 - 自动化数据处理流水线 - 后端服务集成 2. **集成能力** - 任何 AI 提供商(OpenAI、Anthropic 等) - 任何前端框架 - 任何后端服务 - 自定义数据源和 API 3. **自动化系统** - 自动化数据处理工作流 - 文档分析流水线 - 自动化报告系统 - 任务自动化 Agent ## 主要特性 | 特性 | 描述 | | :------------------------ | :--------------------------------------------------------------------------------- | | 🔌 **框架无关 (Node.js 后端)** | 核心库与 Node.js 后端堆栈集成。 | | 🧩 **模块化设计** | 从简单的节点构建复杂的系统 | | 🛠️ **可扩展** | 为任何功能创建自定义节点 | | 🔒 **安全** | 用于 API 密钥和数据的内置安全功能 | | 🔑 **BYOK** | 使用您*自己的 API 密钥*用于 LLM 提供商 | | 📦 **自包含** | 核心框架依赖性极小 | | ⚙️ **多步骤连续工具调用** | 支持*复杂的推理链* | | 📊 **结构化日志记录** | 深入了解 Agent 执行情况 | | 🛡️ **强大的错误处理** | 可预测的行为和简化的调试 | | 📝 **TypeScript 优先** | 类型安全和增强的开发人员体验 | | 🌐 **开源客户端** | 包含完整的 Next.js 参考实现 | | 🔄 **编排** | 基于上下文的 Agent 行为*动态控制* | | 💾 **会话管理** | 并发对话的隔离状态 | | 🎮 **可配置的确定性** | 通过节点逻辑/工作流平衡 AI 创造力和可预测性。 | ## 🧰 组件 AgentDock 的模块化架构建立在以下关键组件之上: * **BaseNode**:系统中所有节点的基础 * **AgentNode**:Agent 功能的主要抽象 * **工具和自定义节点**:作为节点实现的可调用功能和自定义逻辑。 * **节点注册表**:管理所有节点类型的注册和检索 * **工具注册表**:管理 Agent 的工具可用性 * **CoreLLM**:与 LLM 提供商交互的统一接口 * **提供商注册表**:管理 LLM 提供商配置 * **错误处理**:处理错误并确保可预测行为的系统 * **日志记录**:用于监控和调试的结构化日志记录系统 * **编排**:根据对话上下文控制工具可用性和行为 * **会话**:管理并发对话之间的状态隔离 有关这些组件的详细技术文档,请参阅[架构概述](../../docs/architecture/README.md)。 ## 🗺️ 路线图 以下是 AgentDock 的开发路线图。此处列出的大多数改进都与核心 AgentDock 框架(`agentdock-core`)有关,该框架目前在本地开发,并在达到稳定版本后将作为版本化的 NPM 包发布。一些路线图项目也可能涉及对开源客户端实现的增强。 | 特性 | 描述 | 类别 | | :----------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- | :----------- | | [**存储抽象层**](../../docs/roadmap/storage-abstraction.md) | 具有可插拔提供商的灵活存储系统 | **进行中** | | [**高级内存系统**](../../docs/roadmap/advanced-memory.md) | 长期上下文管理 | **进行中** | | [**向量存储集成**](../../docs/roadmap/vector-storage.md) | 用于文档和内存的基于嵌入的检索 | **进行中** | | [**AI Agent 评估**](../../docs/roadmap/evaluation-framework.md) | 全面的测试和评估框架 | **进行中** | | [**平台集成**](../../docs/roadmap/platform-integration.md) | 支持 Telegram、WhatsApp 和其他消息传递平台 | **计划中** | | [**多 Agent 协作**](../../docs/roadmap/multi-agent-collaboration.md) | 使 Agent 能够协同工作 | **计划中** | | [**模型上下文协议 (MCP) 集成**](../../docs/roadmap/mcp-integration.md) | 支持通过 MCP 发现和使用外部工具 | **计划中** | | [**语音 AI Agent**](../../docs/roadmap/voice-agents.md) | 通过 AgentNode 使用语音接口和电话号码的 AI Agent | **计划中** | | [**遥测与可追溯性**](../../docs/roadmap/telemetry.md) | 高级日志记录和性能跟踪 | **计划中** | | [**Workflow Runtime & Node 类型**](../../docs/roadmap/workflow-nodes.md) | 核心 runtime、节点类型和复杂自动化编排逻辑 | **计划中** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | 用于扩展 AI Agent 和工作流的全面企业云平台 | **云平台** | | [**自然语言 AI Agent 构建器**](../../docs/roadmap/nl-agent-builder.md) | 可视化构建器 + 自然语言 Agent 和工作流构建 | **云** | | [**Agent 市场**](../../docs/roadmap/agent-marketplace.md) | 可货币化的 Agent 模板 | **云** | ## 👥 贡献 我们欢迎对 AgentDock 的贡献!请参阅 [CONTRIBUTING.md](../../CONTRIBUTING.md) 了解详细的贡献指南。 ## 📜 许可证 AgentDock 根据 [MIT 许可证](../../LICENSE) 发布。 ## ✨ 无限创造,从这里开始! AgentDock 为您构建几乎任何可以想象的 AI 驱动应用程序或自动化提供了基础。我们鼓励您探索该框架,构建创新的 Agent,并回馈社区。让我们一起构建 AI 交互的未来! --- [返回翻译索引](/docs/i18n/README.md) ## AgentDock: Erschaffe grenzenlose Möglichkeiten mit KI-Agenten

AgentDock Logo

## 🌐 README-Übersetzungen [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock ist ein Framework zur Erstellung hochentwickelter KI-Agenten, die komplexe Aufgaben mit **konfigurierbarer Determiniertheit** erledigen. Es besteht aus zwei Hauptkomponenten: 1. **AgentDock Core**: Ein Open-Source, Backend-fokussiertes Framework zum Erstellen und Bereitstellen von KI-Agenten. Es ist *Framework-agnostisch* und *Anbieter-unabhängig* konzipiert, was Ihnen vollständige Kontrolle über die Implementierung Ihres Agenten gibt. 2. **Open Source Client**: Eine vollständige Next.js-Anwendung, die als Referenzimplementierung und Nutzer des AgentDock Core Frameworks dient. Sie können sie unter [https://hub.agentdock.ai](https://hub.agentdock.ai) in Aktion sehen. AgentDock wurde mit TypeScript entwickelt und legt Wert auf *Einfachheit*, *Erweiterbarkeit* und ***konfigurierbare Determiniertheit*** - ideal für die Erstellung zuverlässiger und vorhersagbarer KI-Systeme, die mit minimaler Aufsicht arbeiten können. ## 🧠 Design-Prinzipien AgentDock basiert auf diesen Kernprinzipien: - **Einfachheit zuerst**: Minimaler Codeaufwand zur Erstellung funktionaler Agenten - **Knotenbasierte Architektur (Nodes)**: Alle Fähigkeiten werden als Knoten implementiert - **Werkzeuge als spezialisierte Knoten**: Werkzeuge erweitern das Knotensystem für Agentenfähigkeiten - **Konfigurierbare Determiniertheit**: Steuern Sie die Vorhersagbarkeit des Agentenverhaltens - **Typsicherheit (Type Safety)**: Umfassende TypeScript-Typisierung durchgehend ### Konfigurierbare Determiniertheit ***Konfigurierbare Determiniertheit*** ist ein Eckpfeiler der Design-Philosophie von AgentDock. Sie ermöglicht es, kreative KI-Fähigkeiten mit vorhersagbarem Systemverhalten in Einklang zu bringen: - `AgentNode`s sind inhärent nicht-deterministisch, da LLMs jedes Mal unterschiedliche Antworten generieren können - Workflows können durch *definierte Ausführungspfade für Werkzeuge* deterministischer gestaltet werden - Entwickler können den **Grad der Determiniertheit steuern**, indem sie konfigurieren, welche Teile des Systems LLM-Inferenz nutzen - Selbst mit LLM-Komponenten bleibt das allgemeine Systemverhalten durch strukturierte Werkzeuginteraktionen **vorhersagbar** - Dieser ausgewogene Ansatz ermöglicht sowohl *Kreativität* als auch **Zuverlässigkeit** in Ihren KI-Anwendungen #### Deterministische Workflows AgentDock unterstützt vollständig die deterministischen Workflows, die Sie von typischen Workflow-Buildern kennen. Alle erwarteten vorhersagbaren Ausführungspfade und zuverlässigen Ergebnisse sind verfügbar, mit oder ohne LLM-Inferenz: ```mermaid flowchart LR Input[Eingabe] --> Process[Verarbeitung] Process --> Database[(Datenbank)] Process --> Output[Ausgabe] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Nicht-deterministisches Agentenverhalten Mit AgentDock können Sie auch `AgentNode`s mit LLMs nutzen, wenn Sie mehr Anpassungsfähigkeit benötigen. Die kreativen Ergebnisse können je nach Bedarf variieren, während strukturierte Interaktionsmuster beibehalten werden: ```mermaid flowchart TD Input[Benutzeranfrage] --> Agent[AgentNode] Agent -->|"LLM-Logik (Nicht-deterministisch)"| ToolChoice{Werkzeugauswahl} ToolChoice -->|"Option A"| ToolA[Tiefenrecherche-Werkzeug] ToolChoice -->|"Option B"| ToolB[Datenanalyse-Werkzeug] ToolChoice -->|"Option C"| ToolC[Direkte Antwort] ToolA --> Response[Endgültige Antwort] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Nicht-deterministische Agenten mit deterministischen Sub-Workflows AgentDock bietet Ihnen das ***Beste aus beiden Welten***, indem es nicht-deterministische Agentenintelligenz mit deterministischer Workflow-Ausführung kombiniert: ```mermaid flowchart TD Input[Benutzeranfrage] --> Agent[AgentNode] Agent -->|"LLM-Logik (Nicht-deterministisch)"| FlowChoice{Sub-Workflow-Auswahl} FlowChoice -->|"Entscheidung A"| Flow1[Deterministischer Workflow 1] FlowChoice -->|"Entscheidung B"| Flow2[Deterministischer Workflow 2] FlowChoice -->|"Entscheidung C"| DirectResponse[Antwort generieren] Flow1 --> |"Schritt 1 → 2 → 3 → ... → 200"| Flow1Result[Workflow 1 Ergebnis] Flow2 --> |"Schritt 1 → 2 → 3 → ... → 100"| Flow2Result[Workflow 2 Ergebnis] Flow1Result --> Response[Endgültige Antwort] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Dieser Ansatz ermöglicht es, komplexe, mehrstufige Workflows (die potenziell Hunderte von deterministischen Schritten umfassen, die in Werkzeugen oder als verbundene Knotensequenzen implementiert sind) durch intelligente Agentenentscheidungen aufzurufen. Jeder Workflow wird vorhersagbar ausgeführt, obwohl er durch nicht-deterministische Agentenlogik ausgelöst wird. Für fortgeschrittenere KI-Agenten-Workflows und mehrstufige Verarbeitungspipelines entwickeln wir [AgentDock Pro](../../docs/agentdock-pro.md) – eine leistungsstarke Plattform zur Erstellung, Visualisierung und Ausführung komplexer Agentensysteme. #### Kurz gesagt: Konfigurierbare Determiniertheit Stellen Sie es sich wie Autofahren vor. Manchmal benötigen Sie die Kreativität der KI (z. B. Navigation in der Stadt - nicht-deterministisch), und manchmal benötigen Sie zuverlässige, schrittweise Prozesse (z. B. das Befolgen von Autobahnschildern - deterministisch). AgentDock ermöglicht es Ihnen, Systeme zu bauen, die *beides* nutzen, indem Sie den richtigen Ansatz für jeden Teil einer Aufgabe wählen. Sie erhalten sowohl die Intelligenz der KI *als auch* vorhersagbare Ergebnisse, wo immer dies erforderlich ist. ## 🏗️ Kernarchitektur Das Framework basiert auf einem leistungsstarken, modularen knotenbasierten System, das als Grundlage für die gesamte Agentenfunktionalität dient. Diese Architektur verwendet verschiedene Knotentypen als Bausteine: - **`BaseNode`**: Die grundlegende Klasse, die die Kernschnittstelle und Fähigkeiten für alle Knoten festlegt. - **`AgentNode`**: Ein spezialisierter Kernknoten, der LLM-Interaktionen, Werkzeugnutzung und Agentenlogik orchestriert. - **Werkzeuge & Benutzerdefinierte Knoten**: Entwickler implementieren Agentenfähigkeiten und benutzerdefinierte Logik als Knoten, die `BaseNode` erweitern. Diese Knoten interagieren über verwaltete Registries und können verbunden werden (unter Nutzung der Ports der Kernarchitektur und einer potenziellen Nachrichtenbus), um komplexe, konfigurierbare und potenziell deterministische Agentenverhalten und Workflows zu ermöglichen. Eine detaillierte Erklärung der Komponenten und Fähigkeiten des Knotensystems finden Sie in der [Dokumentation des Knotensystems](../../docs/nodes/README.md). ## 🚀 Erste Schritte Eine umfassende Anleitung finden Sie im [Leitfaden für die ersten Schritte](../../docs/getting-started.md). ### Anforderungen * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Erforderlich) * API-Schlüssel für LLM-Anbieter (Anthropic, OpenAI, etc.) ### Installation 1. **Repository klonen**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **pnpm installieren**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Abhängigkeiten installieren**: ```bash pnpm install ``` Für eine saubere Neuinstallation (wenn Sie von Grund auf neu bauen müssen): ```bash pnpm run clean-install ``` Dieses Skript entfernt alle `node_modules`, Lock-Dateien und installiert die Abhängigkeiten korrekt neu. 4. **Umgebung konfigurieren**: Erstellen Sie eine Umgebungsdatei (`.env` oder `.env.local`) basierend auf der bereitgestellten `.env.example`-Datei: ```bash # Option 1: .env.local erstellen cp .env.example .env.local # Option 2: .env erstellen cp .env.example .env ``` Fügen Sie dann Ihre API-Schlüssel zur Umgebungsdatei hinzu. 5. **Entwicklungsserver starten**: ```bash pnpm dev ``` ### Erweiterte Funktionen | Funktion | Beschreibung | Dokumentation | | :------------------------ | :--------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------- | | **Sitzungsverwaltung** | Isoliertes, performantes Zustandsmanagement für Konversationen | [Sitzungsdokumentation](../../docs/architecture/sessions/README.md) | | **Orchestrierungsframework**| Steuerung des Agentenverhaltens und der Werkzeugverfügbarkeit basierend auf dem Kontext | [Orchestrierungsdokumentation](../../docs/architecture/orchestration/README.md) | | **Speicherabstraktion** | Flexibles Speichersystem mit austauschbaren Anbietern für KV-, Vektor- und sichere Speicherung | [Speicherdokumentation](../../docs/storage/README.md) | Das Speichersystem wird derzeit weiterentwickelt mit Schlüssel-Wert-Speicher (Anbieter Memory, Redis, Vercel KV) und sicherem clientseitigem Speicher, während Vektorspeicher und zusätzliche Backends in Entwicklung sind. ## 📕 Dokumentation Die Dokumentation für das AgentDock Framework ist verfügbar unter [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) und im Ordner `/docs/` dieses Repositories. Die Dokumentation umfasst: - Anleitungen für die ersten Schritte - API-Referenzen - Tutorials zur Knotenerstellung - Integrationsbeispiele ## 📂 Repository-Struktur Dieses Repository enthält: 1. **AgentDock Core**: Das Kernframework befindet sich in `agentdock-core/` 2. **Open Source Client**: Eine vollständige Referenzimplementierung, die mit Next.js erstellt wurde und als Nutzer des AgentDock Core Frameworks dient. 3. **Beispiel-Agenten**: Gebrauchsfertige Agentenkonfigurationen im Verzeichnis `agents/` Sie können AgentDock Core unabhängig in Ihren eigenen Anwendungen verwenden oder dieses Repository als Ausgangspunkt für die Erstellung Ihrer eigenen agentenbasierten Anwendungen nutzen. ## 📝 Agenten-Vorlagen AgentDock enthält mehrere vorkonfigurierte Agenten-Vorlagen. Erkunden Sie sie im Verzeichnis `agents/` oder lesen Sie die [Dokumentation der Agenten-Vorlagen](../../docs/agent-templates.md) für Konfigurationsdetails. ## 🔧 Beispielimplementierungen Beispielimplementierungen zeigen spezialisierte Anwendungsfälle und erweiterte Funktionalität: | Implementierung | Beschreibung | Status | | :-------------------------- | :------------------------------------------------------------------------------------------- | :----------- | | **Orchestrierter Agent** | Beispielagent, der Orchestrierung zur Anpassung des Verhaltens basierend auf Kontext nutzt | Verfügbar | | **Kognitiver Reasoner** | Bewältigt komplexe Probleme mithilfe strukturierter Logik & kognitiver Werkzeuge | Verfügbar | | **Agenten-Planer** | Spezialisierter Agent zum Entwerfen und Implementieren anderer KI-Agenten | Verfügbar | | [**Code Playground (Code-Spielwiese)**](../../docs/roadmap/code-playground.md) | Sandboxed Code-Generierung und -Ausführung mit reichhaltigen Visualisierungsfunktionen | Geplant | ## 🔐 Details zur Umgebungskonfiguration Der AgentDock Open Source Client benötigt API-Schlüssel für LLM-Anbieter, um zu funktionieren. Diese werden in einer Umgebungsdatei (`.env` oder `.env.local`) konfiguriert, die Sie basierend auf der bereitgestellten `.env.example`-Datei erstellen. ### API-Schlüssel von LLM-Anbietern Fügen Sie Ihre API-Schlüssel von LLM-Anbietern hinzu (mindestens einer erforderlich): ```bash # API-Schlüssel von LLM-Anbietern - mindestens einer erforderlich ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Anthropic API-Schlüssel OPENAI_API_KEY=sk-xxxxxxx # OpenAI API-Schlüssel GEMINI_API_KEY=xxxxxxx # Google Gemini API-Schlüssel DEEPSEEK_API_KEY=xxxxxxx # DeepSeek API-Schlüssel GROQ_API_KEY=xxxxxxx # Groq API-Schlüssel ``` ### Auflösung von API-Schlüsseln Der AgentDock Open Source Client folgt einer Prioritätsreihenfolge bei der Auflösung, welcher API-Schlüssel verwendet werden soll: 1. **Benutzerdefinierter API-Schlüssel pro Agent** (über Agenteneinstellungen in der Benutzeroberfläche festgelegt) 2. **Globaler Einstellungs-API-Schlüssel** (über die Einstellungsseite in der Benutzeroberfläche festgelegt) 3. **Umgebungsvariable** (aus `.env.local` oder Bereitstellungsplattform) ### Werkzeugspezifische API-Schlüssel Einige Werkzeuge benötigen ebenfalls eigene API-Schlüssel: ```bash # Werkzeugspezifische API-Schlüssel SERPER_API_KEY= # Erforderlich für Suchfunktionalität FIRECRAWL_API_KEY= # Erforderlich für tiefere Web-Suche ``` Weitere Details zur Umgebungskonfiguration finden Sie in der Implementierung in [`src/types/env.ts`](../../src/types/env.ts). ### Verwenden Sie Ihren eigenen API-Schlüssel (BYOK - Bring Your Own Key) AgentDock folgt einem BYOK (Bring Your Own Key - Verwenden Sie Ihren eigenen Schlüssel)-Modell: 1. Fügen Sie Ihre API-Schlüssel auf der Einstellungsseite der Anwendung hinzu 2. Alternativ können Sie Schlüssel über Anfrage-Header für die direkte API-Nutzung bereitstellen 3. Schlüssel werden mithilfe des integrierten Verschlüsselungssystems sicher gespeichert 4. Keine API-Schlüssel werden geteilt oder auf unseren Servern gespeichert ## 📦 Paketmanager Dieses Projekt *erfordert* die Verwendung von `pnpm` für eine konsistente Abhängigkeitsverwaltung. `npm` und `yarn` werden nicht unterstützt. ## 💡 Was Sie bauen können 1. **KI-gestützte Anwendungen** - Benutzerdefinierte Chatbots mit beliebigem Frontend - Kommandozeilen-KI-Assistenten - Automatisierte Datenverarbeitungspipelines - Integrationen von Backend-Diensten 2. **Integrationsfähigkeiten** - Beliebiger KI-Anbieter (OpenAI, Anthropic, etc.) - Beliebiges Frontend-Framework - Beliebiger Backend-Dienst - Benutzerdefinierte Datenquellen und APIs 3. **Automatisierungssysteme** - Datenverarbeitungs-Workflows - Dokumentenanalyse-Pipelines - Automatisierte Berichtssysteme - Agenten zur Aufgabenautomatisierung ## Hauptmerkmale | Merkmal | Beschreibung | | :----------------------------------- | :------------------------------------------------------------------------------------------- | | 🔌 **Framework-unabhängig (Node.js Backend)** | Kernbibliothek integriert sich in Node.js-Backend-Stacks. | | 🧩 **Modulares Design** | Erstellen Sie komplexe Systeme aus einfachen Knoten | | 🛠️ **Erweiterbar** | Erstellen Sie benutzerdefinierte Knoten für jede Funktionalität | | 🔒 **Sicher** | Integrierte Sicherheitsfunktionen für API-Schlüssel und Daten | | 🔑 **BYOK** | Verwenden Sie Ihre *eigenen API-Schlüssel* für LLM-Anbieter | | 📦 **Eigenständig (Self-contained)** | Kernframework hat minimale Abhängigkeiten | | ⚙️ **Mehrstufige Werkzeugaufrufe (Multi-Step Tool Calls)**| Unterstützung für *komplexe Logikketten* | | 📊 **Strukturierte Protokollierung** | Detaillierte Einblicke in die Agentenausführung | | 🛡️ **Robuste Fehlerbehandlung** | Vorhersagbares Verhalten und vereinfachtes Debugging | | 📝 **TypeScript First** | Typsicherheit und verbesserte Entwicklererfahrung | | 🌐 **Open Source Client** | Vollständige Next.js-Referenzimplementierung enthalten | | 🔄 **Orchestrierung** | *Dynamische Steuerung* des Agentenverhaltens basierend auf dem Kontext | | 💾 **Sitzungsverwaltung** | Isolierter Zustand für gleichzeitige Konversationen | | 🎮 **Konfigurierbare Determiniertheit**| Balancieren Sie KI-Kreativität & Vorhersagbarkeit durch Knotenlogik/Workflows. | ## 🧰 Komponenten Die modulare Architektur von AgentDock basiert auf diesen Schlüsselkomponenten: * **BaseNode**: Die Grundlage für alle Knoten im System * **AgentNode**: Die primäre Abstraktion für Agentenfunktionalität * **Werkzeuge & Benutzerdefinierte Knoten**: Aufrufbare Fähigkeiten und benutzerdefinierte Logik, implementiert als Knoten. * **Knoten-Registry**: Verwaltet die Registrierung und den Abruf aller Knotentypen * **Werkzeug-Registry**: Verwaltet die Verfügbarkeit von Werkzeugen für Agenten * **CoreLLM**: Einheitliche Schnittstelle zur Interaktion mit LLM-Anbietern * **Anbieter-Registry**: Verwaltet Konfigurationen von LLM-Anbietern * **Fehlerbehandlung**: System zur Behandlung von Fehlern und Sicherstellung vorhersagbaren Verhaltens * **Protokollierung (Logging)**: Strukturiertes Protokollierungssystem für Überwachung und Debugging * **Orchestrierung**: Steuert Werkzeugverfügbarkeit und Verhalten basierend auf dem Konversationskontext * **Sitzungen**: Verwaltet die Zustandsisolierung zwischen gleichzeitigen Konversationen Eine detaillierte technische Dokumentation zu diesen Komponenten finden Sie im [Architekturüberblick](../../docs/architecture/README.md). ## 🗺️ Roadmap Unten finden Sie unsere Entwicklungs-Roadmap für AgentDock. Die meisten hier aufgeführten Verbesserungen beziehen sich auf das Kernframework von AgentDock (`agentdock-core`), das derzeit lokal entwickelt wird und als versioniertes NPM-Paket veröffentlicht wird, sobald eine stabile Version erreicht ist. Einige Roadmap-Punkte können auch Verbesserungen an der Open-Source-Client-Implementierung beinhalten. | Merkmal | Beschreibung | Kategorie | | :--------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------ | :-------------- | | [**Speicherabstraktionsschicht**](../../docs/roadmap/storage-abstraction.md) | Flexibles Speichersystem mit austauschbaren Anbietern | **In Arbeit** | | [**Erweiterte Speichersysteme**](../../docs/roadmap/advanced-memory.md) | Langzeit-Kontextmanagement | **In Arbeit** | | [**Integration von Vektorspeichern**](../../docs/roadmap/vector-storage.md) | Embedding-basierter Abruf für Dokumente und Speicher | **In Arbeit** | | [**Evaluierung für KI-Agenten**](../../docs/roadmap/evaluation-framework.md) | Umfassendes Test- und Evaluierungsframework | **In Arbeit** | | [**Plattformintegration**](../../docs/roadmap/platform-integration.md) | Unterstützung für Telegram, WhatsApp und andere Messaging-Plattformen | **Geplant** | | [**Multi-Agenten-Kollaboration**](../../docs/roadmap/multi-agent-collaboration.md)| Ermöglichen, dass Agenten zusammenarbeiten | **Geplant** | | [**Integration des Model Context Protocol (MCP)**](../../docs/roadmap/mcp-integration.md)| Unterstützung für die Erkennung und Nutzung externer Werkzeuge über MCP | **Geplant** | | [**Sprach-KI-Agenten**](../../docs/roadmap/voice-agents.md) | KI-Agenten, die Sprachschnittstellen und Telefonnummern über AgentNode verwenden | **Geplant** | | [**Telemetrie und Rückverfolgbarkeit**](../../docs/roadmap/telemetry.md) | Erweitertes Logging und Leistungsüberwachung | **Geplant** | | [**Workflow Runtime & Node Typen**](../../docs/roadmap/workflow-nodes.md) | Kern-Runtime, Knotentypen und Orchestrierungslogik für komplexe Automatisierungen | **Geplant** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Umfassende Enterprise-Cloud-Plattform zur Skalierung von KI-Agenten & Workflows | **Cloud** | | [**KI-Agenten-Builder in natürlicher Sprache**](../../docs/roadmap/nl-agent-builder.md)| Visueller Builder + Erstellung von Agenten und Workflows in natürlicher Sprache | **Cloud** | | [**Agenten-Marktplatz**](../../docs/roadmap/agent-marketplace.md) | Monetarisierbare Agentenvorlagen | **Cloud** | ## 👥 Mitwirken Wir freuen uns über Beiträge zu AgentDock! Detaillierte Richtlinien zum Mitwirken finden Sie in [CONTRIBUTING.md](../../CONTRIBUTING.md). ## 📜 Lizenz AgentDock wird unter der [MIT-Lizenz](../../LICENSE) veröffentlicht. ## ✨ Erschaffe grenzenlose Möglichkeiten! AgentDock bietet die Grundlage, um nahezu jede KI-gestützte Anwendung oder Automatisierung zu erstellen, die Sie sich vorstellen können. Wir ermutigen Sie, das Framework zu erkunden, innovative Agenten zu bauen und zur Community beizutragen. Lassen Sie uns gemeinsam die Zukunft der KI-Interaktion gestalten! --- [Zurück zum Übersetzungsindex](/docs/i18n/README.md) ## AgentDock: Onbegrensde mogelijkheden met AI-Agenten

AgentDock Logo

## 🌐 README-vertalingen [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock is een framework voor het bouwen van geavanceerde AI-agenten die complexe taken uitvoeren met **configureerbaar determinisme**. Het bestaat uit twee hoofdcomponenten: 1. **AgentDock Core**: Een open-source, backend-first framework voor het bouwen en implementeren van AI-agenten. Het is ontworpen om *framework-agnostisch* en *provider-agnostisch* te zijn, waardoor je volledige controle hebt over de implementatie van je agent. 2. **Open Source Client**: Een volledige Next.js-applicatie die dient als referentie-implementatie en consument van het AgentDock Core-framework. Je kunt het in actie zien op [https://hub.agentdock.ai](https://hub.agentdock.ai) Gebouwd met TypeScript, legt AgentDock de nadruk op *eenvoud*, *uitbreidbaarheid* en ***configureerbaar determinisme***, waardoor het ideaal is voor het bouwen van betrouwbare, voorspelbare AI-systemen die met minimale supervisie kunnen werken. ## 🧠 Ontwerpprincipes AgentDock is gebouwd op deze kernprincipes: - **Eenvoud Eerst**: Minimale code vereist om functionele agenten te creëren - **Op nodes gebaseerde architectuur**: Alle capaciteiten worden geïmplementeerd als nodes - **Tools als Gespecialiseerde Nodes**: Tools breiden het nodesysteem uit voor agentcapaciteiten - **Configureerbaar Determinisme**: Beheer de voorspelbaarheid van agentgedrag - **Typeveiligheid**: Volledige TypeScript-types overal ### Configureerbaar Determinisme ***Configureerbaar determinisme*** is een hoeksteen van de ontwerpfilosofie van AgentDock, waardoor je de creatieve capaciteiten van AI kunt balanceren met voorspelbaar systeemgedrag: - `AgentNode`s zijn inherent niet-deterministisch aangezien LLM's elke keer verschillende reacties kunnen genereren - Workflows kunnen deterministischer worden gemaakt via *gedefinieerde tool-uitvoeringspaden* - Ontwikkelaars kunnen **het niveau van determinisme controleren** door te configureren welke delen van het systeem LLM-inferentie gebruiken - Zelfs met LLM-componenten blijft het algehele systeemgedrag **voorspelbaar** door gestructureerde tool-interacties - Met deze aanpak kunnen zowel *creativiteit* als **betrouwbaarheid** in je AI-applicaties worden bereikt #### Deterministische Workflows AgentDock ondersteunt volledig de deterministische workflows waarmee je vertrouwd bent vanuit typische workflow-bouwers. Alle voorspelbare uitvoeringspaden en betrouwbare resultaten die je verwacht zijn beschikbaar, met of zonder LLM-inferentie: ```mermaid flowchart LR Input[Input] --> Process[Proces] Process --> Database[(Database)] Process --> Output[Output] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Niet-Deterministisch Agentgedrag Met AgentDock kun je ook `AgentNode`s met LLM's gebruiken wanneer je meer aanpassingsvermogen nodig hebt. Creatieve outputs kunnen variëren op basis van je behoeften, terwijl gestructureerde interactiepatronen behouden blijven: ```mermaid flowchart TD Input[Gebruikersquery] --> Agent[AgentNode] Agent -->|"LLM Redenering (Niet-Deterministisch)"| ToolChoice{Toolkeuze} ToolChoice -->|"Optie A"| ToolA[Diepgaande Onderzoekstool] ToolChoice -->|"Optie B"| ToolB[Data-analysetool] ToolChoice -->|"Optie C"| ToolC[Direct Antwoord] ToolA --> Response[Eindantwoord] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Niet-Deterministische Agenten met Deterministische Sub-Workflows AgentDock biedt je het ***beste van twee werelden*** door niet-deterministische agentintelligentie te combineren met deterministische workflow-uitvoering: ```mermaid flowchart TD Input[Gebruikersquery] --> Agent[AgentNode] Agent -->|"LLM Redenering (Niet-Deterministisch)"| FlowChoice{Sub-Workflowkeuze} FlowChoice -->|"Beslissing A"| Flow1[Deterministische Workflow 1] FlowChoice -->|"Beslissing B"| Flow2[Deterministische Workflow 2] FlowChoice -->|"Beslissing C"| DirectResponse[Genereer Antwoord] Flow1 --> |"Stap 1 → 2 → 3 → ... → 200"| Flow1Result[Workflow 1 Resultaat] Flow2 --> |"Stap 1 → 2 → 3 → ... → 100"| Flow2Result[Workflow 2 Resultaat] Flow1Result --> Response[Eindantwoord] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Met deze aanpak kunnen complexe, meerstaps workflows (mogelijk met honderden deterministische stappen geïmplementeerd binnen tools of als sequenties van verbonden nodes) worden aangeroepen door intelligente agentbeslissingen. Elke workflow wordt voorspelbaar uitgevoerd ondanks dat deze wordt getriggerd door niet-deterministische agentredenering. Voor meer geavanceerde AI-agent workflows en multi-stage verwerkingspipelines bouwen we aan [AgentDock Pro](../../docs/agentdock-pro.md) - een krachtig platform voor het bouwen, visualiseren en uitvoeren van complexe agentsystemen. #### Kort samengevat (TL;DR): Configureerbaar Determinisme Vergelijk het met autorijden. Soms heb je de creativiteit van AI nodig (zoals navigeren door stadsstraten - niet-deterministisch), en soms heb je betrouwbare, stapsgewijze processen nodig (zoals het volgen van snelwegborden - deterministisch). Met AgentDock kun je systemen bouwen die *beide* gebruiken, waarbij je de juiste aanpak kiest voor elk deel van een taak. Je krijgt de intelligentie van AI *en* voorspelbare resultaten waar nodig. ## 🏗️ Kernarchitectuur Het framework is gebouwd rond een krachtig, modulair, op nodes gebaseerd systeem, dat dient als basis voor alle agentfunctionaliteit. Deze architectuur gebruikt verschillende node-typen als bouwstenen: - **`BaseNode`**: De fundamentele klasse die de kerninterface en mogelijkheden voor alle nodes vastlegt. - **`AgentNode`**: Een gespecialiseerde kern-node die LLM-interacties, toolgebruik en agentlogica orkestreert. - **Tools en Aangepaste Nodes**: Ontwikkelaars implementeren agentcapaciteiten en aangepaste logica als nodes die `BaseNode` uitbreiden. Deze nodes interageren via beheerde registers en kunnen worden verbonden (gebruikmakend van kernarchitectuurpoorten en een potentiële message bus) om complexe, configureerbare en potentieel deterministische agentgedragingen en workflows mogelijk te maken. Voor een gedetailleerde uitleg van de componenten en mogelijkheden van het nodesysteem, zie de [Node Systeem Documentatie](../../docs/nodes/README.md). ## 🚀 Aan de slag Voor een uitgebreide gids, zie de [Getting Started Gids](../../docs/getting-started.md). ### Vereisten * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Vereist) * API-sleutels voor LLM-providers (Anthropic, OpenAI, etc.) ### Installatie 1. **Kloon de Repository**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Installeer pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Installeer Afhankelijkheden**: ```bash pnpm install ``` Voor een schone herinstallatie (wanneer je vanaf nul moet herbouwen): ```bash pnpm run clean-install ``` Dit script verwijdert alle `node_modules`, lock-bestanden en herinstalleert de afhankelijkheden correct. 4. **Configureer de Omgeving**: Maak een omgevingsbestand (`.env` of `.env.local`) aan op basis van het meegeleverde `.env.example`-bestand: ```bash # Optie 1: Maak .env.local aan cp .env.example .env.local # Optie 2: Maak .env aan cp .env.example .env ``` Voeg vervolgens je API-sleutels toe aan het omgevingsbestand. 5. **Start de Ontwikkelserver**: ```bash pnpm dev ``` ### Geavanceerde Mogelijkheden | Mogelijkheid | Beschrijving | Documentatie | | :----------------------- | :-------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------- | | **Sessiebeheer** | Geïsoleerd, high-performance state management voor conversaties | [Sessiedocumentatie](../../docs/architecture/sessions/README.md) | | **Orkestratieframework** | Controle over agentgedrag en toolbeschikbaarheid op basis van context | [Orkestratiedocumentatie](../../docs/architecture/orchestration/README.md) | | **Opslagabstractie** | Flexibel opslagsysteem met pluggable providers voor KV, Vector en Secure Storage | [Opslagdocumentatie](../../docs/storage/README.md) | Het opslagsysteem evolueert momenteel met key-value opslag (Memory, Redis, Vercel KV providers) en client-side secure storage, terwijl vectoropslag en extra backends in ontwikkeling zijn. ## 📕 Documentatie De documentatie voor het AgentDock-framework is beschikbaar op [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) en in de `/docs/` map van deze repository. De documentatie omvat: - Getting started-gidsen - API-referenties - Tutorials voor het bouwen van nodes - Integratievoorbeelden ## 📂 Repository Structuur Deze repository bevat: 1. **AgentDock Core**: Het kernframework, te vinden in `agentdock-core/` 2. **Open Source Client**: Een volledige referentie-implementatie gebouwd met Next.js, die dient als consument van het AgentDock Core-framework. 3. **Voorbeeldagenten**: Kant-en-klare agentconfiguraties in de `agents/` map Je kunt AgentDock Core onafhankelijk gebruiken in je eigen applicaties, of deze repository gebruiken als startpunt voor het bouwen van je eigen agent-aangedreven applicaties. ## 📝 Agent Templates AgentDock bevat verschillende vooraf geconfigureerde agent templates. Verken ze in de `agents/` map of lees de [Agent Template Documentatie](../../docs/agent-templates.md) voor configuratiedetails. ## 🔧 Voorbeeldimplementaties Voorbeeldimplementaties tonen gespecialiseerde use cases en geavanceerde functionaliteit: | Implementatie | Beschrijving | Status | | :------------------------ | :------------------------------------------------------------------------------------------- | :----------- | | **Georkestreerde Agent** | Voorbeeldagent die orkestratie gebruikt om gedrag aan te passen op basis van context | Beschikbaar | | **Cognitieve Redeneerder**| Pakt complexe problemen aan met gestructureerd redeneren en cognitieve tools | Beschikbaar | | **Agent Planner** | Gespecialiseerde agent voor het ontwerpen en implementeren van andere AI-agenten | Beschikbaar | | [**Code Playground**](../../docs/roadmap/code-playground.md)| In sandbox uitgevoerde codegeneratie en uitvoering met rijke visualisatiemogelijkheden | Gepland | ## 🔐 Omgevingsconfiguratie Details De AgentDock Open Source Client vereist API-sleutels voor LLM-providers om te functioneren. Deze worden geconfigureerd in een omgevingsbestand (`.env` of `.env.local`) dat je aanmaakt op basis van het meegeleverde `.env.example`-bestand. ### LLM Provider API-sleutels Voeg je LLM-provider API-sleutels toe (minimaal één vereist): ```bash # LLM Provider API Sleutels - minimaal één vereist ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Anthropic API Sleutel OPENAI_API_KEY=sk-xxxxxxx # OpenAI API Sleutel GEMINI_API_KEY=xxxxxxx # Google Gemini API Sleutel DEEPSEEK_API_KEY=xxxxxxx # DeepSeek API Sleutel GROQ_API_KEY=xxxxxxx # Groq API Sleutel ``` ### API-sleutel Resolutie De AgentDock Open Source Client volgt een prioriteitsvolgorde bij het bepalen welke API-sleutel te gebruiken: 1. **Aangepaste API-sleutel per agent** (ingesteld via agentinstellingen in de UI) 2. **Globale instellingen API-sleutel** (ingesteld via de instellingenpagina in de UI) 3. **Omgevingsvariabele** (van `.env.local` of implementatieplatform) ### Tool-Specifieke API-sleutels Sommige tools vereisen ook hun eigen API-sleutels: ```bash # Tool-Specifieke API Sleutels SERPER_API_KEY= # Vereist voor zoekfunctionaliteit FIRECRAWL_API_KEY= # Vereist voor diepere web scraping ``` Voor meer details over omgevingsconfiguratie, zie de implementatie in [`src/types/env.ts`](../../src/types/env.ts). ### Je Eigen API-sleutels Gebruiken (BYOK) AgentDock volgt een BYOK (Bring Your Own Key) model: 1. Voeg je API-sleutels toe op de instellingenpagina van de applicatie 2. Alternatief, lever sleutels via request headers voor direct API-gebruik 3. Sleutels worden veilig opgeslagen met het ingebouwde encryptiesysteem 4. Er worden geen API-sleutels gedeeld of opgeslagen op onze servers ## 📦 Pakketbeheerder Dit project *vereist* het gebruik van `pnpm` voor consistent afhankelijkheidsbeheer. `npm` en `yarn` worden niet ondersteund. ## 💡 Wat Je Kunt Bouwen 1. **AI-Aangedreven Applicaties** - Aangepaste chatbots met elke frontend - Command-line AI-assistenten - Geautomatiseerde dataverwerkingspipelines - Backend service-integraties 2. **Integratiemogelijkheden** - Elke AI-provider (OpenAI, Anthropic, etc.) - Elk frontend framework - Elke backend service - Aangepaste databronnen en API's 3. **Automatiseringssystemen** - Dataverwerkingsworkflows - Documentanalyse pipelines - Geautomatiseerde rapportagesystemen - Taakautomatiseringsagenten ## Kernfuncties | Functie | Beschrijving | | :---------------------------- | :------------------------------------------------------------------------------------------- | | 🔌 **Framework-Agnostisch (Node.js Backend)**| De kernbibliotheek integreert met Node.js backend stacks. | | 🧩 **Modulair Ontwerp** | Bouw complexe systemen van eenvoudige nodes | | 🛠️ **Uitbreidbaar** | Creëer aangepaste nodes voor elke functionaliteit | | 🔒 **Veilig** | Ingebouwde beveiligingsfuncties voor API-sleutels en data | | 🔑 **BYOK** | Gebruik je *eigen API-sleutels* voor LLM-providers | | 📦 **Zelfstandig** | Het kernframework kent slechts weinig afhankelijkheden | | ⚙️ **Multi-Step Tool Calls** | Ondersteuning voor *complexe redeneerketens* | | 📊 **Gestructureerde Logging**| Gedetailleerde inzichten in agentuitvoering | | 🛡️ **Robuuste Foutafhandeling**| Voorspelbaar gedrag en vereenvoudigde debugging | | 📝 **TypeScript Eerst** | Typeveiligheid en verbeterde ontwikkelaarservaring | | 🌐 **Open Source Client** | Bevat volledige Next.js referentie-implementatie | | 🔄 **Orkestratie** | *Dynamische controle* over agentgedrag op basis van context | | 💾 **Sessiebeheer** | Geïsoleerde state voor gelijktijdige conversaties | | 🎮 **Configureerbaar Determinisme**| Balanceer AI-creativiteit en voorspelbaarheid via node/workflow-logica. | ## 🧰 Componenten De modulaire architectuur van AgentDock is gebouwd op deze kerncomponenten: * **BaseNode**: De basis voor alle nodes in het systeem * **AgentNode**: De hoofdabstractie voor agentfunctionaliteit * **Tools en Aangepaste Nodes**: Aanroepbare capaciteiten en aangepaste logica geïmplementeerd als nodes. * **Node Registry**: Beheert de registratie en het ophalen van alle node-typen * **Tool Registry**: Beheert de beschikbaarheid van tools voor agenten * **CoreLLM**: Uniforme interface voor interactie met LLM-providers * **Provider Registry**: Beheert LLM-providerconfiguraties * **Foutafhandeling**: Systeem voor het afhandelen van fouten en het waarborgen van voorspelbaar gedrag * **Logging**: Gestructureerd loggingsysteem voor monitoring en debugging * **Orkestratie**: Controleert toolbeschikbaarheid en gedrag op basis van conversatiecontext * **Sessies**: Beheert state-isolatie tussen gelijktijdige conversaties Voor gedetailleerde technische documentatie over deze componenten, zie het [Architectuuroverzicht](../../docs/architecture/README.md). ## 🗺️ Roadmap Hieronder staat onze ontwikkelingsroadmap voor AgentDock. De meeste hier genoemde verbeteringen hebben betrekking op het AgentDock-kernframework (`agentdock-core`), dat momenteel lokaal wordt ontwikkeld en als een geversioneerd NPM-pakket zal worden gepubliceerd zodra een stabiele release is bereikt. Sommige roadmap-items kunnen ook verbeteringen aan de open-source client-implementatie met zich meebrengen. | Functie | Beschrijving | Categorie | | :------------------------------------------------------------------------ | :---------------------------------------------------------------------------------------------- | :------------- | | [**Opslagabstractielaag**](../../docs/roadmap/storage-abstraction.md) | Flexibel opslagsysteem met pluggable providers | **In Uitvoering**| | [**Geavanceerde Geheugensystemen**](../../docs/roadmap/advanced-memory.md) | Lange-termijn contextbeheer | **In Uitvoering**| | [**Vector Opslag Integratie**](../../docs/roadmap/vector-storage.md) | Embedding-gebaseerde retrieval voor documenten en geheugen | **In Uitvoering**| | [**Evaluatie voor AI-Agenten**](../../docs/roadmap/evaluation-framework.md) | Uitgebreid test- en evaluatieframework | **In Uitvoering**| | [**Platform Integratie**](../../docs/roadmap/platform-integration.md) | Ondersteuning voor Telegram, WhatsApp en andere berichtenplatforms | **Gepland** | | [**Multi-Agent Samenwerking**](../../docs/roadmap/multi-agent-collaboration.md)| Agenten laten samenwerken | **Gepland** | | [**Model Context Protocol (MCP) Integratie**](../../docs/roadmap/mcp-integration.md)| Ondersteuning voor het ontdekken en gebruiken van externe tools via MCP | **Gepland** | | [**Voice AI Agenten**](../../docs/roadmap/voice-agents.md) | AI-agenten die spraakinterfaces en telefoonnummers gebruiken via AgentNode | **Gepland** | | [**Telemetrie en Traceerbaarheid**](../../docs/roadmap/telemetry.md) | Geavanceerde logging en prestatietracering | **Gepland** | | [**Workflow Runtime & Node Types**](../../docs/roadmap/workflow-nodes.md) | Kern runtime, node types en orkestratielogica voor complexe automatiseringen | **Gepland** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Uitgebreid enterprise cloud platform voor het schalen van AI-agenten & workflows | **Cloud** | | [**Natuurlijke Taal AI Agent Bouwer**](../../docs/roadmap/nl-agent-builder.md)| Visuele bouwer + natuurlijke taal agent & workflow constructie | **Cloud** | | [**Agent Marktplaats**](../../docs/roadmap/agent-marketplace.md) | Monetiseerbare agent templates | **Cloud** | ## 👥 Bijdragen We verwelkomen bijdragen aan AgentDock! Zie [CONTRIBUTING.md](../../CONTRIBUTING.md) voor gedetailleerde bijdragerichtlijnen. ## 📜 Licentie AgentDock wordt uitgebracht onder de [MIT Licentie](../../LICENSE). ## ✨ Grenzeloze mogelijkheden! AgentDock biedt de basis om vrijwel elke AI-aangedreven applicatie of automatisering te bouwen die je je kunt voorstellen. We moedigen je aan om het framework te verkennen, innovatieve agenten te bouwen en bij te dragen aan de community. Laten we samen de toekomst van AI-interactie bouwen! --- [Terug naar Vertalingsindex](/docs/i18n/README.md) ## AgentDock : Créez sans limites avec des Agents IA

AgentDock Logo

## 🌐 Traductions du README [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock est un framework pour construire des agents IA sophistiqués qui réalisent des tâches complexes avec un **déterminisme configurable**. Il se compose de deux composants principaux : 1. **AgentDock Core** : Un framework open-source, axé sur le backend, pour construire et déployer des agents IA. Il est conçu pour être *indépendant du framework* et *indépendant du fournisseur*, vous donnant un contrôle complet sur l'implémentation de votre agent. 2. **Client Open Source** : Une application Next.js complète qui sert d'implémentation de référence et de consommateur du framework AgentDock Core. Vous pouvez le voir en action sur [https://hub.agentdock.ai](https://hub.agentdock.ai) Construit avec TypeScript, AgentDock met l'accent sur la *simplicité*, l'*extensibilité* et le ***déterminisme configurable*** - ce qui le rend idéal pour construire des systèmes IA fiables et prévisibles pouvant fonctionner avec une supervision minimale. ## 🧠 Principes de Conception AgentDock est construit sur ces principes fondamentaux : - **La Simplicité d'abord** : Code minimal requis pour créer des agents fonctionnels - **Architecture Basée sur les Nœuds** : Toutes les capacités sont implémentées en tant que nœuds - **Outils en tant que Nœuds Spécialisés** : Les outils étendent le système de nœuds pour les capacités de l'agent - **Déterminisme Configurable** : Contrôlez la prévisibilité du comportement de l'agent - **Sécurité des Types** : Types TypeScript complets partout ### Déterminisme Configurable Le ***déterminisme configurable*** est une pierre angulaire de la philosophie de conception d'AgentDock, vous permettant d'équilibrer les capacités créatives de l'IA avec un comportement système prévisible : - Les AgentNodes sont intrinsèquement non déterministes car les LLMs peuvent générer des réponses différentes à chaque fois - Les workflows peuvent être rendus plus déterministes grâce à des *chemins d'exécution d'outils définis* - Les développeurs peuvent **contrôler le niveau de déterminisme** en configurant quelles parties du système utilisent l'inférence LLM - Même avec des composants LLM, le comportement global du système reste **prévisible** grâce à des interactions d'outils structurées - Cette approche équilibrée permet à la fois la *créativité* et la **fiabilité** dans vos applications IA #### Workflows Déterministes AgentDock prend entièrement en charge les workflows déterministes que vous connaissez des constructeurs de workflows classiques. Tous les chemins d'exécution prévisibles et les résultats fiables que vous attendez sont disponibles, avec ou sans inférence LLM : ```mermaid flowchart LR Input[Entrée] --> Process[Traitement] Process --> Database[(Base de données)] Process --> Output[Sortie] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Comportement d'Agent Non Déterministe Avec AgentDock, vous pouvez également exploiter les AgentNodes avec des LLMs lorsque vous avez besoin de plus d'adaptabilité. Les sorties créatives peuvent varier en fonction de vos besoins, tout en maintenant des modèles d'interaction structurés : ```mermaid flowchart TD Input[Requête Utilisateur] --> Agent[AgentNode] Agent -->|"Raisonnement LLM (Non Déterministe)"| ToolChoice{Sélection d'Outil} ToolChoice -->|"Option A"| ToolA[Outil Recherche Approfondie] ToolChoice -->|"Option B"| ToolB[Outil Analyse de Données] ToolChoice -->|"Option C"| ToolC[Réponse Directe] ToolA --> Response[Réponse Finale] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Agents Non Déterministes avec Sous-Workflows Déterministes AgentDock vous offre le ***meilleur des deux mondes*** en combinant l'intelligence d'agent non déterministe avec l'exécution de workflow déterministe : ```mermaid flowchart TD Input[Requête Utilisateur] --> Agent[AgentNode] Agent -->|"Raisonnement LLM (Non Déterministe)"| FlowChoice{Sélection Sous-Workflow} FlowChoice -->|"Décision A"| Flow1[Workflow Déterministe 1] FlowChoice -->|"Décision B"| Flow2[Workflow Déterministe 2] FlowChoice -->|"Décision C"| DirectResponse[Générer Réponse] Flow1 --> |"Étape 1 → 2 → 3 → ... → 200"| Flow1Result[Résultat Workflow 1] Flow2 --> |"Étape 1 → 2 → 3 → ... → 100"| Flow2Result[Résultat Workflow 2] Flow1Result --> Response[Réponse Finale] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Cette approche permet à des workflows complexes à plusieurs étapes (impliquant potentiellement des centaines d'étapes déterministes implémentées dans des outils ou en tant que séquences de nœuds connectés) d'être invoqués par des décisions d'agents intelligents. Chaque workflow s'exécute de manière prévisible malgré son déclenchement par un raisonnement d'agent non déterministe. Pour des workflows d'agents IA plus avancés et des pipelines de traitement multi-étapes, nous construisons [AgentDock Pro](../../docs/agentdock-pro.md) - une plateforme puissante pour créer, visualiser et exécuter des systèmes d'agents complexes. #### En résumé : le Déterminisme Configurable Imaginez cela comme la conduite automobile. Parfois, vous avez besoin de la créativité de l'IA (comme naviguer dans les rues d'une ville - non déterministe), et parfois vous avez besoin de processus fiables, étape par étape (comme suivre les panneaux d'autoroute - déterministe). AgentDock vous permet de construire des systèmes qui utilisent *les deux*, en choisissant la bonne approche pour chaque partie d'une tâche. Vous profitez à la fois de l'intelligence de l'IA *et* de résultats prévisibles quand vous en avez besoin. ## 🏗️ Architecture de Base Le framework est construit autour d'un système puissant et modulaire basé sur les nœuds, servant de fondation à toutes les fonctionnalités de l'agent. Cette architecture utilise des types de nœuds distincts comme blocs de construction : - **`BaseNode`** : La classe fondamentale établissant l'interface et les capacités de base pour tous les nœuds. - **`AgentNode`** : Un nœud central spécialisé orchestrant les interactions LLM, l'utilisation d'outils et la logique de l'agent. - **Outils & Nœuds Personnalisés** : Les développeurs implémentent les capacités de l'agent et la logique personnalisée en tant que nœuds étendant `BaseNode`. Ces nœuds interagissent via des registres gérés et peuvent être connectés (en tirant parti des ports de l'architecture de base et d'un potentiel bus de messages) pour permettre des comportements et des workflows d'agents complexes, configurables et potentiellement déterministes. Pour une explication détaillée des composants et des capacités du système de nœuds, veuillez consulter la [Documentation du Système de Nœuds](../../docs/nodes/README.md). ## 🚀 Pour Commencer Pour un guide complet, consultez le [Guide de Démarrage](../../docs/getting-started.md). ### Prérequis * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Requis) * Clés API pour les fournisseurs LLM (Anthropic, OpenAI, etc.) ### Installation 1. **Cloner le Dépôt** : ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Installer pnpm** : ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Installer les Dépendances** : ```bash pnpm install ``` Pour une réinstallation propre (lorsque vous devez reconstruire à partir de zéro) : ```bash pnpm run clean-install ``` Ce script supprime tous les node_modules, les fichiers de verrouillage et réinstalle correctement les dépendances. 4. **Configurer l'Environnement** : Créez un fichier d'environnement (`.env` ou `.env.local`) basé sur `.env.example` : ```bash # Option 1: Créer .env.local cp .env.example .env.local # Option 2: Créer .env cp .env.example .env ``` Ajoutez ensuite vos clés API au fichier d'environnement. 5. **Démarrer le Serveur de Développement** : ```bash pnpm dev ``` ### Capacités Avancées | Capacité | Description | Documentation | | :---------------------- | :-------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------- | | **Gestion de Session** | Gestion d'état isolée et performante pour les conversations | [Documentation Session](../../docs/architecture/sessions/README.md) | | **Framework d'Orchestration** | Contrôle du comportement de l'agent et de la disponibilité des outils selon le contexte | [Documentation Orchestration](../../docs/architecture/orchestration/README.md) | | **Abstraction de Stockage** | Système de stockage flexible avec fournisseurs enfichables pour KV, Vecteur et Sécurisé | [Documentation Stockage](../../docs/storage/README.md) | Le système de stockage évolue actuellement avec le stockage clé-valeur (fournisseurs Memory, Redis, Vercel KV) et le stockage sécurisé côté client, tandis que le stockage vectoriel et des backends supplémentaires sont en développement. ## 📕 Documentation La documentation du framework AgentDock est disponible sur [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) et dans le dossier `/docs/` de ce dépôt. La documentation comprend : - Guides de démarrage - Références API - Tutoriels de création de nœuds - Exemples d'intégration ## 📂 Structure du Dépôt Ce dépôt contient : 1. **AgentDock Core** : Le framework principal situé dans `agentdock-core/` 2. **Client Open Source** : Une implémentation de référence complète construite avec Next.js, servant de consommateur du framework AgentDock Core. 3. **Agents d'Exemple** : Configurations d'agents prêtes à l'emploi dans le répertoire `agents/` Vous pouvez utiliser AgentDock Core indépendamment dans vos propres applications, ou utiliser ce dépôt comme point de départ pour construire vos propres applications alimentées par des agents. ## 📝 Modèles d'Agents AgentDock inclut plusieurs modèles d'agents pré-configurés. Explorez-les dans le répertoire `agents/` ou lisez la [Documentation des Modèles d'Agents](../../docs/agent-templates.md) pour les détails de configuration. ## 🔧 Implémentations d'Exemple Les implémentations d'exemple présentent des cas d'utilisation spécialisés et des fonctionnalités avancées : | Implémentation | Description | Statut | | :--------------------- | :--------------------------------------------------------------------------- | :---------- | | **Agent Orchestré** | Agent d'exemple utilisant l'orchestration pour adapter le comportement au contexte | Disponible | | **Raisonnement Cognitif** | Aborde des problèmes complexes en utilisant un raisonnement structuré & outils cognitifs | Disponible | | **Planificateur d'Agent** | Agent spécialisé pour concevoir et implémenter d'autres agents IA | Disponible | | [**Environnement de développement isolé (Code Playground)**](../../docs/roadmap/code-playground.md) | Génération et exécution de code en sandbox avec capacités de visualisation riches | Planifié | ## 🔐 Détails de Configuration de l'Environnement Le Client Open Source AgentDock nécessite des clés API pour les fournisseurs LLM pour fonctionner. Celles-ci sont configurées dans un fichier d'environnement (`.env` ou `.env.local`) que vous créez basé sur le fichier `.env.example` fourni. ### Clés API des Fournisseurs LLM Ajoutez vos clés API de fournisseur LLM (au moins une est requise) : ```bash # Clés API Fournisseur LLM - au moins une est requise ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Clé API Anthropic OPENAI_API_KEY=sk-xxxxxxx # Clé API OpenAI GEMINI_API_KEY=xxxxxxx # Clé API Google Gemini DEEPSEEK_API_KEY=xxxxxxx # Clé API DeepSeek GROQ_API_KEY=xxxxxxx # Clé API Groq ``` ### Résolution des Clés API Le Client Open Source AgentDock suit un ordre de priorité lors de la résolution de la clé API à utiliser : 1. **Clé API personnalisée par agent** (définie via les paramètres de l'agent dans l'interface utilisateur) 2. **Clé API des paramètres globaux** (définie via la page des paramètres dans l'interface utilisateur) 3. **Variable d'environnement** (depuis .env.local ou la plateforme de déploiement) ### Clés API Spécifiques aux Outils Certains outils nécessitent également leurs propres clés API : ```bash # Clés API Spécifiques aux Outils SERPER_API_KEY= # Requis pour la fonctionnalité de recherche FIRECRAWL_API_KEY= # Requis pour une recherche web plus approfondie ``` Pour plus de détails sur la configuration de l'environnement, consultez l'implémentation dans [`src/types/env.ts`](../../src/types/env.ts). ### Utiliser Vos Propres Clés API (BYOK) AgentDock suit un modèle BYOK (Bring Your Own Key, apportez votre propre clé): 1. Ajoutez vos clés API dans la page des paramètres de l'application 2. Alternativement, fournissez les clés via les en-têtes de requête pour une utilisation directe de l'API 3. Les clés sont stockées de manière sécurisée en utilisant le système de chiffrement intégré 4. Aucune clé API n'est partagée ou stockée sur nos serveurs ## 📦 Gestionnaire de Paquets Ce projet *requiert* l'utilisation de `pnpm` pour une gestion cohérente des dépendances. `npm` et `yarn` ne sont pas pris en charge. ## 💡 Ce Que Vous Pouvez Construire 1. **Applications Alimentées par l'IA** - Chatbots personnalisés avec n'importe quel frontend - Assistants IA en ligne de commande - Pipelines de traitement de données automatisés - Intégrations de services backend 2. **Capacités d'Intégration** - Tout fournisseur IA (OpenAI, Anthropic, etc.) - Tout framework frontend - Tout service backend - Sources de données et API personnalisées 3. **Systèmes d'Automatisation** - Workflows de traitement de données - Pipelines d'analyse de documents - Systèmes de reporting automatisés - Agents d'automatisation de tâches ## Fonctionnalités Clés | Fonctionnalité | Description | | :---------------------------- | :---------------------------------------------------------------------------- | | 🔌 **Agnostique du Framework (Backend Node.js)** | La bibliothèque principale s'intègre aux stacks backend Node.js. | | 🧩 **Conception Modulaire** | Construisez des systèmes complexes à partir de nœuds simples | | 🛠️ **Extensible** | Créez des nœuds personnalisés pour n'importe quelle fonctionnalité | | 🔒 **Sécurisé** | Fonctionnalités de sécurité intégrées pour les clés API et les données | | 🔑 **BYOK** | Utilisez vos *propres clés API* pour les fournisseurs LLM | | 📦 **Auto-suffisant** | Le framework principal a des dépendances minimales | | ⚙️ **Appels d'Outils Multi-Étapes** | Prise en charge des *chaînes de raisonnement complexes* | | 📊 **Journalisation Structurée** | Informations détaillées sur l'exécution de l'agent | | 🛡️ **Gestion Robuste des Erreurs**| Comportement prévisible et débogage simplifié | | 📝 **TypeScript d'Abord** | Sécurité des types et expérience développeur améliorée | | 🌐 **Client Open Source** | Implémentation de référence Next.js complète incluse | | 🔄 **Orchestration** | *Contrôle dynamique* du comportement de l'agent basé sur le contexte | | 💾 **Gestion de Session** | État isolé pour les conversations concurrentes | | 🎮 **Déterminisme Configurable** | Équilibrez créativité IA & prévisibilité via logique de nœud/workflows. | ## 🧰 Composants L'architecture modulaire d'AgentDock est construite sur ces composants clés : * **BaseNode** : La fondation pour tous les nœuds du système * **AgentNode** : L'abstraction principale pour la fonctionnalité de l'agent * **Outils & Nœuds Personnalisés** : Capacités appelables et logique personnalisée implémentées en tant que nœuds. * **Registre de Nœuds** : Gère l'enregistrement et la récupération de tous les types de nœuds * **Registre d'Outils** : Gère la disponibilité des outils pour les agents * **CoreLLM** : Interface unifiée pour interagir avec les fournisseurs LLM * **Registre de Fournisseurs** : Gère les configurations des fournisseurs LLM * **Gestion des Erreurs** : Système pour gérer les erreurs et assurer un comportement prévisible * **Journalisation** : Système de journalisation structurée pour la surveillance et le débogage * **Orchestration** : Contrôle la disponibilité des outils et le comportement en fonction du contexte de la conversation * **Sessions** : Gère l'isolation de l'état entre les conversations concurrentes Pour une documentation technique détaillée sur ces composants, consultez la [Vue d'Ensemble de l'Architecture](../../docs/architecture/README.md). ## 🗺️ Feuille de Route Voici notre feuille de route de développement pour AgentDock. La plupart des améliorations listées ici concernent le framework AgentDock principal (`agentdock-core`), qui est actuellement développé localement et sera publié en tant que paquet NPM versionné une fois qu'il aura atteint une version stable. Certains éléments de la feuille de route peuvent également impliquer des améliorations de l'implémentation du client open-source. | Fonctionnalité | Description | Catégorie | | :----------------------------------------------------------------- | :-------------------------------------------------------------------------------- | :-------------- | | [**Couche d'Abstraction de Stockage**](../../docs/roadmap/storage-abstraction.md) | Système de stockage flexible avec fournisseurs enfichables | **En cours** | | [**Systèmes de Mémoire Avancés**](../../docs/roadmap/advanced-memory.md) | Gestion du contexte à long terme | **En cours** | | [**Intégration Stockage Vectoriel**](../../docs/roadmap/vector-storage.md) | Récupération basée sur les embeddings pour les documents et la mémoire | **En cours** | | [**Évaluation pour Agents IA**](../../docs/roadmap/evaluation-framework.md) | Framework complet de test et d'évaluation | **En cours** | | [**Intégration Plateforme**](../../docs/roadmap/platform-integration.md) | Prise en charge de Telegram, WhatsApp et autres plateformes de messagerie | **Planifié** | | [**Collaboration Multi-Agents**](../../docs/roadmap/multi-agent-collaboration.md) | Permettre aux agents de travailler ensemble | **Planifié** | | [**Intégration Model Context Protocol (MCP)**](../../docs/roadmap/mcp-integration.md) | Prise en charge de la découverte et de l'utilisation d'outils externes via MCP | **Planifié** | | [**Agents IA Vocaux**](../../docs/roadmap/voice-agents.md) | Agents IA utilisant des interfaces vocales et numéros de téléphone via AgentNode | **Planifié** | | [**Télémétrie et Traçabilité**](../../docs/roadmap/telemetry.md) | Journalisation avancée et suivi des performances | **Planifié** | | [**Workflow Runtime & Node Types**](../../docs/roadmap/workflow-nodes.md) | Runtime principal, types de nœuds et logique d'orchestration pour automatisations complexes | **Planifié** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Plateforme cloud d'entreprise complète pour la mise à l'échelle des agents IA et des workflows | **Cloud** | | [**Constructeur d'Agent IA en Langage Naturel**](../../docs/roadmap/nl-agent-builder.md) | Constructeur visuel + construction d'agent et workflow en langage naturel | **Cloud** | | [**Place de Marché d'Agents**](../../docs/roadmap/agent-marketplace.md) | Modèles d'agents monétisables | **Cloud** | ## 👥 Contribuer Nous accueillons les contributions à AgentDock ! Veuillez consulter le [CONTRIBUTING.md](../../CONTRIBUTING.md) pour des directives de contribution détaillées. ## 📜 Licence AgentDock est publié sous la [Licence MIT](../../LICENSE). ## ✨ Créez sans limites ! AgentDock fournit la base pour construire presque n'importe quelle application ou automatisation alimentée par l'IA que vous pouvez imaginer. Nous vous encourageons à explorer le framework, à construire des agents innovants et à contribuer à la communauté. Construisons ensemble l'avenir de l'interaction IA ! --- [Retour à l'index des traductions](/docs/i18n/README.md) ## AgentDock: Δημιουργήστε Απεριόριστες Δυνατότητες με Πράκτορες AI

AgentDock Logo

## 🌐 Μεταφράσεις README [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) Το AgentDock είναι ένα framework για την κατασκευή εξελιγμένων πρακτόρων AI που εκτελούν πολύπλοκες εργασίες με **διαμορφώσιμο ντετερμινισμό**. Αποτελείται από δύο κύρια συστατικά: 1. **AgentDock Core**: Ένα framework ανοιχτού κώδικα, επικεντρωμένο στο backend, για την κατασκευή και την ανάπτυξη πρακτόρων AI. Είναι σχεδιασμένο να είναι *ανεξάρτητο από το framework* και *ανεξάρτητο από τον πάροχο*, δίνοντάς σας πλήρη έλεγχο στην υλοποίηση του πράκτορά σας. 2. **Open Source Client**: Μια πλήρης εφαρμογή Next.js που χρησιμεύει ως υλοποίηση αναφοράς και καταναλωτής του framework AgentDock Core. Μπορείτε να το δείτε σε δράση στο [https://hub.agentdock.ai](https://hub.agentdock.ai) Κατασκευασμένο με TypeScript, το AgentDock δίνει έμφαση στην *απλότητα*, την *επεκτασιμότητα* και τον ***διαμορφώσιμο ντετερμινισμό***, καθιστώντας το ιδανικό για την κατασκευή αξιόπιστων, προβλέψιμων συστημάτων AI που μπορούν να λειτουργούν με ελάχιστη επίβλεψη. ## 🧠 Αρχές Σχεδιασμού Το AgentDock βασίζεται σε αυτές τις θεμελιώδεις αρχές: - **Πρώτα η Απλότητα**: Ελάχιστος απαιτούμενος κώδικας για τη δημιουργία λειτουργικών πρακτόρων - **Αρχιτεκτονική Βασισμένη σε Κόμβους (Nodes)**: Όλες οι δυνατότητες υλοποιούνται ως κόμβοι - **Εργαλεία ως Εξειδικευμένοι Κόμβοι**: Τα εργαλεία επεκτείνουν το σύστημα κόμβων για τις δυνατότητες του πράκτορα - **Διαμορφώσιμος Ντετερμινισμός**: Έλεγχος της προβλεψιμότητας της συμπεριφοράς του πράκτορα - **Ασφάλεια Τύπων (Type Safety)**: Πλήρεις τύποι TypeScript παντού ### Διαμορφώσιμος Ντετερμινισμός Ο ***διαμορφώσιμος ντετερμινισμός*** αποτελεί ακρογωνιαίο λίθο της φιλοσοφίας σχεδιασμού του AgentDock, επιτρέποντάς σας να ισορροπήσετε τις δημιουργικές δυνατότητες της AI με την προβλέψιμη συμπεριφορά του συστήματος: - Οι `AgentNode` είναι εγγενώς μη ντετερμινιστικοί καθώς τα LLM μπορούν να παράγουν διαφορετικές απαντήσεις κάθε φορά - Οι ροές εργασίας (Workflows) μπορούν να γίνουν πιο ντετερμινιστικές μέσω *καθορισμένων διαδρομών εκτέλεσης εργαλείων* - Οι προγραμματιστές μπορούν να **ελέγχουν το επίπεδο ντετερμινισμού** διαμορφώνοντας ποια μέρη του συστήματος χρησιμοποιούν την εξαγωγή συμπερασμάτων LLM - Ακόμη και με συστατικά LLM, η συνολική συμπεριφορά του συστήματος παραμένει **προβλέψιμη** μέσω δομημένων αλληλεπιδράσεων εργαλείων - Αυτή η ισορροπημένη προσέγγιση επιτρέπει τόσο τη *δημιουργικότητα* όσο και την **αξιοπιστία** στις εφαρμογές σας AI #### Ντετερμινιστικές Ροές Εργασίας Το AgentDock υποστηρίζει πλήρως τις ντετερμινιστικές ροές εργασίας με τις οποίες είστε εξοικειωμένοι από τους τυπικούς κατασκευαστές ροών εργασίας. Όλες οι προβλέψιμες διαδρομές εκτέλεσης και τα αξιόπιστα αποτελέσματα που περιμένετε είναι διαθέσιμα, με ή χωρίς εξαγωγή συμπερασμάτων LLM: ```mermaid flowchart LR Input[Είσοδος] --> Process[Διαδικασία] Process --> Database[(Βάση Δεδομένων)] Process --> Output[Έξοδος] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Μη Ντετερμινιστική Συμπεριφορά Πράκτορα Με το AgentDock, μπορείτε επίσης να αξιοποιήσετε τους `AgentNode` με LLM όταν χρειάζεστε μεγαλύτερη προσαρμοστικότητα. Τα δημιουργικά αποτελέσματα μπορούν να ποικίλλουν ανάλογα με τις ανάγκες σας, διατηρώντας παράλληλα δομημένα πρότυπα αλληλεπίδρασης: ```mermaid flowchart TD Input[Ερώτημα Χρήστη] --> Agent[AgentNode] Agent -->|"Συλλογισμός LLM (Μη Ντετερμινιστικός)"| ToolChoice{Επιλογή Εργαλείου} ToolChoice -->|"Επιλογή Α"| ToolA[Εργαλείο Βαθιάς Έρευνας] ToolChoice -->|"Επιλογή Β"| ToolB[Εργαλείο Ανάλυσης Δεδομένων] ToolChoice -->|"Επιλογή Γ"| ToolC[Άμεση Απάντηση] ToolA --> Response[Τελική Απάντηση] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Μη Ντετερμινιστικοί Πράκτορες με Ντετερμινιστικές Υπο-Ροές Εργασίας Το AgentDock σας προσφέρει τα ***καλύτερα και από τους δύο κόσμους*** συνδυάζοντας τη μη ντετερμινιστική ευφυΐα του πράκτορα με την ντετερμινιστική εκτέλεση ροής εργασίας: ```mermaid flowchart TD Input[Ερώτημα Χρήστη] --> Agent[AgentNode] Agent -->|"Συλλογισμός LLM (Μη Ντετερμινιστικός)"| FlowChoice{Επιλογή Υπο-Ροής} FlowChoice -->|"Απόφαση Α"| Flow1[Ντετερμινιστική Ροή Εργασίας 1] FlowChoice -->|"Απόφαση Β"| Flow2[Ντετερμινιστική Ροή Εργασίας 2] FlowChoice -->|"Απόφαση Γ"| DirectResponse[Δημιουργία Απάντησης] Flow1 --> |"Βήμα 1 → 2 → 3 → ... → 200"| Flow1Result[Αποτέλεσμα Ροής Εργασίας 1] Flow2 --> |"Βήμα 1 → 2 → 3 → ... → 100"| Flow2Result[Αποτέλεσμα Ροής Εργασίας 2] Flow1Result --> Response[Τελική Απάντηση] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Αυτή η προσέγγιση επιτρέπει την κλήση πολύπλοκων, πολλαπλών βημάτων ροών εργασίας (που ενδέχεται να περιλαμβάνουν εκατοντάδες ντετερμινιστικά βήματα υλοποιημένα εντός εργαλείων ή ως ακολουθίες συνδεδεμένων κόμβων) από έξυπνες αποφάσεις πρακτόρων. Κάθε ροή εργασίας εκτελείται προβλέψιμα παρά το γεγονός ότι ενεργοποιείται από μη ντετερμινιστικό συλλογισμό πράκτορα. Για πιο προηγμένες ροές εργασίας πρακτόρων AI και πολυσταδιακούς αγωγούς επεξεργασίας, κατασκευάζουμε το [AgentDock Pro](../../docs/agentdock-pro.md) - μια ισχυρή πλατφόρμα για την κατασκευή, οπτικοποίηση και εκτέλεση πολύπλοκων συστημάτων πρακτόρων. #### Εν συντομία: ο Διαμορφώσιμος Ντετερμινισμός Σκεφτείτε το όπως την οδήγηση αυτοκινήτου. Μερικές φορές χρειάζεστε τη δημιουργικότητα της AI (όπως η πλοήγηση στους δρόμους της πόλης - μη ντετερμινιστική), και μερικές φορές χρειάζεστε αξιόπιστες, βήμα προς βήμα διαδικασίες (όπως η τήρηση των πινακίδων του αυτοκινητόδρομου - ντετερμινιστική). Το AgentDock σας επιτρέπει να κατασκευάζετε συστήματα που χρησιμοποιούν *και τα δύο*, επιλέγοντας τη σωστή προσέγγιση για κάθε μέρος μιας εργασίας. Συνδυάζετε την ευφυΐα της AI *και* προβλέψιμα αποτελέσματα εκεί που τα χρειάζεστε. ## 🏗️ Κεντρική Αρχιτεκτονική Το framework είναι χτισμένο γύρω από ένα ισχυρό, αρθρωτό σύστημα βασισμένο σε κόμβους (Nodes), το οποίο χρησιμεύει ως θεμέλιο για όλη τη λειτουργικότητα του πράκτορα. Αυτή η αρχιτεκτονική χρησιμοποιεί διακριτούς τύπους κόμβων ως δομικά στοιχεία: - **`BaseNode`**: Η θεμελιώδης κλάση που καθορίζει την κεντρική διεπαφή και τις δυνατότητες για όλους τους κόμβους. - **`AgentNode`**: Ένας εξειδικευμένος κεντρικός κόμβος που ενορχηστρώνει τις αλληλεπιδράσεις LLM, τη χρήση εργαλείων και τη λογική του πράκτορα. - **Εργαλεία και Προσαρμοσμένοι Κόμβοι**: Οι προγραμματιστές υλοποιούν τις δυνατότητες του πράκτορα και την προσαρμοσμένη λογική ως κόμβους που επεκτείνουν το `BaseNode`. Αυτοί οι κόμβοι αλληλεπιδρούν μέσω διαχειριζόμενων μητρών και μπορούν να συνδεθούν (αξιοποιώντας τις θύρες της κεντρικής αρχιτεκτονικής και ένα πιθανό δίαυλο μηνυμάτων) για να επιτρέψουν πολύπλοκες, διαμορφώσιμες και δυνητικά ντετερμινιστικές συμπεριφορές και ροές εργασίας πρακτόρων. Για λεπτομερή επεξήγηση των συστατικών και των δυνατοτήτων του συστήματος κόμβων, ανατρέξτε στην [Τεκμηρίωση Συστήματος Κόμβων](../../docs/nodes/README.md). ## 🚀 Ξεκινώντας Για έναν περιεκτικό οδηγό, ανατρέξτε στον [Οδηγό Εκκίνησης](../../docs/getting-started.md). ### Απαιτήσεις * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Απαιτείται) * Κλειδιά API για παρόχους LLM (Anthropic, OpenAI, κ.λπ.) ### Εγκατάσταση 1. **Κλωνοποιήστε το Αποθετήριο**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Εγκαταστήστε το pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Εγκαταστήστε τις Εξαρτήσεις**: ```bash pnpm install ``` Για καθαρή επανεγκατάσταση (όταν χρειάζεται να ξαναχτίσετε από την αρχή): ```bash pnpm run clean-install ``` Αυτό το σενάριο αφαιρεί όλα τα `node_modules`, τα αρχεία κλειδώματος και επανεγκαθιστά σωστά τις εξαρτήσεις. 4. **Διαμορφώστε το Περιβάλλον**: Δημιουργήστε ένα αρχείο περιβάλλοντος (`.env` ή `.env.local`) βασισμένο στο παρεχόμενο αρχείο `.env.example`: ```bash # Επιλογή 1: Δημιουργία .env.local cp .env.example .env.local # Επιλογή 2: Δημιουργία .env cp .env.example .env ``` Στη συνέχεια, προσθέστε τα κλειδιά API σας στο αρχείο περιβάλλοντος. 5. **Ξεκινήστε τον Διακομιστή Ανάπτυξης**: ```bash pnpm dev ``` ### Προηγμένες Δυνατότητες | Δυνατότητα | Περιγραφή | Τεκμηρίωση | | :------------------------- | :----------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------- | | **Διαχείριση Συνεδριών** | Απομονωμένη, υψηλής απόδοσης διαχείριση κατάστασης για συνομιλίες | [Τεκμηρίωση Συνεδριών](../../docs/architecture/sessions/README.md) | | **Framework Ενορχήστρωσης**| Έλεγχος συμπεριφοράς πράκτορα και διαθεσιμότητας εργαλείων βάσει πλαισίου | [Τεκμηρίωση Ενορχήστρωσης](../../docs/architecture/orchestration/README.md) | | **Αφαίρεση Αποθήκευσης** | Ευέλικτο σύστημα αποθήκευσης με συνδεόμενους παρόχους για KV, Vector και Ασφαλή Αποθήκευση | [Τεκμηρίωση Αποθήκευσης](../../docs/storage/README.md) | Το σύστημα αποθήκευσης εξελίσσεται επί του παρόντος με αποθήκευση κλειδιού-τιμής (πάροχοι Memory, Redis, Vercel KV) και ασφαλή αποθήκευση από την πλευρά του πελάτη, ενώ η αποθήκευση διανυσμάτων και πρόσθετα backends βρίσκονται υπό ανάπτυξη. ## 📕 Τεκμηρίωση Η τεκμηρίωση του framework AgentDock είναι διαθέσιμη στο [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) και στον φάκελο `/docs/` αυτού του αποθετηρίου. Η τεκμηρίωση περιλαμβάνει: - Οδηγούς εκκίνησης - Αναφορές API - Εκπαιδευτικά προγράμματα δημιουργίας κόμβων - Παραδείγματα ενσωμάτωσης ## 📂 Δομή Αποθετηρίου Αυτό το αποθετήριο περιέχει: 1. **AgentDock Core**: Το κεντρικό framework που βρίσκεται στο `agentdock-core/` 2. **Open Source Client**: Μια πλήρης υλοποίηση αναφοράς χτισμένη με Next.js, που χρησιμεύει ως καταναλωτής του framework AgentDock Core. 3. **Παραδείγματα Πρακτόρων**: Έτοιμες προς χρήση διαμορφώσεις πρακτόρων στον κατάλογο `agents/` Μπορείτε να χρησιμοποιήσετε το AgentDock Core ανεξάρτητα στις δικές σας εφαρμογές ή να χρησιμοποιήσετε αυτό το αποθετήριο ως σημείο εκκίνησης για την κατασκευή των δικών σας εφαρμογών που βασίζονται σε πράκτορες. ## 📝 Πρότυπα Πρακτόρων Το AgentDock περιλαμβάνει διάφορα προδιαμορφωμένα πρότυπα πρακτόρων. Εξερευνήστε τα στον κατάλογο `agents/` ή διαβάστε την [Τεκμηρίωση Προτύπων Πρακτόρων](../../docs/agent-templates.md) για λεπτομέρειες διαμόρφωσης. ## 🔧 Παραδείγματα Υλοποιήσεων Οι παραδείγματα υλοποιήσεων παρουσιάζουν εξειδικευμένες περιπτώσεις χρήσης και προηγμένη λειτουργικότητα: | Υλοποίηση | Περιγραφή | Κατάσταση | | :--------------------------- | :------------------------------------------------------------------------------------------------------- | :------------- | | **Ενορχηστρωμένος Πράκτορας**| Παράδειγμα πράκτορα που χρησιμοποιεί ενορχήστρωση για την προσαρμογή της συμπεριφοράς βάσει πλαισίου | Διαθέσιμο | | **Γνωστικός Συλλογιστής** | Αντιμετωπίζει πολύπλοκα προβλήματα χρησιμοποιώντας δομημένο συλλογισμό και γνωστικά εργαλεία | Διαθέσιμο | | **Σχεδιαστής Πρακτόρων** | Εξειδικευμένος πράκτορας για τον σχεδιασμό και την υλοποίηση άλλων πρακτόρων AI | Διαθέσιμο | | [**Code Playground (Περιβάλλον Δοκιμών Κώδικα)**](../../docs/roadmap/code-playground.md) | Δημιουργία και εκτέλεση κώδικα σε sandbox με πλούσιες δυνατότητες οπτικοποίησης | Προγραμματισμένο | ## 🔐 Λεπτομέρειες Διαμόρφωσης Περιβάλλοντος Ο AgentDock Open Source Client απαιτεί κλειδιά API για τους παρόχους LLM για να λειτουργήσει. Αυτά διαμορφώνονται σε ένα αρχείο περιβάλλοντος (`.env` ή `.env.local`) που δημιουργείτε με βάση το παρεχόμενο αρχείο `.env.example`. ### Κλειδιά API Παρόχων LLM Προσθέστε τα κλειδιά API του παρόχου LLM (απαιτείται τουλάχιστον ένα): ```bash # Κλειδιά API Παρόχων LLM - απαιτείται τουλάχιστον ένα ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Κλειδί API Anthropic OPENAI_API_KEY=sk-xxxxxxx # Κλειδί API OpenAI GEMINI_API_KEY=xxxxxxx # Κλειδί API Google Gemini DEEPSEEK_API_KEY=xxxxxxx # Κλειδί API DeepSeek GROQ_API_KEY=xxxxxxx # Κλειδί API Groq ``` ### Επίλυση Κλειδιού API Ο AgentDock Open Source Client ακολουθεί μια σειρά προτεραιότητας κατά την επίλυση του ποιου κλειδιού API θα χρησιμοποιηθεί: 1. **Προσαρμοσμένο κλειδί API ανά πράκτορα** (ορίζεται μέσω των ρυθμίσεων πράκτορα στο UI) 2. **Κλειδί API καθολικών ρυθμίσεων** (ορίζεται μέσω της σελίδας ρυθμίσεων στο UI) 3. **Μεταβλητή περιβάλλοντος** (από το `.env.local` ή την πλατφόρμα ανάπτυξης) ### Κλειδιά API Ειδικά για Εργαλεία Ορισμένα εργαλεία απαιτούν επίσης τα δικά τους κλειδιά API: ```bash # Κλειδιά API Ειδικά για Εργαλεία SERPER_API_KEY= # Απαιτείται για λειτουργικότητα αναζήτησης FIRECRAWL_API_KEY= # Απαιτείται για βαθύτερη περιήγηση στον ιστό ``` Για περισσότερες λεπτομέρειες σχετικά με τη διαμόρφωση περιβάλλοντος, ανατρέξτε στην υλοποίηση στο [`src/types/env.ts`](../../src/types/env.ts). ### Χρησιμοποιήστε τα Δικά σας Κλειδιά API (BYOK) Το AgentDock ακολουθεί ένα μοντέλο BYOK (Bring Your Own Key - Χρησιμοποιήστε το Δικό σας Κλειδί): 1. Προσθέστε τα κλειδιά API σας στη σελίδα ρυθμίσεων της εφαρμογής 2. Εναλλακτικά, παρέχετε κλειδιά μέσω των κεφαλίδων αιτήματος για άμεση χρήση του API 3. Τα κλειδιά αποθηκεύονται με ασφάλεια χρησιμοποιώντας το ενσωματωμένο σύστημα κρυπτογράφησης 4. Κανένα κλειδί API δεν κοινοποιείται ή αποθηκεύεται στους διακομιστές μας ## 📦 Διαχειριστής Πακέτων Αυτό το έργο *απαιτεί* τη χρήση του `pnpm` για συνεπή διαχείριση εξαρτήσεων. Τα `npm` και `yarn` δεν υποστηρίζονται. ## 💡 Τι Μπορείτε να Κατασκευάσετε 1. **Εφαρμογές Βασισμένες στην AI** - Προσαρμοσμένα chatbots με οποιοδήποτε frontend - Βοηθοί AI γραμμής εντολών - Αυτοματοποιημένοι αγωγοί επεξεργασίας δεδομένων - Ενσωματώσεις υπηρεσιών backend 2. **Δυνατότητες Ενσωμάτωσης** - Οποιοσδήποτε πάροχος AI (OpenAI, Anthropic, κ.λπ.) - Οποιοδήποτε framework frontend - Οποιαδήποτε υπηρεσία backend - Προσαρμοσμένες πηγές δεδομένων και API 3. **Συστήματα Αυτοματισμού** - Workflows επεξεργασίας δεδομένων - Pipeline ανάλυσης εγγράφων - Αυτοματοποιημένα συστήματα αναφορών - Πράκτορες αυτοματισμού εργασιών ## Βασικά Χαρακτηριστικά | Χαρακτηριστικό | Περιγραφή | | :--------------------------- | :------------------------------------------------------------------------------------------------- | | 🔌 **Ανεξάρτητο από Framework (Node.js Backend)** | Η κεντρική βιβλιοθήκη ενσωματώνεται με στοίβες backend Node.js. | | 🧩 **Αρθρωτός Σχεδιασμός** | Κατασκευή πολύπλοκων συστημάτων από απλούς κόμβους | | 🛠️ **Επεκτάσιμο** | Δημιουργία προσαρμοσμένων κόμβων για οποιαδήποτε λειτουργικότητα | | 🔒 **Ασφαλές** | Ενσωματωμένα χαρακτηριστικά ασφαλείας για κλειδιά API και δεδομένα | | 🔑 **BYOK** | Χρησιμοποιήστε τα *δικά σας κλειδιά API* για παρόχους LLM | | 📦 **Αυτοτελές** | Το κεντρικό framework έχει ελάχιστες εξαρτήσεις | | ⚙️ **Κλήσεις Εργαλείων Πολλαπλών Σταδίων (Multi-Step Tool Calls)** | Υποστήριξη για *πολύπλοκες αλυσίδες συλλογισμού* | | 📊 **Δομημένη Καταγραφή** | Λεπτομερείς πληροφορίες για την εκτέλεση του πράκτορα | | 🛡️ **Στιβαρός Χειρισμός Σφαλμάτων**| Προβλέψιμη συμπεριφορά και απλοποιημένος εντοπισμός σφαλμάτων | | 📝 **Πρώτα το TypeScript** | Ασφάλεια τύπων και βελτιωμένη εμπειρία προγραμματιστή | | 🌐 **Open Source Client** | Περιλαμβάνει πλήρη υλοποίηση αναφοράς Next.js | | 🔄 **Ενορχήστρωση** | *Δυναμικός έλεγχος* της συμπεριφοράς του πράκτορα βάσει πλαισίου | | 💾 **Διαχείριση Συνεδριών** | Απομονωμένη κατάσταση για ταυτόχρονες συνομιλίες | | 🎮 **Διαμορφώσιμος Ντετερμινισμός**| Ισορροπήστε τη δημιουργικότητα της AI και την προβλεψιμότητα μέσω της λογικής κόμβου/ροής εργασίας.| ## 🧰 Συστατικά Η αρθρωτή αρχιτεκτονική του AgentDock βασίζεται σε αυτά τα βασικά συστατικά: * **BaseNode**: Η βάση για όλους τους κόμβους στο σύστημα * **AgentNode**: Η κύρια αφαίρεση για τη λειτουργικότητα του πράκτορα * **Εργαλεία και Προσαρμοσμένοι Κόμβοι**: Κλητές δυνατότητες και προσαρμοσμένη λογική υλοποιημένες ως κόμβοι. * **Μητρώο Κόμβων**: Διαχειρίζεται την εγγραφή και ανάκτηση όλων των τύπων κόμβων * **Μητρώο Εργαλείων**: Διαχειρίζεται τη διαθεσιμότητα εργαλείων για τους πράκτορες * **CoreLLM**: Ενοποιημένη διεπαφή για αλληλεπίδραση με παρόχους LLM * **Μητρώο Παρόχων**: Διαχειρίζεται τις διαμορφώσεις παρόχων LLM * **Χειρισμός Σφαλμάτων**: Σύστημα για τον χειρισμό σφαλμάτων και τη διασφάλιση προβλέψιμης συμπεριφοράς * **Καταγραφή (Logging)**: Δομημένο σύστημα καταγραφής για παρακολούθηση και εντοπισμό σφαλμάτων * **Ενορχήστρωση**: Ελέγχει τη διαθεσιμότητα εργαλείων και τη συμπεριφορά βάσει του πλαισίου συνομιλίας * **Συνεδρίες**: Διαχειρίζεται την απομόνωση κατάστασης μεταξύ ταυτόχρονων συνομιλιών Για λεπτομερή τεχνική τεκμηρίωση σχετικά με αυτά τα συστατικά, ανατρέξτε στην [Επισκόπηση Αρχιτεκτονικής](../../docs/architecture/README.md). ## 🗺️ Οδικός Χάρτης Παρακάτω παρουσιάζεται ο οδικός χάρτης ανάπτυξης για το AgentDock. Οι περισσότερες από τις βελτιώσεις που αναφέρονται εδώ αφορούν το κεντρικό framework του AgentDock (`agentdock-core`), το οποίο αναπτύσσεται επί του παρόντος τοπικά και θα κυκλοφορήσει ως πακέτο NPM με έκδοση μόλις επιτευχθεί μια σταθερή έκδοση. Ορισμένα στοιχεία του οδικού χάρτη ενδέχεται επίσης να περιλαμβάνουν βελτιώσεις στην υλοποίηση του πελάτη ανοιχτού κώδικα. | Χαρακτηριστικό | Περιγραφή | Κατηγορία | | :--------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------- | :---------------- | | [**Επίπεδο Αφαίρεσης Αποθήκευσης**](../../docs/roadmap/storage-abstraction.md) | Ευέλικτο σύστημα αποθήκευσης με συνδεόμενους παρόχους | **Υπό Εξέλιξη** | | [**Προηγμένα Συστήματα Μνήμης**](../../docs/roadmap/advanced-memory.md) | Διαχείριση μακροπρόθεσμου πλαισίου | **Υπό Εξέλιξη** | | [**Ενσωμάτωση Αποθήκευσης Διανυσμάτων**](../../docs/roadmap/vector-storage.md) | Ανάκτηση βάσει ενσωματώσεων για έγγραφα και μνήμη | **Υπό Εξέλιξη** | | [**Αξιολόγηση για Πράκτορες AI**](../../docs/roadmap/evaluation-framework.md) | Ολοκληρωμένο πλαίσιο δοκιμών και αξιολόγησης | **Υπό Εξέλιξη** | | [**Ενσωμάτωση Πλατφορμών**](../../docs/roadmap/platform-integration.md) | Υποστήριξη για Telegram, WhatsApp και άλλες πλατφόρμες ανταλλαγής μηνυμάτων | **Προγραμματισμένο**| | [**Συνεργασία Πολλαπλών Πρακτόρων**](../../docs/roadmap/multi-agent-collaboration.md)| Δυνατότητα συνεργασίας πρακτόρων | **Προγραμματισμένο**| | [**Ενσωμάτωση Πρωτοκόλλου Πλαισίου Μοντέλου (MCP)**](../../docs/roadmap/mcp-integration.md)| Υποστήριξη για την ανακάλυψη και χρήση εξωτερικών εργαλείων μέσω MCP | **Προγραμματισμένο**| | [**Φωνητικοί Πράκτορες AI**](../../docs/roadmap/voice-agents.md) | Πράκτορες AI που χρησιμοποιούν φωνητικές διεπαφές και αριθμούς τηλεφώνου μέσω του AgentNode | **Προγραμματισμένο**| | [**Τηλεμετρία και Ιχνηλασιμότητα**](../../docs/roadmap/telemetry.md) | Προηγμένη καταγραφή και παρακολούθηση απόδοσης | **Προγραμματισμένο** | | [**Workflow Runtime & Node Τύποι**](../../docs/roadmap/workflow-nodes.md) | Κεντρικός runtime, τύποι κόμβων (Nodes) και λογική ενορχήστρωσης για πολύπλοκες αυτοματοποιήσεις | **Προγραμματισμένο** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Ολοκληρωμένη εταιρική πλατφόρμα cloud για κλιμάκωση πρακτόρων AI & ροών εργασίας | **Cloud** | ## 👥 Συνεισφορά Καλωσορίζουμε τις συνεισφορές στο AgentDock! Ανατρέξτε στο [CONTRIBUTING.md](../../CONTRIBUTING.md) για λεπτομερείς οδηγίες συνεισφοράς. ## 📜 Άδεια Το AgentDock κυκλοφορεί υπό την [Άδεια MIT](../../LICENSE). ## ✨ Δημιουργήστε Χωρίς Όρια! Το AgentDock παρέχει τα θεμέλια για να κατασκευάσετε σχεδόν οποιαδήποτε εφαρμογή ή αυτοματισμό που βασίζεται σε AI μπορείτε να φανταστείτε. Σας ενθαρρύνουμε να εξερευνήσετε το framework, να κατασκευάσετε καινοτόμους πράκτορες και να συνεισφέρετε πίσω στην κοινότητα. Ας χτίσουμε μαζί το μέλλον της αλληλεπίδρασης AI! --- [Επιστροφή στον Κατάλογο Μεταφράσεων](/docs/i18n/README.md) ## AgentDock: Crea Possibilità Infinite con Agenti AI

AgentDock Logo

## 🌐 Traduzioni README [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock è un framework per costruire sofisticati agenti AI che svolgono compiti complessi con **determinismo configurabile**. È composto da due componenti principali: 1. **AgentDock Core**: Un framework open-source, backend-first per costruire e distribuire agenti AI. È progettato per essere *agnostico rispetto al framework* e *agnostico rispetto al provider*, dandoti il controllo completo sull'implementazione del tuo agente. 2. **Client Open Source**: Un'applicazione Next.js completa che serve come implementazione di riferimento e consumatore del framework AgentDock Core. Puoi vederla in azione su [https://hub.agentdock.ai](https://hub.agentdock.ai) Costruito con TypeScript, AgentDock enfatizza la *semplicità*, l'*estensibilità* e il ***determinismo configurabile***, rendendolo ideale per costruire sistemi AI affidabili e prevedibili che possono operare con una supervisione minima. ## 🧠 Principi di Progettazione AgentDock è costruito su questi principi fondamentali: - **Semplicità Prima di Tutto**: Codice minimo richiesto per creare agenti funzionali - **Architettura Basata su Nodi**: Tutte le capacità sono implementate come nodi - **Strumenti come Nodi Specializzati**: Gli strumenti estendono il sistema di nodi per le capacità dell'agente - **Determinismo Configurabile**: Controlla la prevedibilità del comportamento dell'agente - **Sicurezza dei Tipi**: Tipi TypeScript completi ovunque ### Determinismo Configurabile Il ***determinismo configurabile*** è una pietra miliare della filosofia di progettazione di AgentDock, permettendoti di bilanciare le capacità creative dell'AI con un comportamento di sistema prevedibile: - Gli AgentNode sono intrinsecamente non deterministici poiché gli LLM possono generare risposte diverse ogni volta - I workflow possono essere resi più deterministici attraverso *percorsi di esecuzione degli strumenti definiti* - Gli sviluppatori possono **controllare il livello di determinismo** configurando quali parti del sistema utilizzano l'inferenza LLM - Anche con componenti LLM, il comportamento complessivo del sistema rimane **prevedibile** attraverso interazioni strutturate degli strumenti - Questo approccio equilibrato consente sia la *creatività* che l'**affidabilità** nelle tue applicazioni AI #### Workflow Deterministici AgentDock supporta pienamente i workflow deterministici con cui hai familiarità dai tipici costruttori di workflow. Tutti i percorsi di esecuzione prevedibili e i risultati affidabili che ti aspetti sono disponibili, con o senza inferenza LLM: ```mermaid flowchart LR Input[Input] --> Process[Processo] Process --> Database[(Database)] Process --> Output[Output] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Comportamento Agente Non Deterministico Con AgentDock, puoi anche sfruttare gli AgentNode con LLM quando hai bisogno di maggiore adattabilità. Gli output creativi possono variare in base alle tue esigenze, mantenendo comunque pattern di interazione strutturati: ```mermaid flowchart TD Input[Query Utente] --> Agent[AgentNode] Agent -->|"Ragionamento LLM (Non Deterministico)"| ToolChoice{Selezione Strumento} ToolChoice -->|"Opzione A"| ToolA[Strumento Ricerca Approfondita] ToolChoice -->|"Opzione B"| ToolB[Strumento Analisi Dati] ToolChoice -->|"Opzione C"| ToolC[Risposta Diretta] ToolA --> Response[Risposta Finale] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Agenti Non Deterministici con Sotto-Workflow Deterministici AgentDock ti offre il ***meglio di entrambi i mondi*** combinando l'intelligenza dell'agente non deterministico con l'esecuzione deterministica del workflow: ```mermaid flowchart TD Input[Query Utente] --> Agent[AgentNode] Agent -->|"Ragionamento LLM (Non Deterministico)"| FlowChoice{Selezione Sotto-Workflow} FlowChoice -->|"Decisione A"| Flow1[Workflow Deterministico 1] FlowChoice -->|"Decisione B"| Flow2[Workflow Deterministico 2] FlowChoice -->|"Decisione C"| DirectResponse[Genera Risposta] Flow1 --> |"Passo 1 → 2 → 3 → ... → 200"| Flow1Result[Risultato Workflow 1] Flow2 --> |"Passo 1 → 2 → 3 → ... → 100"| Flow2Result[Risultato Workflow 2] Flow1Result --> Response[Risposta Finale] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Questo approccio consente a workflow complessi multi-step (potenzialmente coinvolgendo centinaia di passaggi deterministici implementati all'interno di strumenti o come sequenze di nodi collegati) di essere invocati da decisioni di agenti intelligenti. Ogni workflow si esegue in modo prevedibile nonostante sia attivato da un ragionamento di agente non deterministico. Per workflow di agenti AI più avanzati e pipeline di elaborazione multi-stage, stiamo costruendo [AgentDock Pro](../../docs/agentdock-pro.md) - una potente piattaforma per creare, visualizzare ed eseguire sistemi di agenti complessi. #### In breve: il Determinismo Configurabile Pensalo come quando guidi. A volte hai bisogno della creatività dell'AI (come navigare nelle strade cittadine - non deterministico), e a volte hai bisogno di processi affidabili, passo dopo passo (come seguire i segnali autostradali - deterministico). AgentDock ti consente di costruire sistemi che usano *entrambi*, scegliendo l'approccio giusto per ogni parte di un compito. Ottieni sia l'intelligenza dell'AI *che* risultati prevedibili quando ti servono. ## 🏗️ Architettura Core Il framework è costruito attorno a un sistema potente e modulare basato su nodi, che funge da base per tutte le funzionalità dell'agente. Questa architettura utilizza tipi di nodi distinti come blocchi costitutivi: - **`BaseNode`**: La classe fondamentale che stabilisce l'interfaccia principale e le capacità per tutti i nodi. - **`AgentNode`**: Un nodo core specializzato che orchestra le interazioni LLM, l'uso degli strumenti e la logica dell'agente. - **Strumenti e Nodi Personalizzati**: Gli sviluppatori implementano le capacità dell'agente e la logica personalizzata come nodi che estendono `BaseNode`. Questi nodi interagiscono tramite registri gestiti e possono essere collegati (sfruttando le porte dell'architettura core e un potenziale bus di messaggi) per abilitare comportamenti e workflow di agenti complessi, configurabili e potenzialmente deterministici. Per una spiegazione dettagliata dei componenti e delle capacità del sistema di nodi, consulta la [Documentazione del Sistema di Nodi](../../docs/nodes/README.md). ## 🚀 Iniziare Per una guida completa, consulta la [Guida Introduttiva](../../docs/getting-started.md). ### Requisiti * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Richiesto) * Chiavi API per provider LLM (Anthropic, OpenAI, etc.) ### Installazione 1. **Clona il Repository**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Installa pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Installa le Dipendenze**: ```bash pnpm install ``` Per una reinstallazione pulita (quando devi ricostruire da zero): ```bash pnpm run clean-install ``` Questo script rimuove tutti i node_modules, i file di lock e reinstalla correttamente le dipendenze. 4. **Configura l'Ambiente**: Crea un file di ambiente (`.env` o `.env.local`) basato sul file `.env.example` fornito: ```bash # Opzione 1: Crea .env.local cp .env.example .env.local # Opzione 2: Crea .env cp .env.example .env ``` Poi aggiungi le tue chiavi API al file di ambiente. 5. **Avvia il Server di Sviluppo**: ```bash pnpm dev ``` ### Capacità Avanzate | Capacità | Descrizione | Documentazione | | :------------------------ | :---------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------- | | **Gestione Sessioni** | Gestione dello stato isolata e performante per le conversazioni | [Documentazione Sessioni](../../docs/architecture/sessions/README.md) | | **Framework Orchestrazione** | Controllo del comportamento dell'agente e disponibilità degli strumenti basato sul contesto | [Documentazione Orchestrazione](../../docs/architecture/orchestration/README.md) | | **Astrazione Storage** | Sistema di storage flessibile con provider collegabili per KV, Vector e Secure Storage | [Documentazione Storage](../../docs/storage/README.md) | Il sistema di storage si sta attualmente evolvendo con storage chiave-valore (provider Memory, Redis, Vercel KV) e storage sicuro lato client, mentre lo storage vettoriale e backend aggiuntivi sono in fase di sviluppo. ## 📕 Documentazione La documentazione del framework AgentDock è disponibile su [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) e nella cartella `/docs/` di questo repository. La documentazione include: - Guide introduttive - Riferimenti API - Tutorial sulla creazione di nodi - Esempi di integrazione ## 📂 Struttura Repository Questo repository contiene: 1. **AgentDock Core**: Il framework core situato in `agentdock-core/` 2. **Client Open Source**: Un'implementazione di riferimento completa costruita con Next.js, che serve come consumatore del framework AgentDock Core. 3. **Agenti Esempio**: Configurazioni di agenti pronte all'uso nella directory `agents/` Puoi usare AgentDock Core indipendentemente nelle tue applicazioni, o usare questo repository come punto di partenza per costruire le tue applicazioni basate su agenti. ## 📝 Template Agenti AgentDock include diversi template di agenti preconfigurati. Esplorali nella directory `agents/` o leggi la [Documentazione Template Agenti](../../docs/agent-templates.md) per i dettagli di configurazione. ## 🔧 Implementazioni Esempio Le implementazioni esempio mostrano casi d'uso specializzati e funzionalità avanzate: | Implementazione | Descrizione | Stato | | :--------------------------- | :--------------------------------------------------------------------------------------------- | :---------- | | **Agente Orchestrato** | Agente esempio che utilizza l'orchestrazione per adattare il comportamento in base al contesto | Disponibile | | **Ragionatore Cognitivo** | Affronta problemi complessi usando ragionamento strutturato e strumenti cognitivi | Disponibile | | **Pianificatore Agenti** | Agente specializzato per progettare e implementare altri agenti AI | Disponibile | | [**Playground di Codice (Code Playground)**](../../docs/roadmap/code-playground.md) | Generazione ed esecuzione di codice sandboxed con ricche capacità di visualizzazione | Pianificato | ## 🔐 Dettagli Configurazione Ambiente Il Client Open Source di AgentDock richiede chiavi API per i provider LLM per funzionare. Queste sono configurate in un file di ambiente (`.env` o `.env.local`) che crei basandoti sul file `.env.example` fornito. ### Chiavi API Provider LLM Aggiungi le tue chiavi API del provider LLM (almeno una richiesta): ```bash # Chiavi API Provider LLM - almeno una richiesta ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Chiave API Anthropic OPENAI_API_KEY=sk-xxxxxxx # Chiave API OpenAI GEMINI_API_KEY=xxxxxxx # Chiave API Google Gemini DEEPSEEK_API_KEY=xxxxxxx # Chiave API DeepSeek GROQ_API_KEY=xxxxxxx # Chiave API Groq ``` ### Risoluzione Chiave API Il Client Open Source di AgentDock segue un ordine di priorità nel risolvere quale chiave API usare: 1. **Chiave API personalizzata per agente** (impostata tramite le impostazioni dell'agente nell'UI) 2. **Chiave API di impostazione globale** (impostata tramite la pagina delle impostazioni nell'UI) 3. **Variabile d'ambiente** (da .env.local o piattaforma di deploy) ### Chiavi API Specifiche per Strumento Alcuni strumenti richiedono anche le proprie chiavi API: ```bash # Chiavi API Specifiche per Strumento SERPER_API_KEY= # Richiesto per funzionalità di ricerca FIRECRAWL_API_KEY= # Richiesto per ricerca web più approfondita ``` Per maggiori dettagli sulla configurazione dell'ambiente, consulta l'implementazione in [`src/types/env.ts`](../../src/types/env.ts). ### Usa le Tue Chiavi API (BYOK) AgentDock segue un modello BYOK (Bring Your Own Key - Usa la Tua Chiave): 1. Aggiungi le tue chiavi API nella pagina delle impostazioni dell'applicazione 2. Alternativamente, fornisci le chiavi tramite header di richiesta per l'uso diretto dell'API 3. Le chiavi sono memorizzate in modo sicuro usando il sistema di crittografia integrato 4. Nessuna chiave API viene condivisa o memorizzata sui nostri server ## 📦 Gestore dei Pacchetti Questo progetto *richiede* l'uso di `pnpm` per una gestione coerente delle dipendenze. `npm` e `yarn` non sono supportati. ## 💡 Cosa Puoi Costruire 1. **Applicazioni Basate su AI** - Chatbot personalizzati con qualsiasi frontend - Assistenti AI da riga di comando - Pipeline di elaborazione dati automatizzate - Integrazioni di servizi backend 2. **Capacità di Integrazione** - Qualsiasi provider AI (OpenAI, Anthropic, etc.) - Qualsiasi framework frontend - Qualsiasi servizio backend - Sorgenti dati e API personalizzate 3. **Sistemi di Automazione** - Workflow di elaborazione dati - Pipeline di analisi documenti - Sistemi di reporting automatizzati - Agenti di automazione compiti ## Caratteristiche Principali | Caratteristica | Descrizione | | :----------------------------- | :--------------------------------------------------------------------------------------------- | | 🔌 **Agnostico al Framework (Backend Node.js)** | La libreria core si integra con stack backend Node.js. | | 🧩 **Design Modulare** | Costruisci sistemi complessi da nodi semplici | | 🛠️ **Estensibile** | Crea nodi personalizzati per qualsiasi funzionalità | | 🔒 **Sicuro** | Funzionalità di sicurezza integrate per chiavi API e dati | | 🔑 **BYOK** | Usa le *tue chiavi API* per i provider LLM | | 📦 **Auto-sufficiente** | Il framework core ha dipendenze minime | | ⚙️ **Chiamate Strumento Multi-Fase (Multi-Step Tool Calls)** | Supporto per *catene di ragionamento complesse* | | 📊 **Logging Strutturato** | Insight dettagliati sull'esecuzione dell'agente | | 🛡️ **Gestione Errori Robusta** | Comportamento prevedibile e debugging semplificato | | 📝 **TypeScript First** | Sicurezza dei tipi ed esperienza sviluppatore migliorata | | 🌐 **Client Open Source** | Include implementazione di riferimento completa Next.js | | 🔄 **Orchestrazione** | *Controllo dinamico* del comportamento dell'agente basato sul contesto | | 💾 **Gestione Sessioni** | Stato isolato per conversazioni concorrenti | | 🎮 **Determinismo Configurabile** | Bilancia creatività AI e prevedibilità tramite logica nodi/workflow. | ## 🧰 Componenti L'architettura modulare di AgentDock è costruita su questi componenti chiave: * **BaseNode**: La base per tutti i nodi nel sistema * **AgentNode**: L'astrazione principale per la funzionalità dell'agente * **Strumenti e Nodi Personalizzati**: Capacità invocabili e logica personalizzata implementate come nodi. * **Registro Nodi**: Gestisce la registrazione e il recupero di tutti i tipi di nodo * **Registro Strumenti**: Gestisce la disponibilità degli strumenti per gli agenti * **CoreLLM**: Interfaccia unificata per interagire con i provider LLM * **Registro Provider**: Gestisce le configurazioni dei provider LLM * **Gestione Errori**: Sistema per gestire gli errori e garantire un comportamento prevedibile * **Logging**: Sistema di logging strutturato per monitoraggio e debugging * **Orchestrazione**: Controlla la disponibilità degli strumenti e il comportamento in base al contesto della conversazione * **Sessioni**: Gestisce l'isolamento dello stato tra conversazioni concorrenti Per documentazione tecnica dettagliata su questi componenti, consulta la [Panoramica Architettura](../../docs/architecture/README.md). ## 🗺️ Roadmap Di seguito la nostra roadmap di sviluppo per AgentDock. La maggior parte dei miglioramenti elencati qui riguarda il framework core di AgentDock (`agentdock-core`), attualmente sviluppato localmente e che sarà pubblicato come pacchetto NPM versionato una volta raggiunta una release stabile. Alcuni elementi della roadmap potrebbero anche comportare miglioramenti all'implementazione del client open-source. | Caratteristica | Descrizione | Categoria | | :---------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------- | :------------- | | [**Livello Astrazione Storage**](../../docs/roadmap/storage-abstraction.md) | Sistema di storage flessibile con provider collegabili | **In Corso** | | [**Sistemi Memoria Avanzati**](../../docs/roadmap/advanced-memory.md) | Gestione del contesto a lungo termine | **In Corso** | | [**Integrazione Storage Vettoriale**](../../docs/roadmap/vector-storage.md) | Recupero basato su embedding per documenti e memoria | **In Corso** | | [**Valutazione Agenti AI**](../../docs/roadmap/evaluation-framework.md) | Framework completo di testing e valutazione | **In Corso** | | [**Integrazione Piattaforme**](../../docs/roadmap/platform-integration.md) | Supporto per Telegram, WhatsApp e altre piattaforme di messaggistica | **Pianificato**| | [**Collaborazione Multi-Agente**](../../docs/roadmap/multi-agent-collaboration.md)| Consentire agli agenti di lavorare insieme | **Pianificato**| | [**Integrazione Protocollo Contesto Modello (MCP)**](../../docs/roadmap/mcp-integration.md) | Supporto per scoprire e usare strumenti esterni tramite MCP | **Pianificato**| | [**Agenti AI Vocali**](../../docs/roadmap/voice-agents.md) | Agenti AI che usano interfacce vocali e numeri di telefono tramite AgentNode | **Pianificato**| | [**Telemetria e Tracciabilità**](../../docs/roadmap/telemetry.md) | Logging avanzato e tracciamento delle prestazioni | **Pianificato**| | [**Workflow Runtime & Node Tipi**](../../docs/roadmap/workflow-nodes.md) | Runtime core, tipi di nodi e logica di orchestrazione per automazioni complesse | **Pianificato**| | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Piattaforma cloud enterprise completa per scalare agenti AI e workflow AI | **Cloud** | | [**Costruttore Agenti AI in Linguaggio Naturale**](../../docs/roadmap/nl-agent-builder.md)| Costruttore visuale + costruzione di agenti e workflow in linguaggio naturale | **Cloud** | | [**Marketplace Agenti**](../../docs/roadmap/agent-marketplace.md) | Template agenti monetizzabili | **Cloud** | ## 👥 Contribuire Accogliamo contributi ad AgentDock! Consulta [CONTRIBUTING.md](../../CONTRIBUTING.md) per linee guida dettagliate sulla contribuzione. ## 📜 Licenza AgentDock è rilasciato sotto la [Licenza MIT](../../LICENSE). ## ✨ Crea Possibilità Infinite! AgentDock fornisce la base per costruire quasi qualsiasi applicazione o automazione basata sull'AI che puoi immaginare. Ti incoraggiamo a esplorare il framework, costruire agenti innovativi e contribuire alla comunità. Costruiamo insieme il futuro dell'interazione AI! --- [Torna all'Indice delle Traduzioni](/docs/i18n/README.md) ## AgentDock: AIエージェントで無限の可能性を創造

AgentDock Logo

## 🌐 README 翻訳 [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDockは、**設定可能な決定論**を用いて複雑なタスクを実行する高度なAIエージェントを構築するためのフレームワークです。主に2つのコンポーネントで構成されています: 1. **AgentDock Core**:AIエージェントを構築・展開するためのオープンソースのバックエンドファーストなフレームワーク。*フレームワーク非依存*かつ*プロバイダー非依存*に設計されており、エージェントの実装を完全に制御できます。 2. **オープンソースクライアント**:AgentDock Coreフレームワークのリファレンス実装およびコンシューマーとして機能する完全なNext.jsアプリケーション。[https://hub.agentdock.ai](https://hub.agentdock.ai) で動作を確認できます。 TypeScriptで構築されたAgentDockは、*シンプルさ*、*拡張性*、そして***設定可能な決定論***を重視しており、最小限の監視で動作可能な信頼性と予測可能性の高いAIシステムを構築するのに理想的です。 ## 🧠 設計原則 AgentDockは、以下のコア原則に基づいて構築されています: - **シンプルさ第一**:機能的なエージェントを作成するために必要な最小限のコード - **ノードベースアーキテクチャ**:すべての機能はノードとして実装 - **特殊ノードとしてのツール**:ツールはエージェント機能のためにノードシステムを拡張 - **設定可能な決定論**:エージェントの挙動の予測可能性を制御 - **型安全性**:全体にわたる包括的なTypeScript型 ### 設定可能な決定論 ***設定可能な決定論***は、AgentDockの設計哲学の基盤であり、創造的なAI機能と予測可能なシステム挙動のバランスを取ることを可能にします: - AgentNodeは、LLMが毎回異なる応答を生成する可能性があるため、本質的に非決定的です - ワークフローは、*定義されたツール実行パス*を通じてより決定的にすることができます - 開発者は、システムのどの部分がLLM推論を使用するかを設定することで、**決定論のレベルを制御**できます - LLMコンポーネントがあっても、構造化されたツールインタラクションにより、システム全体の挙動は**予測可能**なままです - このバランスの取れたアプローチにより、AIアプリケーションにおける*創造性*と**信頼性**の両方が可能になります #### 決定論的ワークフロー AgentDockは、典型的なワークフロービルダーでお馴染みの決定論的ワークフローを完全にサポートしています。期待されるすべての予測可能な実行パスと信頼性の高い結果は、LLM推論の有無にかかわらず利用可能です: ```mermaid flowchart LR Input[入力] --> Process[処理] Process --> Database[(データベース)] Process --> Output[出力] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### 非決定論的エージェント挙動 AgentDockでは、より適応性が必要な場合にLLMを備えたAgentNodeを活用することもできます。創造的な出力はニーズに応じて変化する可能性がありますが、構造化されたインタラクションパターンは維持されます: ```mermaid flowchart TD Input[ユーザー クエリ] --> Agent[AgentNode] Agent -->|"LLM推論 (非決定的)"| ToolChoice{ツール選択} ToolChoice -->|"オプション A"| ToolA[詳細調査ツール] ToolChoice -->|"オプション B"| ToolB[データ分析ツール] ToolChoice -->|"オプション C"| ToolC[直接応答] ToolA --> Response[最終応答] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### 決定論的サブワークフローを持つ非決定論的エージェント AgentDockは、非決定論的なエージェントインテリジェンスと決定論的なワークフロー実行を組み合わせることで、***両方の世界の最良の部分***を提供します: ```mermaid flowchart TD Input[ユーザー クエリ] --> Agent[AgentNode] Agent -->|"LLM推論 (非決定的)"| FlowChoice{サブワークフロー選択} FlowChoice -->|"決定 A"| Flow1[決定論的ワークフロー 1] FlowChoice -->|"決定 B"| Flow2[決定論的ワークフロー 2] FlowChoice -->|"決定 C"| DirectResponse[応答生成] Flow1 --> |"ステップ 1 → 2 → 3 → ... → 200"| Flow1Result[ワークフロー 1 結果] Flow2 --> |"ステップ 1 → 2 → 3 → ... → 100"| Flow2Result[ワークフロー 2 結果] Flow1Result --> Response[最終応答] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` このアプローチにより、複雑なマルチステップワークフロー(ツール内または接続されたノードシーケンスとして実装された数百の決定論的ステップを含む可能性がある)が、インテリジェントなエージェントの決定によって呼び出されることが可能になります。各ワークフローは、非決定論的なエージェントの推論によってトリガーされたにもかかわらず、予測どおりに実行されます。 より高度なAIエージェントワークフローとマルチステージ処理パイプラインのために、複雑なエージェントシステムを作成、視覚化、実行するための強力なプラットフォームである[AgentDock Pro](../../docs/agentdock-pro.md)を構築しています。 #### 設定可能な決定論:概要 自動車の運転になぞらえてみましょう。時にはAIの創造性が必要な場合(街中のナビゲーションなど - 非決定的)もあれば、信頼性の高いステップバイステップのプロセスが必要な場合(高速道路の標識に従うなど - 決定的)もあります。AgentDockを使用すると、タスクの各部分に適したアプローチを選択して、*両方*を使用するシステムを構築できます。AIの創造性と、必要なときの予測可能性を両立できます。 ## 🏗️ コアアーキテクチャ このフレームワークは、すべてのエージェント機能の基盤となる、強力でモジュール化されたノードベースシステムを中心に構築されています。このアーキテクチャは、構成要素として異なるノードタイプを使用します: - **`BaseNode`**:すべてのノードのコアインターフェースと機能を確立する基本クラス。 - **`AgentNode`**:LLMインタラクション、ツール使用、エージェントロジックを調整する特殊なコアノード。 - **ツール&カスタムノード**:開発者は、`BaseNode`を拡張するノードとしてエージェント機能とカスタムロジックを実装します。 これらのノードは、管理されたレジストリを通じて相互作用し、複雑で設定可能、かつ潜在的に決定論的なエージェントの挙動とワークフローを可能にするために(コアアーキテクチャのポートと潜在的なメッセージバスを活用して)接続できます。 ノードシステムのコンポーネントと機能の詳細な説明については、[ノードシステムドキュメント](../../docs/nodes/README.md)を参照してください。 ## 🚀 はじめに 包括的なガイドについては、[はじめにガイド](../../docs/getting-started.md)を参照してください。 ### 要件 * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (必須) * LLMプロバイダー(Anthropic、OpenAIなど)のAPIキー ### インストール 1. **リポジトリをクローン**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **pnpmをインストール**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **依存関係をインストール**: ```bash pnpm install ``` クリーンな再インストール(最初から再構築する必要がある場合): ```bash pnpm run clean-install ``` このスクリプトは、すべてのnode_modules、ロックファイルを削除し、依存関係を正しく再インストールします。 4. **環境を設定**: 提供されている`.env.example`ファイルに基づいて環境ファイル(`.env`または`.env.local`)を作成します: ```bash # オプション1:.env.localを作成 cp .env.example .env.local # オプション2:.envを作成 cp .env.example .env ``` 次に、APIキーを環境ファイルに追加します。 5. **開発サーバーを開始**: ```bash pnpm dev ``` ### 高度な機能 | 機能 | 説明 | ドキュメント | | :------------------- | :-------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | **セッション管理** | 会話のための分離された、パフォーマンスの高い状態管理 | [セッションドキュメント](../../docs/architecture/sessions/README.md) | | **オーケストレーションフレームワーク** | コンテキストに基づいてエージェントの挙動とツールの可用性を制御 | [オーケストレーションドキュメント](../../docs/architecture/orchestration/README.md) | | **ストレージ抽象化** | KV、Vector、Secureストレージ用のプラグ可能なプロバイダーを備えた柔軟なストレージシステム | [ストレージドキュメント](../../docs/storage/README.md) | ストレージシステムは現在、キーバリューストレージ(Memory、Redis、Vercel KVプロバイダー)と安全なクライアントサイドストレージで進化しており、ベクトルストレージと追加のバックエンドは開発中です。 ## 📕 ドキュメント AgentDockフレームワークのドキュメントは、[hub.agentdock.ai/docs](https://hub.agentdock.ai/docs)およびこのリポジトリの`/docs/`フォルダで利用可能です。ドキュメントには以下が含まれます: - はじめにガイド - APIリファレンス - ノード作成チュートリアル - 統合例 ## 📂 リポジトリ構造 このリポジトリには以下が含まれます: 1. **AgentDock Core**:`agentdock-core/`にあるコアフレームワーク 2. **オープンソースクライアント**:AgentDock Coreフレームワークのコンシューマーとして機能する、Next.jsで構築された完全なリファレンス実装。 3. **エージェント例**:`agents/`ディレクトリにあるすぐに使えるエージェント設定 AgentDock Coreを独自のアプリケーションで独立して使用することも、このリポジトリを独自のエージェント搭載アプリケーション構築の開始点として使用することもできます。 ## 📝 エージェントテンプレート AgentDockには、事前に設定されたいくつかのエージェントテンプレートが含まれています。`agents/`ディレクトリでそれらを確認するか、設定の詳細については[エージェントテンプレートドキュメント](../../docs/agent-templates.md)をお読みください。 ## 🔧 実装例 実装例は、特殊なユースケースと高度な機能を示しています: | 実装 | 説明 | ステータス | | :-------------------- | :---------------------------------------------------------------------- | :----------- | | **オーケストレーションされたエージェント** | コンテキストに基づいて挙動を適応させるためにオーケストレーションを使用するエージェント例 | 利用可能 | | **認知的推論者** | 構造化された推論と認知的ツールを使用して複雑な問題に取り組む | 利用可能 | | **エージェントプランナー** | 他のAIエージェントを設計・実装するための特殊なエージェント | 利用可能 | | [**コードプレイグラウンド(コード実験環境)**](../../docs/roadmap/code-playground.md) | 豊富な視覚化機能を備えたサンドボックス化されたコード生成と実行 | 計画中 | ## 🔐 環境設定の詳細 AgentDockオープンソースクライアントが機能するには、LLMプロバイダーのAPIキーが必要です。これらは、提供されている`.env.example`ファイルに基づいて作成する環境ファイル(`.env`または`.env.local`)で設定されます。 ### LLMプロバイダーAPIキー LLMプロバイダーのAPIキーを追加します(少なくとも1つ必要です): ```bash # LLMプロバイダーAPIキー - 少なくとも1つ必要 ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Anthropic APIキー OPENAI_API_KEY=sk-xxxxxxx # OpenAI APIキー GEMINI_API_KEY=xxxxxxx # Google Gemini APIキー DEEPSEEK_API_KEY=xxxxxxx # DeepSeek APIキー GROQ_API_KEY=xxxxxxx # Groq APIキー ``` ### APIキーの解決 AgentDockオープンソースクライアントは、使用するAPIキーを解決する際に優先順位に従います: 1. **エージェントごとのカスタムAPIキー**(UIのエージェント設定経由で設定) 2. **グローバル設定APIキー**(UIの設定ページ経由で設定) 3. **環境変数**(.env.localまたはデプロイメントプラットフォームから) ### ツール固有のAPIキー 一部のツールでは、独自のAPIキーも必要です: ```bash # ツール固有のAPIキー SERPER_API_KEY= # 検索機能に必要 FIRECRAWL_API_KEY= # より詳細なウェブ検索に必要 ``` 環境設定の詳細については、[`src/types/env.ts`](../../src/types/env.ts)の実装を参照してください。 ### 独自のAPIキーを使用する (BYOK) AgentDockはBYOK (Bring Your Own Key:自分のAPIキーを使用) モデルに従います: 1. アプリケーションの設定ページでAPIキーを追加します 2. または、直接APIを使用するためにリクエストヘッダー経由でキーを提供します 3. キーは組み込みの暗号化システムを使用して安全に保存されます 4. APIキーは当社のサーバーで共有または保存されることはありません ## 📦 パッケージマネージャー このプロジェクトでは、一貫した依存関係管理のために`pnpm`の使用が*必須*です。`npm`および`yarn`はサポートされていません。 ## 💡 何を構築できるか 1. **AI搭載アプリケーション** - 任意のフロントエンドを備えたカスタムチャットボット - コマンドラインAIアシスタント - 自動化されたデータ処理パイプライン - バックエンドサービス統合 2. **統合機能** - 任意のAIプロバイダー(OpenAI、Anthropicなど) - 任意のフロントエンドフレームワーク - 任意のバックエンドサービス - カスタムデータソースとAPI 3. **自動化システム** - データ処理ワークフロー - ドキュメント分析パイプライン - 自動化されたレポートシステム - タスク自動化エージェント ## 主な機能 | 機能 | 説明 | | :------------------------------- | :-------------------------------------------------------------------------------- | | 🔌 **フレームワーク非依存 (Node.js Backend)** | コアライブラリはNode.jsバックエンドスタックと統合します。 | | 🧩 **モジュール設計** | シンプルなノードから複雑なシステムを構築 | | 🛠️ **拡張可能** | あらゆる機能に対応するカスタムノードを作成 | | 🔒 **セキュア** | APIキーとデータのための組み込みセキュリティ機能 | | 🔑 **BYOK** | LLMプロバイダーには*独自のAPIキーを使用* | | 📦 **独立自己完結型** | コアフレームワークは最小限の依存関係を持ちます | | ⚙️ **マルチステップツールコール(段階的ツール呼び出し)** | *複雑な推論チェーン*をサポート | | 📊 **構造化ロギング** | エージェント実行に関する詳細な洞察 | | 🛡️ **強固なエラー処理** | 予測可能な挙動と簡素化されたデバッグ | | 📝 **TypeScriptファースト** | 型安全性と向上した開発者エクスペリエンス | | 🌐 **オープンソースクライアント** | 完全なNext.jsリファレンス実装を含む | | 🔄 **オーケストレーション** | コンテキストに基づくエージェント挙動の*動的制御* | | 💾 **セッション管理** | 同時会話のための分離された状態 | | 🎮 **設定可能な決定論** | ノードロジック/ワークフローを介してAIの創造性と予測可能性のバランスを取ります。 | ## 🧰 コンポーネント AgentDockのモジュール式アーキテクチャは、以下の主要コンポーネントに基づいて構築されています: * **BaseNode**:システム内のすべてのノードの基盤 * **AgentNode**:エージェント機能の主要な抽象化 * **ツール&カスタムノード**:ノードとして実装された呼び出し可能な機能とカスタムロジック。 * **ノードレジストリ**:すべてのノードタイプの登録と取得を管理 * **ツールレジストリ**:エージェントのツール可用性を管理 * **CoreLLM**:LLMプロバイダーとの対話のための統一インターフェース * **プロバイダーレジストリ**:LLMプロバイダー設定を管理 * **エラー処理**:エラーを処理し、予測可能な挙動を保証するためのシステム * **ロギング**:監視とデバッグのための構造化ロギングシステム * **オーケストレーション**:会話コンテキストに基づいてツールの可用性と挙動を制御 * **セッション**:同時会話間の状態分離を管理 これらのコンポーネントに関する詳細な技術ドキュメントについては、[アーキテクチャ概要](../../docs/architecture/README.md)を参照してください。 ## 🗺️ ロードマップ 以下はAgentDockの開発ロードマップです。ここに記載されている改善点のほとんどは、現在ローカルで開発されており、安定版に達した時点でバージョン管理されたNPMパッケージとして公開されるコアAgentDockフレームワーク(`agentdock-core`)に関連しています。一部のロードマップ項目には、オープンソースクライアント実装の機能強化も含まれる場合があります。 | 機能 | 説明 | カテゴリ | | :------------------------------------------------------------------- | :---------------------------------------------------------------------------------- | :--------------- | | [**ストレージ抽象化レイヤー**](../../docs/roadmap/storage-abstraction.md) | プラグ可能なプロバイダーを備えた柔軟なストレージシステム | **進行中** | | [**高度なメモリシステム**](../../docs/roadmap/advanced-memory.md) | 長期的なコンテキスト管理 | **進行中** | | [**ベクトルストレージ統合**](../../docs/roadmap/vector-storage.md) | ドキュメントとメモリのための埋め込みベースの検索 | **進行中** | | [**AIエージェントの評価**](../../docs/roadmap/evaluation-framework.md) | 包括的なテストおよび評価フレームワーク | **進行中** | | [**プラットフォーム統合**](../../docs/roadmap/platform-integration.md) | Telegram、WhatsApp、その他のメッセージングプラットフォームのサポート | **計画中** | | [**マルチエージェントコラボレーション**](../../docs/roadmap/multi-agent-collaboration.md) | エージェントが連携して作業できるようにする | **計画中** | | [**モデルコンテキストプロトコル(MCP)統合**](../../docs/roadmap/mcp-integration.md) | MCPを介した外部ツールの検出と使用のサポート | **計画中** | | [**音声AIエージェント**](../../docs/roadmap/voice-agents.md) | AgentNodeを介した音声インターフェースと電話番号を使用するAIエージェント | **計画中** | | [**テレメトリとトレーサビリティ**](../../docs/roadmap/telemetry.md) | 高度なロギングとパフォーマンス追跡 | **計画中** | | [**Workflow Runtime & Node タイプ**](../../docs/roadmap/workflow-nodes.md) | コア runtime、ノードタイプ、および複雑な自動化のためのオーケストレーションロジック | **計画中** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | AIエージェントとワークフローをスケーリングするための包括的なエンタープライズクラウドプラットフォーム | **クラウド** | | [**自然言語AIエージェントビルダー**](../../docs/roadmap/nl-agent-builder.md) | ビジュアルビルダー+自然言語エージェントとワークフロー構築 | **クラウド** | | [**エージェントマーケットプレイス**](../../docs/roadmap/agent-marketplace.md) | 収益化可能なエージェントテンプレート | **クラウド** | ## 👥 貢献 AgentDockへの貢献を歓迎します!詳細な貢献ガイドラインについては、[CONTRIBUTING.md](../../CONTRIBUTING.md)をご覧ください。 ## 📜 ライセンス AgentDockは[MITライセンス](../../LICENSE)の下でリリースされています。 ## ✨ 無限の可能性を創造しよう! AgentDockは、想像できるほとんどすべてのAI搭載アプリケーションや自動化を構築するための基盤を提供します。フレームワークを探求し、革新的なエージェントを構築し、コミュニティに貢献することをお勧めします。一緒にAIインタラクションの未来を築きましょう! --- [翻訳インデックスに戻る](/docs/i18n/README.md) ## AgentDock: AI 에이전트로 무한한 가능성을 창조하세요

AgentDock Logo

## 🌐 README 번역 [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock은 **구성 가능한 결정성(Configurable Determinism)**을 통해 복잡한 작업을 수행하는 정교한 AI 에이전트를 구축하기 위한 프레임워크입니다. 두 가지 주요 구성 요소로 구성되어 있습니다: 1. **AgentDock Core**: AI 에이전트를 구축하고 배포하기 위한 오픈 소스, 백엔드 우선 프레임워크입니다. *프레임워크에 구애받지 않고* *공급업체에 독립적*으로 설계되어 에이전트 구현에 대한 완전한 제어권을 제공합니다. 2. **오픈 소스 클라이언트**: AgentDock Core 프레임워크의 참조 구현 및 소비자로 사용되는 완전한 Next.js 애플리케이션입니다. [https://hub.agentdock.ai](https://hub.agentdock.ai)에서 작동하는 것을 볼 수 있습니다. TypeScript로 구축된 AgentDock은 *단순성*, *확장성* 및 ***구성 가능한 결정성***을 강조하여 최소한의 감독으로 작동할 수 있는 신뢰할 수 있고 예측 가능한 AI 시스템을 구축하는 데 이상적입니다. ## 🧠 설계 원칙 AgentDock은 다음과 같은 핵심 원칙을 토대로 개발되었습니다: - **단순성 우선**: 기능적인 에이전트를 만드는 데 필요한 최소한의 코드 - **노드 기반 아키텍처**: 모든 기능은 노드로 구현됩니다. - **특수 노드로서의 도구**: 도구는 에이전트 기능을 위해 노드 시스템을 확장합니다. - **구성 가능한 결정성**: 에이전트 동작의 예측 가능성 제어 - **타입 안전성**: 전체적으로 포괄적인 TypeScript 타입 ### 구성 가능한 결정성 ***구성 가능한 결정성***은 AgentDock 설계 철학의 초석이며, 창의적인 AI 기능과 예측 가능한 시스템 동작 간의 균형을 맞출 수 있게 해줍니다: - AgentNode는 LLM이 매번 다른 응답을 생성할 수 있으므로 본질적으로 비결정적입니다. - 워크플로는 *정의된 도구 실행 경로*를 통해 더 결정적으로 만들 수 있습니다. - 개발자는 시스템의 어느 부분이 LLM 추론을 사용하는지 구성하여 **결정성 수준을 제어**할 수 있습니다. - LLM 구성 요소가 있더라도 전체 시스템 동작은 구조화된 도구 상호 작용을 통해 **예측 가능**하게 유지됩니다. - 이 균형 잡힌 접근 방식은 AI 애플리케이션에서 *창의성*과 **신뢰성**을 모두 가능하게 합니다. #### 결정적 워크플로 AgentDock은 일반적인 워크플로 빌더에서 익숙한 결정적 워크플로를 완벽하게 지원합니다. 기대하는 모든 예측 가능한 실행 경로와 신뢰할 수 있는 결과는 LLM 추론 유무에 관계없이 사용할 수 있습니다: ```mermaid flowchart LR Input[입력] --> Process[처리] Process --> Database[(데이터베이스)] Process --> Output[출력] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### 비결정적 에이전트 동작 AgentDock을 사용하면 더 많은 적응성이 필요할 때 LLM과 함께 AgentNode를 활용할 수도 있습니다. 창의적인 출력은 필요에 따라 달라질 수 있지만 구조화된 상호 작용 패턴은 유지됩니다: ```mermaid flowchart TD Input[사용자 쿼리] --> Agent[AgentNode] Agent -->|"LLM 추론 (비결정적)"| ToolChoice{도구 선택} ToolChoice -->|"옵션 A"| ToolA[심층 조사 도구] ToolChoice -->|"옵션 B"| ToolB[데이터 분석 도구] ToolChoice -->|"옵션 C"| ToolC[직접 응답] ToolA --> Response[최종 응답] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### 결정적 하위 워크플로를 가진 비결정적 에이전트 AgentDock은 비결정적 에이전트 인텔리전스와 결정적 워크플로 실행을 결합하여 ***두 세계의 장점***을 모두 제공합니다: ```mermaid flowchart TD Input[사용자 쿼리] --> Agent[AgentNode] Agent -->|"LLM 추론 (비결정적)"| FlowChoice{하위 워크플로 선택} FlowChoice -->|"결정 A"| Flow1[결정적 워크플로 1] FlowChoice -->|"결정 B"| Flow2[결정적 워크플로 2] FlowChoice -->|"결정 C"| DirectResponse[응답 생성] Flow1 --> |"단계 1 → 2 → 3 → ... → 200"| Flow1Result[워크플로 1 결과] Flow2 --> |"단계 1 → 2 → 3 → ... → 100"| Flow2Result[워크플로 2 결과] Flow1Result --> Response[최종 응답] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` 이 접근 방식을 사용하면 복잡한 다단계 워크플로(도구 내에서 또는 연결된 노드 시퀀스로 구현된 수백 개의 결정적 단계를 포함할 수 있음)를 지능형 에이전트 결정에 의해 호출할 수 있습니다. 각 워크플로는 비결정적 에이전트 추론에 의해 트리거되었음에도 불구하고 예측 가능하게 실행됩니다. 더 고급 AI 에이전트 워크플로 및 다단계 처리 파이프라인을 위해 복잡한 에이전트 시스템을 생성, 시각화 및 실행하기 위한 강력한 플랫폼인 [AgentDock Pro](../../docs/agentdock-pro.md)를 구축하고 있습니다. #### 구성 가능한 결정성: 요약 자동차 운전에 비유해 보겠습니다. 때로는 AI의 창의성이 필요하고(도시 거리 탐색과 같이 - 비결정적), 때로는 신뢰할 수 있는 단계별 프로세스가 필요합니다(고속도로 표지판 따르기와 같이 - 결정적). AgentDock을 사용하면 작업의 각 부분에 적합한 접근 방식을 선택하여 *두 가지*를 모두 사용하는 시스템을 구축할 수 있습니다. AI의 창의성과 필요할 때 예측 가능한 결과를 모두 확보할 수 있습니다. ## 🏗️ 핵심 아키텍처 프레임워크는 모든 에이전트 기능의 기반이 되는 강력하고 모듈화된 노드 기반 시스템을 중심으로 구축되었습니다. 이 아키텍처는 빌딩 블록으로 고유한 노드 유형을 사용합니다: - **`BaseNode`**: 모든 노드의 핵심 인터페이스와 기능을 설정하는 기본 클래스입니다. - **`AgentNode`**: LLM 상호 작용, 도구 사용 및 에이전트 로직을 조율하는 특수 핵심 노드입니다. - **도구 및 사용자 정의 노드**: 개발자는 `BaseNode`를 확장하는 노드로 에이전트 기능과 사용자 정의 로직을 구현합니다. 이러한 노드는 관리되는 레지스트리를 통해 상호 작용하며, 복잡하고 구성 가능하며 잠재적으로 결정적인 에이전트 동작 및 워크플로를 가능하게 하기 위해 (핵심 아키텍처의 포트 및 잠재적 메시지 버스를 활용하여) 연결될 수 있습니다. 노드 시스템의 구성 요소 및 기능에 대한 자세한 설명은 [노드 시스템 문서](../../docs/nodes/README.md)를 참조하십시오. ## 🚀 시작하기 포괄적인 가이드는 [시작하기 가이드](../../docs/getting-started.md)를 참조하십시오. ### 요구 사항 * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (필수) * LLM 공급업체(Anthropic, OpenAI 등)용 API 키 ### 설치 1. **리포지토리 복제**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **pnpm 설치**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **종속성 설치**: ```bash pnpm install ``` 클린 재설치(처음부터 다시 빌드해야 하는 경우): ```bash pnpm run clean-install ``` 이 스크립트는 모든 node_modules, 잠금 파일을 제거하고 종속성을 올바르게 다시 설치합니다. 4. **환경 구성**: 제공된 `.env.example` 파일을 기반으로 환경 파일(`.env` 또는 `.env.local`)을 만듭니다: ```bash # 옵션 1: .env.local 만들기 cp .env.example .env.local # 옵션 2: .env 만들기 cp .env.example .env ``` 그런 다음 API 키를 환경 파일에 추가합니다. 5. **개발 서버 시작**: ```bash pnpm dev ``` ### 고급 기능 | 기능 | 설명 | 문서 | | :------------------- | :--------------------------------------------------------------------------------- | :-------------------------------------------------------------------------- | | **세션 관리** | 대화를 위한 격리되고 성능 좋은 상태 관리 | [세션 문서](../../docs/architecture/sessions/README.md) | | **오케스트레이션 프레임워크** | 컨텍스트에 따라 에이전트 동작 및 도구 가용성 제어 | [오케스트레이션 문서](../../docs/architecture/orchestration/README.md) | | **스토리지 추상화** | KV, Vector 및 Secure 스토리지를 위한 플러그형 공급업체가 있는 유연한 스토리지 시스템 | [스토리지 문서](../../docs/storage/README.md) | 스토리지 시스템은 현재 키-값 스토리지(Memory, Redis, Vercel KV 공급업체) 및 보안 클라이언트 측 스토리지로 발전하고 있으며, 벡터 스토리지 및 추가 백엔드는 개발 중입니다. ## 📕 문서 AgentDock 프레임워크 문서는 [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) 및 이 리포지토리의 `/docs/` 폴더에서 사용할 수 있습니다. 문서에는 다음이 포함됩니다: - 시작하기 가이드 - API 참조 - 노드 생성 튜토리얼 - 통합 예제 ## 📂 리포지토리 구조 이 리포지토리에는 다음이 포함됩니다: 1. **AgentDock Core**: `agentdock-core/`에 있는 핵심 프레임워크 2. **오픈 소스 클라이언트**: AgentDock Core 프레임워크의 소비자로 사용되는 Next.js로 구축된 완전한 참조 구현입니다. 3. **예제 에이전트**: `agents/` 디렉토리에 있는 즉시 사용 가능한 에이전트 구성 AgentDock Core를 자체 애플리케이션에서 독립적으로 사용하거나 이 리포지토리를 자체 에이전트 기반 애플리케이션 구축의 시작점으로 사용할 수 있습니다. ## 📝 에이전트 템플릿 AgentDock에는 사전 구성된 여러 에이전트 템플릿이 포함되어 있습니다. `agents/` 디렉토리에서 탐색하거나 구성 세부 정보는 [에이전트 템플릿 문서](../../docs/agent-templates.md)를 읽어보십시오. ## 🔧 예제 구현 예제 구현은 특수 사용 사례 및 고급 기능을 보여줍니다: | 구현 | 설명 | 상태 | | :-------------------- | :----------------------------------------------------------------------- | :-------- | | **오케스트레이션된 에이전트** | 컨텍스트에 따라 동작을 조정하기 위해 오케스트레이션을 사용하는 예제 에이전트 | 사용 가능 | | **인지적 추론자** | 구조화된 추론 및 인지 도구를 사용하여 복잡한 문제 해결 | 사용 가능 | | **에이전트 플래너** | 다른 AI 에이전트를 설계하고 구현하기 위한 특수 에이전트 | 사용 가능 | | [**코드 플레이그라운드(Code Playground)**](../../docs/roadmap/code-playground.md) | 풍부한 시각화 기능을 갖춘 샌드박스 코드 생성 및 실행 | 계획됨 | ## 🔐 환경 구성 세부 정보 AgentDock 오픈 소스 클라이언트는 작동하려면 LLM 공급업체용 API 키가 필요합니다. 이는 제공된 `.env.example` 파일을 기반으로 생성하는 환경 파일(`.env` 또는 `.env.local`)에서 구성됩니다. ### LLM 공급업체 API 키 LLM 공급업체 API 키를 추가합니다(최소 1개 필요): ```bash # LLM 공급업체 API 키 - 최소 1개 필요 ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Anthropic API 키 OPENAI_API_KEY=sk-xxxxxxx # OpenAI API 키 GEMINI_API_KEY=xxxxxxx # Google Gemini API 키 DEEPSEEK_API_KEY=xxxxxxx # DeepSeek API 키 GROQ_API_KEY=xxxxxxx # Groq API 키 ``` ### API 키 확인 AgentDock 오픈 소스 클라이언트는 사용할 API 키를 확인할 때 우선 순위를 따릅니다: 1. **에이전트별 사용자 정의 API 키**(UI의 에이전트 설정을 통해 설정) 2. **전역 설정 API 키**(UI의 설정 페이지를 통해 설정) 3. **환경 변수**(.env.local 또는 배포 플랫폼에서) ### 도구별 API 키 일부 도구에는 자체 API 키도 필요합니다: ```bash # 도구별 API 키 SERPER_API_KEY= # 검색 기능에 필요 FIRECRAWL_API_KEY= # 더 깊은 웹 검색에 필요 ``` 환경 구성에 대한 자세한 내용은 [`src/types/env.ts`](../../src/types/env.ts)의 구현을 참조하십시오. ### 자체 API 키 사용(BYOK) AgentDock은 BYOK(Bring Your Own Key: 자체 API 키 사용) 모델을 따릅니다: 1. 애플리케이션의 설정 페이지에서 API 키를 추가합니다. 2. 또는 직접 API 사용을 위해 요청 헤더를 통해 키를 제공합니다. 3. 키는 내장된 암호화 시스템을 사용하여 안전하게 저장됩니다. 4. API 키는 당사 서버에서 공유되거나 저장되지 않습니다. ## 📦 패키지 관리자 이 프로젝트는 일관된 종속성 관리를 위해 `pnpm` 사용이 *필수*입니다. `npm` 및 `yarn`은 지원되지 않습니다. ## 💡 무엇을 구축할 수 있나요? 1. **AI 기반 애플리케이션** - 모든 프런트엔드를 갖춘 사용자 정의 챗봇 - 명령줄 AI 어시스턴트 - 자동화된 데이터 처리 파이프라인 - 백엔드 서비스 통합 2. **통합 기능** - 모든 AI 공급업체(OpenAI, Anthropic 등) - 모든 프런트엔드 프레임워크 - 모든 백엔드 서비스 - 사용자 정의 데이터 소스 및 API 3. **자동화 시스템** - 데이터 처리 워크플로 - 문서 분석 파이프라인 - 자동화된 보고 시스템 - 작업 자동화 에이전트 ## 주요 기능 | 기능 | 설명 | | :------------------------ | :--------------------------------------------------------------------------------- | | 🔌 **프레임워크 독립적 (Node.js 백엔드)** | 핵심 라이브러리는 Node.js 백엔드 스택과 통합됩니다. | | 🧩 **모듈식 디자인** | 간단한 노드에서 복잡한 시스템 구축 | | 🛠️ **확장 가능** | 모든 기능에 대한 사용자 정의 노드 생성 | | 🔒 **보안** | API 키 및 데이터를 위한 내장 보안 기능 | | 🔑 **BYOK** | LLM 공급자에는 *자신의 API 키를 사용* | | 📦 **독립형(Self-contained)** | 핵심 프레임워크는 최소한의 종속성을 가집니다 | | ⚙️ **다단계 도구 호출(Multi-Step Tool Calls)** | *복잡한 추론 체인* 지원 | | 📊 **구조화된 로깅** | 에이전트 실행에 대한 상세한 통찰력 | | 🛡️ **강력한 오류 처리** | 예측 가능한 동작 및 간소화된 디버깅 | | 📝 **TypeScript 우선** | 타입 안전성 및 향상된 개발자 경험 | | 🌐 **오픈 소스 클라이언트** | 완전한 Next.js 참조 구현 포함 | | 🔄 **오케스트레이션** | 컨텍스트 기반 에이전트 동작의 *동적 제어* | | 💾 **세션 관리** | 동시 대화를 위한 격리된 상태 | | 🎮 **구성 가능한 결정성** | 노드 로직/워크플로를 통해 AI 창의성 및 예측 가능성 균형 조정. | ## 🧰 구성 요소 AgentDock의 모듈식 아키텍처는 다음과 같은 주요 구성 요소를 기반으로 구축되었습니다: * **BaseNode**: 시스템의 모든 노드 기반 * **AgentNode**: 에이전트 기능의 기본 추상화 * **도구 및 사용자 정의 노드**: 노드로 구현된 호출 가능한 기능 및 사용자 정의 로직입니다. * **노드 레지스트리**: 모든 노드 유형의 등록 및 검색 관리 * **도구 레지스트리**: 에이전트에 대한 도구 가용성 관리 * **CoreLLM**: LLM 공급업체와 상호 작용하기 위한 통합 인터페이스 * **공급업체 레지스트리**: LLM 공급업체 구성 관리 * **오류 처리**: 오류 처리 및 예측 가능한 동작 보장 시스템 * **로깅**: 모니터링 및 디버깅을 위한 구조화된 로깅 시스템 * **오케스트레이션**: 대화 컨텍스트에 따라 도구 가용성 및 동작 제어 * **세션**: 동시 대화 간 상태 격리 관리 이러한 구성 요소에 대한 자세한 기술 문서는 [아키텍처 개요](../../docs/architecture/README.md)를 참조하십시오. ## 🗺️ 로드맵 다음은 AgentDock 개발 로드맵입니다. 여기에 나열된 대부분의 개선 사항은 현재 로컬에서 개발 중이며 안정적인 릴리스에 도달하면 버전 관리된 NPM 패키지로 게시될 핵심 AgentDock 프레임워크(`agentdock-core`)와 관련이 있습니다. 일부 로드맵 항목에는 오픈 소스 클라이언트 구현 개선 사항도 포함될 수 있습니다. | 기능 | 설명 | 카테고리 | | :-------------------------------------------------------------------- | :----------------------------------------------------------------------------------- | :-------------- | | [**스토리지 추상화 계층**](../../docs/roadmap/storage-abstraction.md) | 플러그형 공급업체가 있는 유연한 스토리지 시스템 | **진행 중** | | [**고급 메모리 시스템**](../../docs/roadmap/advanced-memory.md) | 장기 컨텍스트 관리 | **진행 중** | | [**벡터 스토리지 통합**](../../docs/roadmap/vector-storage.md) | 문서 및 메모리를 위한 임베딩 기반 검색 | **진행 중** | | [**AI 에이전트 평가**](../../docs/roadmap/evaluation-framework.md) | 포괄적인 테스트 및 평가 프레임워크 | **진행 중** | | [**플랫폼 통합**](../../docs/roadmap/platform-integration.md) | Telegram, WhatsApp 및 기타 메시징 플랫폼 지원 | **계획됨** | | [**다중 에이전트 협업**](../../docs/roadmap/multi-agent-collaboration.md) | 에이전트가 함께 작동하도록 지원 | **계획됨** | | [**모델 컨텍스트 프로토콜 (MCP) 통합**](../../docs/roadmap/mcp-integration.md) | MCP를 통한 외부 도구 검색 및 사용 지원 | **계획됨** | | [**음성 AI 에이전트**](../../docs/roadmap/voice-agents.md) | AgentNode를 통한 음성 인터페이스 및 전화번호를 사용하는 AI 에이전트 | **계획됨** | | [**텔레메트리 및 추적성**](../../docs/roadmap/telemetry.md) | 고급 로깅 및 성능 추적 | **계획됨** | | [**Workflow Runtime & Node 타입**](../../docs/roadmap/workflow-nodes.md) | 코어 runtime, 노드 타입 및 복잡한 자동화를 위한 오케스트레이션 로직 | **계획됨** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | AI 에이전트 및 워크플로 확장을 위한 포괄적인 엔터프라이즈 클라우드 플랫폼 | **클라우드** | | [**자연어 AI 에이전트 빌더**](../../docs/roadmap/nl-agent-builder.md) | 시각적 빌더 + 자연어 에이전트 및 워크플로 구축 | **클라우드** | | [**에이전트 마켓플레이스**](../../docs/roadmap/agent-marketplace.md) | 수익화 가능한 에이전트 템플릿 | **클라우드** | ## 👥 기여 AgentDock에 대한 기여를 환영합니다! 자세한 기여 가이드라인은 [CONTRIBUTING.md](../../CONTRIBUTING.md)를 참조하십시오. ## 📜 라이선스 AgentDock은 [MIT 라이선스](../../LICENSE)에 따라 출시됩니다. ## ✨ 무한한 가능성을 창조하세요! AgentDock은 상상할 수 있는 거의 모든 AI 기반 애플리케이션 또는 자동화를 구축할 수 있는 기반을 제공합니다. 프레임워크를 탐색하고 혁신적인 에이전트를 구축하며 커뮤니티에 기여해 보시기 바랍니다. AI 상호 작용의 미래를 함께 만들어 갑시다! --- [번역 색인으로 돌아가기](/docs/i18n/README.md) ## AgentDock: Twórz Nieograniczone Możliwości z Agentami AI

AgentDock Logo

## 🌐 Tłumaczenia README [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock to framework do budowania zaawansowanych agentów AI, które wykonują złożone zadania z **konfigurowalnym determinizmem**. Składa się z dwóch głównych komponentów: 1. **AgentDock Core**: Framework open-source, zorientowany na backend, do budowania i wdrażania agentów AI. Został zaprojektowany tak, aby był *niezależny od frameworka* i *niezależny od dostawcy*, dając Ci pełną kontrolę nad implementacją Twojego agenta. 2. **Open Source Client**: Pełna aplikacja Next.js, która służy jako referencyjna implementacja i konsument frameworka AgentDock Core. Możesz zobaczyć ją w akcji na [https://hub.agentdock.ai](https://hub.agentdock.ai) Zbudowany w TypeScript, AgentDock kładzie nacisk na *prostotę*, *rozszerzalność* i ***konfigurowalny determinizm***, co czyni go idealnym do budowania niezawodnych, przewidywalnych systemów AI, które mogą działać przy minimalnym nadzorze. ## 🧠 Zasady Projektowania AgentDock opiera się na tych podstawowych zasadach: - **Prostota na Pierwszym Miejscu**: Minimalny kod wymagany do tworzenia funkcjonalnych agentów - **Architektura Oparta na Węzłach (Nodes)**: Wszystkie możliwości są implementowane jako węzły - **Narzędzia jako Wyspecjalizowane Węzły**: Narzędzia rozszerzają system węzłów o możliwości agenta - **Konfigurowalny Determinizm**: Kontrola przewidywalności zachowania agenta - **Bezpieczeństwo Typów (Type Safety)**: Pełne typy TypeScript w całym systemie ### Konfigurowalny Determinizm ***Konfigurowalny determinizm*** jest kamieniem węgielnym filozofii projektowania AgentDock, pozwalającym zrównoważyć kreatywne możliwości AI z przewidywalnym zachowaniem systemu: - `AgentNode` są z natury niedeterministyczne, ponieważ LLM mogą generować różne odpowiedzi za każdym razem - Przepływy pracy (Workflows) można uczynić bardziej deterministycznymi poprzez *zdefiniowane ścieżki wykonywania narzędzi* - Deweloperzy mogą **kontrolować poziom determinizmu**, konfigurując, które części systemu wykorzystują wnioskowanie LLM - Nawet z komponentami LLM, ogólne zachowanie systemu pozostaje **przewidywalne** dzięki ustrukturyzowanym interakcjom narzędzi - To zrównoważone podejście pozwala zarówno na *kreatywność*, jak i **niezawodność** w Twoich aplikacjach AI #### Deterministyczne Przepływy Pracy AgentDock w pełni obsługuje deterministyczne przepływy pracy, które znasz z typowych kreatorów przepływów pracy. Wszystkie przewidywalne ścieżki wykonania i niezawodne wyniki, których oczekujesz, są dostępne, z wnioskowaniem LLM lub bez: ```mermaid flowchart LR Input[Wejście] --> Process[Proces] Process --> Database[(Baza Danych)] Process --> Output[Wyjście] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Niedeterministyczne Zachowanie Agenta Z AgentDock możesz również wykorzystać `AgentNode` z LLM, gdy potrzebujesz większej adaptacyjności. Kreatywne wyniki mogą się różnić w zależności od Twoich potrzeb, zachowując jednocześnie ustrukturyzowane wzorce interakcji: ```mermaid flowchart TD Input[Zapytanie Użytkownika] --> Agent[AgentNode] Agent -->|"Rozumowanie LLM (Niedeterministyczne)"| ToolChoice{Wybór Narzędzia} ToolChoice -->|"Opcja A"| ToolA[Narzędzie Dogłębnego Badania] ToolChoice -->|"Opcja B"| ToolB[Narzędzie Analizy Danych] ToolChoice -->|"Opcja C"| ToolC[Bezpośrednia Odpowiedź] ToolA --> Response[Ostateczna Odpowiedź] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Niedeterministyczni Agenci z Deterministycznymi Pod-Przepływami Pracy AgentDock oferuje Ci ***najlepsze z obu światów***, łącząc niedeterministyczną inteligencję agenta z deterministycznym wykonywaniem przepływu pracy: ```mermaid flowchart TD Input[Zapytanie Użytkownika] --> Agent[AgentNode] Agent -->|"Rozumowanie LLM (Niedeterministyczne)"| FlowChoice{Wybór Pod-Przepływu} FlowChoice -->|"Decyzja A"| Flow1[Deterministyczny Przepływ Pracy 1] FlowChoice -->|"Decyzja B"| Flow2[Deterministyczny Przepływ Pracy 2] FlowChoice -->|"Decyzja C"| DirectResponse[Generuj Odpowiedź] Flow1 --> |"Krok 1 → 2 → 3 → ... → 200"| Flow1Result[Wynik Przepływu Pracy 1] Flow2 --> |"Krok 1 → 2 → 3 → ... → 100"| Flow2Result[Wynik Przepływu Pracy 2] Flow1Result --> Response[Ostateczna Odpowiedź] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` To podejście pozwala na wywoływanie złożonych, wieloetapowych przepływów pracy (potencjalnie obejmujących setki deterministycznych kroków zaimplementowanych w narzędziach lub jako sekwencje połączonych węzłów) przez inteligentne decyzje agentów. Każdy przepływ pracy jest wykonywany w sposób przewidywalny, mimo że jest wyzwalany przez niedeterministyczne rozumowanie agenta. Dla bardziej zaawansowanych przepływów pracy agentów AI i wieloetapowych potoków przetwarzania, budujemy [AgentDock Pro](../../docs/agentdock-pro.md) - potężną platformę do budowania, wizualizacji i uruchamiania złożonych systemów agentów. #### W skrócie: Konfigurowalny Determinizm Wyobraź to sobie jak prowadzenie samochodu. Czasami potrzebujesz kreatywności AI (jak nawigacja po ulicach miasta - niedeterministyczna), a czasami potrzebujesz niezawodnych, krok po kroku procesów (jak podążanie za znakami na autostradzie - deterministyczne). AgentDock pozwala budować systemy, które wykorzystują *oba*, wybierając odpowiednie podejście dla każdej części zadania. Zyskujesz zarówno kreatywność AI, *jak i* przewidywalne wyniki tam, gdzie ich potrzebujesz. ## 🏗️ Architektura Rdzenia Framework jest zbudowany wokół potężnego, modułowego systemu opartego na węzłach (Nodes), który służy jako podstawa dla całej funkcjonalności agenta. Ta architektura wykorzystuje odrębne typy węzłów jako bloki konstrukcyjne: - **`BaseNode`**: Podstawowa klasa, która ustanawia podstawowy interfejs i możliwości dla wszystkich węzłów. - **`AgentNode`**: Wyspecjalizowany węzeł rdzenia, który koordynuje interakcje LLM, użycie narzędzi i logikę agenta. - **Narzędzia i Węzły Niestandardowe**: Deweloperzy implementują możliwości agenta i logikę niestandardową jako węzły rozszerzające `BaseNode`. Te węzły współdziałają za pośrednictwem zarządzanych rejestrów i mogą być połączone (wykorzystując porty architektury rdzenia i potencjalną magistralę komunikatów), aby umożliwić złożone, konfigurowalne i potencjalnie deterministyczne zachowania i przepływy pracy agentów. Szczegółowe wyjaśnienie komponentów i możliwości systemu węzłów znajduje się w [Dokumentacji Systemu Węzłów](../../docs/nodes/README.md). ## 🚀 Pierwsze Kroki Kompleksowy przewodnik znajduje się w [Przewodniku Wprowadzającym](../../docs/getting-started.md). ### Wymagania * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Wymagane) * Klucze API dla dostawców LLM (Anthropic, OpenAI, itp.) ### Instalacja 1. **Sklonuj Repozytorium**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Zainstaluj pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Zainstaluj Zależności**: ```bash pnpm install ``` Dla czystej ponownej instalacji (gdy musisz przebudować od zera): ```bash pnpm run clean-install ``` Ten skrypt usuwa wszystkie `node_modules`, pliki blokady i poprawnie ponownie instaluje zależności. 4. **Skonfiguruj Środowisko**: Utwórz plik środowiskowy (`.env` lub `.env.local`) na podstawie dostarczonego pliku `.env.example`: ```bash # Opcja 1: Utwórz .env.local cp .env.example .env.local # Opcja 2: Utwórz .env cp .env.example .env ``` Następnie dodaj swoje klucze API do pliku środowiskowego. 5. **Uruchom Serwer Deweloperski**: ```bash pnpm dev ``` ### Zaawansowane Możliwości | Możliwość | Opis | Dokumentacja | | :------------------------- | :------------------------------------------------------------------------------------------ | :----------------------------------------------------------------------------------- | | **Zarządzanie Sesjami** | Izolowane, wysokowydajne zarządzanie stanem dla konwersacji | [Dokumentacja Sesji](../../docs/architecture/sessions/README.md) | | **Framework Orkiestracji** | Kontrola zachowania agenta i dostępności narzędzi w oparciu o kontekst | [Dokumentacja Orkiestracji](../../docs/architecture/orchestration/README.md) | | **Abstrakcja Pamięci Masowej** | Elastyczny system pamięci masowej z podłączanymi dostawcami dla KV, Vector i Secure Storage | [Dokumentacja Pamięci Masowej](../../docs/storage/README.md) | System pamięci masowej obecnie ewoluuje wraz z pamięcią masową klucz-wartość (dostawcy Memory, Redis, Vercel KV) i bezpieczną pamięcią masową po stronie klienta, podczas gdy pamięć masowa wektorowa i dodatkowe backendy są w fazie rozwoju. ## 📕 Dokumentacja Dokumentacja frameworka AgentDock jest dostępna na [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) oraz w folderze `/docs/` tego repozytorium. Dokumentacja zawiera: - Przewodniki wprowadzające - Referencje API - Samouczki tworzenia węzłów - Przykłady integracji ## 📂 Struktura Repozytorium To repozytorium zawiera: 1. **AgentDock Core**: Framework rdzenia znajdujący się w `agentdock-core/` 2. **Open Source Client**: Pełna implementacja referencyjna zbudowana w Next.js, służąca jako konsument frameworka AgentDock Core. 3. **Przykładowi Agenci**: Gotowe konfiguracje agentów w katalogu `agents/` Możesz używać AgentDock Core niezależnie we własnych aplikacjach lub użyć tego repozytorium jako punktu wyjścia do budowania własnych aplikacji opartych na agentach. ## 📝 Szablony Agentów AgentDock zawiera kilka prekonfigurowanych szablonów agentów. Przeglądaj je w katalogu `agents/` lub przeczytaj [Dokumentację Szablonów Agentów](../../docs/agent-templates.md), aby uzyskać szczegóły konfiguracji. ## 🔧 Przykładowe Implementacje Przykładowe implementacje prezentują wyspecjalizowane przypadki użycia i zaawansowaną funkcjonalność: | Implementacja | Opis | Status | | :--------------------------- | :------------------------------------------------------------------------------------------- | :----------- | | **Agent Orkiestrowany** | Przykładowy agent wykorzystujący orkiestrację do adaptacji zachowania w oparciu o kontekst | Dostępny | | **Rozumujący Kognitywny** | Rozwiązuje złożone problemy za pomocą ustrukturyzowanego rozumowania i narzędzi kognitywnych | Dostępny | | **Planista Agentów** | Wyspecjalizowany agent do projektowania i implementowania innych agentów AI | Dostępny | | [**Code Playground (Środowisko Testowe Kodu)**](../../docs/roadmap/code-playground.md) | Generowanie i wykonywanie kodu w piaskownicy z bogatymi możliwościami wizualizacji | Planowany | ## 🔐 Szczegóły Konfiguracji Środowiska AgentDock Open Source Client wymaga kluczy API dla dostawców LLM do działania. Są one konfigurowane w pliku środowiskowym (`.env` lub `.env.local`), który tworzysz na podstawie dostarczonego pliku `.env.example`. ### Klucze API Dostawców LLM Dodaj swoje klucze API dostawców LLM (wymagany co najmniej jeden): ```bash # Klucze API Dostawców LLM - wymagany co najmniej jeden ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Klucz API Anthropic OPENAI_API_KEY=sk-xxxxxxx # Klucz API OpenAI GEMINI_API_KEY=xxxxxxx # Klucz API Google Gemini DEEPSEEK_API_KEY=xxxxxxx # Klucz API DeepSeek GROQ_API_KEY=xxxxxxx # Klucz API Groq ``` ### Rozstrzyganie Kluczy API AgentDock Open Source Client stosuje kolejność priorytetów podczas rozstrzygania, którego klucza API użyć: 1. **Niestandardowy klucz API dla agenta** (ustawiony za pomocą ustawień agenta w interfejsie użytkownika) 2. **Globalny klucz API ustawień** (ustawiony za pomocą strony ustawień w interfejsie użytkownika) 3. **Zmienna środowiskowa** (z `.env.local` lub platformy wdrożeniowej) ### Klucze API Specyficzne dla Narzędzi Niektóre narzędzia wymagają również własnych kluczy API: ```bash # Klucze API Specyficzne dla Narzędzi SERPER_API_KEY= # Wymagany do funkcjonalności wyszukiwania FIRECRAWL_API_KEY= # Wymagany do głębszego przeszukiwania sieci ``` Więcej szczegółów na temat konfiguracji środowiska znajduje się w implementacji w [`src/types/env.ts`](../../src/types/env.ts). ### Użyj Własnego Klucza (BYOK) AgentDock działa w modelu BYOK (Bring Your Own Key - Użyj Własnego Klucza): 1. Dodaj swoje klucze API na stronie ustawień aplikacji 2. Alternatywnie, podaj klucze za pomocą nagłówków żądań do bezpośredniego użycia API 3. Klucze są bezpiecznie przechowywane za pomocą wbudowanego systemu szyfrowania 4. Żadne klucze API nie są udostępniane ani przechowywane na naszych serwerach ## 📦 Menedżer Pakietów Ten projekt *wymaga* użycia `pnpm` do spójnego zarządzania zależnościami. `npm` i `yarn` nie są obsługiwane. ## 💡 Co Możesz Zbudować 1. **Aplikacje Oparte na AI** - Niestandardowe chatboty z dowolnym frontendem - Asystenci AI wiersza poleceń - Zautomatyzowane potoki przetwarzania danych - Integracje usług backendowych 2. **Możliwości Integracji** - Dowolny dostawca AI (OpenAI, Anthropic, itp.) - Dowolny framework frontendowy - Dowolna usługa backendowa - Niestandardowe źródła danych i API 3. **Systemy Automatyzacji** - Przepływy pracy przetwarzania danych - Potoki analizy dokumentów - Zautomatyzowane systemy raportowania - Agenci automatyzacji zadań ## Kluczowe Cechy | Cecha | Opis | | :---------------------------- | :-------------------------------------------------------------------------------------------- | | 🔌 **Niezależny od Frameworka (Node.js Backend)** | Biblioteka rdzenia integruje się ze stosami backendowymi Node.js. | | 🧩 **Projekt Modułowy** | Buduj złożone systemy z prostych węzłów | | 🛠️ **Rozszerzalny** | Twórz niestandardowe węzły dla dowolnej funkcjonalności | | 🔒 **Bezpieczny** | Wbudowane funkcje bezpieczeństwa dla kluczy API i danych | | 🔑 **BYOK** | *Użyj Własnego Klucza* dla dostawców LLM | | 📦 **Autonomiczny (Self-contained)**| Framework rdzenia ma minimalne zależności | | ⚙️ **Wieloetapowe Wywołania Narzędzi (Multi-Step Tool Calls)**| Obsługa *złożonych łańcuchów rozumowania* | | 📊 **Logowanie Strukturalne** | Szczegółowy wgląd w wykonywanie agenta | | 🛡️ **Niezawodna Obsługa Błędów** | Przewidywalne zachowanie i uproszczone debugowanie | | 📝 **TypeScript na Pierwszym Miejscu** | Bezpieczeństwo typów i ulepszone doświadczenie deweloperskie | | 🌐 **Klient Open Source** | Zawiera pełną implementację referencyjną Next.js | | 🔄 **Orkiestracja** | *Dynamiczna kontrola* zachowania agenta w oparciu o kontekst | | 💾 **Zarządzanie Sesjami** | Izolowany stan dla współbieżnych konwersacji | | 🎮 **Konfigurowalny Determinizm**| Zrównoważ kreatywność AI i przewidywalność za pomocą logiki węzłów/przepływów pracy. | ## 🧰 Komponenty Modułowa architektura AgentDock opiera się na tych kluczowych komponentach: * **BaseNode**: Podstawa dla wszystkich węzłów w systemie * **AgentNode**: Główna abstrakcja dla funkcjonalności agenta * **Narzędzia i Węzły Niestandardowe**: Wywoływalne możliwości i logika niestandardowa implementowane jako węzły. * **Rejestr Węzłów**: Zarządza rejestracją i pobieraniem wszystkich typów węzłów * **Rejestr Narzędzi**: Zarządza dostępnością narzędzi dla agentów * **CoreLLM**: Zunifikowany interfejs do interakcji z dostawcami LLM * **Rejestr Dostawców**: Zarządza konfiguracjami dostawców LLM * **Obsługa Błędów**: System do obsługi błędów i zapewniania przewidywalnego zachowania * **Logowanie (Logging)**: Strukturalny system logowania do monitorowania i debugowania * **Orkiestracja**: Kontroluje dostępność narzędzi i zachowanie w oparciu o kontekst konwersacji * **Sesje**: Zarządza izolacją stanu między współbieżnymi konwersacjami Szczegółowa dokumentacja techniczna dotycząca tych komponentów znajduje się w [Przeglądzie Architektury](../../docs/architecture/README.md). ## 🗺️ Plan Rozwoju Poniżej znajduje się nasz plan rozwoju dla AgentDock. Większość wymienionych tutaj ulepszeń dotyczy frameworka rdzenia AgentDock (`agentdock-core`), który jest obecnie rozwijany lokalnie i zostanie opublikowany jako wersjonowany pakiet NPM po osiągnięciu stabilnej wersji. Niektóre pozycje planu rozwoju mogą również obejmować ulepszenia implementacji klienta open-source. | Cecha | Opis | Kategoria | | :-------------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------- | :------------- | | [**Warstwa Abstrakcji Pamięci Masowej**](../../docs/roadmap/storage-abstraction.md) | Elastyczny system pamięci masowej z podłączanymi dostawcami | **W Trakcie** | | [**Zaawansowane Systemy Pamięci**](../../docs/roadmap/advanced-memory.md) | Zarządzanie kontekstem długoterminowym | **W Trakcie** | | [**Integracja Pamięci Masowej Wektorowej**](../../docs/roadmap/vector-storage.md)| Odzyskiwanie oparte na osadzaniu dla dokumentów i pamięci | **W Trakcie** | | [**Ocena dla Agentów AI**](../../docs/roadmap/evaluation-framework.md) | Kompleksowy framework testowania i oceny | **W Trakcie** | | [**Integracja Platform**](../../docs/roadmap/platform-integration.md) | Wsparcie dla Telegrama, WhatsApp i innych platform komunikacyjnych | **Planowany** | | [**Współpraca Wielu Agentów**](../../docs/roadmap/multi-agent-collaboration.md)| Umożliwienie agentom współpracy | **Planowany** | | [**Integracja Protokołu Kontekstu Modelu (MCP)**](../../docs/roadmap/mcp-integration.md)| Wsparcie dla odkrywania i używania zewnętrznych narzędzi za pomocą MCP | **Planowany** | | [**Agenci AI Głosowi**](../../docs/roadmap/voice-agents.md) | Agenci AI używający interfejsów głosowych i numerów telefonów za pośrednictwem AgentNode | **Planowany** | | [**Telemetria i Identyfikowalność**](../../docs/roadmap/telemetry.md) | Zaawansowane logowanie i śledzenie wydajności | **Planowane** | | [**Workflow Runtime & Node Typy**](../../docs/roadmap/workflow-nodes.md) | Podstawowy runtime, typy węzłów (Nodes) i logika orkiestracji dla złożonych automatyzacji | **Planowane** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Kompleksowa platforma chmurowa dla przedsiębiorstw do skalowania agentów AI i przepływów pracy | **Chmura** | ## 👥 Współtworzenie Zapraszamy do współtworzenia AgentDock! Szczegółowe wytyczne dotyczące współtworzenia znajdują się w [CONTRIBUTING.md](../../CONTRIBUTING.md). ## 📜 Licencja AgentDock jest wydany na licencji [MIT License](../../LICENSE). ## ✨ Twórz Nieograniczone Możliwości! AgentDock stanowi fundament do budowania niemal każdej aplikacji opartej na AI lub automatyzacji, jaką możesz sobie wyobrazić. Zachęcamy do eksploracji frameworka, budowania innowacyjnych agentów i współtworzenia społeczności. Razem kształtujmy przyszłość interakcji z AI! --- [Powrót do Indeksu Tłumaczeń](/docs/i18n/README.md) ## AgentDock README Translations Welcome to the translated versions of the AgentDock README. ## Available Languages * [Français](./french/README.md) (French) * [日本語](./japanese/README.md) (Japanese) * [한국어](./korean/README.md) (Korean) * [中文](./chinese/README.md) (Chinese) * [Español](./spanish/README.md) (Spanish) * [Italiano](./italian/README.md) (Italian) * [Nederlands](./dutch/README.md) (Dutch) * [Deutsch](./deutsch/README.md) (German) * [Polski](./polish/README.md) (Polish) * [Türkçe](./turkish/README.md) (Turkish) * [Українська](./ukrainian/README.md) (Ukrainian) * [Ελληνικά](./greek/README.md) (Greek) * [Русский](./russian/README.md) (Russian) * [العربية](./arabic/README.md) (Arabic) > **Note:** Translations may lag behind the main English README. ## AgentDock: Создавайте Безграничные Возможности с Помощью ИИ-Агентов

AgentDock Logo

## 🌐 Переводы README [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock — это фреймворк для создания продвинутых ИИ-агентов, выполняющих сложные задачи с **настраиваемым детерминизмом**. Он состоит из двух основных компонентов: 1. **AgentDock Core**: Фреймворк с открытым исходным кодом, ориентированный на бэкенд, для создания и развертывания ИИ-агентов. Он спроектирован как *независимый от фреймворка* и *независимый от провайдера*, предоставляя вам полный контроль над реализацией вашего агента. 2. **Open Source Client**: Полноценное приложение Next.js, служащее эталонной реализацией и потребителем фреймворка AgentDock Core. Вы можете увидеть его в действии на [https://hub.agentdock.ai](https://hub.agentdock.ai) Созданный с использованием TypeScript, AgentDock делает упор на *простоту*, *расширяемость* и ***настраиваемый детерминизм***, что делает его идеальным для создания надежных, предсказуемых систем ИИ, способных работать с минимальным контролем. ## 🧠 Принципы Дизайна AgentDock основан на следующих ключевых принципах: - **Простота Прежде Всего**: Минимальный код, необходимый для создания функциональных агентов - **Архитектура на Основе Узлов (Nodes)**: Все возможности реализованы как узлы - **Инструменты как Специализированные Узлы**: Инструменты расширяют систему узлов для возможностей агента - **Настраиваемый Детерминизм**: Контролируйте предсказуемость поведения агента - **Типовая безопасность (Type Safety)**: Полная типизация TypeScript во всем фреймворке ### Настраиваемый Детерминизм ***Настраиваемый детерминизм*** является фундаментом философии дизайна AgentDock, позволяя сбалансировать творческие возможности ИИ с предсказуемым поведением системы: - `AgentNode` по своей природе недетерминирован, так как LLM могут генерировать разные ответы каждый раз - Рабочие процессы (Workflows) можно сделать более детерминированными с помощью *заранее определенных путей выполнения инструментов* - Разработчики могут **контролировать уровень детерминизма**, настраивая, какие части системы используют LLM-выводы - Даже с компонентами LLM общее поведение системы остается **предсказуемым** благодаря структурированным взаимодействиям инструментов - Этот сбалансированный подход обеспечивает как *творчество*, так и **надежность** в ваших ИИ-приложениях #### Детерминированные Рабочие Процессы AgentDock полностью поддерживает детерминированные рабочие процессы, знакомые вам по типичным конструкторам workflow. Все ожидаемые предсказуемые пути выполнения и надежные результаты доступны, с использованием LLM-выводов или без них: ```mermaid flowchart LR Input[Ввод] --> Process[Процесс] Process --> Database[(База данных)] Process --> Output[Вывод] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Недетерминированное Поведение Агента С AgentDock вы также можете использовать `AgentNode` с LLM, когда требуется большая адаптивность. Творческие результаты могут варьироваться в зависимости от ваших потребностей, сохраняя при этом структурированные шаблоны взаимодействия: ```mermaid flowchart TD Input[Запрос пользователя] --> Agent[AgentNode] Agent -->|"Рассуждение LLM (Недетерминированное)"| ToolChoice{Выбор инструмента} ToolChoice -->|"Вариант A"| ToolA[Инструмент глубинного исследования] ToolChoice -->|"Вариант B"| ToolB[Инструмент анализа данных] ToolChoice -->|"Вариант C"| ToolC[Прямой ответ] ToolA --> Response[Конечный ответ] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Недетерминированные Агенты с Детерминированными Подпроцессами AgentDock предлагает вам ***лучшее из обоих миров***, сочетая недетерминированный интеллект агента с детерминированным выполнением рабочих процессов: ```mermaid flowchart TD Input[Запрос пользователя] --> Agent[AgentNode] Agent -->|"Рассуждение LLM (Недетерминированное)"| FlowChoice{Выбор подпроцесса} FlowChoice -->|"Решение A"| Flow1[Детерминированный рабочий процесс 1] FlowChoice -->|"Решение B"| Flow2[Детерминированный рабочий процесс 2] FlowChoice -->|"Решение C"| DirectResponse[Сгенерировать ответ] Flow1 -->|"Шаг 1 → 2 → 3 → ... → 200"| Flow1Result[Результат рабочего процесса 1] Flow2 -->|"Шаг 1 → 2 → 3 → ... → 100"| Flow2Result[Результат рабочего процесса 2] Flow1Result --> Response[Конечный ответ] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Этот подход позволяет запускать сложные многошаговые рабочие процессы (потенциально включающие сотни детерминированных шагов, реализованных в инструментах или как последовательности связанных узлов) с помощью интеллектуальных решений агента. Каждый рабочий процесс выполняется предсказуемо, несмотря на то, что он запускается недетерминированным рассуждением агента. Для более продвинутых рабочих процессов ИИ-агентов и многоэтапных конвейеров обработки мы создаем [AgentDock Pro](../../docs/agentdock-pro.md) - мощную платформу для создания, визуализации и запуска сложных систем агентов. #### Кратко: Настраиваемый Детерминизм Представьте, что вы ведете машину. Иногда вам нужна креативность ИИ (например, навигация по городским улицам - недетерминированная), а иногда — надежные пошаговые процессы (например, следование знакам на шоссе - детерминированные). AgentDock позволяет создавать системы, использующие *оба* подхода, выбирая правильный для каждой части задачи. Вы получаете как интеллект ИИ, *так и* предсказуемые результаты там, где это необходимо. ## 🏗️ Ключевая Архитектура Фреймворк построен вокруг мощной модульной системы на основе узлов (Nodes), служащей фундаментом для всей функциональности агента. Эта архитектура использует различные типы узлов как строительные блоки: - **`BaseNode`**: Фундаментальный узел, определяющий основной интерфейс и возможности для всех узлов. - **`AgentNode`**: Специализированный ключевой узел, координирующий взаимодействия с LLM, использование инструментов и логику агента. - **Инструменты и Пользовательские Узлы**: Разработчики реализуют возможности агента и пользовательскую логику как узлы, расширяющие `BaseNode`. Эти узлы взаимодействуют через управляемые реестры и могут быть соединены (используя порты основной архитектуры и потенциально шину сообщений) для обеспечения сложного, настраиваемого и потенциально детерминированного поведения и рабочих процессов агентов. Подробное объяснение компонентов и возможностей системы узлов см. в [Документации Системы Узлов](../../docs/nodes/README.md). ## 🚀 Начало Работы Полное руководство см. в [Руководстве по Началу Работы](../../docs/getting-started.md). ### Требования * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Обязательно) * API-ключи для провайдеров LLM (Anthropic, OpenAI и т.д.) ### Установка 1. **Клонируйте Репозиторий**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Установите pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Установите Зависимости**: ```bash pnpm install ``` Для чистой переустановки (когда нужно пересобрать с нуля): ```bash pnpm run clean-install ``` Этот скрипт удаляет все `node_modules`, файлы блокировки и корректно переустанавливает зависимости. 4. **Настройте Окружение**: Создайте файл окружения (`.env` или `.env.local`) на основе предоставленного `.env.example`: ```bash # Вариант 1: Создать .env.local cp .env.example .env.local # Вариант 2: Создать .env cp .env.example .env ``` Затем добавьте ваши API-ключи в файл окружения. 5. **Запустите Сервер Разработки**: ```bash pnpm dev ``` ### Расширенные Возможности | Возможность | Описание | Документация | | :------------------------- | :----------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | **Управление Сессиями** | Изолированное, производительное управление состоянием для диалогов | [Документация Сессий](../../docs/architecture/sessions/README.md) | | **Фреймворк Оркестрации** | Контроль поведения агента и доступности инструментов в зависимости от контекста | [Документация Оркестрации](../../docs/architecture/orchestration/README.md) | | **Абстракция Хранилища** | Гибкая система хранения с подключаемыми провайдерами для KV, векторного и защищённого хранения | [Документация Хранилища](../../docs/storage/README.md) | Система хранения в настоящее время развивается: добавляется хранилище ключ-значение (провайдеры Memory, Redis, Vercel KV) и защищённое хранилище на стороне клиента, в то время как векторное хранилище и дополнительные бэкенды находятся в разработке. ## 📕 Документация Документация по фреймворку AgentDock доступна на [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) и в папке `/docs/` этого репозитория. Документация включает: - Руководства по началу работы - Справочники API - Учебники по созданию узлов - Примеры интеграции ## 📂 Структура Репозитория Этот репозиторий содержит: 1. **AgentDock Core**: Основной фреймворк, расположенный в `agentdock-core/` 2. **Open Source Client**: Полная эталонная реализация, созданная с помощью Next.js, служащая потребителем фреймворка AgentDock Core. 3. **Примеры Агентов**: Готовые к использованию конфигурации агентов в каталоге `agents/` Вы можете использовать AgentDock Core независимо в своих приложениях или использовать этот репозиторий как отправную точку для создания собственных приложений на основе агентов. ## 📝 Шаблоны Агентов AgentDock включает несколько предварительно настроенных шаблонов агентов. Изучите их в каталоге `agents/` или прочитайте [Документацию Шаблонов Агентов](../../docs/agent-templates.md) для деталей конфигурации. ## 🔧 Примеры Реализаций Примеры реализаций демонстрируют специализированные сценарии использования и расширенную функциональность: | Реализация | Описание | Статус | | :--------------------------- | :--------------------------------------------------------------------------------------------- | :---------- | | **Оркестрованный Агент** | Пример агента, использующего оркестрацию для адаптации поведения в зависимости от контекста | Доступно | | **Когнитивный Рассуждающий** | Решает сложные проблемы, используя структурированное рассуждение и когнитивные инструменты | Доступно | | **Планировщик Агентов** | Специализированный агент для проектирования и реализации других ИИ-агентов | Доступно | | [**Code Playground (Песочница для Кода)**](../../docs/roadmap/code-playground.md) | Генерация и выполнение кода в песочнице с богатыми возможностями визуализации | Запланировано | ## 🔐 Детали Конфигурации Окружения Для работы AgentDock Open Source Client требуются API-ключи для провайдеров LLM. Они настраиваются в файле окружения (`.env` или `.env.local`), который вы создаете на основе предоставленного `.env.example`. ### API-Ключи Провайдеров LLM Добавьте ваши API-ключи провайдеров LLM (требуется как минимум один): ```bash # API-Ключи Провайдеров LLM - требуется как минимум один ANTHROPIC_API_KEY=sk-ant-xxxxxxx # API-ключ Anthropic OPENAI_API_KEY=sk-xxxxxxx # API-ключ OpenAI GEMINI_API_KEY=xxxxxxx # API-ключ Google Gemini DEEPSEEK_API_KEY=xxxxxxx # API-ключ DeepSeek GROQ_API_KEY=xxxxxxx # API-ключ Groq ``` ### Разрешение API-Ключей AgentDock Open Source Client следует порядку приоритета при определении используемого API-ключа: 1. **Пользовательский API-ключ для агента** (устанавливается через настройки агента в UI) 2. **Глобальный API-ключ настроек** (устанавливается через страницу настроек в UI) 3. **Переменная окружения** (из `.env.local` или платформы развертывания) ### API-Ключи, Специфичные для Инструментов Некоторые инструменты также требуют собственных API-ключей: ```bash # API-Ключи, Специфичные для Инструментов SERPER_API_KEY= # Требуется для функциональности поиска FIRECRAWL_API_KEY= # Требуется для более глубокого веб-сканирования ``` Подробнее о конфигурации окружения см. в реализации [`src/types/env.ts`](../../src/types/env.ts). ### Используйте Свой Собственный Ключ (BYOK - Bring Your Own Key) AgentDock работает по модели BYOK (Bring Your Own Key - Используйте Свой Собственный Ключ): 1. Добавьте ваши API-ключи на странице настроек приложения 2. Либо предоставьте ключи через заголовки запросов для прямого использования API 3. Ключи надежно хранятся с использованием встроенной системы шифрования 4. Никакие API-ключи не передаются и не хранятся на наших серверах ## 📦 Менеджер Пакетов Этот проект *требует* использования `pnpm` для согласованного управления зависимостями. `npm` и `yarn` не поддерживаются. ## 💡 Что Вы Можете Создать 1. **Приложения на Основе ИИ** - Пользовательские чат-боты с любым фронтендом - ИИ-ассистенты командной строки - Автоматизированные конвейеры обработки данных - Интеграции с бэкенд-сервисами 2. **Возможности Интеграции** - Любой провайдер ИИ (OpenAI, Anthropic и т.д.) - Любой фронтенд-фреймворк - Любой бэкенд-сервис - Пользовательские источники данных и API 3. **Системы Автоматизации** - Рабочие процессы обработки данных - Конвейеры анализа документов - Автоматизированные системы отчетности - Агенты автоматизации задач ## Ключевые Особенности | Особенность | Описание | | :--------------------------------- | :------------------------------------------------------------------------------------------ | | 🔌 **Независимость от Фреймворка (Node.js Backend)** | Основная библиотека интегрируется со стеками бэкенда Node.js. | | 🧩 **Модульный Дизайн** | Создавайте сложные системы из простых узлов | | 🛠️ **Расширяемость** | Создавайте пользовательские узлы для любой функциональности | | 🔒 **Безопасность** | Встроенные функции безопасности для API-ключей и данных | | 🔑 **BYOK** | Используйте *свои собственные API-ключи* для провайдеров LLM | | 📦 **Самодостаточность (Self-contained)**| Основной фреймворк имеет минимальные зависимости | | ⚙️ **Многошаговые Вызовы Инструментов (Multi-Step Tool Calls)**| Поддержка *сложных цепочек рассуждений* | | 📊 **Структурированное Логирование** | Подробная информация о выполнении агента | | 🛡️ **Надежная Обработка Ошибок** | Предсказуемое поведение и упрощенная отладка | | 📝 **TypeScript Прежде Всего** | Типовая безопасность и улучшенный опыт разработчика | | 🌐 **Open Source Клиент** | Включает полную эталонную реализацию Next.js | | 🔄 **Оркестрация** | *Динамический контроль* поведения агента в зависимости от контекста | | 💾 **Управление Сессиями** | Изолированное состояние для параллельных диалогов | | 🎮 **Настраиваемый Детерминизм** | Балансируйте креативность ИИ и предсказуемость с помощью логики узлов/рабочих процессов. | ## 🧰 Компоненты Модульная архитектура AgentDock основана на этих ключевых компонентах: * **BaseNode**: Основа для всех узлов в системе * **AgentNode**: Основная абстракция для функциональности агента * **Инструменты и Пользовательские Узлы**: Вызываемые возможности и пользовательская логика, реализованные как узлы. * **Реестр Узлов**: Управляет регистрацией и извлечением всех типов узлов * **Реестр Инструментов**: Управляет доступностью инструментов для агентов * **CoreLLM**: Унифицированный интерфейс для взаимодействия с провайдерами LLM * **Реестр Провайдеров**: Управляет конфигурациями провайдеров LLM * **Обработка Ошибок**: Система для обработки ошибок и обеспечения предсказуемого поведения * **Логирование (Logging)**: Структурированная система логирования для мониторинга и отладки * **Оркестрация**: Контролирует доступность инструментов и поведение в зависимости от контекста диалога * **Сессии**: Управляет изоляцией состояния между параллельными диалогами Подробную техническую документацию по этим компонентам см. в [Обзоре Архитектуры](../../docs/architecture/README.md). ## 🗺️ Дорожная Карта Ниже представлена наша дорожная карта разработки AgentDock. Большинство перечисленных здесь улучшений относятся к основному фреймворку AgentDock (`agentdock-core`), который в настоящее время разрабатывается локально и будет опубликован как версионированный пакет NPM после достижения стабильного релиза. Некоторые пункты дорожной карты могут также включать улучшения в реализации клиента с открытым исходным кодом. | Особенность | Описание | Категория | | :-------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------- | :----------------- | | [**Слой Абстракции Хранилища**](../../docs/roadmap/storage-abstraction.md) | Гибкая система хранения с подключаемыми провайдерами | **В Разработке** | | [**Продвинутые Системы Памяти**](../../docs/roadmap/advanced-memory.md) | Управление долгосрочным контекстом | **В Разработке** | | [**Интеграция Векторного Хранилища**](../../docs/roadmap/vector-storage.md) | Поиск на основе вложений для документов и памяти | **В Разработке** | | [**Оценка для ИИ-Агентов**](../../docs/roadmap/evaluation-framework.md) | Комплексный фреймворк для тестирования и оценки | **В Разработке** | | [**Интеграция Платформ**](../../docs/roadmap/platform-integration.md) | Поддержка Telegram, WhatsApp и других платформ обмена сообщениями | **Запланировано** | | [**Сотрудничество Нескольких Агентов**](../../docs/roadmap/multi-agent-collaboration.md)| Возможность совместной работы агентов | **Запланировано** | | [**Интеграция Протокола Контекста Модели (MCP)**](../../docs/roadmap/mcp-integration.md)| Поддержка обнаружения и использования внешних инструментов через MCP | **Запланировано** | | [**Голосовые ИИ-Агенты**](../../docs/roadmap/voice-agents.md) | ИИ-агенты, использующие голосовые интерфейсы и телефонные номера через AgentNode | **Запланировано** | | [**Телеметрия и Отслеживаемость**](../../docs/roadmap/telemetry.md) | Расширенное логирование и отслеживание производительности | **Запланировано** | | [**Workflow Runtime & Node Типы**](../../docs/roadmap/workflow-nodes.md) | Основной runtime, типы узлов (Nodes) и логика оркестрации для сложных автоматизаций | **Запланировано** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Комплексная корпоративная облачная платформа для масштабирования ИИ-агентов и рабочих процессов | **Облако** | ## 👥 Вклад Мы приветствуем вклад в AgentDock! Подробные инструкции см. в [CONTRIBUTING.md](https://github.com/AgentDock/AgentDock/blob/main/CONTRIBUTING.md). ## 📜 Лицензия AgentDock выпускается под [Лицензией MIT](https://github.com/AgentDock/AgentDock/blob/main/LICENSE). ## ✨ Создавайте Безграничные Возможности! AgentDock предоставляет основу для создания практически любого приложения или автоматизации на базе ИИ, которые вы можете себе представить. Мы призываем вас изучать фреймворк, создавать инновационных агентов и вносить вклад в сообщество. Давайте вместе формировать будущее взаимодействия с ИИ! --- [Назад к Индексу Переводов](/docs/i18n/README.md) ## AgentDock: Crea Posibilidades Ilimitadas con Agentes de IA

AgentDock Logo

## 🌐 Traducciones del README [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock es un framework para construir agentes de IA sofisticados que realizan tareas complejas con **determinismo configurable**. Consta de dos componentes principales: 1. **AgentDock Core**: Un framework open-source, enfocado en el backend, para construir y desplegar agentes de IA. Está diseñado para ser *agnóstico al framework* y *agnóstico al proveedor*, dándote control completo sobre la implementación de tu agente. 2. **Cliente Open Source**: Una aplicación Next.js completa que sirve como implementación de referencia y consumidor del framework AgentDock Core. Puedes verlo en acción en [https://hub.agentdock.ai](https://hub.agentdock.ai) Construido con TypeScript, AgentDock enfatiza la *simplicidad*, la *extensibilidad* y el ***determinismo configurable***, lo que lo hace ideal para construir sistemas de IA fiables y predecibles que pueden operar con mínima supervisión. ## 🧠 Principios de Diseño AgentDock se basa en estos principios fundamentales: - **Primero la Simplicidad**: Código mínimo requerido para crear agentes funcionales - **Arquitectura Basada en Nodos**: Todas las capacidades se implementan como nodos - **Herramientas como Nodos Especializados**: Las herramientas extienden el sistema de nodos para las capacidades del agente - **Determinismo Configurable**: Controla la previsibilidad del comportamiento del agente - **Seguridad de Tipos**: Tipos TypeScript completos en todo el sistema ### Determinismo Configurable El ***determinismo configurable*** es una piedra angular de la filosofía de diseño de AgentDock, permitiéndote equilibrar las capacidades creativas de la IA con un comportamiento predecible del sistema: - Los AgentNodes son inherentemente no deterministas ya que los LLMs pueden generar respuestas diferentes cada vez - Los flujos de trabajo (Workflows) pueden hacerse más deterministas a través de *rutas de ejecución de herramientas definidas* - Los desarrolladores pueden **controlar el nivel de determinismo** configurando qué partes del sistema utilizan la inferencia LLM - Incluso con componentes LLM, el comportamiento general del sistema sigue siendo **predecible** a través de interacciones de herramientas estructuradas - Este enfoque equilibrado permite tanto la *creatividad* como la **fiabilidad** en tus aplicaciones de IA #### Flujos de Trabajo Deterministas AgentDock soporta completamente los flujos de trabajo deterministas con los que estás familiarizado de los constructores de flujos de trabajo típicos. Todas las rutas de ejecución predecibles y los resultados fiables que esperas están disponibles, con o sin inferencia LLM: ```mermaid flowchart LR Input[Entrada] --> Process[Proceso] Process --> Database[(Base de Datos)] Process --> Output[Salida] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Comportamiento de Agente No Determinista Con AgentDock, también puedes aprovechar los AgentNodes con LLMs cuando necesites más adaptabilidad. Las salidas creativas pueden variar según tus necesidades, manteniendo patrones de interacción estructurados: ```mermaid flowchart TD Input[Consulta Usuario] --> Agent[AgentNode] Agent -->|"Razonamiento LLM (No Determinista)"| ToolChoice{Selección Herramienta} ToolChoice -->|"Opción A"| ToolA[Herramienta Investigación Profunda] ToolChoice -->|"Opción B"| ToolB[Herramienta Análisis Datos] ToolChoice -->|"Opción C"| ToolC[Respuesta Directa] ToolA --> Response[Respuesta Final] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Agentes No Deterministas con Sub-Flujos Deterministas AgentDock te ofrece lo ***mejor de ambos mundos*** combinando la inteligencia de agente no determinista con la ejecución de flujos de trabajo deterministas: ```mermaid flowchart TD Input[Consulta Usuario] --> Agent[AgentNode] Agent -->|"Razonamiento LLM (No Determinista)"| FlowChoice{Selección Sub-Flujo} FlowChoice -->|"Decisión A"| Flow1[Flujo Determinista 1] FlowChoice -->|"Decisión B"| Flow2[Flujo Determinista 2] FlowChoice -->|"Decisión C"| DirectResponse[Generar Respuesta] Flow1 --> |"Paso 1 → 2 → 3 → ... → 200"| Flow1Result[Resultado Flujo 1] Flow2 --> |"Paso 1 → 2 → 3 → ... → 100"| Flow2Result[Resultado Flujo 2] Flow1Result --> Response[Respuesta Final] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Este enfoque permite que flujos de trabajo complejos de múltiples pasos (que potencialmente involucran cientos de pasos deterministas implementados dentro de herramientas o como secuencias de nodos conectados) sean invocados por decisiones de agentes inteligentes. Cada flujo de trabajo se ejecuta de manera predecible a pesar de ser activado por un razonamiento de agente no determinista. Para flujos de trabajo de agentes de IA más avanzados y pipelines de procesamiento de múltiples etapas, estamos construyendo [AgentDock Pro](../../docs/agentdock-pro.md), una plataforma potente para crear, visualizar y ejecutar sistemas de agentes complejos. #### En resumen: Determinismo Configurable Imagínalo como conducir un automóvil. A veces necesitas la creatividad de la IA (como navegar por las calles de la ciudad - no determinista), y a veces necesitas procesos fiables, paso a paso (como seguir las señales de la autopista - determinista). AgentDock te permite construir sistemas que usan *ambos*, eligiendo el enfoque adecuado para cada parte de una tarea. Consigues tanto la creatividad de la IA *como* resultados predecibles cuando los necesitas. ## 🏗️ Arquitectura Central El framework se construye alrededor de un sistema potente y modular basado en nodos, que sirve como base para toda la funcionalidad del agente. Esta arquitectura utiliza tipos de nodos distintos como bloques de construcción: - **`BaseNode`**: La clase fundamental que establece la interfaz central y las capacidades para todos los nodos. - **`AgentNode`**: Un nodo central especializado que orquesta las interacciones LLM, el uso de herramientas y la lógica del agente. - **Herramientas y Nodos Personalizados**: Los desarrolladores implementan capacidades de agente y lógica personalizada como nodos que extienden `BaseNode`. Estos nodos interactúan a través de registros gestionados y pueden conectarse (aprovechando los puertos de la arquitectura central y un posible bus de mensajes) para permitir comportamientos y flujos de trabajo de agentes complejos, configurables y potencialmente deterministas. Para una explicación detallada de los componentes y capacidades del sistema de nodos, consulta la [Documentación del Sistema de Nodos](../../docs/nodes/README.md). ## 🚀 Empezando Para una guía completa, consulta la [Guía de Inicio](../../docs/getting-started.md). ### Requisitos * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Requerido) * Claves API para proveedores LLM (Anthropic, OpenAI, etc.) ### Instalación 1. **Clonar el Repositorio**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Instalar pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Instalar Dependencias**: ```bash pnpm install ``` Para una reinstalación limpia (cuando necesites reconstruir desde cero): ```bash pnpm run clean-install ``` Este script elimina todos los node_modules, archivos de bloqueo y reinstala correctamente las dependencias. 4. **Configurar el Entorno**: Crea un archivo de entorno (`.env` o `.env.local`) basado en el archivo `.env.example` proporcionado: ```bash # Opción 1: Crear .env.local cp .env.example .env.local # Opción 2: Crear .env cp .env.example .env ``` Luego agrega tus claves API al archivo de entorno. 5. **Iniciar el Servidor de Desarrollo**: ```bash pnpm dev ``` ### Capacidades Avanzadas | Capacidad | Descripción | Documentación | | :------------------------ | :---------------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------- | | **Gestión de Sesiones** | Gestión de estado aislada y de alto rendimiento para conversaciones | [Documentación de Sesiones](../../docs/architecture/sessions/README.md) | | **Framework de Orquestación** | Control del comportamiento del agente y disponibilidad de herramientas basado en el contexto | [Documentación de Orquestación](../../docs/architecture/orchestration/README.md) | | **Abstracción de Almacenamiento** | Sistema de almacenamiento flexible con proveedores conectables para KV, Vector y Secure Storage | [Documentación de Almacenamiento](../../docs/storage/README.md) | El sistema de almacenamiento está evolucionando actualmente con almacenamiento clave-valor (proveedores Memory, Redis, Vercel KV) y almacenamiento seguro del lado del cliente, mientras que el almacenamiento vectorial y backends adicionales están en desarrollo. ## 📕 Documentación La documentación del framework AgentDock está disponible en [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) y en la carpeta `/docs/` de este repositorio. La documentación incluye: - Guías de inicio - Referencias de API - Tutoriales de creación de nodos - Ejemplos de integración ## 📂 Estructura del Repositorio Este repositorio contiene: 1. **AgentDock Core**: El framework central ubicado en `agentdock-core/` 2. **Cliente Open Source**: Una implementación de referencia completa construida con Next.js, que sirve como consumidor del framework AgentDock Core. 3. **Agentes de Ejemplo**: Configuraciones de agentes listas para usar en el directorio `agents/` Puedes usar AgentDock Core de forma independiente en tus propias aplicaciones, o usar este repositorio como punto de partida para construir tus propias aplicaciones impulsadas por agentes. ## 📝 Plantillas de Agentes AgentDock incluye varias plantillas de agentes preconfiguradas. Explóralas en el directorio `agents/` o lee la [Documentación de Plantillas de Agentes](../../docs/agent-templates.md) para detalles de configuración. ## 🔧 Implementaciones de Ejemplo Las implementaciones de ejemplo muestran casos de uso especializados y funcionalidad avanzada: | Implementación | Descripción | Estado | | :------------------------- | :----------------------------------------------------------------------------------- | :---------- | | **Agente Orquestado** | Agente de ejemplo que usa orquestación para adaptar el comportamiento según el contexto | Disponible | | **Razonador Cognitivo** | Aborda problemas complejos usando razonamiento estructurado y herramientas cognitivas | Disponible | | **Planificador de Agentes** | Agente especializado para diseñar e implementar otros agentes de IA | Disponible | | [**Playground de Código (Code Playground)**](../../docs/roadmap/code-playground.md) | Generación y ejecución de código en sandbox con ricas capacidades de visualización | Planificado | ## 🔐 Detalles de Configuración del Entorno El Cliente Open Source de AgentDock requiere claves API para los proveedores LLM para funcionar. Estas se configuran en un archivo de entorno (`.env` o `.env.local`) que creas basándote en el archivo `.env.example` proporcionado. ### Claves API de Proveedores LLM Agrega tus claves API de proveedor LLM (se requiere al menos una): ```bash # Claves API Proveedor LLM - se requiere al menos una ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Clave API Anthropic OPENAI_API_KEY=sk-xxxxxxx # Clave API OpenAI GEMINI_API_KEY=xxxxxxx # Clave API Google Gemini DEEPSEEK_API_KEY=xxxxxxx # Clave API DeepSeek GROQ_API_KEY=xxxxxxx # Clave API Groq ``` ### Resolución de Claves API El Cliente Open Source de AgentDock sigue un orden de prioridad al resolver qué clave API usar: 1. **Clave API personalizada por agente** (establecida a través de la configuración del agente en la UI) 2. **Clave API de configuración global** (establecida a través de la página de configuración en la UI) 3. **Variable de entorno** (desde .env.local o plataforma de despliegue) ### Claves API Específicas de Herramientas Algunas herramientas también requieren sus propias claves API: ```bash # Claves API Específicas de Herramientas SERPER_API_KEY= # Requerido para funcionalidad de búsqueda FIRECRAWL_API_KEY= # Requerido para búsqueda web más profunda ``` Para más detalles sobre la configuración del entorno, consulta la implementación en [`src/types/env.ts`](../../src/types/env.ts). ### Usa Tu Propia Clave (BYOK - Bring Your Own Key) AgentDock opera bajo un modelo BYOK (Bring Your Own Key - Usa Tu Propia Clave): 1. Agrega tus claves API en la página de configuración de la aplicación 2. Alternativamente, proporciona claves a través de encabezados de solicitud para uso directo de la API 3. Las claves se almacenan de forma segura utilizando el sistema de cifrado incorporado 4. No se comparten ni almacenan claves API en nuestros servidores ## 📦 Gestor de Paquetes Este proyecto *requiere* el uso de `pnpm` para una gestión de dependencias consistente. `npm` y `yarn` no son compatibles. ## 💡 Qué Puedes Construir 1. **Aplicaciones Impulsadas por IA** - Chatbots personalizados con cualquier frontend - Asistentes de IA de línea de comandos - Pipelines de procesamiento de datos automatizados - Integraciones de servicios backend 2. **Capacidades de Integración** - Cualquier proveedor de IA (OpenAI, Anthropic, etc.) - Cualquier framework frontend - Cualquier servicio backend - Fuentes de datos y APIs personalizadas 3. **Sistemas de Automatización** - Flujos de trabajo de procesamiento de datos - Pipelines de análisis de documentos - Sistemas de informes automatizados - Agentes de automatización de tareas ## Características Clave | Característica | Descripción | | :------------------------------ | :---------------------------------------------------------------------------------------- | | 🔌 **Agnóstico al Framework (Backend Node.js)** | La biblioteca central se integra con stacks backend Node.js. | | 🧩 **Diseño Modular** | Construye sistemas complejos a partir de nodos simples | | 🛠️ **Extensible** | Construye nodos personalizados para cualquier funcionalidad | | 🔒 **Seguro** | Características de seguridad integradas para claves API y datos | | 🔑 **BYOK** | Usa tus *propias claves API* para proveedores LLM | | 📦 **Autónomo (Self-contained)**| El framework central tiene dependencias mínimas | | ⚙️ **Llamadas a Herramientas Multi-Paso (Multi-Step Tool Calls)**| Soporte para *cadenas de razonamiento complejas* | | 📊 **Registro Estructurado** | Información detallada sobre la ejecución del agente | | 🛡️ **Gestión Robusta de Errores** | Comportamiento predecible y depuración simplificada | | 📝 **TypeScript Primero** | Seguridad de tipos y experiencia de desarrollador mejorada | | 🌐 **Cliente Open Source** | Incluye una implementación de referencia completa de Next.js | | 🔄 **Orquestación** | *Control dinámico* del comportamiento del agente basado en el contexto | | 💾 **Gestión de Sesiones** | Estado aislado para conversaciones concurrentes | | 🎮 **Determinismo Configurable**| Equilibra la creatividad de la IA y la previsibilidad mediante lógica de nodos/flujos de trabajo. | ## 🧰 Componentes La arquitectura modular de AgentDock se basa en estos componentes clave: * **BaseNode**: La base para todos los nodos del sistema * **AgentNode**: La abstracción principal para la funcionalidad del agente * **Herramientas y Nodos Personalizados**: Capacidades invocables y lógica personalizada implementadas como nodos. * **Registro de Nodos**: Gestiona el registro y la recuperación de todos los tipos de nodos * **Registro de Herramientas**: Gestiona la disponibilidad de herramientas para los agentes * **CoreLLM**: Interfaz unificada para interactuar con proveedores LLM * **Registro de Proveedores**: Gestiona las configuraciones de los proveedores LLM * **Manejo de Errores**: Sistema para manejar errores y asegurar un comportamiento predecible * **Registro (Logging)**: Sistema de registro estructurado para monitoreo y depuración * **Orquestación**: Controla la disponibilidad de herramientas y el comportamiento según el contexto de la conversación * **Sesiones**: Gestiona el aislamiento del estado entre conversaciones concurrentes Para documentación técnica detallada sobre estos componentes, consulta la [Visión General de la Arquitectura](../../docs/architecture/README.md). ## 🗺️ Hoja de Ruta A continuación se muestra nuestra hoja de ruta de desarrollo para AgentDock. La mayoría de las mejoras enumeradas aquí se relacionan con el framework central de AgentDock (`agentdock-core`), que actualmente se desarrolla localmente y se publicará como un paquete NPM versionado al alcanzar una versión estable. Algunos elementos de la hoja de ruta también pueden implicar mejoras en la implementación del cliente open-source. | Característica | Descripción | Categoría | | :--------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------- | :-------------- | | [**Capa de Abstracción de Almacenamiento**](../../docs/roadmap/storage-abstraction.md) | Sistema de almacenamiento flexible con proveedores conectables | **En Progreso** | | [**Sistemas Avanzados de Memoria**](../../docs/roadmap/advanced-memory.md) | Gestión de contexto a largo plazo | **En Progreso** | | [**Integración de Almacenamiento Vectorial**](../../docs/roadmap/vector-storage.md) | Recuperación basada en embeddings para documentos y memoria | **En Progreso** | | [**Evaluación para Agentes de IA**](../../docs/roadmap/evaluation-framework.md) | Framework completo de pruebas y evaluación | **En Progreso** | | [**Integración de Plataformas**](../../docs/roadmap/platform-integration.md) | Soporte para Telegram, WhatsApp y otras plataformas de mensajería | **Planificado** | | [**Colaboración Multi-Agente**](../../docs/roadmap/multi-agent-collaboration.md) | Permitir que los agentes trabajen juntos | **Planificado** | | [**Integración del Protocolo de Contexto del Modelo (MCP)**](../../docs/roadmap/mcp-integration.md) | Soporte para descubrir y usar herramientas externas a través de MCP | **Planificado** | | [**Agentes de IA por Voz**](../../docs/roadmap/voice-agents.md) | Agentes de IA que usan interfaces de voz y números de teléfono a través de AgentNode | **Planificado** | | [**Telemetría y Trazabilidad**](../../docs/roadmap/telemetry.md) | Registro avanzado y seguimiento del rendimiento | **Planificado** | | [**Workflow Runtime & Node Tipos**](../../docs/roadmap/workflow-nodes.md) | Runtime central, tipos de nodos y lógica de orquestación para automatizaciones complejas | **Planificado** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Plataforma cloud empresarial completa para escalar agentes IA y flujos de trabajo | **Cloud** | ## 👥 Contribuyendo ¡Agradecemos las contribuciones a AgentDock! Consulta [CONTRIBUTING.md](../../CONTRIBUTING.md) para obtener pautas detalladas de contribución. ## 📜 Licencia AgentDock se publica bajo la [Licencia MIT](../../LICENSE). ## ✨ ¡Crea Posibilidades Ilimitadas! AgentDock proporciona la base para construir casi cualquier aplicación o automatización impulsada por IA que puedas imaginar. Te animamos a explorar el framework, construir agentes innovadores y contribuir a la comunidad. ¡Construyamos juntos el futuro de la interacción con la IA! --- [Volver al Índice de Traducciones](/docs/i18n/README.md) ## AgentDock: Yapay Zeka Ajanları ile Sınırsız Olasılıklar Yaratın

AgentDock Logo

## 🌐 README Çevirileri [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock, **yapılandırılabilir determinizm** ile karmaşık görevleri yerine getiren sofistike yapay zeka ajanları oluşturmak için bir framework'tür. İki ana bileşenden oluşur: 1. **AgentDock Core**: Yapay zeka ajanları oluşturmak ve dağıtmak için açık kaynaklı, backend öncelikli bir framework. *Framework'ten bağımsız* ve *sağlayıcıdan bağımsız* olacak şekilde tasarlanmıştır, bu da size ajanın implementasyonu üzerinde tam kontrol sağlar. 2. **Açık Kaynak İstemci**: AgentDock Core framework'ünün bir referans implementasyonu ve tüketicisi olarak hizmet veren eksiksiz bir Next.js uygulaması. [https://hub.agentdock.ai](https://hub.agentdock.ai) adresinde çalışırken görebilirsiniz. TypeScript ile oluşturulan AgentDock, *basitlik*, *genişletilebilirlik* ve ***yapılandırılabilir determinizmi*** vurgular - bu da onu minimum denetimle çalışabilen güvenilir ve öngörülebilir yapay zeka sistemleri oluşturmak için ideal hale getirir. ## 🧠 Tasarım Prensipleri AgentDock şu temel prensipler üzerine kurulmuştur: - **Önce Basitlik**: Fonksiyonel ajanlar oluşturmak için gereken minimum kod - **Node Tabanlı Mimari**: Tüm yetenekler node'lar olarak uygulanır - **Özel Node'lar Olarak Araçlar**: Araçlar, ajan yetenekleri için node sistemini genişletir - **Yapılandırılabilir Determinizm**: Ajan davranışının öngörülebilirliğini kontrol edin - **Tip Güvenliği**: Baştan sona kapsamlı TypeScript tipleri ### Yapılandırılabilir Determinizm ***Yapılandırılabilir determinizm***, AgentDock'un tasarım felsefesinin temel taşıdır ve yaratıcı yapay zeka yeteneklerini öngörülebilir sistem davranışıyla dengelemenizi sağlar: - AgentNode'lar doğası gereği deterministik değildir, çünkü LLM'ler her seferinde farklı yanıtlar üretebilir - Workflow'lar, *tanımlanmış araç yürütme yolları* aracılığıyla daha deterministik hale getirilebilir - Geliştiriciler, sistemin hangi bölümlerinin LLM çıkarımı kullandığını yapılandırarak **determinizm seviyesini kontrol edebilirler** - LLM bileşenleriyle bile, genel sistem davranışı yapılandırılmış araç etkileşimleri sayesinde **öngörülebilir** kalır - Bu dengeli yaklaşım, yapay zeka uygulamalarınızda hem *yaratıcılığı* hem de **güvenilirliği** mümkün kılar #### Deterministik Workflow'lar AgentDock, tipik workflow oluşturucularından aşina olduğunuz deterministik workflow'ları tam olarak destekler. Beklediğiniz tüm öngörülebilir yürütme yolları ve güvenilir sonuçlar, LLM çıkarımı olsun veya olmasın mevcuttur: ```mermaid flowchart LR Input[Girdi] --> Process[İşlem] Process --> Database[(Veritabanı)] Process --> Output[Çıktı] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Deterministik Olmayan Ajan Davranışı AgentDock ile, daha fazla uyarlanabilirliğe ihtiyaç duyduğunuzda LLM'lerle AgentNode'lardan da yararlanabilirsiniz. Yaratıcı çıktılar ihtiyaçlarınıza göre değişebilirken, yapılandırılmış etkileşim kalıplarını korur: ```mermaid flowchart TD Input[Kullanıcı Sorgusu] --> Agent[AgentNode] Agent -->|"LLM Muhakemesi (Deterministik Değil)"| ToolChoice{Araç Seçimi} ToolChoice -->|"Seçenek A"| ToolA[Derin Araştırma Aracı] ToolChoice -->|"Seçenek B"| ToolB[Veri Analizi Aracı] ToolChoice -->|"Seçenek C"| ToolC[Doğrudan Yanıt] ToolA --> Response[Nihai Yanıt] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Deterministik Alt Workflow'lara Sahip Deterministik Olmayan Ajanlar AgentDock, deterministik olmayan ajan zekasını deterministik workflow yürütmesiyle birleştirerek size ***her iki dünyanın en iyisini*** sunar: ```mermaid flowchart TD Input[Kullanıcı Sorgusu] --> Agent[AgentNode] Agent -->|"LLM Muhakemesi (Deterministik Değil)"| FlowChoice{Alt Workflow Seçimi} FlowChoice -->|"Karar A"| Flow1[Deterministik Workflow 1] FlowChoice -->|"Karar B"| Flow2[Deterministik Workflow 2] FlowChoice -->|"Karar C"| DirectResponse[Yanıt Oluştur] Flow1 --> |"Adım 1 → 2 → 3 → ... → 200"| Flow1Result[Workflow 1 Sonucu] Flow2 --> |"Adım 1 → 2 → 3 → ... → 100"| Flow2Result[Workflow 2 Sonucu] Flow1Result --> Response[Nihai Yanıt] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Bu yaklaşım, karmaşık çok adımlı workflow'ların (potansiyel olarak araçlar içinde veya bağlı node dizileri olarak uygulanan yüzlerce deterministik adımı içerebilir) akıllı ajan kararlarıyla çağrılmasını sağlar. Her workflow, deterministik olmayan ajan muhakemesi tarafından tetiklenmesine rağmen öngörülebilir bir şekilde yürütülür. Daha gelişmiş yapay zeka ajan workflow'ları ve çok aşamalı işleme pipeline'ları için, karmaşık ajan sistemleri oluşturmak, görselleştirmek ve çalıştırmak için güçlü bir platform olan [AgentDock Pro](../../docs/agentdock-pro.md)'yu geliştiriyoruz. #### Özetle: Yapılandırılabilir Determinizm Bunu otomobil kullanmaya benzetebilirsiniz. Bazen yapay zekanın yaratıcılığına ihtiyacınız vardır (şehir sokaklarında gezinmek gibi - deterministik olmayan), bazen de güvenilir, adım adım süreçlere ihtiyacınız vardır (otoban tabelalarını takip etmek gibi - deterministik). AgentDock, bir görevin her bölümü için doğru yaklaşımı seçerek *her ikisini* de kullanan sistemler oluşturmanıza olanak tanır. Hem yapay zekanın yaratıcılığından *hem de* ihtiyaç duyduğunuzda öngörülebilir sonuçlardan yararlanırsınız. ## 🏗️ Çekirdek Mimari Framework, tüm ajan işlevselliğinin temelini oluşturan güçlü, modüler bir node tabanlı sistem etrafında inşa edilmiştir. Bu mimari, yapı taşları olarak farklı node tiplerini kullanır: - **`BaseNode`**: Tüm node'lar için temel arayüzü ve yetenekleri oluşturan temel sınıf. - **`AgentNode`**: LLM etkileşimlerini, araç kullanımını ve ajan mantığını yöneten özel bir çekirdek node. - **Araçlar ve Özel Node'lar**: Geliştiriciler, ajan yeteneklerini ve özel mantığı `BaseNode`'u genişleten node'lar olarak uygular. Bu node'lar, yönetilen kayıt defterleri aracılığıyla etkileşime girer ve karmaşık, yapılandırılabilir ve potansiyel olarak deterministik ajan davranışlarını ve workflow'larını etkinleştirmek için (çekirdek mimarinin portlarından ve potansiyel mesajlaşma sisteminden yararlanarak) bağlanabilir. Node sisteminin bileşenleri ve yetenekleri hakkında ayrıntılı bir açıklama için lütfen [Node Sistemi Dokümantasyonu](../../docs/nodes/README.md)'na bakın. ## 🚀 Başlarken Kapsamlı bir kılavuz için [Başlangıç Kılavuzu](../../docs/getting-started.md)'na bakın. ### Gereksinimler * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Gerekli) * LLM sağlayıcıları için API anahtarları (Anthropic, OpenAI, vb.) ### Kurulum 1. **Depoyu Klonlayın**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **pnpm'i Kurun**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Bağımlılıkları Kurun**: ```bash pnpm install ``` Temiz bir yeniden kurulum için (sıfırdan yeniden oluşturmanız gerektiğinde): ```bash pnpm run clean-install ``` Bu betik tüm node_modules'ı, kilit dosyalarını kaldırır ve bağımlılıkları doğru şekilde yeniden yükler. 4. **Ortamı Yapılandırın**: Sağlanan `.env.example` dosyasına dayanarak bir ortam dosyası (`.env` veya `.env.local`) oluşturun: ```bash # Seçenek 1: .env.local oluşturun cp .env.example .env.local # Seçenek 2: .env oluşturun cp .env.example .env ``` Ardından API anahtarlarınızı ortam dosyasına ekleyin. 5. **Geliştirme Sunucusunu Başlatın**: ```bash pnpm dev ``` ### Gelişmiş Yetenekler | Yetenek | Açıklama | Dokümantasyon | | :------------------------ | :-------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | **Oturum Yönetimi** | Konuşmalar için izole edilmiş, performanslı durum yönetimi | [Oturum Dokümantasyonu](../../docs/architecture/sessions/README.md) | | **Orkestrasyon Framework'ü** | Bağlama göre ajan davranışını ve araç kullanılabilirliğini kontrol etme | [Orkestrasyon Dokümantasyonu](../../docs/architecture/orchestration/README.md) | | **Depolama Soyutlaması** | KV, Vektör ve Güvenli depolama için takılabilir sağlayıcılara sahip esnek depolama sistemi | [Depolama Dokümantasyonu](../../docs/storage/README.md) | Depolama sistemi şu anda anahtar-değer depolama (Memory, Redis, Vercel KV sağlayıcıları) ve güvenli istemci tarafı depolama ile gelişmektedir, vektör depolama ve ek backend'ler ise geliştirme aşamasındadır. ## 📕 Dokümantasyon AgentDock framework'ünün dokümantasyonu [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) adresinde ve bu deponun `/docs/` klasöründe mevcuttur. Dokümantasyon şunları içerir: - Başlangıç kılavuzları - API referansları - Node oluşturma eğitimleri - Entegrasyon örnekleri ## 📂 Depo Yapısı Bu depo şunları içerir: 1. **AgentDock Core**: `agentdock-core/` içinde bulunan çekirdek framework 2. **Açık Kaynak İstemci**: AgentDock Core framework'ünün bir tüketicisi olarak hizmet veren, Next.js ile oluşturulmuş eksiksiz bir referans implementasyonu. 3. **Örnek Ajanlar**: `agents/` dizininde kullanıma hazır ajan yapılandırmaları AgentDock Core'u kendi uygulamalarınızda bağımsız olarak kullanabilir veya bu depoyu kendi ajan destekli uygulamalarınızı oluşturmak için bir başlangıç noktası olarak kullanabilirsiniz. ## 📝 Ajan Şablonları AgentDock, önceden yapılandırılmış birkaç ajan şablonu içerir. Bunları `agents/` dizininde keşfedin veya yapılandırma ayrıntıları için [Ajan Şablonları Dokümantasyonu](../../docs/agent-templates.md)'nu okuyun. ## 🔧 Örnek Implementasyonlar Örnek implementasyonlar, özel kullanım durumlarını ve gelişmiş işlevselliği sergiler: | Implementasyon | Açıklama | Durum | | :------------------------- | :--------------------------------------------------------------------------- | :---------- | | **Orkestre Edilmiş Ajan** | Bağlama göre davranışı uyarlamak için orkestrasyon kullanan örnek ajan | Mevcut | | **Bilişsel Muhakemeci** | Yapılandırılmış muhakeme ve bilişsel araçlar kullanarak karmaşık sorunları ele alır | Mevcut | | **Ajan Planlayıcı** | Diğer yapay zeka ajanlarını tasarlamak ve uygulamak için özel ajan | Mevcut | | [**Kod Oyun Alanı (Code Playground)**](../../docs/roadmap/code-playground.md) | Zengin görselleştirme yetenekleriyle korumalı kod oluşturma ve yürütme | Planlandı | ## 🔐 Ortam Yapılandırma Detayları AgentDock Açık Kaynak İstemcisi, çalışması için LLM sağlayıcıları için API anahtarları gerektirir. Bunlar, sağlanan `.env.example` dosyasına dayanarak oluşturduğunuz bir ortam dosyasında (`.env` veya `.env.local`) yapılandırılır. ### LLM Sağlayıcı API Anahtarları LLM sağlayıcı API anahtarlarınızı ekleyin (en az biri gereklidir): ```bash # LLM Sağlayıcı API Anahtarları - en az biri gereklidir ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Anthropic API anahtarı OPENAI_API_KEY=sk-xxxxxxx # OpenAI API anahtarı GEMINI_API_KEY=xxxxxxx # Google Gemini API anahtarı DEEPSEEK_API_KEY=xxxxxxx # DeepSeek API anahtarı GROQ_API_KEY=xxxxxxx # Groq API anahtarı ``` ### API Anahtarı Çözümlemesi AgentDock Açık Kaynak İstemcisi, hangi API anahtarının kullanılacağını çözerken bir öncelik sırası izler: 1. **Ajan başına özel API anahtarı** (UI'daki ajan ayarları aracılığıyla ayarlanır) 2. **Genel ayarlar API anahtarı** (UI'daki ayarlar sayfası aracılığıyla ayarlanır) 3. **Ortam değişkeni** (.env.local veya dağıtım platformundan) ### Araca Özel API Anahtarları Bazı araçlar ayrıca kendi API anahtarlarını gerektirir: ```bash # Araca Özel API Anahtarları SERPER_API_KEY= # Arama işlevselliği için gerekli FIRECRAWL_API_KEY= # Daha derin web araması için gerekli ``` Ortam yapılandırması hakkında daha fazla ayrıntı için [`src/types/env.ts`](../../src/types/env.ts) içindeki implementasyona bakın. ### Kendi API Anahtarınızı Kullanın (BYOK - Bring Your Own Key) AgentDock bir BYOK (Bring Your Own Key - Kendi API Anahtarınızı Kullanın) modeliyle çalışır: 1. API anahtarlarınızı uygulama ayarları sayfasında ekleyin 2. Alternatif olarak, doğrudan API kullanımı için istek başlıkları aracılığıyla anahtarları sağlayın 3. Anahtarlar, yerleşik şifreleme sistemi kullanılarak güvenli bir şekilde saklanır 4. Sunucularımızda hiçbir API anahtarı paylaşılmaz veya saklanmaz ## 📦 Paket Yöneticisi Bu proje, tutarlı bağımlılık yönetimi için `pnpm` kullanımını *gerektirir*. `npm` ve `yarn` desteklenmez. ## 💡 Ne İnşa Edebilirsiniz 1. **Yapay Zeka Destekli Uygulamalar** - Herhangi bir frontend ile özel chatbotlar - Komut satırı yapay zeka asistanları - Otomatik veri işleme pipeline'ları - Backend hizmet entegrasyonları 2. **Entegrasyon Yetenekleri** - Herhangi bir yapay zeka sağlayıcısı (OpenAI, Anthropic, vb.) - Herhangi bir frontend framework'ü - Herhangi bir backend hizmeti - Özel veri kaynakları ve API'ler 3. **Otomasyon Sistemleri** - Veri işleme workflow'ları - Belge analizi pipeline'ları - Otomatik raporlama sistemleri - Görev otomasyon ajanları ## Ana Özellikler | Özellik | Açıklama | | :----------------------------- | :------------------------------------------------------------------------------ | | 🔌 **Framework'ten Bağımsız (Node.js Backend)** | Çekirdek kütüphane Node.js backend yığınlarıyla entegre olur. | | 🧩 **Modüler Tasarım** | Basit node'lardan karmaşık sistemler oluşturun | | 🛠️ **Genişletilebilir** | Herhangi bir işlevsellik için özel node'lar oluşturun | | 🔒 **Güvenli** | API anahtarları ve veriler için yerleşik güvenlik özellikleri | | 🔑 **BYOK** | LLM sağlayıcıları için *Kendi API Anahtarınızı Kullanın* | | 📦 **Bağımsız Çalışabilir (Self-contained)**| Çekirdek framework minimum bağımlılıklara sahiptir | | ⚙️ **Çok Adımlı Araç Çağrıları (Multi-Step Tool Calls)**| *Karmaşık muhakeme zincirleri* için destek | | 📊 **Yapılandırılmış Kayıt** | Ajan yürütmesine ilişkin ayrıntılı bilgiler | | 🛡️ **Güçlü Hata Yönetimi** | Öngörülebilir davranış ve basitleştirilmiş hata ayıklama | | 📝 **Önce TypeScript** | Tip güvenliği ve geliştirilmiş geliştirici deneyimi | | 🌐 **Açık Kaynak İstemci** | Eksiksiz bir Next.js referans implementasyonu içerir | | 🔄 **Orkestrasyon** | Bağlama göre ajan davranışının *dinamik kontrolü* | | 💾 **Oturum Yönetimi** | Eşzamanlı konuşmalar için izole edilmiş durum | | 🎮 **Yapılandırılabilir Determinizm** | Yapay zeka yaratıcılığını ve öngörülebilirliği node mantığı/workflow'ları aracılığıyla dengeleyin. | ## 🧰 Bileşenler AgentDock'un modüler mimarisi şu ana bileşenler üzerine kurulmuştur: * **BaseNode**: Sistemdeki tüm node'lar için temel * **AgentNode**: Ajan işlevselliği için birincil soyutlama * **Araçlar ve Özel Node'lar**: Node'lar olarak uygulanan çağrılabilir yetenekler ve özel mantık. * **Node Kayıt Defteri**: Tüm node tiplerinin kaydedilmesini ve alınmasını yönetir * **Araç Kayıt Defteri**: Ajanlar için araç kullanılabilirliğini yönetir * **CoreLLM**: LLM sağlayıcılarıyla etkileşim için birleşik arayüz * **Sağlayıcı Kayıt Defteri**: LLM sağlayıcı yapılandırmalarını yönetir * **Hata Yönetimi**: Hataları yönetmek ve öngörülebilir davranış sağlamak için sistem * **Günlükleme**: İzleme ve hata ayıklama için yapılandırılmış günlükleme sistemi * **Orkestrasyon**: Konuşma bağlamına göre araç kullanılabilirliğini ve davranışını kontrol eder * **Oturumlar**: Eşzamanlı konuşmalar arasında durum izolasyonunu yönetir Bu bileşenler hakkında ayrıntılı teknik dokümantasyon için [Mimariye Genel Bakış](../../docs/architecture/README.md)'a bakın. ## 🗺️ Yol Haritası Aşağıda AgentDock için geliştirme yol haritamız bulunmaktadır. Burada listelenen iyileştirmelerin çoğu, şu anda yerel olarak geliştirilen ve kararlı bir sürüme ulaştığında sürümlenmiş bir NPM paketi olarak yayınlanacak olan çekirdek AgentDock framework'ü (`agentdock-core`) ile ilgilidir. Bazı yol haritası öğeleri, açık kaynak istemci implementasyonunda geliştirmeler de içerebilir. | Özellik | Açıklama | Kategori | | :------------------------------------------------------------------- | :---------------------------------------------------------------------------------- | :-------------- | | [**Depolama Soyutlama Katmanı**](../../docs/roadmap/storage-abstraction.md) | Takılabilir sağlayıcılara sahip esnek depolama sistemi | **Devam Ediyor** | | [**Gelişmiş Bellek Sistemleri**](../../docs/roadmap/advanced-memory.md) | Uzun vadeli bağlam yönetimi | **Devam Ediyor** | | [**Vektör Depolama Entegrasyonu**](../../docs/roadmap/vector-storage.md) | Belgeler ve bellek için embedding tabanlı erişim | **Devam Ediyor** | | [**Yapay Zeka Ajanları için Değerlendirme**](../../docs/roadmap/evaluation-framework.md) | Kapsamlı test ve değerlendirme framework'ü | **Devam Ediyor** | | [**Platform Entegrasyonu**](../../docs/roadmap/platform-integration.md) | Telegram, WhatsApp ve diğer mesajlaşma platformları için destek | **Planlandı** | | [**Çoklu Ajan İşbirliği**](../../docs/roadmap/multi-agent-collaboration.md) | Ajanların birlikte çalışmasını sağlama | **Planlandı** | | [**Model Bağlam Protokolü (MCP) Entegrasyonu**](../../docs/roadmap/mcp-integration.md) | MCP aracılığıyla harici araçları keşfetme ve kullanma desteği | **Planlandı** | | [**Sesli Yapay Zeka Ajanları**](../../docs/roadmap/voice-agents.md) | AgentNode aracılığıyla sesli arayüzler ve telefon numaraları kullanan yapay zeka ajanları | **Planlandı** | | [**Telemetri ve İzlenebilirlik**](../../docs/roadmap/telemetry.md) | Gelişmiş loglama ve performans takibi | **Planlandı** | | [**Workflow Runtime & Node Türleri**](../../docs/roadmap/workflow-nodes.md) | Çekirdek runtime, node tipleri ve karmaşık otomasyonlar için orkestrasyon mantığı | **Planlandı** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Yapay zeka ajanlarını ve workflow'larını ölçeklendirmek için kapsamlı kurumsal bulut platformu | **Bulut** | ## 👥 Katkıda Bulunma AgentDock'a katkıda bulunmanızı bekliyoruz! Ayrıntılı katkıda bulunma yönergeleri için lütfen [CONTRIBUTING.md](../../CONTRIBUTING.md)'ye bakın. ## 📜 Lisans AgentDock, [MIT Lisansı](../../LICENSE) altında yayınlanmıştır. ## ✨ Sınırsız Olasılıklar Yaratın! AgentDock, hayal edebileceğiniz hemen hemen her yapay zeka destekli uygulama veya otomasyonu oluşturmak için temel sağlar. Framework'ü keşfetmeye, yenilikçi ajanlar oluşturmaya ve topluluğa katkıda bulunmaya teşvik ediyoruz. Yapay zeka etkileşiminin geleceğini birlikte şekillendirelim! --- [Çeviri dizinine geri dön](/docs/i18n/README.md) ## AgentDock: Створюйте Безмежні Можливості з Агентами ШІ

AgentDock Logo

## 🌐 Переклади README [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock — це фреймворк для створення складних агентів ШІ, які виконують складні завдання з **конфігурованою детермінованістю**. Він складається з двох основних компонентів: 1. **AgentDock Core**: Фреймворк з відкритим кодом, орієнтований на бекенд, для створення та розгортання агентів ШІ. Він розроблений як *незалежний від фреймворку* та *незалежний від постачальника*, що дає вам повний контроль над реалізацією вашого агента. 2. **Open Source Client**: Повнофункціональний додаток Next.js, який служить еталонною реалізацією та споживачем фреймворку AgentDock Core. Ви можете побачити його в дії на [https://hub.agentdock.ai](https://hub.agentdock.ai) Створений за допомогою TypeScript, AgentDock робить акцент на *простоті*, *розширюваності* та ***конфігурованій детермінованості***, що робить його ідеальним для створення надійних, передбачуваних систем ШІ, які можуть працювати з мінімальним наглядом. ## 🧠 Принципи Дизайну AgentDock побудований на цих основних принципах: - **Простота Перш за Все**: Мінімальний код, необхідний для створення функціональних агентів - **Архітектура на Основі Вузлів (Nodes)**: Усі можливості реалізовані як вузли - **Інструменти як Спеціалізовані Вузли**: Інструменти розширюють систему вузлів для можливостей агента - **Конфігурована Детермінованість**: Контролюйте передбачуваність поведінки агента - **Типова Безпека (Type Safety)**: Повна типізація TypeScript у всьому фреймворку ### Конфігурована Детермінованість ***Конфігурована детермінованість*** є основою філософії дизайну AgentDock, дозволяючи вам збалансувати творчі можливості ШІ з передбачуваною поведінкою системи: - `AgentNode` за своєю природою є недетермінованими, оскільки LLM можуть генерувати різні відповіді кожного разу - Робочі процеси (Workflows) можна зробити більш детермінованими за допомогою *визначених шляхів виконання інструментів* - Розробники можуть **контролювати рівень детермінованості**, налаштовуючи, які частини системи використовують висновки LLM - Навіть з компонентами LLM загальна поведінка системи залишається **передбачуваною** завдяки структурованим взаємодіям інструментів - Цей збалансований підхід дозволяє досягти як *творчості*, так і **надійності** у ваших додатках ШІ #### Детерміновані Робочі Процеси AgentDock повністю підтримує детерміновані робочі процеси, з якими ви знайомі з типових конструкторів робочих процесів. Усі передбачувані шляхи виконання та надійні результати, яких ви очікуєте, доступні, з висновками LLM або без них: ```mermaid flowchart LR Input[Вхід] --> Process[Процес] Process --> Database[(База Даних)] Process --> Output[Вихід] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Недетермінована Поведінка Агента З AgentDock ви також можете використовувати `AgentNode` з LLM, коли вам потрібна більша адаптивність. Творчі результати можуть змінюватися залежно від ваших потреб, зберігаючи при цьому структуровані шаблони взаємодії: ```mermaid flowchart TD Input[Запит Користувача] --> Agent[AgentNode] Agent -->|"Міркування LLM (Недетерміноване)"| ToolChoice{Вибір Інструменту} ToolChoice -->|"Варіант A"| ToolA[Інструмент Поглибленого Дослідження] ToolChoice -->|"Варіант B"| ToolB[Інструмент Аналізу Даних] ToolChoice -->|"Варіант C"| ToolC[Пряма Відповідь] ToolA --> Response[Кінцева Відповідь] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Недетерміновані Агенти з Детермінованими Підпроцесами AgentDock пропонує вам ***найкраще з обох світів***, поєднуючи недетермінований інтелект агента з детермінованим виконанням робочого процесу: ```mermaid flowchart TD Input[Запит Користувача] --> Agent[AgentNode] Agent -->|"Міркування LLM (Недетерміноване)"| FlowChoice{Вибір Підпроцесу} FlowChoice -->|"Рішення A"| Flow1[Детермінований Робочий Процес 1] FlowChoice -->|"Рішення B"| Flow2[Детермінований Робочий Процес 2] FlowChoice -->|"Рішення C"| DirectResponse[Згенерувати Відповідь] Flow1 --> |"Крок 1 → 2 → 3 → ... → 200"| Flow1Result[Результат Робочого Процесу 1] Flow2 --> |"Крок 1 → 2 → 3 → ... → 100"| Flow2Result[Результат Робочого Процесу 2] Flow1Result --> Response[Кінцева Відповідь] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` Цей підхід дозволяє викликати складні, багатоетапні робочі процеси (потенційно залучаючи сотні детермінованих кроків, реалізованих в інструментах або як послідовності пов'язаних вузлів) за допомогою інтелектуальних рішень агента. Кожен робочий процес виконується передбачувано, незважаючи на те, що його запускає недетерміноване міркування агента. Для більш просунутих робочих процесів агентів ШІ та багатоетапних конвеєрів обробки ми створюємо [AgentDock Pro](../../docs/agentdock-pro.md) - потужну платформу для створення, візуалізації та виконання складних систем агентів. #### Стисло: Конфігурована Детермінованість Уявіть це як керування автомобілем. Іноді вам потрібна творчість ШІ (наприклад, навігація вулицями міста - недетермінована), а іноді вам потрібні надійні, покрокові процеси (наприклад, дотримання знаків на автомагістралі - детерміновані). AgentDock дозволяє створювати системи, які використовують *обидва* підходи, вибираючи правильний для кожної частини завдання. Ви отримуєте як творчість ШІ, *так і* передбачувані результати там, де вони потрібні. ## 🏗️ Основна Архітектура Фреймворк побудований навколо потужної, модульної системи на основі вузлів (Nodes), яка служить основою для всієї функціональності агента. Ця архітектура використовує різні типи вузлів як будівельні блоки: - **`BaseNode`**: Фундаментальний клас, який встановлює основний інтерфейс та можливості для всіх вузлів. - **`AgentNode`**: Спеціалізований основний вузол, який керує взаємодіями LLM, використанням інструментів та логікою агента. - **Інструменти та Спеціальні Вузли**: Розробники реалізують можливості агента та спеціальну логіку як вузли, що розширюють `BaseNode`. Ці вузли взаємодіють через керовані реєстри та можуть бути з'єднані (використовуючи порти основної архітектури та потенційну шину повідомлень) для забезпечення складної, конфігурованої та потенційно детермінованої поведінки та робочих процесів агентів. Детальний опис компонентів та можливостей системи вузлів дивіться в [Документації Системи Вузлів](../../docs/nodes/README.md). ## 🚀 Початок Роботи Для більш детального ознайомлення дивіться [Керівництво по Початку Роботи](../../docs/getting-started.md). ### Вимоги * Node.js ≥ 20.11.0 (LTS) * pnpm ≥ 9.15.0 (Обов'язково) * Ключі API для постачальників LLM (Anthropic, OpenAI, тощо) ### Встановлення 1. **Клонуйте Репозиторій**: ```bash git clone https://github.com/AgentDock/AgentDock.git cd AgentDock ``` 2. **Встановіть pnpm**: ```bash corepack enable corepack prepare pnpm@latest --activate ``` 3. **Встановіть Залежності**: ```bash pnpm install ``` Для чистої перевстановки (коли вам потрібно перебудувати з нуля): ```bash pnpm run clean-install ``` Цей скрипт видаляє всі `node_modules`, файли блокування та коректно перевстановлює залежності. 4. **Налаштуйте Середовище**: Створіть файл середовища (`.env` або `.env.local`) на основі наданого файлу `.env.example`: ```bash # Варіант 1: Створити .env.local cp .env.example .env.local # Варіант 2: Створити .env cp .env.example .env ``` Потім додайте свої ключі API до файлу середовища. 5. **Запустіть Сервер Розробки**: ```bash pnpm dev ``` ### Розширені Можливості | Можливість | Опис | Документація | | :------------------------- | :-------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------ | | **Управління Сесіями** | Ізольоване, високопродуктивне управління станом для діалогів | [Документація Сесій](../../docs/architecture/sessions/README.md) | | **Фреймворк Оркестрації** | Контроль поведінки агента та доступності інструментів на основі контексту | [Документація Оркестрації](../../docs/architecture/orchestration/README.md) | | **Абстракція Сховища** | Гнучка система зберігання з можливістю підключення постачальників для KV, Vector та Secure Storage | [Документація Сховища](../../docs/storage/README.md) | Система сховища наразі розвивається з ключовим сховищем (постачальники Memory, Redis, Vercel KV) та захищеним сховищем на стороні клієнта, тоді як векторне сховище та додаткові бекенди перебувають у розробці. ## 📕 Документація Документація фреймворку AgentDock доступна на [hub.agentdock.ai/docs](https://hub.agentdock.ai/docs) та в папці `/docs/` цього репозиторію. Документація включає: - Керівництво по початку роботи - Довідники API - Навчальні посібники зі створення вузлів - Приклади інтеграції ## 📂 Структура Репозиторію Цей репозиторій містить: 1. **AgentDock Core**: Основний фреймворк, розташований у `agentdock-core/` 2. **Open Source Client**: Повна еталонна реалізація, створена за допомогою Next.js, яка служить споживачем фреймворку AgentDock Core. 3. **Приклади Агентів**: Готові конфігурації агентів у каталозі `agents/` Ви можете використовувати AgentDock Core незалежно у власних додатках або використовувати цей репозиторій як відправну точку для створення власних додатків на основі агентів. ## 📝 Шаблони Агентів AgentDock включає кілька попередньо налаштованих шаблонів агентів. Дослідіть їх у каталозі `agents/` або прочитайте [Документацію Шаблонів Агентів](../../docs/agent-templates.md) для деталей конфігурації. ## 🔧 Приклади Реалізацій Приклади реалізацій демонструють спеціалізовані випадки використання та розширену функціональність: | Реалізація | Опис | Статус | | :--------------------------- | :----------------------------------------------------------------------------------------------- | :----------- | | **Оркестрований Агент** | Приклад агента, який використовує оркестрацію для адаптації поведінки на основі контексту | Доступно | | **Когнітивний Розмірковувач**| Розв'язує складні проблеми за допомогою структурованого міркування та когнітивних інструментів | Доступно | | **Планувальник Агентів** | Спеціалізований агент для проектування та реалізації інших агентів ШІ | Доступно | | [**Code Playground (Середовище Розробки Коду)**](../../docs/roadmap/code-playground.md) | Генерація та виконання коду в пісочниці з багатими можливостями візуалізації | Заплановано | ## 🔐 Деталі Конфігурації Середовища AgentDock Open Source Client потребує ключів API для постачальників LLM для функціонування. Вони налаштовуються у файлі середовища (`.env` або `.env.local`), який ви створюєте на основі наданого файлу `.env.example`. ### Ключі API Постачальників LLM Додайте ключі API постачальників LLM (потрібен принаймні один): ```bash # Ключі API Постачальників LLM - потрібен принаймні один ANTHROPIC_API_KEY=sk-ant-xxxxxxx # Ключ API Anthropic OPENAI_API_KEY=sk-xxxxxxx # Ключ API OpenAI GEMINI_API_KEY=xxxxxxx # Ключ API Google Gemini DEEPSEEK_API_KEY=xxxxxxx # Ключ API DeepSeek GROQ_API_KEY=xxxxxxx # Ключ API Groq ``` ### Визначення Ключа API AgentDock Open Source Client дотримується порядку пріоритету при визначенні, який ключ API використовувати: 1. **Спеціальний ключ API для агента** (встановлюється через налаштування агента в інтерфейсі користувача) 2. **Глобальний ключ API налаштувань** (встановлюється через сторінку налаштувань в інтерфейсі користувача) 3. **Змінна середовища** (з `.env.local` або платформи розгортання) ### Ключі API, Специфічні для Інструментів Деякі інструменти також потребують власних ключів API: ```bash # Ключі API, Специфічні для Інструментів SERPER_API_KEY= # Необхідно для функціональності пошуку FIRECRAWL_API_KEY= # Необхідно для глибшого веб-сканування ``` Для отримання додаткової інформації про конфігурацію середовища дивіться реалізацію в [`src/types/env.ts`](../../src/types/env.ts). ### Використовуйте Власний Ключ (BYOK - Bring Your Own Key) AgentDock працює за моделлю BYOK (Bring Your Own Key - Використовуйте Власний Ключ): 1. Додайте свої ключі API на сторінці налаштувань програми 2. Або надайте ключі через заголовки запитів для прямого використання API 3. Ключі надійно зберігаються за допомогою вбудованої системи шифрування 4. Жодні ключі API не передаються та не зберігаються на наших серверах ## 📦 Менеджер Пакетів Цей проект *вимагає* використання `pnpm` для послідовного управління залежностями. `npm` та `yarn` не підтримуються. ## 💡 Що Ви Можете Створити 1. **Додатки на Основі ШІ** - Спеціальні чат-боти з будь-яким фронтендом - Асистенти ШІ командного рядка - Автоматизовані конвеєри обробки даних - Інтеграції бекенд-сервісів 2. **Можливості Інтеграції** - Будь-який постачальник ШІ (OpenAI, Anthropic, тощо) - Будь-який фронтенд-фреймворк - Будь-який бекенд-сервіс - Спеціальні джерела даних та API 3. **Системи Автоматизації** - Робочі процеси обробки даних - Конвеєри аналізу документів - Автоматизовані системи звітності - Агенти автоматизації завдань ## Ключові Особливості | Особливість | Опис | | :--------------------------- | :------------------------------------------------------------------------------------------------- | | 🔌 **Незалежність від Фреймворку (Node.js Backend)** | Основна бібліотека інтегрується зі стеками бекенду Node.js. | | 🧩 **Модульний Дизайн** | Створюйте складні системи з простих вузлів | | 🛠️ **Розширюваність** | Створюйте спеціальні вузли для будь-якої функціональності | | 🔒 **Безпека** | Вбудовані функції безпеки для ключів API та даних | | 🔑 **BYOK** | Використовуйте *власні ключі API* для постачальників LLM | | 📦 **Самодостатність (Self-contained)** | Основний фреймворк має мінімальні залежності | | ⚙️ **Багатоетапні Виклики Інструментів (Multi-Step Tool Calls)** | Підтримка *складних ланцюжків міркувань* | | 📊 **Структуроване Логування**| Детальна інформація про виконання агента | | 🛡️ **Стійка Обробка Помилок** | Передбачувана поведінка та спрощене налагодження | | 📝 **TypeScript Перш за Все**| Типова безпека та покращений досвід розробника | | 🌐 **Open Source Клієнт** | Включає повну еталонну реалізацію Next.js | | 🔄 **Оркестрація** | *Динамічний контроль* поведінки агента на основі контексту | | 💾 **Управління Сесіями** | Ізольований стан для паралельних розмов | | 🎮 **Конфігурована Детермінованість**| Збалансуйте творчість ШІ та передбачуваність за допомогою логіки вузлів/робочих процесів. | ## 🧰 Компоненти Модульна архітектура AgentDock побудована на цих ключових компонентах: * **BaseNode**: Основа для всіх вузлів у системі * **AgentNode**: Основна абстракція для функціональності агента * **Інструменти та Спеціальні Вузли**: Викликані можливості та спеціальна логіка, реалізовані як вузли. * **Реєстр Вузлів**: Керує реєстрацією та отриманням усіх типів вузлів * **Реєстр Інструментів**: Керує доступністю інструментів для агентів * **CoreLLM**: Уніфікований інтерфейс для взаємодії з постачальниками LLM * **Реєстр Постачальників**: Керує конфігураціями постачальників LLM * **Обробка Помилок**: Система для обробки помилок та забезпечення передбачуваної поведінки * **Логування (Logging)**: Структурована система логування для моніторингу та налагодження * **Оркестрація**: Контролює доступність інструментів та поведінку на основі контексту розмови * **Сесії**: Керує ізоляцією стану між паралельними розмовами Для отримання детальної технічної документації щодо цих компонентів дивіться [Огляд Архітектури](../../docs/architecture/README.md). ## 🗺️ Дорожня Карта Нижче наведена наша дорожня карта розробки AgentDock. Більшість перелічених тут удосконалень стосуються основного фреймворку AgentDock (`agentdock-core`), який наразі розробляється локально та буде опублікований як версіонований пакет NPM після досягнення стабільного релізу. Деякі елементи дорожньої карти можуть також передбачати вдосконалення реалізації клієнта з відкритим кодом. | Особливість | Опис | Категорія | | :--------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------ | :---------------- | | [**Шар Абстракції Сховища**](../../docs/roadmap/storage-abstraction.md) | Гнучка система зберігання з підключаємими постачальниками | **В Розробці** | | [**Розширені Системи Пам'яті**](../../docs/roadmap/advanced-memory.md) | Управління довгостроковим контекстом | **В Розробці** | | [**Інтеграція Векторного Сховища**](../../docs/roadmap/vector-storage.md) | Пошук на основі вбудовування для документів та пам'яті | **В Розробці** | | [**Оцінка для Агентів ШІ**](../../docs/roadmap/evaluation-framework.md) | Комплексний фреймворк тестування та оцінки | **В Розробці** | | [**Інтеграція Платформ**](../../docs/roadmap/platform-integration.md) | Підтримка Telegram, WhatsApp та інших платформ обміну повідомленнями | **Заплановано** | | [**Співпраця Багатьох Агентів**](../../docs/roadmap/multi-agent-collaboration.md)| Дозволити агентам працювати разом | **Заплановано** | | [**Інтеграція Протоколу Контексту Моделі (MCP)**](../../docs/roadmap/mcp-integration.md)| Підтримка виявлення та використання зовнішніх інструментів через MCP | **Заплановано** | | [**Голосові Агенти ШІ**](../../docs/roadmap/voice-agents.md) | Агенти ШІ, які використовують голосові інтерфейси та телефонні номери через AgentNode | **Заплановано** | | [**Телеметрія та Відстежуваність**](../../docs/roadmap/telemetry.md) | Розширене логування та відстеження продуктивності | **Заплановано** | | [**Workflow Runtime & Node Типи**](../../docs/roadmap/workflow-nodes.md) | Основний runtime, типи вузлів (Nodes) та логіка оркестрації для складних автоматизацій | **Заплановано** | | [**AgentDock Pro**](../../docs/agentdock-pro.md) | Повноцінна корпоративна хмарна платформа для масштабування агентів ШІ та робочих процесів | **Хмара** | | [**Конструктор Агентів ШІ Природною Мовою**](../../docs/roadmap/nl-agent-builder.md)| Візуальний конструктор + створення агентів та робочих процесів природною мовою | **Хмара** | | [**Ринок Агентів**](../../docs/roadmap/agent-marketplace.md) | Монетизовані шаблони агентів | **Хмара** | ## 👥 Внесок Ми вітаємо внески в AgentDock! Дивіться [CONTRIBUTING.md](https://github.com/AgentDock/AgentDock/blob/main/CONTRIBUTING.md) для отримання детальних інструкцій щодо внесення внеску. ## 📜 Ліцензія AgentDock випускається під [Ліцензією MIT](https://github.com/AgentDock/AgentDock/blob/main/LICENSE). ## ✨ Створюйте Безмежні Можливості! AgentDock надає основу для створення практично будь-якого додатка або автоматизації на базі ШІ, які ви можете собі уявити. Ми заохочуємо вас досліджувати фреймворк, створювати інноваційних агентів та робити внесок у спільноту. Давайте разом формувати майбутнє взаємодії з ШІ! --- [Повернутися до Індексу Перекладів](../README.md) ## Initial Security Audit This document summarizes the findings of an initial security review performed on the AgentDock codebase (focusing on `agentdock-core` and the open source client layer). It identifies potential vulnerabilities, analyzes risks, and tracks actions taken or recommended. Key: * ✅ = Issue Addressed / Mitigated / Low Risk / Current State OK * ⚠️ = Action Required / Future Enhancement / High Priority --- **1. API Key Handling and Security:** * **Issue:** Flexible API key management using environment variables and client-side `localStorage` (via `SecureStorage`). * **Analysis:** Offers flexibility suitable for the OS client. `SecureStorage` uses AES-GCM encryption and HMAC, but is vulnerable to XSS attacks as encryption keys are also stored in `localStorage`. Environment variables depend on secure deployment configuration. Keys are masked in logs. * **Status:** ✅ (Current implementation acceptable for OS client, risks noted) * **Recommendation:** ✅ Document `SecureStorage` XSS risk clearly. Emphasize env vars/BYOK for production. (Documentation updated). **2. Input Validation:** * **Issue:** Ensuring comprehensive validation of all external inputs. Potential ReDoS risk in specific regex. * **Analysis:** Zod validation is used effectively in key areas. ReDoS risk in `extractArxivId` assessed as low due to prior Zod validation. * **Status:** ✅ (Current validation good, risk low) * **Recommendation:** ⚠️ Perform focused audit of remaining API inputs and `JSON.parse` points for completeness. **3. Error Handling and Information Disclosure:** * **Issue:** Potential for verbose errors leaking internal details in production. * **Analysis:** The `parseProviderError` and `normalizeError` system correctly sanitizes errors and conditionally excludes details in production based on `NODE_ENV`. * **Status:** ✅ (Mechanism prevents info disclosure in production) * **Recommendation:** None (Ensure `NODE_ENV` is set correctly in deployments). **4. Authentication and Authorization:** * **Issue:** Lack of explicit user authentication in `agentdock-core`. Security relies on API key protection. * **Analysis:** User auth is intentionally out-of-scope for `agentdock-core`. API key security relies on environment variables and `SecureStorage` (with its XSS risk). * **Status:** ✅ (Acknowledged scope, risk noted) * **Recommendation:** ✅ Document `SecureStorage` XSS risk and secure key management practices. (Documentation updated). **5. Data Handling and Storage:** * **Issue:** Default `MemoryStorageProvider` is non-persistent. * **Analysis:** The framework defaults to non-persistent memory storage. Persistent options (`RedisStorageProvider`, `VercelKVProvider`) **are implemented** and **must** be explicitly configured via environment variables for production. * **Status:** ✅ (Persistent options exist, but configuration required) * **Recommendation:** ⚠️ Emphasize **critical** need for configuring Redis/Vercel KV in production documentation. **6. Code Structure and Common Errors:** * **Issue:** Potential inconsistencies in error handling patterns and lack of general retry mechanisms. * **Analysis:** `agentdock-core` uses standardized `AgentError`. The open source client layer uses `console.error` more variably. General retry mechanism for transient errors is missing. * **Status:** ⚠️ (Inconsistencies and lack of retries identified) * **Recommendation:** ⚠️ Standardize logging/API error responses in client layer. Implement general retry mechanism (e.g., exponential backoff) as future enhancement. **7. Dependencies:** * **Issue:** Vulnerabilities in dependencies. * **Analysis:** `pnpm audit` initially found 1 critical (`next`) and 2 moderate (`undici`, `esbuild`) vulnerabilities. * **Status:** ✅ (Vulnerabilities resolved via updates and overrides) * **Recommendation:** ✅ Perform regular dependency audits (`pnpm audit`) and updates. **8. Browser Security (XSS):** * **Issue:** Use of `rehype-raw` in Markdown components allows potential XSS. * **Analysis:** Risk medium/high (LLM output, community docs). * **Status:** ✅ (Resolved by switching to `rehype-sanitize`, testing confirmed OK) * **Recommendation:** Consider future sandboxing for Mermaid diagrams. **9. Rate Limiting and Resource Management:** * **Issue:** Lack of server-side API rate limiting and basic tool throttling. * **Analysis:** No server-side rate limiting implemented (DoS risk). Tool throttling is basic (`sleep()`). Internal plan exists for implementation. * **Status:** ⚠️ (Rate limiting not implemented) * **Recommendation:** ⚠️ **Implement server-side rate limiting** (e.g., using `@upstash/ratelimit` with KV store) as planned internally (high priority). ⚠️ Improve tool throttling beyond `sleep()`. **10. NoSQL Injection (if applicable):** * **Issue:** Potential future risk if NoSQL databases are added. * **Analysis:** Not currently applicable to KV stores. * **Status:** ✅ (Not applicable currently) * **Recommendation:** Note for future database integrations. --- ## General Recommendations * ⚠️ Conduct regular security audits and penetration testing. * ⚠️ Maintain clear security best practices documentation for users and contributors. * ⚠️ Consider dedicated security code reviews before major releases. --- ## Next Actions (Based on Audit) 1. **Documentation Updates:** * ✅ Clearly document the XSS risk associated with `SecureStorage` (client-side API key storage) and recommend secure alternatives (env vars, BYOK). (Updated in `docs/oss-client/nextjs-implementation.md` and linked from `docs/roadmap/storage-abstraction.md`). (See Issue 1, 4) * ⚠️ Emphasize the **critical** need for users to configure a persistent storage provider (Redis/Vercel KV) for production, detailing environment variable setup. (See Issue 5) * ⚠️ Create/expand security best practices documentation covering key management, input validation principles, etc. (See General Recs) 2. **High Priority Implementation:** * ⚠️ Implement server-side API rate limiting based on the internal plan (using `@upstash/ratelimit` or similar). (See Issue 9) 3. **Future Enhancements / Code Improvements:** * ⚠️ Perform a focused audit of API inputs and `JSON.parse` points to ensure comprehensive validation coverage. (See Issue 2) * ⚠️ Standardize logging (using structured `logger`) and API error responses in the open source client layer. (See Issue 6) * ⚠️ Implement a general retry mechanism (e.g., exponential backoff) for external API calls (LLMs, tools). (See Issue 6) * ⚠️ Improve tool throttling beyond simple `sleep()` delays. (See Issue 9) * ⚠️ Consider sandboxing for Mermaid diagrams for future enhancement. (See Issue 8) 4. **Process Improvements:** * ✅ Establish a process for regular dependency audits (`pnpm audit`). (Implicitly done by performing this audit, recommend formalizing) * ⚠️ Incorporate regular security reviews/audits into the development lifecycle. (See General Recs) _This audit provides a snapshot. Ongoing vigilance and security practices are crucial._ ## AgentDock Memory Architecture Overview ## Complete Architecture ```mermaid graph LR A[Conversation Messages] --> B[PRIME Extraction] B --> C[Memory System Storage & Search] C --> D[Intelligence Layer] C --> E[Supporting Services] D --> F[Workflow Learning Service] style B fill:#e1f5fe style C fill:#f3e5f5 style D fill:#e8f5e8 ``` ## PRIME: Intelligent Memory Extraction **Purpose**: Transform conversations into structured memories ```mermaid graph TD A["Raw Message: 'I met Sarah at the coffee shop, she mentioned the project deadline is Friday'"] --> B[PRIME Extraction] B --> C[Person: Sarah - Semantic] B --> D[Location: coffee shop - Episodic] B --> E[Deadline: project due Friday - Procedural] style A fill:#f9f9f9 style B fill:#e1f5fe style C fill:#e8f5e8 style D fill:#fff3e0 style E fill:#f3e5f5 ``` **Key Features**: - Smart model selection (standard/advanced 2-tier) - Rule-based extraction guidance - Cost optimization with budget tracking - Real-time message processing ## Memory System: Vector-First Storage & Retrieval **Purpose**: Store, index, and retrieve memories efficiently ```mermaid graph TD A["Query: What did Sarah say about deadlines?"] --> B[Vector + Text Search] B --> C[Memory Storage] C --> D["Embeddings
0.1,0.2
0.3,0.4"] C --> E["FTS5
deadline
friday"] C --> F["Metadata
semantic
episodic"] D --> G["Hybrid Scoring
70% vector + 30% text"] E --> G F --> G G --> H["Results
Sarah deadline memory
related project memories"] style A fill:#f9f9f9 style B fill:#e1f5fe style C fill:#fff3e0 style G fill:#f3e5f5 style H fill:#e8f5e8 ``` **Key Features**: - Hybrid vector + text search - Specialized memory adapters for PostgreSQL and SQLite - Community-extensible adapters available for ChromaDB, Pinecone, and Qdrant - Memory type specialization - Performance: <50ms recall ## Architecture Flow ```mermaid graph TD A[User Message] --> B[PRIME Extraction] B --> C[Memory Storage] C --> D[Vector Indexing] C --> E[Text Indexing] F[User Query] --> G[Embedding Generation] G --> H[Vector Search] F --> I[Text Search] H --> J[Hybrid Fusion] I --> J J --> K[Ranked Results] style B fill:#e1f5fe style G fill:#f3e5f5 style J fill:#e8f5e8 ``` ## Advanced Features ### PRIME Extraction - **Rule-based guidance**: Natural language extraction rules - **Tier optimization**: Auto-select model based on complexity - **Cost intelligence**: Budget tracking with <$20/month for 100k operations ### Memory Retrieval (Enhanced) - **Vector-first**: Semantic similarity using text-embedding-3-small - **Hybrid search**: Combines vector (70%) + text (30%) scoring - **Multi-adapter**: PostgreSQL ts_rank_cd + SQLite FTS5 BM25 - **Performance**: <50ms recall, >95% accuracy - **Configurable hops**: 1-3 connection hops based on recall preset - **Temporal boost**: Relevance boost for time-pattern matches - **Evolution tracking**: Access events logged automatically ## Key Technical Differentiators **Four-Layer Memory Architecture**: Unlike single-layer systems, AgentDock mirrors human cognition with working, episodic, semantic, and procedural memory types, each optimized for different information patterns and retrieval scenarios. **PRIME Extraction Intelligence**: Intelligent 2-tier model selection with rule-based guidance reduces extraction costs by 60% while maintaining quality. Most systems use expensive models for all extractions. **Hybrid Vector-Text Search**: Pure vector search fails on specialized terminology. Our research-validated 70/30 vector/text split prevents catastrophic failures while maintaining semantic understanding across domains. **Memory Connection Graph**: SQL-based graph operations without dedicated graph databases. 5 research-backed connection types (similar, related, causes, part_of, opposite) with intelligent relationship traversal up to 3 hops deep. **Progressive Enhancement Connection Discovery**: Tiered approach (embeddings → rules → LLM) reduces connection discovery costs by 65% while maintaining quality. Smart triage automatically classifies 65% of connections without LLM calls. **Automatic Memory Consolidation**: Episodic-to-semantic conversion with merge, synthesize, and hierarchy strategies. Reduces storage while improving recall quality through intelligent memory lifecycle management. **Lazy Memory Decay System**: On-demand decay calculation with configurable half-lives per memory type. 65-100% write avoidance through batch processing and access reinforcement patterns. **Temporal Intelligence Integration**: Built-in pattern analysis, time-based memory relationships, and temporal influence on decay/recall. Statistical approach with optional LLM enhancement for behavioral insights. **Multi-Adapter Architecture**: Single API works with PostgreSQL, SQLite, ChromaDB, Pinecone, and Qdrant without vendor lock-in. Managed service compatibility without database extensions. **Cost-Optimized Operations**: Built-in budget tracking, smart triage, lazy calculations, and transparent cost reporting. Designed for production deployment with predictable costs under $20/month for 100k operations. **Production-Ready Persistence**: SQL-based storage with optional vector enhancements. Transaction management, encryption support, and no complex graph database management requirements. ## Intelligence Layer: Advanced Memory Processing **Purpose**: Enhance memory system with intelligent analysis and connections ### Memory Connections & Graph - **MemoryConnectionManager**: Language-agnostic connection discovery - **ConnectionGraph**: Graph operations for relationship traversal - **5 core connection types**: similar, related, causes, part_of, opposite - **Smart triage**: 40% auto-similar, 25% auto-related, 35% LLM classification - **Progressive enhancement**: embeddings → user rules → LLM analysis ### Memory Consolidation - **MemoryConsolidator**: Convert episodic → semantic memories - **Strategies**: merge, synthesize, hierarchy - **Language-agnostic**: Uses embeddings, optional LLM enhancement - **Batch processing**: Efficient consolidation operations ### Temporal Pattern Analysis (Production Ready) - **TemporalPatternAnalyzer**: Analyze memory access patterns - **Pattern detection**: hourly, weekly, burst patterns - **Activity clusters**: Identify periods of high memory activity - **Statistical approach**: Optional LLM enhancement - **Pattern storage**: Results stored in memory metadata as `temporalInsights` - **Recall boost**: Daily patterns boost relevance during peak hours - **Decay influence**: Burst patterns slow decay by 30% - **Connection detection**: Temporal relationships between memories ```mermaid graph TD A[Memory Storage] --> B[Temporal Pattern Analysis] B --> C[Pattern Detection] C --> D[Daily Patterns] C --> E[Weekly Patterns] C --> F[Burst Patterns] D --> G[Store in Memory Metadata] E --> G F --> G G --> H[Recall Boost] G --> I[Decay Influence] G --> J[Connection Detection] style A fill:#f9f9f9 style B fill:#e1f5fe style G fill:#fff3e0 style H fill:#e8f5e8 style I fill:#f3e5f5 style J fill:#e8f5e8 ``` ### Memory Evolution Tracking (Basic Implementation) - **Event logging**: Track memory lifecycle (created, accessed) - **Storage**: Via `storage.evolution.trackEvent()` interface - **Batched processing**: Efficient event handling - **Sources**: BaseMemoryType, MemoryManager, RecallService - **Note**: Basic events only - full PRD compliance pending ## Supporting Services ### Lazy Memory Decay - **LazyDecayCalculator**: On-demand decay calculation - **LazyDecayBatchProcessor**: Efficient batch updates - **Access reinforcement**: Frequently used memories stay strong - **Configurable half-lives**: Different decay rates per memory type - **Archival threshold**: Low-resonance memory management ### Encryption Service - **Column-level encryption**: PostgreSQL pgcrypto integration - **Key rotation support**: Secure key management - **Batch operations**: Performance-optimized encryption - **Multiple providers**: ENV, AWS KMS, Vault support ### Cost Tracking - **CostTracker**: Real-time operation cost monitoring - **Budget enforcement**: Configurable spending limits - **Cost breakdown**: Track by extractor type - **Transparent reporting**: Clear cost visibility ### Transaction Management - **MemoryTransaction**: Atomic operations with rollback - **Consistency guarantee**: Multi-step operation safety - **Scope helpers**: Automatic transaction management - **Error recovery**: Graceful failure handling ## Workflow Learning Service (Built, Not Wired) **Status**: Foundation implemented, awaiting integration with commercial product support **Purpose**: Learn and suggest tool execution patterns ```typescript // Located at: /orchestration/workflow-learning/WorkflowLearningService.ts // PRD: Phase 1 ✅ COMPLETED - Service built // PRD: Phase 2-3 🔧 PENDING - Integration with LLMOrchestrationService ``` **Key Features**: - Pattern recognition for tool sequences - Success tracking and confidence scoring - Configurable learning thresholds - Pattern merging and optimization - Storage via procedural memory type ## Summary **PRIME**: Intelligent extraction from conversations **Memory System**: Fast, accurate memory retrieval **Intelligence Layer**: Connections, consolidation, pattern analysis **Supporting Services**: Encryption, transactions, cost tracking, decay **Workflow Learning**: Built foundation, awaiting commercial integration **Together**: Complete memory pipeline from raw text to connected knowledge, enabling **Conversational RAG** through agent runtime memory injection AgentDock provides clean architectural separation with no content duplication across memory types while maintaining production-ready performance. ## Related Documentation - [Memory System README](./README.md) - Getting started with the memory system - [Memory Connections](./memory-connections.md) - Detailed connection system explanation - [Graph Architecture](./graph-architecture.md) - Technical graph implementation - [Conversational RAG Guide](./retrieval-augmented-generation.md) - RAG implementation details - [Complete Configuration Guide](./complete-configuration-guide.md) - Configuration examples ## Complete AgentDock Configuration Guide ## **THE 3-SECOND SETUP** ```bash # 1. Set your API key export OPENAI_API_KEY=sk-xxx # 2. That's it! ``` ```typescript // 3. Start using AgentDock import { createMemorySystem } from 'agentdock-core'; const memory = await createMemorySystem(); // METHOD 1: Manual Direct Storage (bypasses PRIME) await memory.store('user-123', 'User prefers dark mode'); // METHOD 2: Automatic PRIME Extraction (AI-powered) const extractedMemories = await memory.addMessage('user-123', { id: 'msg-123', agentId: 'default', content: 'I love dark mode and high contrast themes', role: 'user', timestamp: Date.now() }); // Recall memories (works with both methods) const results = await memory.recall('user-123', 'user preferences'); ``` --- ## **Quick Start Options** ### Option 1: Zero Configuration (Recommended) ```typescript // Uses smart defaults - perfect for 95% of use cases const memory = await createMemorySystem(); ``` ### Option 2: Choose Your Environment ```typescript // Local development (SQLite) const memory = await createMemorySystem({ environment: 'local' }); // Production (PostgreSQL) const memory = await createMemorySystem({ environment: 'production', databaseUrl: process.env.DATABASE_URL }); ``` ### Option 3: Choose Your Use Case ```typescript // Medical/Legal (High Precision) const memory = await createMemorySystem({ environment: 'production', recallPreset: 'precision', databaseUrl: process.env.DATABASE_URL }); // Customer Support (High Performance) const memory = await createMemorySystem({ environment: 'production', recallPreset: 'performance', databaseUrl: process.env.DATABASE_URL }); // Research/Analysis (Deep Understanding) const memory = await createMemorySystem({ environment: 'production', recallPreset: 'research', databaseUrl: process.env.DATABASE_URL }); ``` --- ## **Memory Creation Methods** The memory system provides two distinct methods for creating memories: ### **Method 1: Manual Direct Storage** Use when you know exactly what memory to create. Bypasses AI extraction. ```typescript // Direct storage with full control await memoryManager.store( 'user-123', // userId 'agent-456', // agentId 'User is allergic to peanuts', // content MemoryType.SEMANTIC, // type: semantic, episodic, working, procedural { timestamp: Date.now(), // Optional: custom timestamp neverDecay: true, // Optional: prevent decay customHalfLife: 365 // Optional: days before 50% decay } ); ``` **Best for:** - Critical information (medical conditions, legal requirements) - Pre-processed or validated data - Migration from other systems - Testing and debugging ### **Method 2: Automatic PRIME Extraction** AI analyzes messages to extract multiple relevant memories automatically. ```typescript // Let AI determine what's important const memories = await memory.addMessage('user-123', { id: 'msg-789', agentId: 'agent-456', content: 'I work night shifts so I prefer afternoon meetings. Also, I\'m lactose intolerant.', role: 'user', timestamp: Date.now() }); // Returns: Array of extracted memories with AI-determined types and importance ``` **Best for:** - Natural conversations - Complex messages with multiple facts - When you want AI to determine importance - Real-time chat applications ### **Comparison** | Feature | Manual Storage | PRIME Extraction | |---------|---------------|------------------| | AI Processing | None | Full analysis | | Control | Complete | AI-guided | | Speed | Fastest | Slower (AI processing) | | Cost | Storage only | Storage + AI tokens | | Memory Count | 1 per call | 0-N per message | | Use Case | Known facts | Conversations | --- ## **Environment Variables That Actually Work** ### **Minimal Setup (Just Works™)** ```bash # Only one required: OPENAI_API_KEY=sk-xxx ``` ### **Force Quality Models** ```bash # Always use premium models (costs more, better quality) OPENAI_API_KEY=sk-xxx PRIME_DEFAULT_TIER=advanced # ✅ VERIFIED WORKING CONNECTION_ALWAYS_ADVANCED=true # ✅ VERIFIED WORKING ``` ### **Force Single Model Everywhere** ```bash # Use same model for everything (simple & predictable) OPENAI_API_KEY=sk-xxx PRIME_MODEL=gpt-4.1 # ✅ VERIFIED WORKING CONNECTION_MODEL=gpt-4.1 # ✅ VERIFIED WORKING ``` ### **Cost Optimization** ```bash # Use cheapest models (save money) OPENAI_API_KEY=sk-xxx PRIME_MODEL=gpt-4.1-mini # ✅ VERIFIED WORKING CONNECTION_MODEL=gpt-4.1-mini # ✅ VERIFIED WORKING ``` ### **Smart Balance (Default)** ```bash # Auto-optimize cost vs quality (recommended) OPENAI_API_KEY=sk-xxx # No other variables needed - system chooses best model per task ``` --- ## **Available Presets** | Environment | Description | Database | Use Case | |-------------|-------------|----------|----------| | `local` | **Default** | SQLite | Development, testing | | `production` | Optimized | PostgreSQL | Live applications | | Recall Preset | Description | Best For | |---------------|-------------|----------| | `default` | **Recommended** | General purpose | | `precision` | High accuracy | Medical, legal, finance | | `performance` | Fast response | Customer support | | `research` | Deep analysis | Academic, content discovery | --- ## **Real-World Examples** ### Example 1: Startup (Simple & Cheap) ```typescript // Perfect for MVP, prototypes, small teams const memory = await createMemorySystem(); ``` **Environment Variables:** ```bash OPENAI_API_KEY=sk-xxx PRIME_MODEL=gpt-4.1-mini # Saves ~80% on costs CONNECTION_MODEL=gpt-4.1-mini ``` ### Example 2: Medical App (Safety First) ```typescript // High precision for safety-critical applications const memory = await createMemorySystem({ environment: 'production', recallPreset: 'precision', databaseUrl: process.env.DATABASE_URL }); ``` **Environment Variables:** ```bash OPENAI_API_KEY=sk-xxx PRIME_DEFAULT_TIER=advanced # Always use best models CONNECTION_ALWAYS_ADVANCED=true # Safety first PRIME_PROVIDER=openai # Industry standard provider ``` ### Example 3: Customer Support (High Volume) ```typescript // Optimized for speed and throughput const memory = await createMemorySystem({ environment: 'production', recallPreset: 'performance', databaseUrl: process.env.DATABASE_URL }); ``` **Environment Variables:** ```bash OPENAI_API_KEY=sk-xxx PRIME_ADVANCED_MIN_CHARS=1000 # Rarely use expensive models CONNECTION_AUTO_SIMILAR=0.7 # More auto-classification (cheaper) ``` ### Example 4: Research Platform (Deep AI) ```typescript // Maximum intelligence and connection discovery const memory = await createMemorySystem({ environment: 'production', recallPreset: 'research', databaseUrl: process.env.DATABASE_URL }); ``` **Environment Variables:** ```bash OPENAI_API_KEY=sk-xxx PRIME_ADVANCED_MIN_CHARS=200 # Use advanced models more often CONNECTION_PREFER_QUALITY=true # Bias toward quality ``` ### Example 5: Enterprise (Balanced Production) ```typescript // Production-ready with smart cost optimization const memory = await createMemorySystem({ environment: 'production', databaseUrl: process.env.DATABASE_URL }); ``` **Environment Variables:** ```bash OPENAI_API_KEY=sk-xxx NODE_ENV=production # Uses smart defaults - auto-optimizes cost vs quality ``` --- ## **Advanced Customization** Only use this if the presets don't meet your needs: ```typescript const memory = await createMemorySystem({ environment: 'production', databaseUrl: process.env.DATABASE_URL, overrides: { // Custom PRIME configuration prime: { primeConfig: { provider: 'openai', standardModel: 'gpt-4.1-mini', advancedModel: 'gpt-4.1', autoTierSelection: true, tierThresholds: { advancedMinChars: 300, // Custom threshold advancedMinRules: 3 // Custom threshold } } }, // Custom memory configuration memory: { working: { maxTokens: 8000, // Larger context ttlSeconds: 7200 // 2-hour TTL } }, // Custom recall configuration recall: { defaultLimit: 20, // More results cacheResults: true, cacheTTL: 600, // 10-minute cache defaultConnectionHops: 2 // Graph traversal depth: 1=direct, 2=friends-of-friends, 3=research-depth }, // Intelligence layer configuration intelligence: { temporal: { enabled: true }, // Enable temporal pattern analysis connectionDetection: { enabled: true, // Enable memory connections method: 'embedding-only' // Cost-optimized connection discovery } }, // Custom storage configuration for pgvector storage: { type: 'postgresql-vector', config: { connectionString: process.env.DATABASE_URL, enableVector: true, defaultDimension: 1536, // OpenAI embeddings defaultMetric: 'cosine', // Best for semantic similarity // Production pgvector tuning ivfflat: { lists: 100, // Number of clusters (sqrt(rows) is good start) probes: 10 // Clusters to search (10 = 94% recall) } } } } }); ``` --- ## **Intelligence Layer Configuration** The intelligence layer adds advanced memory features like temporal patterns and connection discovery: ### **Temporal Pattern Analysis** ```typescript intelligence: { temporal: { enabled: true } // Analyzes memory access patterns over time } ``` - **What it does**: Detects daily, weekly, and burst patterns in memory creation - **Benefits**: Provides relevance boost during peak activity hours - **Storage**: Patterns stored as `temporalInsights` in memory metadata - **Performance**: Statistical analysis with optional LLM enhancement ### **Connection Discovery** ```typescript intelligence: { connectionDetection: { enabled: true, method: 'embedding-only' // Cost-optimized approach } } ``` - **What it does**: Automatically discovers relationships between memories - **Methods**: `embedding-only` (fast, cheap) or `enhanced` (includes LLM analysis) - **Connection types**: similar, related, causes, part_of, opposite - **Performance**: 65% cost reduction through smart triage ### **Connection Hops Configuration** ```typescript recall: { defaultConnectionHops: 2 // How deep to traverse memory connections } ``` - **1 hop**: Direct connections only (fastest) - **2 hops**: Friends-of-friends (balanced) - **3 hops**: Research depth (most comprehensive) - **Presets**: Default/Performance/Precision use 1, Research uses 3 ### **Evolution Tracking** Evolution tracking is automatically enabled when storage supports it: ```typescript // Events tracked: created, accessed, updated, connected // Storage: via storage.evolution.trackEvent() interface // Performance: Batched processing for efficiency ``` --- ## **Environment Variables Reference** ### **Core System Variables** ```bash # Embedding Configuration EMBEDDING_PROVIDER=openai # Provider: openai EMBEDDING_MODEL=text-embedding-3-small # Model for embeddings # Recall Cache Configuration (Performance Optimization) RECALL_CACHE_HIGH_WATER=1000 # Cache cleanup trigger (when cache hits this size) RECALL_CACHE_LOW_WATER=900 # Target cache size after cleanup # Example: When cache reaches 1000 items, it cleans down to 900 items ``` ### **PRIME System (Memory Extraction)** ```bash # Provider & API Keys PRIME_PROVIDER=openai # LLM provider PRIME_API_KEY=sk-xxx # Dedicated API key OPENAI_API_KEY=sk-xxx # Fallback API key # 2-Tier Model Control ✅ VERIFIED PRIME_MODEL=gpt-4.1 # Override both tiers PRIME_STANDARD_MODEL=gpt-4.1-mini # Standard tier only PRIME_ADVANCED_MODEL=gpt-4.1 # Advanced tier only PRIME_DEFAULT_TIER=standard # Force tier (standard|advanced) # Smart Thresholds PRIME_ADVANCED_MIN_CHARS=500 # Use advanced for content >N chars PRIME_ADVANCED_MIN_RULES=5 # Use advanced for >N active rules PRIME_MAX_TOKENS=4000 # Maximum tokens per request # Cost Control PRIME_ENABLE_COST_TRACKING=true # Track costs PRIME_COST_THRESHOLD=10.00 # Daily limit ($USD) ``` ### **CONNECTION System (Memory Connections)** ```bash # Provider & API Keys (inherits from PRIME by default) CONNECTION_PROVIDER=openai # Override provider CONNECTION_API_KEY=sk-xxx # Override API key # 2-Tier Model Control ✅ VERIFIED CONNECTION_MODEL=gpt-4.1 # Override both tiers CONNECTION_STANDARD_MODEL=gpt-4.1-mini # Standard tier only CONNECTION_ENHANCED_MODEL=gpt-4.1 # Advanced tier only CONNECTION_ALWAYS_ADVANCED=false # Force advanced (true|false) CONNECTION_PREFER_QUALITY=false # Bias toward quality in production # Smart Triage (Cost Optimization) CONNECTION_AUTO_SIMILAR=0.8 # Auto "similar" threshold (40% FREE) CONNECTION_AUTO_RELATED=0.6 # Auto "related" threshold (25% FREE) CONNECTION_LLM_REQUIRED=0.3 # LLM analysis threshold (35% PAID) ``` ### **Database Configuration** ```bash # PostgreSQL (Production) DATABASE_URL=postgresql://... # Full connection string POSTGRES_HOST=localhost POSTGRES_PORT=5432 POSTGRES_DB=agentdock POSTGRES_USER=postgres POSTGRES_PASSWORD=xxx # SQLite (Development) SQLITE_PATH=./agentdock.db # Database file path ENABLE_SQLITE_VEC=true # Vector support ``` ### **Database Configuration** ```bash # PostgreSQL with pgvector (PRODUCTION-READY) DATABASE_URL=postgresql://... # Full connection string ENABLE_PGVECTOR=true # Enable vector search # pgvector Performance Tuning (PRODUCTION-READY) PGVECTOR_IVFFLAT_LISTS=100 # Index clusters (default: sqrt(n) rows) PGVECTOR_IVFFLAT_PROBES=10 # Search probes (accuracy vs speed) # Production Guidelines: # - Lists: Start with sqrt(expected_rows). 100 = good for ~10k vectors # - Probes: 10 = 94% recall, 20 = 97% recall, 50 = 99% recall # - For 100k+ vectors: lists=316, probes=15-20 # - Rebuild index when doubling vector count # pgvector Index Creation (run manually in production): # CREATE INDEX ON memories USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100); ``` ### **System Configuration** ```bash # Environment NODE_ENV=production # Environment mode LOG_LEVEL=info # Logging level DEBUG_MEMORY=false # Enable memory debug logs DEBUG_STORAGE=false # Enable storage debug logs # Memory System MEMORY_MAX_TOKENS=10000 # Max context tokens MEMORY_TTL=86400 # Memory TTL (seconds) MEMORY_ENCRYPTION_KEY=xxx # Encryption key for PII ``` --- ## **Advanced Recall Features** ### **Connection Graph Configuration** ```typescript // Use memory connections to find related memories const results = await memory.recall('user-123', 'JavaScript', { // Connection Graph Features (Brief Explanation) useConnections: true, // Find connected memories (default: true) connectionHops: 2, // How deep to traverse (1 = direct, 2 = friends of friends) connectionTypes: ['similar', 'causes'], // Filter connection types boostCentralMemories: true // Prioritize highly-connected memories }); ``` ## **Storage Adapter Priority** | Adapter | Status | Use Case | Performance | |---------|--------|----------|-------------| | **pgvector** | **PRODUCTION-READY** | **Primary choice** - PostgreSQL with vectors | 10k+ QPS with proper indexing | | **postgresql** | Production-Ready | PostgreSQL without vectors | High performance | | **sqlite-vec** | Supported | Local development with vectors | Good for <50k vectors | | **sqlite** | Supported | Local development | Fast for small datasets | | **memory** | Testing Only | No persistence | In-memory only | | ChromaDB/Pinecone/Qdrant | Community Extensible | Base classes for extension | Varies | ## **Troubleshooting** ### "No API key found" ```bash # Fix: Set a provider API key export OPENAI_API_KEY=sk-xxx ``` ### "High API costs" ```bash # Fix: Use cheaper models export PRIME_MODEL=gpt-4.1-mini export CONNECTION_MODEL=gpt-4.1-mini ``` ### "Storage connection failed" ```bash # Fix: Check database URL and credentials export DATABASE_URL=postgresql://user:pass@host:5432/dbname ``` ### "Poor memory quality" ```bash # Fix: Use higher quality models export PRIME_DEFAULT_TIER=advanced export CONNECTION_ALWAYS_ADVANCED=true ``` ### "pgvector performance issues" ```bash # Fix: Tune index parameters based on dataset export PGVECTOR_IVFFLAT_LISTS=200 # Increase for larger datasets export PGVECTOR_IVFFLAT_PROBES=20 # Increase for better accuracy ``` ### "Memory decay configuration" ```bash # Fix: Configure memory lifecycle for your use case # See Memory Lifecycle Examples section below ``` --- ## **Memory Lifecycle Configuration Examples** ### **Therapy Agent: Never Forget Critical Information** ```typescript // Critical patient information protected from decay const memory = await createMemorySystem({ environment: 'production', overrides: { lifecycle: { decayConfig: { defaultDecayRate: 0.02, // Slow decay (60 day half-life) deleteThreshold: 0.05, // Keep memories longer rules: [{ id: 'critical-info', condition: 'importance > 0.8', neverDecay: true, // Protect critical memories enabled: true }] } } } }); // Store protected memory await memory.store('user-123', 'Patient has severe allergy to penicillin', { importance: 1.0, neverDecay: true // This memory will never decay }); ``` ### **Business Agent: Fresh Data Priority** ```typescript // Recent market data prioritized, old data expires quickly const memory = await createMemorySystem({ environment: 'production', overrides: { lifecycle: { decayConfig: { defaultDecayRate: 0.1, // Fast decay (14 day half-life) deleteThreshold: 0.2, // Remove old data quickly rules: [{ id: 'recent-data', condition: 'accessCount > 5', decayRate: 0.05, // Slower decay for accessed data enabled: true }] } } } }); ``` ### **Assistant: Balanced Memory** ```typescript // Standard balanced configuration const memory = await createMemorySystem({ environment: 'production', overrides: { lifecycle: { decayConfig: { defaultDecayRate: 0.05, // 30 day half-life deleteThreshold: 0.1, rules: [{ id: 'user-preferences', condition: 'type = "semantic" AND importance > 0.7', customHalfLife: 90, // User preferences last 90 days enabled: true }] } } } }); ``` --- ## **Best Practices** 1. **Start Simple**: Use `createMemorySystem()` with no options first 2. **Environment Variables First**: Set API keys in environment, not code 3. **Pick Your Use Case**: Choose the right `recallPreset` for your domain 4. **Monitor Costs**: Start with defaults, then optimize based on usage 5. **Test Locally**: Use `environment: 'local'` for development --- ## **Related Documentation** - [Architecture Overview](./architecture-overview.md) - [Memory Connections](./memory-connections.md) --- **That's it! You now have everything you need to configure AgentDock. Start with the 3-second setup and expand as needed.** ## Memory Consolidation Guide Memory consolidation in AgentDock is an intelligent optimization system that prevents memory bloat while improving knowledge quality through automatic conversion, deduplication, and synthesis. ## What is Memory Consolidation? Memory consolidation transforms raw memories into refined knowledge through three key processes: 1. **Episodic → Semantic Conversion**: Converts time-specific experiences into general knowledge 2. **Memory Deduplication**: Finds and merges similar memories to reduce redundancy 3. **Hierarchical Abstraction**: Creates higher-level concepts from detailed memories This mirrors how human memory works - we don't remember every detail of every experience, but we extract patterns and knowledge that serve us better over time. ## Why Memory Consolidation Matters Without consolidation, memory systems face critical challenges: - **Memory Bloat**: Storing every interaction leads to exponential growth - **Redundancy**: Similar information stored multiple times - **Poor Recall**: Too many memories make finding relevant ones harder - **No Learning**: Raw events don't become actionable knowledge Consolidation solves these by creating a more efficient, intelligent memory structure. ## Resource Usage ### What Uses Server Resources Only - Database queries - CPU processing for comparisons - Memory allocation - Text concatenation ### What Costs Extra Money - LLM API calls (OpenAI) - Cloud embedding services - External API usage ## How Consolidation Works ### 1. Episodic to Semantic Conversion After a configurable age threshold (default: 7 days), important episodic memories are converted to semantic knowledge: ```mermaid flowchart LR A["Episodic Memory
User said I prefer email over phone on Jan 1"] B["Age Check
7+ days old?"] C["Importance Check
≥ 0.5?"] D["Extract Knowledge
LLM or Simple"] E["Semantic Memory
User prefers email communication"] F["Archive/Delete
Original"] A --> B B -->|Yes| C C -->|Yes| D D --> E E --> F style A fill:#ffebee style E fill:#e8f5e9 ``` **Example Conversion:** ```typescript // Before (Episodic) { type: 'episodic', content: 'During our meeting on Monday, the client mentioned they always check email first thing in the morning but rarely answer phone calls before noon', timestamp: '2024-01-01T10:30:00Z', importance: 0.7 } // After (Semantic) { type: 'semantic', content: 'Client prefers email communication and checks it first thing in the morning. Avoids phone calls before noon.', importance: 0.8, // Boosted by 0.1 metadata: { convertedFrom: 'episodic-123', conversionDate: '2024-01-08T00:00:00Z' } } ``` ### 2. Memory Deduplication The consolidator identifies and merges similar memories using multiple similarity metrics: ```mermaid flowchart TD A[Semantic Memories] B[Similarity Analysis] C{Similarity > 0.85?} D[Merge Memories] E[Create Consolidated] F[Delete Originals
Optional] A --> B B --> C C -->|Yes| D D --> E E --> F style B fill:#fff3e0 style E fill:#e1f5fe ``` **Similarity Metrics:** - **Vector Embedding Similarity**: Semantic meaning comparison - **Keyword Overlap**: Shared important terms - **Metadata Similarity**: Same categories, entities, or topics - **Temporal Proximity**: Memories created around the same time - **Temporal Pattern Matching**: Memories from similar activity patterns (daily routines, burst periods) **Example Merge:** ```typescript // Memory 1 "User prefers Python for data science projects" // Memory 2 "User likes using Python for machine learning" // Memory 3 "User mentioned Python is their go-to for analytics" // Consolidated Result "User primarily uses Python for data science, machine learning, and analytics projects" ``` ### 3. Consolidation Strategies The system supports multiple strategies that can be combined: | Strategy | Description | Use Case | Preserves Detail | |----------|-------------|----------|------------------| | **Merge** | Simple concatenation of similar content | High similarity (>0.9) | Low | | **Synthesize** | LLM creates new summary from multiple | Medium similarity (0.7-0.9) | Medium | | **Abstract** | Extract high-level patterns | Pattern recognition | Low | | **Hierarchy** | Create parent-child relationships | Categorical organization | High | ### Temporal Pattern Integration Consolidation now considers temporal patterns when grouping memories: ```typescript // Memories from the same burst period are prioritized for consolidation const burstMemories = memories.filter(m => m.metadata.temporalInsights?.patterns?.some(p => p.type === 'burst') ); // Daily patterns inform consolidation timing const dailyPatterns = getTemporalPatterns(memories, 'daily'); if (dailyPatterns.length > 0) { // Schedule consolidation during low-activity periods scheduleConsolidation(offPeakHours); } ``` **Benefits:** - **Burst Memory Consolidation**: Memories from intense activity periods are consolidated together - **Pattern-Aware Grouping**: Similar temporal patterns help identify related memories - **Optimal Timing**: Consolidation runs during low-activity periods for better performance ## Configuration ### Basic Configuration ```typescript const memoryConfig = { consolidation: { enabled: true, similarityThreshold: 0.85, // Minimum similarity for merging maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days in milliseconds preserveOriginals: false, // Delete after consolidation strategies: ['merge', 'synthesize'], batchSize: 20 // Process in batches } }; ``` ### Advanced Configuration with LLM ```typescript const advancedConfig = { consolidation: { enabled: true, similarityThreshold: 0.85, maxAge: 7 * 24 * 60 * 60 * 1000, preserveOriginals: true, // Keep originals for safety strategies: ['merge', 'synthesize', 'abstract'], batchSize: 20, enableLLMSummarization: true, // Use AI for better synthesis llmConfig: { provider: 'openai', model: 'gpt-4.1-mini', // Cost-effective model maxTokensPerSummary: 200, temperature: 0.3, // Low for consistency costPerToken: 0.0000002 } } }; ``` ## Safety and Balance ### Preventing Over-Consolidation The system includes multiple safeguards: 1. **Time Delays**: Only consolidate memories older than `maxAge` 2. **Importance Threshold**: Only memories with importance ≥ 0.5 3. **Confidence Scores**: Skip low-confidence consolidations 4. **Batch Limits**: Process small batches to prevent runaway operations 5. **Cost Controls**: Monthly budget limits for LLM usage ### Transaction Safety All consolidation operations are atomic: ```typescript try { // 1. Create consolidated memory const consolidated = await createConsolidated(memories); // 2. Store successfully await storage.setMemory(consolidated); // 3. Only then delete originals (if configured) if (!preserveOriginals) { await storage.deleteMemories(originals); } } catch (error) { // Originals remain untouched on any failure } ``` ## Cost Management ### LLM Usage Optimization The consolidator intelligently manages LLM usage: ```typescript // Skip LLM if embeddings are very similar if (embeddingSimilarity > 0.9) { return simpleTextMerge(memories); // No API calls, but uses CPU } // Cost tracking if (monthlySpend + estimatedCost > monthlyBudget) { return simpleTextMerge(memories); // Fallback to local compute only } // Use LLM only for complex synthesis return llmSynthesize(memories); ``` ### Cost Configuration ```typescript costControl: { monthlyBudget: 50.00, // $50/month limit preferEmbeddingWhenSimilar: true, // Skip LLM for high similarity maxLLMCallsPerBatch: 5, // Limit per batch trackTokenUsage: true // Monitor consumption } ``` ## Best Practices ### 1. Start Conservative Begin with high thresholds and preservation: ```typescript { similarityThreshold: 0.9, // Very similar only preserveOriginals: true, // Keep everything initially strategies: ['merge'], // Simple strategy first enableLLMSummarization: false } ``` ### 2. Monitor and Adjust Track consolidation metrics: - Number of memories consolidated - Storage space saved - Recall accuracy changes - User feedback on missing information ### 3. Schedule Wisely Run consolidation during low-activity periods: - Nightly batch jobs - After user sessions end - During maintenance windows ### 4. Test Configurations Test consolidation settings in development: ```typescript // Aggressive for testing const testConfig = { maxAge: 1 * 24 * 60 * 60 * 1000, // 1 day similarityThreshold: 0.7, // Lower threshold preserveOriginals: false // Delete originals }; ``` ## Performance Considerations ### Processing Time - **Similarity calculation**: ~5ms per memory pair - **LLM synthesis**: 500-2000ms per consolidation - **Batch of 20 memories**: 5-30 seconds total ### Storage Impact Typical consolidation ratios: - **Episodic → Semantic**: 3:1 reduction - **Deduplication**: 2:1 to 5:1 reduction - **Overall**: 60-80% storage reduction ### Memory Quality Consolidation improves retrieval: - **Faster searches**: Fewer memories to scan - **Better relevance**: Consolidated knowledge matches queries better - **Reduced noise**: Eliminates redundant information ## Integration with Memory System The consolidator integrates seamlessly with other memory components: 1. **With Decay System**: Important memories survive, trivial ones fade 2. **With Connections**: Consolidated memories maintain relationships 3. **With Search**: Better recall through refined knowledge 4. **With PRIME**: Extraction rules guide what becomes semantic ## Troubleshooting ### Common Issues 1. **Too Much Consolidation** - Increase `similarityThreshold` - Enable `preserveOriginals` - Reduce `batchSize` 2. **Not Enough Consolidation** - Decrease `maxAge` requirement - Lower `similarityThreshold` - Add more strategies 3. **High LLM Costs** - Reduce `maxLLMCallsPerBatch` - Lower `monthlyBudget` - Use simpler model ## Summary Memory consolidation is a powerful feature that: - Prevents memory bloat through intelligent optimization - Improves knowledge quality through synthesis - Reduces costs through deduplication - Maintains system performance at scale When configured properly, it creates a self-organizing memory system that gets better over time - just like human memory. ## Memory Graph Architecture > **Technical documentation for developers and architects** This document provides the technical rationale and implementation details behind AgentDock's decision to use a hybrid SQL + in-memory graph approach instead of a dedicated graph database. ## Executive Summary AgentDock implements a hybrid approach to memory connections, combining relational database persistence with in-memory graph operations. This architecture provides graph-like functionality while maintaining the operational simplicity of traditional databases. ## Technical Overview Rather than using a dedicated graph database (Neo4j, ArangoDB, etc.), AgentDock stores memory connections in relational tables and performs graph operations through a combination of SQL recursive CTEs and in-memory algorithms. This approach balances performance, reliability, and operational complexity. ## Why We Chose SQL Over Graph Databases: Technical Analysis ### 1. Scale Reality Check **Agent Memory Characteristics:** ``` - Nodes per agent: 100-10,000 memories - Edges per node: 2-10 connections average - Graph diameter: 3-5 hops typical - Cross-agent queries: None (isolated graphs) - Update frequency: ~1-10 Hz per agent ``` **Conclusion**: These are tiny graphs by graph database standards. Facebook's social graph has billions of nodes with thousands of edges each. Our use case is 6-7 orders of magnitude smaller. ### 2. Query Pattern Analysis **Our Actual Query Needs:** - 90% queries: Direct connections (1 hop) - 9% queries: 2-3 hop traversals - 1% queries: Complex patterns - 0% queries: Global graph algorithms **SQL Performance for These Patterns:** - 1 hop: Native JOIN - extremely fast - 2-3 hops: Recursive CTE - still fast - Complex: Load subgraph to memory - acceptable ### 3. Operational Cost-Benefit **Graph Database Hidden Costs:** - Separate infrastructure management - Specialized backup/restore procedures - Limited cloud provider support - Requires graph query expertise - Complex high availability setup - Vendor lock-in concerns **SQL Advantages We Leverage:** - Runs on existing PostgreSQL/SQLite - Standard backup/restore tools - Available on all cloud providers - SQL expertise is ubiquitous - Built-in HA solutions - No vendor lock-in ### 4. Feature Requirements Analysis **What We Actually Need:** - Store connections with metadata (type, strength, reason) - Traverse relationships 1-3 levels deep - Combine with vector similarity search - Maintain ACID consistency - Handle 100-10,000 memories per agent - Support user-isolated graphs **What We Don't Need:** - Complex graph algorithms (PageRank, community detection) - Massive parallel graph processing - Cross-user graph traversal - Real-time graph updates at scale - Billions of nodes/edges - Sub-millisecond traversal of deep graphs ## Architecture Components ### 1. Relational Storage Layer Memory connections are persisted in standard relational tables: ```mermaid erDiagram memories { uuid id PK text content vector embedding float importance timestamp created_at } memory_connections { uuid id PK uuid source_memory_id FK uuid target_memory_id FK enum connection_type float strength text reason } memories ||--o{ memory_connections : has_source memories ||--o{ memory_connections : has_target ``` **Actual SQL Schema:** ```sql CREATE TABLE memory_connections ( id UUID PRIMARY KEY, source_memory_id UUID REFERENCES memories(id), target_memory_id UUID REFERENCES memories(id), connection_type ENUM('similar', 'related', 'causes', 'part_of', 'opposite'), strength FLOAT, -- 0.0 to 1.0 reason TEXT, -- Why this connection exists created_at TIMESTAMP, -- Ensure unique connections UNIQUE(source_memory_id, target_memory_id), -- Indexes for fast lookups INDEX idx_source (source_memory_id, strength DESC), INDEX idx_target (target_memory_id, strength DESC) ); ``` ### 2. SQL-Based Graph Traversal For simple graph operations, we use SQL recursive Common Table Expressions (CTEs): **Direct Connection Query:** ```sql -- Find direct connections (1 hop) SELECT m.* FROM memories m JOIN memory_connections mc ON m.id = mc.target_memory_id WHERE mc.source_memory_id = :memory_id AND mc.strength > 0.5 ORDER BY mc.strength DESC; ``` **Multi-Hop Traversal:** ```sql -- Find all memories connected within 3 hops WITH RECURSIVE connected_memories AS ( -- Base case: direct connections SELECT target_memory_id as memory_id, 1 as depth, strength FROM memory_connections WHERE source_memory_id = :starting_memory_id UNION ALL -- Recursive case: connections of connections SELECT mc.target_memory_id, cm.depth + 1, cm.strength * mc.strength as combined_strength FROM memory_connections mc JOIN connected_memories cm ON mc.source_memory_id = cm.memory_id WHERE cm.depth < 3 ) SELECT DISTINCT * FROM connected_memories ORDER BY combined_strength DESC; ``` **Alternative Multi-Hop Query (from original implementation):** ```sql -- Multi-hop traversal using recursive CTE WITH RECURSIVE connected AS ( SELECT target_memory_id, strength, 1 as depth FROM memory_connections WHERE source_memory_id = :memory_id UNION ALL SELECT mc.target_memory_id, c.strength * mc.strength, c.depth + 1 FROM memory_connections mc JOIN connected c ON mc.source_memory_id = c.target_memory_id WHERE c.depth < 3 ) SELECT * FROM connected WHERE strength > 0.3; ``` ### 3. In-Memory Graph Engine For complex graph algorithms, we load relevant subgraphs into memory: ```mermaid graph LR A[SQL Database] -->|Load Subgraph| B[ConnectionGraph] B --> C[BFS Traversal] B --> D[Shortest Path] B --> E[Cluster Detection] B --> F[Centrality Analysis] style B fill:#f9f,stroke:#333,stroke-width:2px ``` **ConnectionGraph Implementation:** ```typescript class ConnectionGraph { // Basic operations addNode(id: string, metadata: any): void addEdge(from: string, to: string, type: string, strength: number): void // Path finding findPath(from: string, to: string): string[] getConnectionPath(sourceId: string, targetId: string): string[] // Graph analysis detectCommunity(nodeId: string): Set getMemoryClusters(minSize: number): string[][] // Centrality metrics calculateCentrality(nodeId: string): number getCentralMemories(limit: number): Array<{memoryId: string; centrality: number}> // NEW: Pattern analysis integration analyzeGraphPatterns(memoryId: string): MemoryConnection[] } ``` This in-memory graph now actively enhances connection discovery through: - **2-hop traversal**: Finding indirect relationships via `analyzeGraphPatterns()` - **Community detection**: Identifying memory clusters with `detectCommunity()` - **Centrality analysis**: Highlighting important memories using degree centrality - **Path finding**: Discovering connection paths between any two memories This in-memory graph is used when: - Query depth exceeds 3 hops - Complex pattern matching is required - Graph algorithms (centrality, clustering) are needed - Performance optimization for frequent queries ## Performance Characteristics ### Operation Performance Comparison | Operation | SQL Approach | Graph DB | Our Hybrid | |-----------|-------------|----------|------------| | Single connection lookup | <10ms | <5ms | <10ms | | 2-hop traversal | <50ms | <20ms | <50ms | | 5-hop traversal | 200-500ms | <50ms | <100ms* | | Pattern matching | 100-300ms | <50ms | <150ms* | | Aggregations | <50ms | 100-200ms | <50ms | | Bulk inserts | <100ms | 200-500ms | <100ms | *Using in-memory graph for complex operations ### Scalability Profile - **Optimal range**: 100-10,000 memories per agent - **Connection density**: 2-10 connections per memory - **Query depth**: Best performance at 1-3 hops - **Concurrent operations**: Scales with database connection pool ## Advantages of This Approach ### 1. Operational Simplicity - No additional database infrastructure required - Works with managed database services (RDS, Supabase) - Standard SQL backup and recovery procedures - Familiar query language for debugging ### 2. Data Consistency - ACID transactions for all operations - Foreign key constraints ensure referential integrity - No eventual consistency challenges - Atomic connection updates ### 3. Hybrid Query Capabilities - Combine vector similarity with graph traversal - Efficient aggregations and reporting - Flexible query patterns - Full-text search integration ### 4. Cost Efficiency - No specialized graph database licensing - Runs on existing PostgreSQL/SQLite infrastructure - Lower operational overhead - Simpler monitoring and alerting ## Limitations and Mitigations ### 1. Deep Traversal Performance **Limitation**: Performance degrades exponentially beyond 3-4 hops. **Mitigation**: - Load subgraphs into memory for deep analysis - Limit default traversal depth - Use materialized views for common patterns ### 2. Complex Pattern Matching **Limitation**: Complex graph patterns require multiple queries or in-memory processing. **Mitigation**: - Pre-compute common patterns - Use in-memory graph for complex algorithms - Cache frequently accessed subgraphs ### 3. Scale Limitations **Limitation**: Not optimal for millions of densely connected nodes. **Mitigation**: - Partition by user/agent - Archive old connections - Use connection strength thresholds ## Implementation Details ### Connection Discovery Process ```mermaid sequenceDiagram participant M as New Memory participant E as Embedding Service participant DB as Database participant CG as ConnectionGraph M->>E: Generate embedding E-->>M: Vector representation M->>DB: Find similar memories (vector search) DB-->>M: Candidate memories M->>M: Apply semantic rules M->>DB: Store new connections M->>CG: Update in-memory graph (if loaded) ``` ### Query Optimization Strategies 1. **Indexed Foreign Keys** ```sql CREATE INDEX idx_connections_source ON memory_connections(source_memory_id, strength DESC); CREATE INDEX idx_connections_target ON memory_connections(target_memory_id, strength DESC); ``` 2. **Materialized Paths** (for frequently accessed routes) ```sql CREATE MATERIALIZED VIEW memory_paths AS WITH RECURSIVE paths AS (...) SELECT * FROM paths; ``` 3. **Connection Limits** - Maximum connections per memory: 50 - Default traversal depth: 3 - Similarity threshold: 0.7 ## Best Practices ### 1. Connection Management - Limit connections per memory to maintain performance - Use connection strength to filter weak relationships - Periodically prune low-value connections ### 2. Query Patterns - Prefer shallow traversals (1-3 hops) - Use in-memory graph for complex algorithms - Cache frequently accessed subgraphs ### 3. Scaling Strategies - Partition large graphs by user or time period - Use read replicas for graph analysis - Consider graph sampling for very large datasets ## Comparison with Graph Databases | Aspect | SQL + In-Memory | Graph Database | |--------|-----------------|----------------| | **Setup Complexity** | Low - uses existing DB | High - new infrastructure | | **Operational Cost** | Low - standard SQL tools | High - specialized skills | | **Simple Queries** | Fast (<50ms) | Very Fast (<20ms) | | **Complex Queries** | Moderate (100-500ms) | Fast (<100ms) | | **ACID Compliance** | Full | Varies by vendor | | **Hybrid Search** | Native | Requires integration | | **Backup/Recovery** | Standard SQL | Vendor-specific | | **Cloud Support** | All major providers | Limited options | ## Real-World Benefits ### Pragmatic Advantages Our hybrid approach delivers concrete benefits for production deployments: 1. **Simple Operations** - Works with existing PostgreSQL/SQLite databases - No new infrastructure to learn or manage - Standard SQL tools and monitoring 2. **Excellent Performance** - Optimized for typical agent workloads (100-10,000 memories) - Sub-100ms response times for common queries - Efficient batch operations 3. **Flexible Querying** - Combine vector search with graph traversal in single queries - Rich SQL ecosystem for analytics and reporting - Easy integration with existing data pipelines 4. **Low Operational Overhead** - Use familiar backup/restore procedures - Deploy on any managed database service (RDS, Supabase, etc.) - No specialized expertise required ## Conclusion AgentDock's hybrid SQL + in-memory graph architecture provides an effective solution for agent memory systems. While it may not match the raw performance of dedicated graph databases for complex traversals, it offers significant advantages in operational simplicity, data consistency, and integration with existing infrastructure. This pragmatic approach delivers the benefits of connected knowledge while maintaining the simplicity and reliability that production systems require. ### Best Suited For: - Agent systems with moderate graph complexity (100-10,000 memories) - Teams prioritizing operational simplicity - Applications requiring hybrid vector + graph search - Deployments on managed database services - Organizations with existing SQL infrastructure ### Not Recommended For: - Social networks with billions of users - Real-time graph analytics at massive scale - Applications requiring complex graph algorithms - Systems with dense graphs (>100 connections per node) For most agent memory use cases, this architecture provides the right balance of functionality, performance, and maintainability. ## Related Documentation - **[Memory Connections](./memory-connections.md)** - Complete guide to connection discovery and configuration using this SQL + graph architecture - **[Research Foundations](./research-foundations.md)** - Cognitive science principles behind memory connection types - **[Complete Configuration Guide](./complete-configuration-guide.md)** - Environment variables and production settings ## Memory Connections AgentDock's memory connection system automatically discovers relationships between memories, enabling agents to understand context and provide more relevant responses. The system uses cost-optimized smart triage for 65% cost reduction. ## Quick Overview (TLDR) Most AI systems store information in isolation. AgentDock automatically discovers five types of relationships between memories based on established knowledge representation principles: - **Similar:** Related semantic content ("pasta recipe" ↔ "Italian cooking") - **Causal:** Cause-and-effect relationships ("error occurred" → "bug fix applied") - **Related:** General associations ("React learning" ↔ "JavaScript notes") - **Part Of:** Hierarchical relationships ("login system" → "authentication project") - **Opposite:** Conflicting information ("prefers dark mode" ↔ "prefers light mode") > **Theoretical Background:** These connection types are informed by cognitive science and semantic network theory. For theoretical foundations and research citations, see [Research Foundations](./research-foundations.md). **Default behavior:** Connections work automatically with zero configuration. System uses smart triage for cost optimization. ## How Connection Discovery Works ### Smart Triage System The system uses a 2-tier approach with automatic cost optimization: ```mermaid flowchart TD A[New Memory Stored] --> B[Generate Embedding] B --> C[Find Similar Memories] C --> D{Smart Triage} D -->|40% Auto-Similar| E[Create 'similar' connection] D -->|25% Auto-Related| F[Create 'related' connection] D -->|35% LLM Analysis| G[AI Classification] G --> H[Create typed connection] E --> I[Store Connection] F --> I H --> I style D fill:#e1f5fe,stroke:#0277bd,stroke-width:2px style G fill:#fff3e0,stroke:#f57c00,stroke-width:2px ``` **Cost Optimization:** - **65% FREE:** Auto-classified based on similarity thresholds - **35% PAID:** Complex relationships use AI analysis - **Result:** ~65% cost reduction vs. analyzing every connection ### Connection Types in Action | Type | Example User Input | Agent Response | |------|-------------------|----------------| | Similar | "I need to cook dinner" | "You mentioned that pasta recipe last week, and you have Italian herbs." | | Causal | "My code isn't working" | "Last time this error occurred, it was due to a dependency conflict." | | Part Of | "Working on the login system" | "That's part of your authentication project. Here's the related documentation." | | Opposite | "I prefer dark mode" | "Previously you mentioned preferring light mode. Has this changed?" | | Related | "Tell me about React" | "You've been learning JavaScript and mentioned building web applications." | ## Configuration ### Default (Recommended) ```typescript const memory = await createMemorySystem(); // Smart triage enabled automatically ``` ### Environment Variables ```bash # Force high-quality models for all connections CONNECTION_ALWAYS_ADVANCED=true # Use specific model for connections CONNECTION_MODEL=gpt-4.1 # Tune smart triage thresholds CONNECTION_AUTO_SIMILAR=0.8 # 40% auto-similar (FREE) CONNECTION_AUTO_RELATED=0.6 # 25% auto-related (FREE) CONNECTION_LLM_REQUIRED=0.3 # 35% LLM analysis (PAID) ``` ### Disable Connections ```typescript const memory = await createMemorySystem({ overrides: { intelligence: { connectionDetection: { enabled: false } } } }); ``` ### Advanced Configuration ```typescript const memory = await createMemorySystem({ overrides: { intelligence: { connectionDetection: { enabled: true, enhancedModel: 'gpt-4.1', // Use better model for complex analysis maxCandidates: 20, // Limit comparison candidates batchSize: 10, // Batch LLM calls for efficiency temperature: 0.2, // Low temperature for consistency // Smart triage thresholds thresholds: { autoSimilar: 0.8, // Similarity >0.8 = auto "similar" autoRelated: 0.6, // Similarity >0.6 = auto "related" llmRequired: 0.3 // Similarity >0.3 = needs LLM } } } } }); ``` ## Technical Implementation ### Architecture AgentDock uses a **hybrid SQL + in-memory graph approach** that provides graph functionality without requiring a separate graph database: - **Storage:** PostgreSQL/SQLite with connection tables - **Performance:** Optimized for 100-10,000 memories per agent - **Queries:** Standard SQL with smart caching for complex traversals - **Cost:** No specialized database licensing > **Architecture Deep Dive:** For complete technical details on why we chose SQL over dedicated graph databases, performance comparisons, and implementation decisions, see [Graph Architecture](./graph-architecture.md). ### Performance Characteristics | Operation | Latency | Scale | |-----------|---------|-------| | Connection discovery | ~50ms | 50-100 candidates | | Direct connections | <10ms | Unlimited | | 2-hop traversal | <50ms | Best performance | | 3-hop traversal | <100ms | Recommended limit | ### Smart Triage Thresholds The system uses embedding similarity scores to automatically classify connections: ```typescript // Similarity ranges and automatic classification if (similarity > 0.8) { connectionType = 'similar'; // 40% of connections (FREE) } else if (similarity > 0.6) { connectionType = 'related'; // 25% of connections (FREE) } else if (similarity > 0.3) { // Use LLM for complex analysis // 35% of connections (PAID) connectionType = await llm.classify(memory1, memory2); } ``` ### Connection Storage Connections are stored as database records with metadata: ```sql CREATE TABLE memory_connections ( id UUID PRIMARY KEY, source_memory_id UUID NOT NULL, target_memory_id UUID NOT NULL, connection_type TEXT NOT NULL, -- similar|related|causes|part_of|opposite confidence FLOAT NOT NULL, -- 0.0 to 1.0 reasoning TEXT, -- Optional explanation created_at TIMESTAMP DEFAULT NOW(), user_id TEXT NOT NULL -- Security isolation ); ``` ### Graph Operations The system provides graph-like operations through SQL and in-memory processing: ```typescript // Find connected memories const connected = await memory.findConnectedMemories(userId, memoryId, depth: 2); // Get memory clusters const clusters = await memory.getMemoryClusters(minSize: 3); // Get central memories (highly connected) const central = await memory.getCentralMemories(limit: 10); // Find path between memories const path = await memory.getConnectionPath(sourceId, targetId); ``` ## Cost & Performance Optimization ### Smart Triage Benefits - **Cost reduction:** 65% fewer LLM calls - **Speed improvement:** Instant classification for 65% of connections - **Quality maintained:** AI analysis for complex relationships ### Tuning Guidelines - **High accuracy:** Lower thresholds (more LLM usage, higher cost) - **High speed:** Higher thresholds (more auto-classification, lower cost) - **Balanced:** Default thresholds provide good accuracy/cost balance ### Production Recommendations ```bash # Production environment variables CONNECTION_AUTO_SIMILAR=0.8 # Conservative threshold CONNECTION_AUTO_RELATED=0.6 # Balanced threshold CONNECTION_ENHANCED_MODEL=gpt-4.1 # Quality model for complex cases CONNECTION_PREFER_QUALITY=true # Bias toward accuracy in production ``` ## Integration with Recall Memory connections enhance recall by providing related context: ```typescript // Recall with connection context const results = await memory.recall(userId, 'user preferences', { useConnections: true, // Include connected memories connectionHops: 2, // Traverse 2 levels deep connectionTypes: ['similar', 'related'], // Filter connection types boostCentralMemories: true // Prioritize highly-connected memories }); ``` Connected memories appear in recall results with relationship context, enabling agents to provide more contextual and relevant responses. ## Temporal Pattern Integration {#temporal-pattern-integration} The connection system now integrates with temporal pattern analysis for enhanced memory relationships: ### Temporal Connections - **Burst Detection:** Memories created within 30 minutes are automatically connected - **Pattern Storage:** Temporal insights stored in memory metadata as `temporalInsights` - **Recall Boost:** Daily patterns boost relevance during peak hours - **Decay Influence:** Burst patterns slow decay by 30% based on confidence ### Configuration ```typescript // Enable temporal features const intelligenceConfig = { temporal: { enabled: true }, connectionDetection: { enabled: true } }; // Configurable connection hops (1-3 based on preset) const results = await memory.recall(userId, query, { connectionHops: 3 // Research preset maximum }); ``` ## Benefits - **Contextual Understanding:** Agents understand relationships between user information - **Pattern Recognition:** System learns user preferences and workflows over time - **Efficient Discovery:** Finds relevant information across conversation history - **Cost Optimized:** 65% cost reduction through smart triage - **Production Ready:** Scales to thousands of memories per agent - **Zero Configuration:** Works automatically with sensible defaults ## Related Documentation - **[Research Foundations](./research-foundations.md)** - Scientific background for the 5 connection types and cognitive science principles - **[Graph Architecture](./graph-architecture.md)** - Technical deep-dive on SQL vs. graph database implementation decisions - **[Complete Configuration Guide](./complete-configuration-guide.md)** - Environment variables and advanced configuration options ## AgentDock Memory System > A four-layer memory architecture that gives AI agents human-like memory capabilities The AgentDock Memory System transforms how AI agents remember, learn, and connect information across conversations. Unlike traditional stateless AI interactions, our memory system creates persistent, intelligent agents that build knowledge over time through **Conversational Retrieval-Augmented Generation (RAG)** - dynamically retrieving and injecting relevant memories into agent responses. ## Key Technical Innovations AgentDock introduces potentially revolutionary approaches to conversational memory: - **Four-Dimensional Memory Fusion**: Combines vector + text + temporal + procedural relevance scoring (beyond typical vector-only RAG systems) - **PRIME Extraction System**: Cost-optimized intelligent memory extraction with automatic 2-tier model selection - **Hybrid SQL + In-Memory Graph**: Graph-like memory connections without dedicated graph database complexity - **Research-Validated Hybrid Search**: 30% text + 70% vector configuration prevents catastrophic failures on specialized domains - **Progressive Memory Connections**: Multi-tier relationship discovery that scales from embedding similarity to LLM analysis These innovations work together to create conversational agents that truly learn and evolve while remaining operationally simple for production deployment. ### Intelligence Features - **Memory Consolidation**: Automatic optimization through episodic→semantic conversion and deduplication - reduces storage and improves recall quality (see [Consolidation Guide](./consolidation-guide.md)) - **Graph Analysis**: Multi-hop traversal and clustering via ConnectionGraph for discovering indirect relationships - now actively integrated (see [Graph Architecture](./graph-architecture.md)) - **Temporal Patterns**: Activity detection and behavioral insights through statistical analysis with optional LLM enhancement (see [Memory Connections](./memory-connections.md#temporal-pattern-integration)) Note: All intelligence features use computational resources (database queries, CPU cycles, memory). Optional LLM enhancements incur additional API costs. ## What is Memory in AgentDock? Memory in AgentDock is a **multi-layered cognitive architecture** that mirrors human memory patterns: - **Working Memory**: Immediate conversation context (like your mental notepad) - **Episodic Memory**: Time-ordered experiences and events (like your personal diary) - **Semantic Memory**: Facts, knowledge, and learned concepts (like your personal encyclopedia) - **Procedural Memory**: Learned patterns and successful action sequences (like your muscle memory) Each layer serves a distinct purpose and works together to create agents that truly learn and evolve. ## Current Implementation Status | Component | Status | Notes | |-----------|--------|-------| | Four-Layer Memory Architecture | Implemented | Working, Episodic, Semantic, Procedural | | PRIME Extraction System | Implemented | Intelligent tier selection with cost controls | | Hybrid Search (30-70 split) | Implemented | PostgreSQL and SQLite adapters | | Memory Connections | Implemented | Progressive enhancement approach | | Preset Configurations | Implemented | Default, Precision, Performance, Research | | Lazy Memory Decay System | Implemented | On-demand decay calculation, 65-100% write avoidance | | Temporal Pattern Integration | Implemented | Pattern storage, recall boost, decay influence | | Configurable Connection Hops | Implemented | 1-3 hops based on recall preset | | Basic Evolution Tracking | Implemented | Memory lifecycle events (created, accessed) | ## Work in Progress - Full System Integration The memory system is production-ready and the following integrations are being developed to wire everything together: | Integration | Target | Description | |-------------|--------|-------------| | Message Persistence Layer | Q3 2025 | Server-side conversation history storage for seamless memory extraction | | HTTP/REST Adapter | Q3 2025 | Universal API access for agentdock-core operations | | Session Management Bridge | Q3 2025 | Automatic conversation-to-memory pipeline | | Workflow Learning Service | Q3 2025 | Public API for procedural memory patterns | These enhancements will enable the memory system to automatically process conversations from any HTTP source. The agentdock-core transformation and open source client evolution are actively under development. ## How AgentDock Memory Works When a user sends a message to your agent, the **PRIME (Priority Rules Intelligent Memory Extraction)** system intelligently processes it: ```mermaid graph TB subgraph "User Input" A["User message: 'I tried making that risotto recipe again but I think I added too much wine this time'"] end subgraph "PRIME Extraction System" B["Message Analysis
Character count: 87"] C["Fast Tier Selected
< 100 characters
gpt-4.1-mini"] D["Extract Memories
with Zod validation"] end subgraph "Four Memory Types Created" E["Working Memory
'Current cooking conversation'"] F["Episodic Memory
'Made risotto again, too much wine'"] G["Semantic Memory
'User cooks risotto, learning wine balance'"] H["Procedural Memory
'When wine too strong → reduce amount next time'"] end subgraph "Memory Connections" I["MemoryConnectionManager
Progressive Enhancement:
• Embedding similarity
• User-defined rules
• LLM analysis
• Temporal patterns"] end A --> B B --> C C --> D C --> E C --> F C --> G C --> H E --> I F --> I G --> I H --> I ``` **The Four-Layer Architecture** ensures each type of information is stored optimally: - **Working Memory** maintains conversation context - **Episodic Memory** preserves the specific experience - **Semantic Memory** extracts general knowledge - **Procedural Memory** learns patterns for future recommendations See [Architecture Overview](./architecture-overview.md) for complete technical details. ## Storage Architecture AgentDock follows a **configurable storage strategy** optimized for different environments: ### **Why SQL + In-Memory Instead of Graph Databases?** AgentDock deliberately uses a **hybrid SQL + in-memory graph approach** rather than dedicated graph databases (Neo4j, ArangoDB). This architectural decision provides graph-like functionality while maintaining operational simplicity: - **No additional infrastructure** - Works with your existing PostgreSQL or SQLite database - **Optimized for agent scale** - Perfect for 100-10,000 memories per agent (not billions like social networks) - **Fast common queries** - Most agent queries are 1-3 hops, where SQL performs excellently - **Operational simplicity** - Standard backup, monitoring, and deployment procedures For the complete technical analysis of this decision, see [Graph Architecture Deep-Dive](./graph-architecture.md). ```mermaid graph TB subgraph "Development" A["SQLite + sqlite-vec
Zero-configuration setup
Local vector search
Perfect for prototyping"] end subgraph "Production" B["PostgreSQL + pgvector
Production-grade performance
ACID compliance
Optimized for memory operations"] end subgraph "Memory Layer" C["MemoryManager"] D["Memory Types"] E["Connection Discovery"] end subgraph "Configuration" F["User Configs"] end A --> C B --> C C --> D C --> E F --> C ``` ## Core Features ### **Research-Based Design** Based on established cognitive science principles, AgentDock implements proven memory concepts: - **Spreading Activation**: Related memories activate automatically - **Episodic-Semantic Interdependence**: Experiences become general knowledge over time - **Connection Types**: Grounded in semantic network theory (similar, causal, temporal, hierarchical) See [Research Foundations](./research-foundations.md) for scientific background. ### **PRIME Extraction System** Intelligent, cost-optimized memory extraction: - **Character-based tier selection**: Automatically routes to optimal model (standard/advanced) - **Budget controls**: Monthly spending limits and usage tracking - **Validated output**: Type-safe memory creation with Zod schema validation - **Graceful degradation**: Falls back to pattern-based extraction when needed ### **Progressive Memory Connections** Multi-tier relationship discovery that balances cost and capability: 1. **Embedding similarity**: Vector-based semantic relationships 2. **User-defined rules**: Custom pattern matching for domain logic 3. **LLM enhancement** (optional): AI-powered deep relationship analysis 4. **Temporal patterns**: Time-based connection heuristics Uses hybrid SQL + in-memory graph approach for simplicity without sacrificing functionality. See [Memory Connections Guide](./memory-connections.md) for details and [Graph Architecture](./graph-architecture.md) for technical implementation. ### **Conversational RAG** Infrastructure-level retrieval-augmented generation: - **Hybrid search**: Research-validated 30% text + 70% vector prevents failure modes - **Four-dimensional fusion**: Vector + text + temporal + procedural relevance scoring - **Automatic injection**: Agent runtime integration without manual prompt construction See [Conversational RAG Guide](./retrieval-augmented-generation.md) for complete implementation details. ### **Memory Recall Presets** Ready-made configurations for different agent types: - **Default**: Balanced for general-purpose applications - **Precision**: Exact terminology for medical/legal/financial agents - **Performance**: Optimized for high-volume customer support - **Research**: Enhanced connection discovery for analysis and content discovery ### **Production-Ready Architecture** - **Configurable memory decay**: Human-like forgetting with rule-based protection - **Specialized memory adapters**: Production-ready implementations for PostgreSQL (pgvector) and SQLite. - **Community-extensible adapters**: Base classes available for ChromaDB, Pinecone, and Qdrant. - **User isolation**: Complete data separation with proper security - **Cost tracking**: Built-in monitoring and budget controls See [Architecture Overview](./architecture-overview.md) for complete technical reference. ## Use Cases AgentDock memory enables agents that learn and evolve across conversations: ### **Customer Support Evolution** **Day 1**: Customer reports account lock issue **Day 15**: "Hi, it's John again, different issue with billing" **Agent Response**: "Hi John! I see you had an account issue before. How can I help with billing?" The agent recalls previous interactions, communication preferences, and successful resolution patterns. ### **Coaching Agent Development** **Session 1**: User reports stress, sleep issues, recent divorce **Session 5**: User shares presentation success and exercise progress **Agent Learning**: Connects stress patterns to life changes, identifies effective coping strategies, reinforces positive behaviors **Procedural Memory Development**: - When user reports anxiety → suggest proven breathing exercises - When presentations mentioned → recall past successes - When progress reported → reinforce positive patterns ### **Research Assistant Growth** **Month 1**: Tracks literature on specific topics **Month 3**: Identifies patterns across research domains **Month 6**: Suggests novel connections and research directions based on accumulated knowledge See detailed implementation examples in [Architecture Overview](./architecture-overview.md). ## Quick Start ### **Simple Setup with Presets** ```typescript import { createMemorySystem } from 'agentdock-core'; // Development setup const memory = await createMemorySystem({ environment: 'local' }); // Production with preset optimization const memory = await createMemorySystem({ environment: 'production', recallPreset: 'precision', // For medical/legal/financial databaseUrl: process.env.DATABASE_URL }); // Two primary methods for adding memories: // METHOD 1: Manual Direct Storage (bypasses PRIME extraction) // Use when you know exactly what memory to create const manualMemoryId = await memoryManager.store( 'user-123', 'agent-456', 'User prefers dark mode interfaces', MemoryType.SEMANTIC // or 'semantic' string ); // METHOD 2: Automatic PRIME Extraction (AI-powered) // Processes messages to intelligently extract multiple memories const extractedMemories = await memory.addMessage('user-123', { id: 'msg-789', agentId: 'agent-456', content: 'I prefer email notifications over SMS and usually check my email in the morning', role: 'user', timestamp: Date.now() }); // Returns array of memories extracted by AI // Advanced: Batch conversation processing with PRIME import { PRIMEOrchestrator } from 'agentdock-core'; const result = await primeOrchestrator.processMessages( 'user-123', 'agent-456', conversationMessages // Array of messages ); // Advanced: Historical memory injection with custom timestamps // Note: Custom timestamps only work with vector-enabled storage const historicalMemoryId = await memoryManager.store( 'user-123', 'agent-456', 'User completed onboarding last year', MemoryType.EPISODIC, { timestamp: Date.now() - (365 * 24 * 60 * 60 * 1000) } ); ``` ### **Storage Options** - **Development**: SQLite + sqlite-vec (zero configuration) - **Production**: PostgreSQL + pgvector (managed service compatible) - **Alternative**: ChromaDB, Pinecone, Qdrant adapters available ### **Memory Recall Presets** - **Default**: Balanced for general use - **Precision**: Exact terminology (medical, legal, financial) - **Performance**: High-volume customer support - **Research**: Enhanced connection discovery See [Architecture Overview](./architecture-overview.md) for detailed configuration examples and deployment guides. ## Memory Architecture Details ### **Four-Layer Memory System** - **Working Memory**: Recent conversation context (immediate access, TTL-based) - **Episodic Memory**: Time-ordered experiences with temporal decay - **Semantic Memory**: Knowledge and facts with confidence scoring - **Procedural Memory**: Learned patterns with reinforcement-based evolution Each layer has specific configuration options for retention, decay rates, confidence thresholds, and learning parameters. See [Architecture Overview](./architecture-overview.md) for complete configuration reference. ## Memory Lifecycle Management **Lazy Memory Decay**: Efficient on-demand decay calculation that scales with usage, not data size - **65-100% write avoidance**: Only update memories that are actually accessed - **Exponential decay formula**: Human-like forgetting with configurable half-lives - **Rule-based protection**: Prevent critical information from decaying (neverDecay flag) - **Access reinforcement**: Frequently recalled memories stay strong - **Automatic cleanup**: Remove memories below relevance threshold - **No scheduled jobs**: Eliminates batch processing failures and resource bottlenecks Example configurations: Never decay medical allergies, slow decay for user preferences (90 days), faster decay for casual conversations (7 days). **Performance Benefits**: - Scales with memory access patterns, not total memory count - Sub-second processing for typical workloads - Eliminates the scalability bottleneck of processing millions of memories daily See [Architecture Overview](./architecture-overview.md) for complete decay configuration examples. ## Memory Connections **Progressive relationship discovery** that potentially revolutionizes how agents understand context: ### **Connection Types** - **Similar**: Semantically related content (stress patterns, topic clustering) - **Causal**: One thing leads to another (actions → outcomes) - **Temporal**: Time-based relationships (events before/after patterns) - **References**: Explicit mentions and callbacks - **Hierarchical**: Part-of relationships (details → concepts) ### **Discovery Process** 1. **Embedding similarity**: Vector-based semantic relationships 2. **User-defined rules**: Custom pattern matching for domain logic 3. **LLM analysis** (optional): AI-powered deep relationship discovery 4. **Temporal patterns**: Time-based connection heuristics ### **Real-World Impact** **Month 1**: Agent handles individual queries **Month 6**: "I remember this pattern... Your parents visit in 2 weeks. How are you and Lisa doing? I know family stress affects how you interact." The agent learns to connect stress patterns, relationship dynamics, and temporal cues for contextual understanding. See [Memory Connections Guide](./memory-connections.md) for detailed examples and [Graph Architecture](./graph-architecture.md) for technical implementation. ## Production Deployment ### **Development Setup** - **SQLite + sqlite-vec**: Zero-configuration local development - **Automatic vector search**: Built-in embedding support - **Simple installation**: Works with existing SQLite tooling ### **Production Setup** - **PostgreSQL + pgvector**: Enterprise-grade vector search - **Managed service compatible**: Works with RDS, Supabase, Neon - **Optimized indexing**: IVFFlat and HNSW support for large datasets - **Connection pooling**: Efficient resource management See [Architecture Overview](./architecture-overview.md) for complete deployment guides, database setup instructions, and production optimization examples. ## Security and Performance ### **Data Protection** - **User isolation**: Complete data separation with database-level user ID constraints - **Session scoping**: Working memory isolated by session ID - **Configurable encryption**: PostgreSQL field-level encryption support - **Memory decay**: Automatic cleanup of old memories based on relevance thresholds ### **Performance Characteristics** - **Retrieval speed**: Sub-100ms for typical queries (100-10,000 memories per user) - **Vector search**: Optimized with configurable similarity thresholds - **Caching**: Built-in result caching with configurable TTL - **Batch processing**: Efficient bulk operations for large conversations ### **Production Considerations** This is an open-source framework. Users are responsible for: - Authentication and authorization implementation - API key and database credential security - Network security and access controls - Regular security audits and monitoring ### **Architecture Philosophy** **Configurable Determinism**: Reliable, predictable behavior with intelligent fallbacks - Consistent memory recall based on configured parameters - AI-powered processing with pattern-based fallbacks - User-controlled behavior through comprehensive configuration - Cost tracking and budget controls throughout the system --- ## Documentation Navigation - **[Complete Configuration Guide](./complete-configuration-guide.md)** - **START HERE** - ALL configuration options including 2-tier models, storage, presets, and environment variables - **[Architecture Overview](./architecture-overview.md)** - Technical architecture and implementation details - **[Conversational RAG](./retrieval-augmented-generation.md)** - RAG implementation and hybrid retrieval strategy - **[Memory Connections](./memory-connections.md)** - **INCLUDES TLDR** - Complete guide to connection discovery with simplified overview - **[Graph Architecture](./graph-architecture.md)** - Technical implementation of connection system - **[Memory Consolidation](./consolidation-guide.md)** - Memory optimization and lifecycle management - **[Research Foundations](./research-foundations.md)** - Scientific background and cognitive science principles --- **The AgentDock Memory System transforms AI agents from stateless tools into intelligent, learning companions with human-like memory capabilities.** ## Research Foundations of Memory Connections > **Scientific basis for AgentDock's memory connection system** AgentDock's memory architecture is informed by established cognitive science principles on how human memory works. This document explains the theoretical foundations behind our design decisions. ## Core Research Principles ### 1. Spreading Activation Theory Based on **Collins & Loftus (1975)**, memories are interconnected nodes that activate related memories when accessed. ```mermaid graph TD A[Activated Memory:
'Customer complaint'] --> B[Related Memory:
'Product issue'] A --> C[Similar Memory:
'Support ticket'] B --> D[Causal Memory:
'Bug fix deployed'] C --> E[Part-of Memory:
'Q3 feedback summary'] style A fill:#ff9999,stroke:#333,stroke-width:3px style B fill:#ffcc99,stroke:#333,stroke-width:2px style C fill:#ffcc99,stroke:#333,stroke-width:2px style D fill:#fff0cc,stroke:#333,stroke-width:1px style E fill:#fff0cc,stroke:#333,stroke-width:1px ``` **Key Insight**: When one memory is activated, related memories become more accessible through spreading activation. ### 2. Episodic-Semantic Interdependence **Tulving (1972)** established the distinction between: - **Episodic Memory**: Time-stamped personal experiences - **Semantic Memory**: General knowledge and facts **Greenberg & Verfaellie (2010)** showed these systems are interdependent: ```mermaid flowchart LR subgraph "Episodic Memories" E1["Met client at conference"] E2["Client mentioned AI needs"] E3["Follow-up call scheduled"] end subgraph "Semantic Knowledge" S1["Client works in healthcare"] S2["Healthcare AI compliance rules"] S3["Our AI solutions portfolio"] end E1 -.->|extracts| S1 E2 -.->|enriches| S2 S3 -.->|informs| E3 style E1 fill:#e1f5fe,stroke:#01579b style E2 fill:#e1f5fe,stroke:#01579b style E3 fill:#e1f5fe,stroke:#01579b style S1 fill:#f3e5f5,stroke:#4a148c style S2 fill:#f3e5f5,stroke:#4a148c style S3 fill:#f3e5f5,stroke:#4a148c ``` ### 3. Conceptual Graphs **Sowa (1984)** formalized knowledge representation using typed relationships: ```mermaid graph TB subgraph "Connection Types (Research-Based)" A[Memory Node] -->|similar| B[Semantic Similarity] A -->|causes| C[Causal Relationship] A -->|part_of| D[Hierarchical Structure] A -->|opposite| E[Contradictory Information] A -->|related| F[General Association] end ``` ## How Research Informs Our Design ### Connection Discovery Pipeline Our progressive enhancement approach follows the cognitive principle of **graded activation**: ```mermaid flowchart TD A[New Memory] --> B{Embedding
Similarity} B -->|High Similarity| C[Strong Connection] B -->|Medium| D{Apply
User Rules} B -->|Low| E{LLM
Analysis} D -->|Match| C D -->|No Match| E E -->|Found| C E -->|None| F[No Connection] style B fill:#90caf9,stroke:#1565c0 style D fill:#fff59d,stroke:#f57f17 style E fill:#ffab91,stroke:#d84315 ``` 1. **Fast Path** (Embedding): Like automatic memory associations 2. **Rule Path** (User Rules): Like learned patterns 3. **Deep Path** (LLM): Like conscious reasoning ### 4. Temporal Pattern Detection Our system implements practical temporal pattern analysis to identify usage patterns and memory activity clustering: **Conway (2009)** provided insights into episodic memory structure that inform our approach to temporal pattern detection. ```mermaid gantt title Memory Activity Patterns (Research-Based) dateFormat HH:mm axisFormat %H:%M section Daily Pattern Morning standup :active, 09:00, 30m Code review :10:30, 45m Afternoon debug :14:00, 90m section Burst Detection Incident response :crit, 16:00, 120m Related memories :active, 16:30, 90m section Temporal Clustering Learning session :done, 11:00, 2h Follow-up practice :done, 13:30, 1h ``` **Key Insights:** - **Burst periods** of high activity strengthen memory formation - **Daily patterns** reflect natural cognitive rhythms - Temporal proximity influences connection strength - Pattern detection enables intelligent memory organization ## Scientific Validation Our approach aligns with established cognitive principles: | Principle | Research | Our Implementation | |-----------|----------|-------------------| | **Connection Networks** | Collins & Loftus, 1975 | Multi-hop graph traversal | | **Semantic Networks** | Sowa, 1984 | Typed connection relationships | | **Memory Interdependence** | Greenberg & Verfaellie, 2010 | Episodic→Semantic promotion | | **Temporal Patterns** | Conway, 2009 | Activity pattern detection | ## Key Insights for Developers 1. **Not Random**: Connection types based on established cognitive science principles 2. **Biologically Inspired**: Mimics human memory organization 3. **Computationally Efficient**: Leverages known patterns from cognitive science 4. **Proven Effective**: These principles power human intelligence ## References - Collins, A. M., & Loftus, E. F. (1975). A spreading-activation theory of semantic processing. *Psychological Review*, 82(6), 407-428. - Conway, M. A. (2009). Episodic memories. *Neuropsychologia*, 47(11), 2305-2313. - Greenberg, D. L., & Verfaellie, M. (2010). Interdependence of episodic and semantic memory. *Journal of the International Neuropsychological Society*, 16(5), 748-753. - Sowa, J. F. (1984). *Conceptual Structures: Information Processing in Mind and Machine*. Addison-Wesley. - Tulving, E. (1972). Episodic and semantic memory. In *Organization of memory* (pp. 381-403). Academic Press. ## Related Documentation - **[Memory Connections](./memory-connections.md)** - See these research principles implemented in AgentDock's connection system - **[Graph Architecture](./graph-architecture.md)** - Technical implementation of spreading activation and semantic networks - **[Architecture Overview](./architecture-overview.md)** - How the four-layer memory system reflects cognitive science principles ## AgentDock: Conversational Retrieval-Augmented Generation (RAG) > The AgentDock Recall Service implements **Conversational RAG** (Retrieval-Augmented Generation) specifically optimized for agent memory and real-time knowledge augmentation. AgentDock implements a sophisticated **Conversational Retrieval-Augmented Generation (RAG)** system specifically optimized for agent memory and real-time knowledge augmentation. Unlike traditional document-based RAG systems, AgentDock provides dynamic memory retrieval that evolves with ongoing conversations. ## What is RAG? **Retrieval-Augmented Generation (RAG)** enhances Large Language Models (LLMs) by: 1. **Retrieving** relevant information from a knowledge base 2. **Augmenting** the LLM prompt with retrieved context 3. **Generating** responses informed by both the model's training and retrieved knowledge Traditional RAG focuses on static document retrieval. AgentDock implements **Conversational RAG** with dynamic, personalized memory. ## How to Choose the Right Memory Configuration AgentDock provides ready-made presets so you don't have to guess at the right settings: ### **When to Use Each Preset:** **Default Preset** - Start here for most applications: - General-purpose conversational agents - Mixed content types (questions, facts, casual chat) - When you're not sure what your agent will primarily handle **Precision Preset** - When exactness matters: - Medical agents (drug names, dosages, symptoms) - Legal assistants (case citations, statutes, regulations) - Financial advisors (account numbers, tax codes, regulations) - Technical support (error codes, product models, procedures) **Performance Preset** - When speed matters: - High-volume customer support - Real-time chat applications - Simple FAQ bots - When you need fast responses over deep understanding **Research Preset** - When connections and insights matter: - Academic research assistants - Content discovery and analysis - Creative writing helpers - Strategic planning and brainstorming ### **Simple Usage Examples:** ```typescript // Medical assistant - use precision for exact terminology const medicalMemory = await createMemorySystem({ environment: 'production', recallPreset: 'precision', databaseUrl: process.env.DATABASE_URL }); // Customer support - use performance for speed const supportMemory = await createMemorySystem({ recallPreset: 'performance' }); // Research assistant - use research for connections const researchMemory = await createMemorySystem({ recallPreset: 'research', overrides: { recall: { minRelevanceThreshold: 0.1 // Even more permissive for discovery } } }); ``` ## AgentDock's RAG Architecture ```mermaid graph TB subgraph "AgentDock Recall Service (Conversational RAG Pipeline)" A["User Query"] --> B["RecallService.recall()"] B --> C["4-Layer Memory Search"] subgraph "Parallel Memory Retrieval" C --> D["Working Memory"] C --> E["Episodic Memory"] C --> F["Semantic Memory"] C --> G["Procedural Memory"] end subgraph "Hybrid Search (30% Text + 70% Vector)" D --> H["Text + Vector Fusion"] E --> H F --> H G --> H end subgraph "Memory Fusion & Enhancement" H --> I["Apply Hybrid Scoring"] I --> J["Enhance with Connections"] J --> K["Filter by Relevance"] K --> L["Apply Limits"] end L --> M["Ranked Memory Results"] M --> N["Agent Runtime Injection"] N --> O["Memory-Enhanced Response"] end ``` ### **Hybrid Retrieval Strategy (RAG-Enhanced Recall)** The AgentDock Recall Service uses **hybrid search** combining: - **70% Vector Search**: Semantic understanding for conceptual queries - **30% Text Search**: Exact matching for precise terms, codes, names This split aligns with natural query patterns: ~75% of user queries benefit from semantic understanding, while ~25% require exact matching for critical precision (medical dosages, error codes, legal citations). #### Implementation Details **PostgreSQL**: Weighted score fusion with 70%/30% default weights: ```sql SELECT *, (0.7 * vector_similarity + 0.3 * text_score) as combined_score ``` **SQLite**: Reciprocal Rank Fusion (RRF) with k=60 constant: ```typescript const score = vectorWeight * (1 / (60 + vectorRank)) + textWeight * (1 / (60 + textRank)) ``` ## AgentDock vs Traditional RAG | Aspect | Traditional RAG | AgentDock Conversational RAG | |--------|-----------------|-------------------------------| | **Knowledge Source** | Static documents | Dynamic 4-layer memory system | | **Retrieval Strategy** | Document chunks | Memory types + connections | | **Context Awareness** | Query-level | Conversation-level | | **Learning** | No learning | Continuous memory formation | | **Personalization** | Generic responses | Agent-specific knowledge | | **Connection Discovery** | None | Progressive memory linking | | **Search Method** | Vector-only/Text-only | Hybrid retrieval (30-70 split) | ## Four-Layer Memory Fusion The RecallService implements sophisticated memory fusion combining different relevance signals: ```typescript // Configurable weights for hybrid scoring hybridSearchWeights: { vector: 0.4, // Semantic similarity text: 0.3, // Exact text matching temporal: 0.2, // Time-based relevance procedural: 0.1 // Pattern matching } ``` Each memory type contributes specialized knowledge: - **Working Memory**: Recent conversation context - **Episodic Memory**: Time-ordered experiences with temporal relevance - **Semantic Memory**: Facts and knowledge with confidence weighting - **Procedural Memory**: Learned patterns with success rate scoring SQL adapters handle the storage layer independently: - PostgreSQL uses weighted score fusion for optimal performance - SQLite uses RRF (Reciprocal Rank Fusion) for consistent ranking - All adapters support the same memory operations interface ### **Memory Connections (Graph RAG)** AgentDock enhances retrieved memories with stored connections: - **Embedding similarity**: Vector-based semantic relationships - **User-defined rules**: Custom pattern matching - **LLM enhancement**: AI-powered relationship discovery - **Temporal patterns**: Time-based connection heuristics ## Conversational RAG Benefits Unlike document RAG that treats each query independently, AgentDock maintains conversational context: **Traditional Document RAG**: ``` Query: "How do I reset my password?" → Retrieves: Generic password reset documentation → Response: Standard password reset instructions ``` **AgentDock Conversational RAG**: ``` Query: "How do I reset my password?" → Retrieves: User's previous login issues + current account status + successful solutions → Response: "I see you had trouble with two-factor auth last time. Let me walk you through the reset process that worked for your account setup..." ``` ## Production Use Cases ### **Customer Support RAG** ```typescript // Agent recalls customer history, preferences, and previous solutions const memories = await recallService.recall({ userId: 'customer_123', agentId: 'support_agent', query: 'billing issue', memoryTypes: [MemoryType.EPISODIC, MemoryType.PROCEDURAL] }); // Result: Previous billing conversations + successful resolution patterns ``` ### **Code Assistant RAG** ```typescript // Agent remembers project context, coding patterns, and debugging history const memories = await recallService.recall({ userId: 'developer_456', agentId: 'code_assistant', query: 'database connection error', memoryTypes: [MemoryType.SEMANTIC, MemoryType.PROCEDURAL] }); // Result: Project-specific database config + proven debugging steps ``` ### **Research Assistant RAG** ```typescript // Agent builds on previous research, tracks sources, and connects findings const memories = await recallService.recall({ userId: 'researcher_789', agentId: 'research_assistant', query: 'climate change adaptation strategies', memoryTypes: [MemoryType.SEMANTIC, MemoryType.EPISODIC], includeRelated: true }); // Result: Previously researched papers + related findings + source connections ``` ## Implementation: RAG Through Agent Runtime Integration AgentDock implements conversational RAG through automatic memory injection at the agent runtime level: ```typescript // Agent automatically enhances system prompts with recalled memories const memoryRecall = await recallService.recall({ userId: options.userId, agentId: this.id, query: messages[messages.length - 1].content, limit: 10 }); // Automatic context augmentation if (memoryRecall.conversationContext) { finalSystemPrompt = `${finalSystemPrompt}\n\nPrevious conversation context:\n${memoryRecall.conversationContext}`; } if (memoryRecall.memories && memoryRecall.memories.length > 0) { const memoryContext = memoryRecall.memories.map(m => `- ${m.content}`).join('\n'); finalSystemPrompt = `${finalSystemPrompt}\n\nRelevant memories:\n${memoryContext}`; } ``` This provides **infrastructure-level RAG** where: - **Retrieval**: RecallService performs hybrid search across 4 memory layers - **Augmentation**: Agent runtime automatically injects memories into system prompt - **Generation**: LLM receives enhanced context without manual prompt construction The agent naturally incorporates memory context without requiring explicit RAG instructions, creating seamless conversational continuity. ### **Advanced RAG Features** - **Multi-Agent RAG**: Coordinated memory sharing across agents - **Federated RAG**: Privacy-preserving distributed memory - **Real-time RAG**: Streaming memory updates during conversations - **Contextual RAG**: Session-aware memory retrieval - **Connection-enhanced RAG**: Graph-like memory relationships ## Mathematical Foundation: Why BEIR Benchmarks Align Well with 30-70 Split The 30% text + 70% vector configuration emerges from BEIR benchmark analysis that aligns well with natural query patterns: **Query Distribution Analysis** (verified across multiple studies): - 25% of queries require exact matching (medical codes, legal citations, error codes) - 75% benefit from semantic understanding (conceptual questions, natural language) **BEIR Benchmark Performance** (calculated from 18 diverse datasets): - Text search advantage on exact-match tasks: +10.7% average - Vector search advantage on semantic tasks: +16.7% average - 30-70 configuration balances both query types effectively **Practical Robustness**: - Prevents catastrophic failures on most specialized domains - BEIR benchmarks show consistent hybrid search advantages - Production systems benefit from balanced approach over pure methods - Some extreme cases (like Touche-2020 arguments) may still show degradation, demonstrating the value of configurable weights ## Conclusion AgentDock represents the next evolution of RAG technology: **Conversational Retrieval-Augmented Generation**. By focusing on dynamic, personalized memory rather than static document retrieval, AgentDock enables agents that truly learn and grow with each interaction. Unlike traditional RAG systems optimized for knowledge lookup, AgentDock's memory-augmented generation creates agents with persistent, evolving understanding that improves through continued interaction. **Key Advantages**: - **Conversational continuity** through persistent memory - **Production-ready** hybrid retrieval with managed service compatibility - **BEIR benchmark validation** with consistent hybrid search advantages - **Enterprise scalability** with configurable performance tiers - **Zero infrastructure overhead** - works with existing PostgreSQL/SQLite - **Enhanced relevance** with temporal patterns and configurable connection traversal AgentDock transforms RAG from a document lookup system into an intelligent memory companion for conversational AI. Enhanced with temporal patterns and configurable connection traversal - see [Memory Connections](./memory-connections.md) for advanced recall features. ## See Also - [Memory Architecture Overview](./architecture-overview.md) - Complete technical reference - [Memory Connections Guide](./memory-connections.md) - User-friendly relationship explanation - [Graph Architecture Deep-Dive](./graph-architecture.md) - SQL vs graph database analysis - [Research Foundations](./research-foundations.md) - Scientific background and validation ## Custom Node Development This guide explains how to create custom nodes for AgentDock Core. ## Overview AgentDock provides two main approaches to extending its capabilities through custom nodes: 1. **Core Extension**: Extending BaseNode from AgentDock Core (covered in this guide) 2. **Tool Implementation**: Creating tools in the open source reference implementation (see [Custom Tool Development](./custom-tool-development.md)) ## Advanced Node Development For extending the AgentDock Core directly: ### Extending BaseNode ```typescript import { BaseNode, NodeMetadata, NodePort } from 'agentdock-core'; import { NodeCategory } from 'agentdock-core/types/node-category'; interface MyNodeConfig { parameter: string; } export class MyCustomNode extends BaseNode { readonly type = 'custom.myNode'; constructor(id: string, config: MyNodeConfig) { super(id, config); } protected getCategory(): NodeCategory { return NodeCategory.CUSTOM; } protected getLabel(): string { return 'My Custom Node'; } protected getDescription(): string { return 'Description of what my node does'; } protected getVersion(): string { return '1.0.0'; } protected getCompatibility() { return { core: true, pro: false, custom: true }; } protected getInputs(): NodePort[] { return [ { id: 'input', type: 'string', label: 'Input', required: true } ]; } protected getOutputs(): NodePort[] { return [ { id: 'output', type: 'string', label: 'Output' } ]; } async execute(input: unknown): Promise { // Implementation goes here return `Processed: ${input}`; } } ``` ### Registering Custom Nodes ```typescript import { getNodeRegistry } from 'agentdock-core'; import { MyCustomNode } from './my-custom-node'; // Register your custom node getNodeRegistry().registerNode(MyCustomNode); // Create an instance const myNode = getNodeRegistry().createNode('custom.myNode', 'instance-id', { parameter: 'value' }); ``` ## Custom Tools For developing tools that can be used by AI agents (which is a more common use case), please refer to the [Custom Tool Development](./custom-tool-development.md) guide, which covers: - Tool implementation patterns - Parameter schemas with Zod - Error handling - API access - Component-based output formatting - Complete examples ## Custom Tool Development This guide provides a comprehensive overview of creating custom tools for AgentDock, with complete examples and best practices. ## Introduction Custom tools extend the capabilities of AI agents in AgentDock, allowing them to perform specialized tasks such as searching the web, analyzing data, or integrating with external APIs. Tools are essentially specialized nodes that follow a consistent pattern, making them easy to create and maintain. ## Tool Structure in the Reference Implementation In the AgentDock reference implementation, tools are organized as follows: ``` src/nodes/[tool-name]/ ├── index.ts # Main tool implementation ├── components.tsx # React components for output └── utils.ts # Helper functions (optional) ``` ## Complete Custom Tool Example: Weather Tool Let's walk through creating a complete weather forecasting tool. ### Step 1: Create Directory Structure ``` src/nodes/weather/ ├── index.ts # Main implementation ├── components.tsx # Output formatting └── utils.ts # API utilities ``` ### Step 2: Implement the Tool ```typescript // index.ts import { z } from 'zod'; import { Tool } from '../types'; import { logger, LogCategory } from '@/lib/logger'; import { createToolResult, formatErrorMessage } from '@/lib/utils/markdown-utils'; import { WeatherForecast } from './components'; import { fetchWeatherData } from './utils'; // Parameter schema for the weather tool const weatherSchema = z.object({ location: z.string().describe('City name or location to get weather for'), days: z.number().optional().default(3).describe('Number of days to forecast (1-7)') }); // Weather tool implementation export const weatherTool: Tool = { name: 'weather', description: 'Get weather forecast for any location', parameters: weatherSchema, async execute({ location, days = 3 }, options) { try { // Validate input if (!location) { return createToolResult( 'weather_error', formatErrorMessage('Error', 'Location is required') ); } // Limit days to a reasonable range const forecastDays = Math.min(Math.max(days, 1), 7); // Fetch weather data const weatherData = await fetchWeatherData(location, forecastDays); // Return formatted results return WeatherForecast({ location: weatherData.location.name, days: weatherData.forecast.forecastday }); } catch (error) { // Log and handle errors logger.error(LogCategory.NODE, '[Weather]', 'Weather tool error:', { error, location }); const errorMessage = error instanceof Error ? error.message : String(error); return createToolResult( 'weather_error', formatErrorMessage('Error', `Unable to get weather for "${location}": ${errorMessage}`) ); } } }; // Export for auto-registration export const tools = { weather: weatherTool }; ``` ### Step 3: Create Output Components ```typescript // components.tsx import { formatBold, formatHeader, formatItalic, joinSections, createToolResult } from '@/lib/utils/markdown-utils'; // Types for weather data export interface WeatherDay { date: string; day: { maxtemp_c: number; mintemp_c: number; condition: { text: string; icon: string; }; daily_chance_of_rain: number; }; } export interface WeatherForecastProps { location: string; days: WeatherDay[]; } // Component to format weather forecast output export function WeatherForecast(props: WeatherForecastProps) { const { location, days } = props; // Format each day's forecast const forecastDays = days.map(day => { const date = new Date(day.date).toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' }); return `${formatBold(date)} Temperature: ${day.day.mintemp_c}°C to ${day.day.maxtemp_c}°C Condition: ${day.day.condition.text} Chance of rain: ${day.day.daily_chance_of_rain}%`; }); // Combine into a single result return createToolResult( 'weather_forecast', joinSections( formatHeader(`Weather forecast for ${location}`), forecastDays.join('\n\n') ) ); } ``` ### Step 4: Implement API Utilities ```typescript // utils.ts import { z } from 'zod'; // Type validation for API response const weatherResponseSchema = z.object({ location: z.object({ name: z.string(), region: z.string(), country: z.string(), }), forecast: z.object({ forecastday: z.array(z.object({ date: z.string(), day: z.object({ maxtemp_c: z.number(), mintemp_c: z.number(), condition: z.object({ text: z.string(), icon: z.string(), }), daily_chance_of_rain: z.number(), }) })) }) }); // Function to fetch weather data from API export async function fetchWeatherData(location: string, days: number) { // Get API key from environment variable const apiKey = process.env.WEATHER_API_KEY; if (!apiKey) { throw new Error('Weather API key not configured'); } // Make API request const response = await fetch( `https://api.weatherapi.com/v1/forecast.json?key=${apiKey}&q=${encodeURIComponent(location)}&days=${days}&aqi=no&alerts=no` ); // Handle API errors if (!response.ok) { let errorText = `API error: ${response.status}`; try { const errorData = await response.json(); if (errorData.error && errorData.error.message) { errorText = errorData.error.message; } } catch (e) { // Ignore JSON parsing errors } throw new Error(errorText); } // Parse and validate response const data = await response.json(); return weatherResponseSchema.parse(data); } ``` ## Using the LLM in Custom Tools Custom tools can access the agent's LLM instance for generating content or analyzing data: ```typescript // Example: Using LLM in a news summarization tool async execute({ query }, options) { try { // Fetch news articles const articles = await fetchNewsArticles(query); // Use LLM to generate a summary if available if (options.llmContext?.llm) { // Format articles for the LLM const articlesText = articles.map(a => `TITLE: ${a.title}\nSUMMARY: ${a.description}` ).join('\n\n'); // Create prompt for the LLM const messages = [ { role: 'system', content: 'You are a news summarization assistant. Create a concise summary of these news articles about the given topic. Focus on the most important information and common themes.' }, { role: 'user', content: `Topic: ${query}\n\nArticles:\n${articlesText}\n\nPlease create a concise summary of these news articles.` } ]; // Generate summary with the LLM const result = await options.llmContext.llm.generateText({ messages, temperature: 0.3, maxTokens: 500 }); // Return formatted result return NewsSummary({ query, articles, summary: result.text }); } // Fallback if LLM is not available return NewsSummary({ query, articles, summary: "AI-generated summary not available. Please review the article excerpts below." }); } catch (error) { // Error handling return createToolResult( 'news_error', formatErrorMessage('Error', `Failed to fetch news: ${error.message}`) ); } } ``` ## Tool Registration Process Tools are automatically registered when imported by the `src/nodes/init.ts` file: ```typescript // src/nodes/init.ts example import { tools as searchTools } from './search'; import { tools as weatherTools } from './weather'; import { tools as stockPriceTools } from './stock-price'; // ... other tool imports // Combine all tools into a single object export const allTools = { ...searchTools, ...weatherTools, ...stockPriceTools, // ... other tools }; // Register tools with the registry export function registerTools() { const registry = getToolRegistry(); Object.entries(allTools).forEach(([name, tool]) => { registry.registerTool(name, tool); }); } ``` ## Advanced Tool Features ### 1. Tool Chaining Tools can use the results of previous tools: ```typescript // Research tool using search results export const researchTool: Tool = { name: 'research', description: 'Research a topic in depth', parameters: researchSchema, async execute({ query, depth = 2 }, options) { // First, search for information const searchResults = await searchWeb(query); // Then, analyze the results with the LLM if (options.llmContext?.llm) { const analysis = await options.llmContext.llm.generateText({ messages: [ { role: 'system', content: 'Analyze these search results and identify key insights.' }, { role: 'user', content: `Analyze these search results about "${query}": ${JSON.stringify(searchResults)}` } ] }); return ResearchResults({ query, results: searchResults, analysis: analysis.text }); } return ResearchResults({ query, results: searchResults }); } }; ``` ### 2. Multi-Step Tools Tools can implement multi-step processes: ```typescript // Multi-step data analysis tool export const dataAnalysisTool: Tool = { name: 'analyze_data', description: 'Analyze data in multiple steps', parameters: dataAnalysisSchema, async execute({ dataset, analysis_type }, options) { try { // Step 1: Load and validate data const data = await loadDataset(dataset); // Step 2: Perform statistical analysis const stats = performStatisticalAnalysis(data, analysis_type); // Step 3: Generate insights with LLM let insights = "Statistical analysis complete"; if (options.llmContext?.llm) { const result = await options.llmContext.llm.generateText({ messages: [ { role: 'system', content: `You are a data analysis expert. Generate insights based on the statistical analysis of a dataset.` }, { role: 'user', content: `Dataset: ${dataset}\nAnalysis Type: ${analysis_type}\nStatistics: ${JSON.stringify(stats)}\n\nWhat insights can we draw from this analysis?` } ] }); insights = result.text; } // Return formatted results return DataAnalysisResults({ dataset, analysis_type, statistics: stats, insights }); } catch (error) { return createToolResult( 'analysis_error', formatErrorMessage('Error', `Analysis failed: ${error.message}`) ); } } }; ``` ## Best Practices ### 1. Input Validation Always validate inputs with Zod schemas: ```typescript const stockPriceSchema = z.object({ symbol: z.string().describe('Stock ticker symbol (e.g., AAPL, MSFT)'), period: z.enum(['1d', '1w', '1m', '3m', '6m', '1y', '5y']) .default('1m') .describe('Time period for historical data') }); ``` ### 2. Error Handling Implement comprehensive error handling: ```typescript try { // Tool logic } catch (error) { logger.error(LogCategory.NODE, '[MyTool]', 'Execution error:', { error }); // Provide user-friendly error messages let errorMessage = 'An unexpected error occurred'; if (error instanceof Error) { errorMessage = error.message; } else if (typeof error === 'string') { errorMessage = error; } return createToolResult( 'error', formatErrorMessage('Error', errorMessage) ); } ``` ### 3. Output Formatting Format outputs consistently: ```typescript return createToolResult( 'my_tool_result', joinSections( formatHeader(`Results for ${query}`), formatBold('Key Findings:'), results.join('\n\n') ) ); ``` ### 4. API Security Secure API access: ```typescript // Never include API keys in the code const apiKey = process.env.MY_API_KEY; if (!apiKey) { throw new Error('API key not configured'); } // Use HTTPS for all external requests const response = await fetch(`https://api.example.com/data?key=${apiKey}&q=${encodeURIComponent(query)}`); // Validate API responses if (!response.ok) { throw new Error(`API error: ${response.status}`); } ``` ### 5. Performance Optimize performance: ```typescript // Cache expensive operations const cachedResults = await redis.get(`cache:${cacheKey}`); if (cachedResults) { return JSON.parse(cachedResults); } // Set reasonable timeouts const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 5000); try { const response = await fetch(url, { signal: controller.signal }); // Process response } finally { clearTimeout(timeoutId); } ``` ## Troubleshooting Common issues and solutions: ### 1. Tool Not Registered If your tool isn't appearing in the agent: ```typescript // Make sure you're exporting the tools object export const tools = { my_tool: myTool }; // Check that your tool is imported in src/nodes/init.ts ``` ### 2. Parameter Errors If parameters aren't working correctly: ```typescript // Use descriptive parameter names const searchSchema = z.object({ query: z.string().describe('Search query to look up'), // NOT: q: z.string().describe('Search query') }); // Set reasonable defaults for optional parameters const limit = z.number().optional().default(10).describe('Maximum results'); ``` ### 3. Output Not Displaying If tool output isn't displaying correctly: ```typescript // Make sure you're using createToolResult return createToolResult('my_tool_result', formattedOutput); // NOT: return formattedOutput; ``` ## More Examples ### Stock Price Tool ```typescript // stock-price/index.ts import { z } from 'zod'; import { Tool } from '../types'; import { StockPriceResults } from './components'; import { fetchStockData } from './utils'; const stockPriceSchema = z.object({ symbol: z.string().describe('Stock ticker symbol (e.g., AAPL, MSFT)'), period: z.enum(['1d', '1w', '1m', '3m', '6m', '1y', '5y']) .default('1m') .describe('Time period for historical data') }); export const stockPriceTool: Tool = { name: 'stock_price', description: 'Get stock price information and historical data', parameters: stockPriceSchema, async execute({ symbol, period = '1m' }) { try { const stockData = await fetchStockData(symbol, period); return StockPriceResults({ symbol, period, data: stockData }); } catch (error) { return createToolResult( 'stock_price_error', formatErrorMessage('Error', `Unable to get stock data for ${symbol}: ${error.message}`) ); } } }; export const tools = { stock_price: stockPriceTool }; ``` ### Image Analysis Tool ```typescript // image-analysis/index.ts import { z } from 'zod'; import { Tool } from '../types'; import { analyzeImage } from './utils'; import { ImageAnalysisResults } from './components'; const imageAnalysisSchema = z.object({ url: z.string().url().describe('URL of the image to analyze'), analysis_type: z.enum(['objects', 'faces', 'text', 'colors']) .default('objects') .describe('Type of analysis to perform on the image') }); export const imageAnalysisTool: Tool = { name: 'analyze_image', description: 'Analyze an image to detect objects, faces, text, or colors', parameters: imageAnalysisSchema, async execute({ url, analysis_type = 'objects' }) { try { const results = await analyzeImage(url, analysis_type); return ImageAnalysisResults({ url, analysis_type, results }); } catch (error) { return createToolResult( 'image_analysis_error', formatErrorMessage('Error', `Image analysis failed: ${error.message}`) ); } } }; export const tools = { analyze_image: imageAnalysisTool }; ``` ## Conclusion Custom tools are a powerful way to extend AgentDock's capabilities. By following the patterns and practices outlined in this guide, you can create sophisticated tools that enhance your AI agents with specialized functionality. For more information, refer to the Node System documentation and the AgentDock Core API reference. ## Node System AgentDock is built around a powerful **node-based architecture** using `BaseNode` as the foundation for all functionality. This design allows for modular, extensible, and highly configurable systems. `BaseNode` supports various node categories, including core functionalities like LLM interaction (`AgentNode`) and callable tools, forming the basis for sophisticated agent behaviors. **Looking Ahead: The Workflow Vision** The underlying structure, with defined `input`/`output` ports and `MessageBus` integration, provides the core capabilities necessary to build complex workflow engines and chained execution patterns directly using the open-source library. While the reference client currently focuses on `AgentNode` orchestrating individual tool executions, the architecture is designed for much more. We are actively developing a richer set of node types to unlock true workflow automation, including: - **Event Nodes**: To trigger workflows from external sources or schedules. - **Transform & AI Inference Nodes**: For powerful data manipulation and specialized AI tasks. - **Connector & Action Nodes**: To seamlessly integrate with external services and databases. - **Logic Nodes**: For sophisticated flow control like branching and looping. These planned additions, detailed further in the [Workflow Nodes Roadmap](./../roadmap/workflow-nodes.md), will empower users to build complex, multi-step automations visually and programmatically, extending far beyond the current agent-tool interaction model. AgentDock Pro aims to enhance this capability by providing advanced tooling, such as visual workflow builders and management interfaces, built upon this expanding core open-source node system. ## Core Node Types While developers can create many types of custom nodes, AgentDock Core provides key foundational types: ### BaseNode The `BaseNode` is the foundation of AgentDock's architecture, provided by **AgentDock Core**. It creates a consistent interface and core functionality for all node types: - **Metadata Management**: Each node provides detailed, immutable `NodeMetadata` including: - `category`: 'core' or 'custom' - `label`: Display name - `description`: Functionality overview - `inputs`/`outputs`: Defined ports (see below) - `version`: Semantic version string - `compatibility`: Flags indicating core/pro/custom environment support - **Port System**: Type-safe `inputs` and `outputs` defined using the `NodePort` interface: - `id`: Unique port identifier - `type`: Data type string - `label`: Display name - `schema`: Optional Zod schema for validation - `required`: Boolean flag - `defaultValue`: Optional default value - **Validation Hooks**: Provides methods like `validateInput`, `validateOutput`, and `validateConnection` for ensuring data integrity and connection validity (subclasses can override). - **Message Passing**: Integrates with a `MessageBus` (set via `setMessageBus`). Nodes can send messages (`sendMessage`) and register handlers (`addMessageHandler`, `removeMessageHandler`), enabling potential asynchronous coordination between nodes. - **Lifecycle Management**: `initialize()` for setup, `execute()` for core logic, and `cleanup()` for resource disposal. - **Serialization**: Includes a `toJSON()` method for converting the node's state (ID, type, config, metadata) to a JSON representation. ```typescript // From AgentDock Core export abstract class BaseNode { readonly id: string; abstract readonly type: string; // e.g., 'core.agent' protected config: TConfig; // Static configuration readonly metadata: NodeMetadata; // Core execution abstract execute(input: unknown): Promise; // Lifecycle async initialize(): Promise; async cleanup(): Promise; // Validation validateInput(input: unknown): boolean; validateOutput(output: unknown): boolean; validateConnection(sourcePort: string, targetPort: string): boolean; // Messaging setMessageBus(messageBus: MessageBus): void; protected async sendMessage(targetId: string, type: string, payload: T): Promise; protected addMessageHandler(type: string, handler: MessageHandler): void; protected removeMessageHandler(type: string): void; // Serialization toJSON(): { id: string; type: string; config: TConfig; metadata: NodeMetadata }; } ``` ### AgentNode The `AgentNode` (`type: 'core.agent'`) is a specialized node in **AgentDock Core** orchestrating conversational AI interactions: - **Configuration (`AgentNodeConfig`)**: Initialized with provider details, API keys (primary and fallback), LLM options, and the crucial `agentConfig` object containing the full agent definition (personality, nodes, orchestration rules). - **LLM Integration**: Manages `CoreLLM` instances (primary and optional fallback), handling provider/model derivation logic via `createLLMInstance` if not explicitly configured. - **Dynamic Tool Selection**: Determines available tools for each turn via `getAvailableTools`, consulting the `ToolRegistry` and the agent's `orchestration` rules via an injected `OrchestrationManager`. - **Runtime Execution (`handleMessage`)**: Requires `AgentNodeHandleMessageOptions` including conversation `messages`, the `OrchestrationManager`, `sessionId`, and optional overrides for system prompts or LLM configuration. - **Stream Delegation**: Sets up the LLM call (using `streamText` from the LLM service) and returns the `AgentDockStreamResult` (containing the stream and promises) immediately. *It delegates the consumption of the stream and handling of tool calls/results to the calling adapter/API route.* - **Error Handling**: Implements fallback mechanisms for LLM provider issues. ```typescript // From AgentDock Core export class AgentNode extends BaseNode { readonly type = 'core.agent'; // Main entry point for conversational turns async handleMessage(options: AgentNodeHandleMessageOptions): Promise; // Direct execution (less common for conversational flow) async execute(input: unknown): Promise; // Retrieve token usage from the last interaction getLastTokenUsage(): LanguageModelUsage | null; } ``` ### Tools as Nodes Tools in AgentDock are implemented as specialized node types, registered in the `NodeRegistry` with `isTool: true`: - **Registration**: Registered like any other node but with additional tool-specific options (see `NodeRegistry` below). - **Schema & Description**: Require a `parameters` (Zod schema) and `description` during registration, used for LLM interaction. - **Consistent Interface**: Follow the same `BaseNode` pattern (`execute`, `initialize`, `cleanup`). The `NodeRegistry` can wrap them to fit the standard AI SDK `Tool` interface. - **Dynamic Availability**: Availability during a conversation is managed by the `AgentNode` using the `ToolRegistry` and `OrchestrationManager`. ## Node Registration System AgentDock uses registry systems to manage node and tool types: ### Node Registry The `NodeRegistry` from **AgentDock Core** provides a central system for discovering and instantiating node types: - **Type Management**: Registers `NodeRegistration` objects (containing `nodeClass`, `version`, `isTool`, `parameters`, `description`) mapped by a unique type string (e.g., `'core.agent'`). - **Core vs. Custom**: Uses separate methods (`register` for 'core', `registerCustomNode` for 'custom') enforcing category constraints. - **Instantiation (`create`)**: Creates node instances, performing version compatibility checks between the registered version and the node class's reported version. - **Tool Definition Generation (`getToolDefinitions`)**: Generates an object mapping tool node types to AI SDK-compatible `Tool` objects, automatically wrapping the node's `execute` method. - **Metadata Access (`getNodeMetadata`)**: Returns comprehensive metadata for all registered core and custom nodes. ### Tool Registry The `ToolRegistry` from **AgentDock Core** manages the *runtime availability* of tools for specific agent interactions: - **Purpose**: Primarily used by `AgentNode` to determine which tools (identified by their node type strings) are available *for a given agent configuration* during a specific turn. - **Filtering (`getToolsForAgent`)**: Takes a list of node names (from agent config) and returns the corresponding tool objects registered globally. - **Global Instance**: Typically accessed via a singleton pattern (`getToolRegistry()`). ## Custom Node Development (This section primarily describes the pattern in the NextJS reference implementation, which uses a simplified tool definition format compared to the core `NodeRegistry` registration.) In the **open source reference client implementation** (NextJS), custom tools are implemented slightly differently, often directly defining objects conforming to the Vercel AI SDK `Tool` interface: ### Implementation Pattern (Reference Client) ```typescript // Example from the NextJS reference implementation (src/nodes/tools) import { z } from 'zod'; import { Tool } from 'ai'; // Vercel AI SDK Tool type // ... potentially import React components ... const myToolSchema = z.object({ /* ... */ }); export const myTool: Tool = { name: 'my_tool_id', // Matches the key in the tools object description: 'What this tool does', parameters: myToolSchema, execute: async (args) => { /* ... server-side logic ... */ }, // Optional: render function for UI display in NextJS client // render: (props) => }; // Exported for auto-registration via src/nodes/init.ts export const tools = { my_tool_id: myTool, }; ``` *(Note: This reference implementation pattern bypasses direct registration with `agentdock-core`'s `NodeRegistry` for simpler tool definition, relying on its own loading mechanism.)* ### Security Best Practices (These apply regardless of the implementation pattern) - Keep API calls server-side within the tool's `execute` function. - Use environment variables for secrets (API keys). - Implement robust error handling. - Consider rate limiting. ## Design Patterns The node system implements several key design patterns: 1. **Factory Pattern**: `NodeRegistry.create` acts as a factory for node instances. 2. **Registry Pattern**: `NodeRegistry` and `ToolRegistry` manage node/tool types. 3. **Observer Pattern (Potential)**: The `MessageBus` integration allows for observer-like patterns between nodes. 4. **Strategy Pattern**: Different node implementations can represent different strategies for achieving a task. ## Node Lifecycle Nodes go through a defined lifecycle managed by the system interacting with them (e.g., an agent runner or workflow engine): 1. **Registration**: Node *type* is registered with `NodeRegistry`. 2. **Instantiation**: Node *instance* is created via `NodeRegistry.create`. 3. **Initialization**: Node's `initialize()` method is called (e.g., before first use). 4. **Execution**: Node's `execute()` (or `handleMessage` for `AgentNode`) is called potentially multiple times. 5. **Cleanup**: Node's `cleanup()` method is called when the instance is no longer needed. ## Node Relationships Nodes can interact or be connected conceptually: - **Message Passing**: Asynchronous communication via the `MessageBus` enables decoupled interactions, suitable for complex event-driven workflows. - **Tool Invocation**: `AgentNode` invokes tool nodes based on LLM requests, orchestrated via `ToolRegistry` and `OrchestrationManager`. - **Workflow Connections**: The `input`/`output` port system and `validateConnection` method provide the foundation for defining explicit data flow chains between diverse node types (Event, Transform, Action, Logic, etc.), enabling the construction of complex, automated processes and future visual workflow builders. ## Future Enhancements The node system is designed to support future enhancements: - **Rich Workflow Node Library**: Expanding the core library with robust implementations of Event, Transform, AI Inference, Connector, Action, and Logic nodes. - **Visual Node Editor**: Leveraging `NodeMetadata` (ports, descriptions) for a UI to connect the full range of workflow nodes. - **Node Versioning**: Core registry already supports versioning checks. - **Node Marketplace**: Sharing custom node implementations. - **Workflow Engine**: Building upon the message bus and port connections. ## Documentation and Examples For detailed guidance: - Review `agentdock-core` source code in `src/nodes/`. - See `src/nodes/custom-tool-contributions.md` in the reference implementation for client-specific tool patterns. - Examine existing tools in the reference implementation's `src/nodes/tools/` directory. ## Bring Your Own Keys (BYOK) Mode ## Overview BYOK (Bring Your Own Keys) mode is a security setting in the AgentDock Open Source Client that controls how API keys are managed. When enabled, AgentDock will **only** use API keys that have been explicitly provided by the user through the settings interface, and will never fall back to environment variables. This feature provides an additional layer of security and transparency, especially in multi-user or shared environments where users should be responsible for their own API key usage. ## Configuration Options BYOK mode can be configured in two ways, listed in order of priority: 1. **URL Parameter**: Add `?byokMode=true` or `?byokMode=false` to any AgentDock URL (temporary override) 2. **Settings Interface**: Toggle the "Bring Your Own Keys Mode" switch in the Settings page (persistent setting) ## Implementation Details BYOK mode is implemented across several key components in the AgentDock architecture: ### Client-Side Components 1. **Environment Override Provider** (`src/components/env-override-provider.tsx`): - Handles the URL parameter `byokMode=true|false` - Stores the setting in localStorage for persistence - Ensures the setting is available to all components 2. **Chat Container** (`src/components/chat/chat-container.tsx`): - Reads BYOK setting from localStorage - Adds the `x-byok-mode` header to API requests - Includes proper error handling for BYOK-related errors ### Server-Side Components 1. **API Route Handler** (`src/app/api/chat/[agentId]/route.ts`): - Reads the `x-byok-mode` header from requests - Implements the API key resolution logic with BYOK mode awareness - Provides detailed error messages when API keys are missing in BYOK mode 2. **Environment Types** (`src/types/env.ts`): - Defines type-safe interfaces for BYOK mode - Centralizes API key resolution logic ## API Key Resolution Logic When a request is made to the API, the following resolution logic is applied: 1. Try to get API key from request headers (`x-api-key`) 2. Try to get API key from global settings in secure storage 3. If BYOK mode is enabled and no key is found, throw an error 4. If BYOK mode is disabled, fall back to environment variables ```typescript // Simplified version of the API key resolution logic async function resolveApiKey(request, provider, isByokOnly) { // Try request headers let apiKey = request.headers.get('x-api-key'); // Try global settings if (!apiKey) { const globalSettings = await storage.get("global_settings"); apiKey = globalSettings?.apiKeys?.[provider]; } // If BYOK mode is enabled and no key, throw error if (isByokOnly && !apiKey) { throw new APIError( 'API key is required. In "Bring Your Own Keys Mode", you must provide your own API key in settings.', ErrorCode.LLM_API_KEY ); } // If BYOK mode is disabled, try environment variables if (!apiKey && !isByokOnly) { apiKey = process.env[`${provider.toUpperCase()}_API_KEY`]; } return apiKey; } ``` ## Error Handling When an API key is required but not found in BYOK mode, the API returns a specific error: ```json { "error": "API key is required. In \"Bring Your Own Keys Mode\", you must provide your own API key in settings.", "code": "LLM_API_KEY", "details": { "provider": "openai" } } ``` The client displays this as a user-friendly error message with a link to the settings page. ## BYOK in AgentDock Pro vs. Open Source The Open Source Client requires you to provide your own API keys for all services. **AgentDock Pro** enhances this model: ### AgentDock Pro Benefits - **Cost-Effective API Access**: - Get LLM and API services at lower prices than going directly to providers - Save 80-90% compared to setting up individual accounts with each provider - Utilize bulk purchasing power for better rates across all services - **Simplified Cost Management**: - Single billing relationship instead of managing multiple provider accounts - Predictable pricing with unified credit system - No minimum spend requirements that many premium services impose - **Enterprise-Grade Access**: - Access to enterprise tiers without meeting enterprise qualification criteria - Higher rate limits without lengthy approval processes - Premium services at a fraction of direct provider costs AgentDock Pro eliminates the overhead of managing relationships with multiple AI and API providers, delivering superior economics for production deployments. ## Best Practices - **Development Environment**: Disable BYOK mode for easier testing with environment variables - **Production Environment**: Consider enabling BYOK mode to ensure users are accountable for their own API key usage - **Sensitive Deployments**: Always enable BYOK mode in environments where API key usage needs to be strictly controlled - **Cost Optimization**: For commercial deployments, consider AgentDock Pro for significant cost savings across multiple services ## Security Considerations 1. **API Key Storage**: User-provided API keys are stored in SecureStorage, which encrypts the data 2. **BYOK Setting Storage**: The BYOK mode setting itself is stored in localStorage for accessibility 3. **Header Security**: The `x-byok-mode` header is validated server-side to prevent tampering ## Debugging BYOK Mode When troubleshooting BYOK mode issues: 1. Check localStorage for the `byokOnly` key 2. Verify request headers include `x-byok-mode` 3. Check console logs in development mode for detailed information about API key resolution 4. Use Network tab in browser dev tools to inspect API responses for error messages ## Diagram Examples in the Open Source Client This page demonstrates how to create and render various types of diagrams using Mermaid in the AgentDock Open Source Client. These diagram examples can be used for visualizing different aspects of your application architecture, workflows, and components when building with AgentDock. ## AgentDock Architecture Flow Chart ```mermaid graph TD A[User Request] --> B{Is session active?} B -->|Yes| C[Create Agent Node] B -->|No| D[Initialize Session] D --> C C --> E[Process Request] E --> F{Success?} F -->|Yes| G[Return Result] F -->|No| H[Handle Error] H --> G G --> I[End] ``` ## Request Sequence Diagram ```mermaid sequenceDiagram participant User participant App participant AgentDock participant LLM User->>App: Make request App->>AgentDock: Initialize session AgentDock->>LLM: Send prompt LLM-->>AgentDock: Return response AgentDock->>App: Process response App->>User: Display result ``` ## AgentDock Core Class Diagram ```mermaid classDiagram class BaseNode { +String id +String name +execute() } class AgentNode { +LLMContext context +processMessage() } class ToolNode { +Object parameters +executeWithContext() } BaseNode <|-- AgentNode BaseNode <|-- ToolNode ``` ## AgentDock State Diagram ```mermaid stateDiagram-v2 [*] --> Idle Idle --> Processing: receive_request Processing --> Responding: generate_response Processing --> Error: throw_error Responding --> Idle: complete_response Error --> Idle: handle_error Idle --> [*]: shutdown ``` ## AgentDock Data Model ER Diagram ```mermaid erDiagram SESSION ||--o{ MESSAGE : contains SESSION { string id string userId timestamp created } MESSAGE { string id string content string role timestamp created } SESSION ||--|| USER : belongs_to USER { string id string name string email } ``` ## AgentDock Development Roadmap ```mermaid gantt title AgentDock Development Roadmap dateFormat YYYY-MM-DD section Core Framework Provider-Agnostic API :done, des1, 2023-01-01, 2023-03-01 Node System :done, des2, 2023-02-15, 2023-05-01 Storage Abstraction :active, des3, 2023-04-01, 2023-08-01 section Features Error Handling :done, des4, 2023-03-01, 2023-04-15 BYOK Mode :active, des5, 2023-05-01, 2023-07-01 Advanced Memory : des6, 2023-06-01, 2023-09-01 Vector Storage : des7, 2023-08-01, 2023-10-01 ``` ## Node Distribution Chart ```mermaid pie title AgentDock Node Usage "Agent Nodes" : 42 "Tool Nodes" : 28 "Custom Nodes" : 30 ``` ## User Journey Diagram ```mermaid journey title User Request Journey section Request Phase Receive Request: 5: User, App Parse Parameters: 3: App Initialize Session: 3: App, AgentDock section Processing Phase Agent Node Execution: 5: AgentDock Tool Node Execution: 4: AgentDock Error Handling: 2: AgentDock section Response Phase Format Response: 3: AgentDock Return Result: 5: App, User ``` ## Adding Diagrams to Your Application These diagrams demonstrate the visualization capabilities available in the AgentDock Open Source Client, helping to visualize concepts when building your own applications. To add a Mermaid diagram to any Markdown content in your application, use the following syntax: ``` ```mermaid graph TD A[Start] --> B[End] ``` For more information on Mermaid syntax, visit the [official Mermaid documentation](https://mermaid.js.org/syntax/flowchart.html). ## Open Source Client Rendering The AgentDock Open Source Client includes built-in support for Mermaid diagrams, automatically rendering them in both light and dark modes. You can use these diagram examples as templates for creating your own visualizations of components and workflows in your AgentDock-based applications. ## Image Generation The AgentDock Open Source Client includes a dedicated image generation feature that demonstrates how to integrate advanced AI capabilities into applications built with AgentDock Core. ## Overview The image generation page provides a full-featured interface for creating and editing images using Gemini's multimodal capabilities. It showcases how the Open Source Client extends beyond basic chat functionality to implement richer AI experiences. ## Key Features - **Text-to-Image Generation**: Create images from text prompts - **Image Editing**: Upload and modify existing images - **Image Gallery**: View and manage previously generated images - **Responsive Design**: Works on mobile and desktop devices - **Integration with Chat**: Images can be sent from chat for editing ## Implementation Details The image generation functionality is implemented as a standalone page in the Open Source Client, showcasing: 1. **Client-Server Architecture**: - Client-side UI components for image upload, prompt input, and result display - Server-side actions for image generation using Gemini 2. **Stateful UI**: - Local state management for image data and generation process - Progress indicators and error handling 3. **API Integration**: - Direct integration with Gemini's multimodal capabilities - Image persistence API leveraging: - **Vercel Blob:** For storing image URLs when deployed to Vercel. - **Browser `localStorage`:** For storing image data (e.g., base64 or URLs) when running locally, providing temporary persistence during development. 4. **UI Components**: - `ImageUpload`: Handles image file selection and preview - `ImagePromptInput`: Provides an interface for entering generation prompts - `ImageResultDisplay`: Shows generation results with download/share options - `ImageGallerySkeleton`: Loading state for the image gallery ## Technical Architecture The image generation feature demonstrates these key patterns: ```mermaid graph LR A["React UI Components (Client)"] -- User Action --> B["Server Action (Server)"]; A -- Displays --> G["Image Data (from State)"]; B -- Calls --> C["Gemini API"]; C -- Returns --> B; B -- Saves Image URL/Data --> E{"Persistence API (Server)"}; E -- If Deployed --> F["(Vercel Blob)"]; E -- If Local --> A; A -- Saves to --> H["(localStorage)"]; A -- Reads from --> H; subgraph Client-Side A G H end subgraph Server-Side B C E F end ``` **Key Flow:** 1. UI components trigger server actions for generation. 2. Server actions call the Gemini API. 3. Server actions use a persistence API route (`/api/images/store/add`) to save the resulting image URL (from Vercel Blob if deployed) or potentially pass data back to the client. 4. Client-side code receives the image URL/data and stores it in `localStorage` for local persistence during development, updating the UI state. ## Usage Example 1. Navigate to the Image Generation page 2. Enter a text prompt describing the desired image 3. Optionally upload an existing image to modify 4. Click "Generate" to create the image 5. View, download, or continue editing the generated image 6. Access previously generated images from the gallery ## Integration with AgentDock Core This feature demonstrates how the Open Source Client extends the capabilities of AgentDock Core by: 1. Leveraging the provider-agnostic API design to integrate with Gemini 2. Implementing specialized UI components for multimodal interactions 3. Managing state and persistence for complex AI workflows 4. Providing a complete reference implementation of an advanced AI feature ## Future Enhancements Potential future enhancements for the image generation feature include: - Support for additional image generation models - Enhanced image editing capabilities - Integration with other parts of the application - Advanced prompt techniques like negative prompting - Collections and organization for generated images ## Open Source Client (Next.js Implementation) This reference implementation, built with Next.js and the App Router, serves as a practical example of how to consume and interact with the AgentDock Core framework to build a full-featured web application for conversational AI agents. **Important Note:** * AgentDock Core is currently in a pre-release stage. We are treating it as a local package (`file:./agentdock-core`) within this repository for now. It will be published as a versioned NPM package once it reaches a stable release. * As Core evolves, the separation of concerns between the framework and this Next.js Client implementation is actively being improved. * If you notice areas where the integration could be cleaner or have suggestions, please don't hesitate to reach out or open an issue on GitHub! See the main [AgentDock Roadmap](./../roadmap.md) for planned features across both Core and the Client. ## Core Purpose - **Demonstrate Core Integration:** Showcases how to connect a frontend application to AgentDock Core's capabilities (agents, tools, session management, orchestration). - **Provide a User Interface:** Offers a functional chat interface, agent selection, and settings management. - **Reference Architecture:** Provides patterns for handling API communication, streaming responses, state management, and configuration in a web context. ## Key Features & Implementation Details - **Framework:** Next.js (App Router) - Utilizes Server Components, Client Components, and API Routes. - Leverages file-based routing (`/app` directory). - **API Routes (`/app/api`):** - `/api/chat/[agentId]/route.ts`: The primary endpoint for handling chat messages. It receives messages, instantiates the corresponding `AgentNode` from AgentDock Core, manages the `sessionId`, handles streaming responses, and potentially returns session/token usage information. - Other routes might exist for configuration, image handling, etc. - **AgentDock Core Integration (`/lib/agent-adapter.ts` or similar):** - Contains logic to load agent templates (`template.json`). - Instantiates `AgentNode` with appropriate configuration (API keys, provider settings). - Calls `AgentNode.handleMessage` to process user input and generate responses. - Manages the flow of data (messages, session IDs) between the API route and the Core library. - **Session ID Handling:** - The API route handler is responsible for extracting the `sessionId` from request headers/body or generating a new one if needed (maintaining the Single Source of Truth principle). - The `sessionId` is passed to `AgentNode` and potentially returned in response headers for the client to persist (e.g., in `localStorage` or session storage) for subsequent requests. - **Session Management:** - The API route handler manages the `sessionId` (extracting or generating). - The `sessionId` is passed to `AgentNode` and returned in response headers. - **Session TTL** is configured via the `SESSION_TTL_SECONDS` environment variable, as detailed in the [Next.js Session Integration docs](../architecture/sessions/nextjs-integration.md#environment-based-ttl-configuration). - **UI Components (`/components`):** - Built using React, Shadcn/ui, Radix UI, and Tailwind CSS. - Includes components for the chat interface (message display, input, streaming), agent selection, settings panels, etc. - **State Management (UI):** - Uses standard React state and context management. - May use libraries like Zustand for more complex global UI state if necessary. - **Client-Side Storage & API Keys (BYOK):** - This open source client uses `localStorage` or `sessionStorage` for user preferences and potentially the session ID. - For Bring Your Own Key (BYOK) mode, user-provided API keys are stored client-side using the `SecureStorage` utility from `agentdock-core`. - **Security Considerations (`SecureStorage`):** `SecureStorage` enhances security by encrypting API keys using AES-GCM and adding an HMAC signature to detect tampering before use. However, to decrypt the data, the necessary encryption keys are also stored within the browser's `localStorage`. This is a standard technique for client-side encryption but carries an inherent risk: if a Cross-Site Scripting (XSS) vulnerability exists in *any* part of the application (or potentially a browser extension), malicious JavaScript could gain access to `localStorage`, read the encryption keys, and potentially decrypt the stored API keys. - **Risk Context:** The practical risk depends on the overall security of the user's browser environment and the application itself against XSS attacks. If the browser and application environment are secure (e.g., up-to-date browser, no malicious extensions, robust application XSS defenses), the likelihood of exploitation is lower. However, the vulnerability exists if an XSS attack *can* be successfully executed. - **Recommendation:** Users employing BYOK mode should be aware of this XSS risk associated with storing sensitive data like API keys in `localStorage`, even when encrypted. Evaluate this risk based on your specific security requirements and environment. For maximum security, configuring API keys server-side via environment variables is the preferred approach. If using client-side storage, ensuring the application is well-protected against XSS vulnerabilities is crucial. - **Image Generation:** Includes a dedicated page for image generation and editing using Gemini, demonstrating advanced feature integration. Image persistence uses Vercel Blob when deployed and `localStorage` locally. See the [Image Generation docs](./image-generation.md) for details. ## File Structure (`/src`) ``` /src ├── app/ # Next.js App Router │ ├── api/ # API routes interfacing with Core │ ├── chat/ # Main chat page components/logic │ ├── docs/ # Documentation site pages │ └── settings/ # User settings pages ├── components/ # Reusable React components │ ├── chat/ # Components specific to the chat UI │ ├── ui/ # Base UI elements (from shadcn/ui) │ └── layout/ # Page layout components ├── lib/ # Shared utilities, config, core integration │ ├── agent-adapter.ts # Logic for interacting with AgentNode │ ├── docs-config.ts # Documentation sidebar config │ └── store/ # UI state management stores (if any) ├── public/ # Static assets (images, fonts) └── templates/ # Agent template definitions (e.g., *.json) ``` ## Using This Implementation Refer to the [Getting Started Guide](../getting-started.md) for instructions on setting up, configuring (including environment variables for API keys and storage), and running the Open Source Client locally. ## PRD: AgentDock Evaluation Framework - Building for Measurable Quality ## 1. Introduction: The Need for Standardized Evaluation As AgentDock evolves, the ability to systematically measure and improve agent quality becomes paramount. While various ad-hoc methods and external tools have been used previously, a standardized, integrated **Evaluation Framework** within AgentDock Core is essential to: * **Ensure Consistency:** Provide a common yardstick for quality across all agents and development cycles. * **Enable Systematic Improvement:** Establish a data-driven feedback loop to identify weaknesses and track progress effectively. * **Facilitate Benchmarking:** Reliably compare the performance of different models, prompts, or agent versions. * **Guarantee Production Readiness:** Implement objective quality gates before deploying agents into production environments. Building this framework is a foundational step towards delivering robust, reliable, and continuously improving AI agents. (Ref: [GitHub Issue #105](https://github.com/AgentDock/AgentDock/issues/105)). ## 2. The Goal: A Foundational, Adaptable Evaluation Core The objective is clear: Implement a **modular and extensible Evaluation Framework** within `agentdock-core`. We are *not* building every possible metric upfront. The focus is squarely on the **foundational architecture**: interfaces, data structures, execution logic, and integration points. This foundation must allow developers to: * Define diverse evaluation criteria specific to their needs. * Implement various evaluation methods (`Evaluators`) using a standard contract. * Execute evaluations systematically. * Aggregate and store results for analysis. * **Critically:** Integrate *external* tools or custom logic *without modifying the core framework*. Adaptability is a fundamental design principle, not an afterthought. The goal is straightforward: Give developers the tools to **systematically measure and improve agent quality** using methods appropriate for their specific constraints. It needs to function both as an in-process library and be suitable for wrapping in a service layer later. ### Intended Use Cases (Beyond Simple Invocation) This framework must support standard development workflows: * **CI/CD Integration:** Run evaluation suites automatically on code/model/prompt changes to catch regressions. * **Benchmarking:** Systematically compare agent versions, LLMs, or prompts against standard datasets/criteria. * **Observability Integration:** Feed structured evaluation results (scores, metadata, failures) into monitoring/tracing systems (e.g., OpenTelemetry). * **Production Monitoring:** Allow periodic evaluation runs on live traffic samples (potentially with different criteria than CI). ## 3. Scope: What We're Building Now (and What We're Not) Focus is essential. We build the core infrastructure first. **In Scope (Phase 1 - Largely Completed):** * 🟢 **Core Architecture:** Defined TypeScript interfaces (`EvaluationInput`, `EvaluationResult`, `EvaluationCriteria`, `AggregatedEvaluationResult`, `Evaluator`, `EvaluationStorageProvider`). These contracts are non-negotiable. * 🟢 **Evaluation Runner:** Implemented the `EvaluationRunner` orchestrator, including score normalization and weighted aggregation. * 🟢 **Initial Evaluators:** Provided essential building blocks: * `RuleBasedEvaluator`: For simple, fast, deterministic checks (e.g., keyword presence, length, includes, JSON parsing). Cheap, essential guardrails. * `LLMJudgeEvaluator`: Uses a configurable `CoreLLM` (via Vercel AI SDK) for nuanced quality assessment. Expensive but necessary for subjective measures. * 🟢 **Criteria Definition:** Mechanism to define/manage `EvaluationCriteria` sets programmatically is in place. * 🟢 **Result Aggregation:** Implemented weighted averaging with score normalization (0-1 range where applicable) in the runner. * 🟢 **Storage Interface & Basic Implementation:** Defined `EvaluationStorageProvider` interface. Provided `JsonFileStorageProvider` which appends JSON to a local file. * 🟢 **Core Integration Points & Example:** `runEvaluation` function is established, and `run_evaluation_example.ts` demonstrates its usage. * 🟡 **Unit Tests:** Foundational tests for core types and some components exist, but comprehensive coverage for all evaluators, runner logic, and storage provider contracts is still pending. **Out of Scope (Initial Version - No Change):** * **UI/Dashboard:** No frontend visualization. Focus is on the backend engine. * **Dedicated Scalable Database Backend:** Default file storage is for utility. Robust storage (PostgreSQL, MLOps DBs) requires separate `EvaluationStorageProvider` implementations later. * **Dedicated HTTP Service Layer:** Design must *allow* wrapping in a service, but building that service is out of scope for Phase 1. * **Specific 3rd-Party Tool Wrappers:** Won't build wrappers for DeepEval/TruLens initially, but the `Evaluator` interface must make this straightforward. * **Advanced NLP/Statistical Metrics:** Complex metrics (BLEU, ROUGE) can be added as custom `Evaluator` implementations later. * **Human Feedback Annotation UI:** Framework should *ingest* structured human feedback, but the UI for collection is external. ## 4. Functional Requirements: What It Must Do * **FR1: Define Evaluation Criteria:** 🟢 Implemented. * Provide a clear mechanism to define individual evaluation criteria, including `name` (string, unique identifier), `description` (string, explanation for humans), `scale` (`EvaluationScale` enum/union type), and an optional `weight` (number, for weighted aggregation). * Support loading or managing sets of these criteria for specific evaluation runs (currently programmatically). * **FR2: Implement Diverse Evaluators:** 🟢 Core interface and initial evaluators implemented. * Define a standard `Evaluator` interface contract: `interface Evaluator { type: string; /* Unique identifier for the evaluator type */ evaluate(input: EvaluationInput, criteria: EvaluationCriteria[]): Promise; }`. * **FR2.1 (Rule-Based):** 🟢 Implemented `RuleBasedEvaluator`. This evaluator is configurable with a set of rules, where each rule is linked to a specific `EvaluationCriteria` (by name) and performs a deterministic check (e.g., regex match, length check, keyword count, JSON parse). It provides fast, low-cost checks suitable for basic validation. * **FR2.2 (LLM-as-Judge):** 🟢 Implemented `LLMJudgeEvaluator`. This evaluator accepts a configured `CoreLLM` instance (compatible with Vercel AI SDK). It uses robust prompt templating and `generateObject` for structured output to assess the `EvaluationInput` against the provided `EvaluationCriteria`. It reliably parses the LLM's response to extract scores and reasoning. * **FR2.3 (NLP-Accuracy - Semantic):** 🟢 Implemented `NLPAccuracyEvaluator`. This evaluator uses embedding models (via Vercel AI SDK or compatible providers) to generate vector embeddings for the agent's response and `groundTruth`. It then calculates cosine similarity, providing a score for semantic alignment. Essential for understanding meaning beyond lexical match. * **FR2.4 (Tool Usage):** 🟢 Implemented `ToolUsageEvaluator`. This rule-based evaluator checks for correct tool invocation, argument validation, and required tool usage based on configured rules. It inspects `messageHistory` or `context` for tool call data. * **FR2.5 (Lexical Suite - Practical & Fast):** 🟢 Implemented a suite of practical, non-LLM lexical evaluators for rapid, cost-effective checks: * `LexicalSimilarityEvaluator`: Measures string similarity (Sorensen-Dice, Jaro-Winkler, Levenshtein) between a source field (e.g., response) and a reference field (e.g., groundTruth). Useful for assessing how close an answer is to an expected textual output. * `KeywordCoverageEvaluator`: Determines the percentage of predefined keywords found in a source text. Critical for ensuring key concepts or entities are addressed. Configurable for case sensitivity, keyword source (config, groundTruth, context), and whitespace normalization. * `SentimentEvaluator`: Analyzes the sentiment of a text (positive, negative, neutral) using an AFINN-based library. Provides options for normalized comparative scores, raw scores, or categorical output. Essential for gauging the tone of a response. * `ToxicityEvaluator`: Scans text for a predefined list of toxic terms. Returns a binary score (toxic/not-toxic). A fundamental check for safety and appropriateness. Configurable for case sensitivity and whole-word matching. * **FR2.6 (Extensibility):** 🟢 The framework makes it straightforward for developers to create and integrate their own custom `Evaluator` classes by simply implementing the `Evaluator` interface. This is the primary hook for custom logic. * **FR3: Execute Evaluations Systematically:** 🟢 Implemented. * The `EvaluationRunner` component orchestrates the evaluation process. * It accepts an `EvaluationInput` object and an `EvaluationRunConfig` (which includes `evaluatorConfigs` and `criteria` defined in the input). * It iterates through the configured evaluators, invoking their `evaluate` method. * It handles errors at the individual evaluator level, logging errors and continuing where possible. * Execution leverages asynchronous operations (`Promise`). * It collects all successfully generated `EvaluationResult` objects. * **FR4: Aggregate Evaluation Results:** 🟢 Implemented. * The `EvaluationRunner` aggregates the collected `EvaluationResult[]` into a single `AggregatedEvaluationResult` object. * It supports weighted average scoring, normalizing scores from different scales (e.g., Likert, boolean, numeric 0-1 or 0-100) to a 0-1 range for consistent aggregation where appropriate. * **FR5: Store Evaluation Results Persistently:** 🟢 Implemented. * Defined a clear, serializable schema for `AggregatedEvaluationResult`, capturing essential information. * Defined `EvaluationStorageProvider` interface: `interface EvaluationStorageProvider { saveResult(result: AggregatedEvaluationResult): Promise; }`. * Provided `JsonFileStorageProvider`, which appends the serialized `AggregatedEvaluationResult` to a file. * **FR6: Integrate with Core AgentDock:** 🟢 Implemented. * The primary invocation API `runEvaluation(input: EvaluationInput, config: EvaluationRunConfig): Promise` is established. * The `EvaluationRunConfig` expects `evaluatorConfigs` (an array of `RuleBasedEvaluatorConfig | LLMJudgeEvaluatorConfig`) which specify the type and specific configuration for each evaluator to be instantiated by the runner. ## 5. Non-Functional Requirements: Ensuring Production Readiness Beyond just features, the framework must be built for real-world use. * **NFR1: Modularity & Extensibility:** This is paramount. The design must heavily rely on interfaces (`Evaluator`, `EvaluationStorageProvider`) to ensure loose coupling. Adding new evaluation methods or storage backends should require *no* changes to the core `EvaluationRunner`. The architecture must inherently support different deployment models (e.g., running evaluations as an in-process library call vs. wrapping the core logic in a separate microservice). This future-proofs the framework. * **NFR2: Configurability:** Users must be able to easily configure evaluation runs: selecting which evaluators to use, defining the criteria set, adjusting settings for specific evaluators (e.g., the LLM model for the judge), and specifying the storage provider. Usability depends on good configuration options. * **Configuration Strategy Options:** * 🟢 **Programmatic (Primary for Phase 1):** Configuration objects are passed directly to the `runEvaluation` function via `EvaluationRunConfig`. * **File-Based (Future Consideration):** Design should not preclude loading evaluation configurations (criteria definitions, evaluator selections, specific settings) from dedicated configuration files (e.g., `evaluation.config.ts`, JSON files). * **Agent Definition Integration (Future Consideration):** Potentially allow defining default evaluation configurations as part of an agent's overall definition. * *Initial implementation will focus on programmatic configuration for simplicity and direct control, but the underlying structures should support file-based loading later.* * **NFR3: Performance & Cost Awareness:** LLM-based evaluations can be slow and expensive. * The framework must support selective execution of evaluators (e.g., running only fast rule-based checks in some contexts). * IO-bound evaluators (`LLMJudgeEvaluator`, storage providers) must operate asynchronously (`Promise`-based) to avoid blocking the main thread. * Documentation should clearly outline the relative cost and latency implications of different evaluators (e.g., RuleBased vs. LLMJudge). Production decisions often hinge on these factors. * **NFR4: Testability:** All core components (runner, evaluators, storage providers, type definitions) must be designed for unit testing. Dependencies should be injectable or easily mockable. Reliable software development demands comprehensive testing. ## 6. High-Level Architecture & Key Data Structures The implementation will reside primarily within a new top-level directory in the core library. * **Primary Directory:** `agentdock-core/src/evaluation/` * **Core Types (`evaluation/types.ts`):** * `EvaluationScale = 'binary' | 'likert5' | 'numeric' | 'pass/fail' | string;` // binary: Simple yes/no, true/false. (Normalized to 0 or 1) // likert5: Standard 1-5 rating scale. (Normalized to 0-1: (score-1)/4) // numeric: Any plain number score. (If 0-1, used as is. If 0-100, normalized to 0-1 by dividing by 100. Other ranges currently not normalized for aggregation unless they are 0 or 1). // pass/fail: Clear categorical outcome. (Normalized to 0 or 1) // string: For custom scales or categorical results. (Normalized to 0 or 1 if 'true'/'false', 'pass'/'fail', etc., otherwise not typically included in numeric aggregation unless parsable to a number and fitting a numeric/likert scale). * `EvaluationCriteria`: `{ name: string; // Unique identifier for the criterion description: string; // Human-readable explanation scale: EvaluationScale; // The scale used for scoring this criterion weight?: number; // Optional weight for aggregation }` * `EvaluationInput`: `{ // Rich context for the evaluation prompt?: string; // Optional initiating prompt response: string | AgentMessage; // The agent output being evaluated context?: Record; // Arbitrary contextual data groundTruth?: string | any; // Optional reference answer/data criteria: EvaluationCriteria[]; // Criteria being evaluated against agentConfig?: Record; // Snapshot of agent config at time of response messageHistory?: AgentMessage[]; // Relevant message history timestamp?: number; // Timestamp of the response generation sessionId?: string; // Identifier for the session/conversation agentId?: string; // Identifier for the agent instance metadata?: Record; // Other arbitrary metadata (e.g., test runner context if applicable) }` * `EvaluationResult`: `{ // Result for a single criterion from one evaluator criterionName: string; // Links back to EvaluationCriteria.name score: number | boolean | string; // The actual score/judgment reasoning?: string; // Optional explanation from the evaluator (esp. LLM judge) evaluatorType: string; // Identifier for the evaluator producing this result error?: string; // Error message if this specific evaluation failed metadata?: Record; // Evaluator-specific metadata }` * `AggregatedEvaluationResult`: `{ // Overall result for an evaluation run overallScore?: number; // Optional aggregated score (e.g., weighted avg) results: EvaluationResult[]; // List of individual results from all evaluators timestamp: number; // Timestamp of the evaluation run completion agentId?: string; // Copied from input sessionId?: string; // Copied from input inputSnapshot: EvaluationInput; // Capture the exact input used evaluationConfigSnapshot?: { evaluatorTypes: string[]; criteriaNames: string[]; storageProviderType: string; metadataKeys: string[]; }; // Snapshot of criteria, evaluators used metadata?: Record; // Run-level metadata }` * `Evaluator`: `interface Evaluator { type: string; evaluate(input: EvaluationInput, criteria: EvaluationCriteria[]): Promise; }` * `EvaluationStorageProvider`: `interface EvaluationStorageProvider { saveResult(result: AggregatedEvaluationResult): Promise; }` * **Sub-directories & Components:** * `evaluation/criteria/`: Utilities or helpers related to defining/managing criteria sets (if needed beyond simple objects). * `evaluation/evaluators/`: Implementations of the `Evaluator` interface, organized into subdirectories by type (e.g., `rule-based/`, `llm/`, `nlp/`, `tool/`, `lexical/`). * `evaluation/runner/`: Implementation of the `EvaluationRunner` logic (`index.ts`). * `evaluation/storage/`: The `EvaluationStorageProvider` interface definition and concrete implementations (`json_file_storage.ts`, potentially others later). * `evaluation/types.ts`: Location for all core type definitions and interfaces listed above. * `evaluation/index.ts`: Main entry point exporting the public API of the evaluation module (e.g., `runEvaluation` function, core types, interfaces). ## 7. Where We Start: Phased Implementation & Next Steps **On Test Implementation Timing.** There's a common reflex to demand unit tests for every line of code the moment it's written. We called (NFR4) testability 'mandatory,' and fundamentally, that's not wrong. However, in the context of iterative development--especially when new capabilities are being forged--front-loading comprehensive unit tests for features still in flux often leads to wasted effort. My approach, grounded in experience shipping actual product, is more pragmatic: 1. **Build the core feature.** Get it to a point where it functions and its core value can be assessed. 2. **Validate it in a realistic scenario.** This could be through example scripts, integration into a local build--whatever proves it does the intended job effectively. This is about confirming *what* we've built is right. 3. **Refine based on this practical validation.** 4. **Once the feature is stable and its design proven, *then* implement the comprehensive unit tests.** These tests then serve their true purpose: to lock in the proven behavior and guard against regressions. Writing tests for rapidly evolving or unproven code is an exercise in churn. We'll build, we'll validate functionally, and then we'll write the tests that matter for the long term. This ensures our testing effort is targeted and efficient, not just a checkbox exercise. **Note on Evaluator Test Scenarios:** While initial functional validation (e.g., via `run_evaluation_example.ts`) ensures core evaluator capabilities, the development of comprehensive test suites covering diverse edge cases (e.g., for `ToolUsageEvaluator`: missing required tools, invalid arguments, multiple calls, different data sources) will be a dedicated effort during the unit test writing phase for each evaluator. This ensures robust coverage once the evaluator's primary functionality is stabilized. We've built the foundation using a "tracer bullet" approach, establishing an end-to-end flow that validates the core architecture. **Status Legend:** * 🟢: Done * 🟡: Needs Implementation/Refinement/Tests * 🔴: Not Started **Phase 1: Foundational Implementation (Largely Complete)** 1. 🟢 **Establish Module & Structure:** Created `agentdock-core/src/evaluation/` and sub-directories. 2. 🟢 **Define Core Interfaces & Types:** Implemented in `evaluation/types.ts`. 3. 🟢 **Basic Criteria Handling:** `EvaluationCriteria[]` defined and passed programmatically. 4. 🟢 **Evaluation Runner Implemented:** Core logic, evaluator instantiation from `evaluatorConfigs`, error handling, and score normalization with weighted aggregation are in place. 5. 🟢 **Basic Storage Implementation:** `JsonFileStorageProvider` implemented and functional. 6. 🟢 **RuleBasedEvaluator Implemented:** Supports regex, length, includes, json_parse rules. 7. 🟢 **LLMJudgeEvaluator Implemented:** Uses Vercel AI SDK's `generateObject` for structured output and `CoreLLM`. 8. 🟢 **Example Script (`run_evaluation_example.ts`):** Successfully demonstrates programmatic configuration and execution of the framework with both rule-based and LLM judges, outputting to console and JSONL file. Relocated to `examples/` directory. **Phase 1.5: Core Enhancements & New Evaluator Types (Largely Complete)** 1. 🟢 **`NLPAccuracyEvaluator` Implementation (Semantic Similarity):** * **Goal:** Evaluate how semantically similar an agent\'s response is to a ground truth reference. * **Approach:** Created `agentdock-core/src/evaluation/evaluators/nlp/accuracy.ts`. This evaluator uses embedding models (e.g., via Vercel AI SDK or other compatible sentence transformer providers) to generate vector embeddings for both the agent\'s response and the `groundTruth` from `EvaluationInput`. It then calculates the cosine similarity between these embeddings. The resulting score (0-1 range) will represent the semantic accuracy. * **Configuration:** `NLPAccuracyEvaluatorConfig` allows specifying the embedding model and criterion name. * **Output:** `EvaluationResult` with the cosine similarity as the score. * **Status:** Implemented and functionally tested via example script. Unit tests pending. 2. 🟢 **`ToolUsageEvaluator` Implementation:** * **Goal:** Assess if an agent correctly used its designated tools. * **Approach:** Created `agentdock-core/src/evaluation/evaluators/tool/usage.ts`. This rule-based evaluator checks for expected tool calls, validates argument structure/content via custom functions, and enforces required tool usage. It sources tool call data from `messageHistory` (structured `tool_call` and `tool_result` content parts) or `context`. * **Configuration:** `ToolUsageEvaluatorConfig` takes an array of `ToolUsageRule`s (specifying `criterionName`, `expectedToolName`, `argumentChecks` function, `isRequired`) and a `toolDataSource` option. * **Output:** `EvaluationResult` (typically binary pass/fail per rule) for criteria like \"ToolInvocationCorrectness\", \"ToolParameterAccuracy\". * **Status:** Implemented and functionally tested via example script. Unit tests pending. **Phase 1.6: Practical Lexical Evaluator Suite (New & Complete)** This phase focuses on delivering a suite of fast, cost-effective, and practical lexical evaluators, providing essential checks without reliance on LLMs, aligning with a pragmatic evaluation philosophy. 1. 🟢 **`LexicalSimilarityEvaluator` Implementation:** * **Goal:** Measure direct textual similarity between an agent\'s response and a reference. * **Approach:** Implemented in `agentdock-core/src/evaluation/evaluators/lexical/similarity.ts`. Uses algorithms like Sorensen-Dice (default), Jaro-Winkler, or Levenshtein. * **Configuration:** `LexicalSimilarityEvaluatorConfig` includes `criterionName`, `sourceField` (e.g., \'response\'), `referenceField` (e.g., \'groundTruth\'), `algorithm`, `caseSensitive`, `normalizeWhitespace`. * **Output:** `EvaluationResult` with a normalized similarity score (0-1). * **Status:** Implemented and functionally tested. Unit tests pending. 2. 🟢 **`KeywordCoverageEvaluator` Implementation:** * **Goal:** Ensure key terms or concepts are present in the agent\'s response. * **Approach:** Implemented in `agentdock-core/src/evaluation/evaluators/lexical/keyword_coverage.ts`. Calculates the percentage of `expectedKeywords` found in the `sourceTextField`. * **Configuration:** `KeywordCoverageEvaluatorConfig` includes `criterionName`, `expectedKeywords` (or `keywordsSourceField` to pull from `groundTruth` or `context`), `sourceTextField`, `caseSensitive`, `matchWholeWord`, `normalizeWhitespace`. * **Output:** `EvaluationResult` with a coverage score (0-1). * **Status:** Implemented and functionally tested. Unit tests pending. 3. 🟢 **`SentimentEvaluator` Implementation:** * **Goal:** Assess the emotional tone of the agent\'s response. * **Approach:** Implemented in `agentdock-core/src/evaluation/evaluators/lexical/sentiment.ts`. Uses the `sentiment` npm package (AFINN-based wordlist). * **Configuration:** `SentimentEvaluatorConfig` includes `criterionName`, `sourceTextField`, `outputType` (\'comparativeNormalized\', \'rawScore\', \'category\'), and thresholds for categorization. * **Output:** `EvaluationResult` with a sentiment score or category. * **Status:** Implemented and functionally tested. (Note: `sentiment` package is old, flagged for future review/replacement if needed). Unit tests pending. 4. 🟢 **`ToxicityEvaluator` Implementation:** * **Goal:** Detect presence of undesirable or toxic language. * **Approach:** Implemented in `agentdock-core/src/evaluation/evaluators/lexical/toxicity.ts`. Checks text against a list of `toxicTerms`. * **Configuration:** `ToxicityEvaluatorConfig` includes `criterionName`, `toxicTerms`, `sourceTextField`, `caseSensitive`, `matchWholeWord`. * **Output:** `EvaluationResult` with a binary score (true if not toxic, false if toxic). * **Status:** Implemented and functionally tested. Unit tests pending. **Phase 1.6.1: Initial Core Documentation (New & Complete)** 1. 🟢 **Detailed Evaluator Documentation:** * **Goal:** Provide clear, comprehensive documentation for each implemented evaluator and for creating custom evaluators. * **Approach:** Created individual Markdown files for each evaluator within the `docs/evaluations/evaluators/` directory. Each document includes an overview, core workflow (with a Mermaid diagram), use cases, configuration guidance (with a conceptual code example), and expected output details. A guide for creating custom evaluators (`custom-evaluators.md`) has also been created. * **Covered Evaluators:** `RuleBasedEvaluator`, `LLMJudgeEvaluator`, `NLPAccuracyEvaluator`, `ToolUsageEvaluator`, and the Lexical Suite (`LexicalSimilarityEvaluator`, `KeywordCoverageEvaluator`, `SentimentEvaluator`, `ToxicityEvaluator`). An overview page for the Lexical Suite (`lexical-evaluators.md`) was also added. * **Status:** Initial drafts complete and available in `docs/evaluations/`. The main `docs/evaluations/README.md` provides an overview and links. **Phase 1.7: Comprehensive Testing (Next Up)** 1. 🟢 **Unit & Integration Tests:** Systematically add tests for all evaluators (RuleBased, LLMJudge, NLPAccuracy, ToolUsage, and all Lexical evaluators), detailed runner logic (including edge cases for normalization and aggregation), and storage provider interactions. Ensure robust mocking of external dependencies like LLMs. (Note: One context variable assertion in LLMJudge test is temporarily skipped - requires investigation. Jaro-Winkler test in LexicalSimilarity is also skipped due to suspected library issue). **Phase 2: Advanced Features & Ecosystem Integration (Future Work)** * 🔴 **Advanced Storage Solutions:** Implement `EvaluationStorageProvider` for robust backends (e.g., PostgreSQL, specialized MLOps databases). * 🔴 **Sophisticated Aggregation & Reporting:** Allow for more complex aggregation strategies, configurable reporting formats, or basic statistical analysis on results. * 🔴 **Agent-Level Evaluation Paradigms:** Develop patterns or specialized evaluators for assessing multi-turn conversation quality, complex task completion across multiple steps, or agent adherence to long-term goals. * 🔴 **Configuration from Files:** Allow loading `EvaluationRunConfig` (or parts of it, like criteria sets or evaluator profiles) from static files (e.g., JSON, TS) for easier management of standard evaluation suites. * 🔴 **Observability Enhancements:** Deeper integration with tracing/logging systems, potentially emitting OpenTelemetry-compatible evaluation events. * 🔴 **UI for Evaluation Results:** Develop a basic UI component or page within the AgentDock dashboard (or as a standalone tool) to view, filter, and compare evaluation results persisted via the SAL. * 🔴 **Benchmark Suite:** Establish a standardized benchmark suite using the evaluation framework to track performance of core agent capabilities over time and across different model versions. * 🔴 **Community Evaluators:** Document and streamline the process for community contributions of new evaluators to `agentdock-core`. * 🔴 **Improve Test Mock Robustness:** Transition simple test stubs (e.g., for `CoreLLM` in runner tests) to full `jest.mock()` implementations for better coverage and type safety as tests evolve. * 🔴 **Refactor Score Normalization Logic:** Extract the `normalizeEvaluationScore` function from the runner and its duplicate in tests into a shared utility to prevent drift and improve test reliability. * 🔴 **Improve Evaluation Module Exports:** Refactor `agentdock-core/evaluation` to expose necessary components like `JsonFileStorageProvider` via its public API (`index.ts`) to avoid deep internal imports in consuming code. *Previously listed items (status may need review as Phase 2 progresses):* * 🟡 **Resolve Skipped Tests:** Investigate and fix the skipped context variable assertion test in `LLMJudgeEvaluator` and the Jaro-Winkler test in `LexicalSimilarityEvaluator`. * 🟡 **Implement Runner Validation:** Complete the `validateEvaluatorConfigs` logic in the `EvaluationRunner` to ensure evaluator configurations are valid before execution. * 🟡 **Implement Advanced Evaluator Features:** Address Phase 2 TODOs within existing evaluators, such as advanced LLM Judge configurations (e.g., reference-free evaluation), sequence checking in `ToolUsageEvaluator`, and potentially adding more algorithms or features to the Lexical Suite. ## Memory Evolution Tracker: Complete Observability for Intelligent Memory Systems > Transform your memory system from a black box into a transparent, analyzable intelligence layer The Memory Evolution Tracker brings **unprecedented visibility** into how memories change, evolve, and interact over time within the AgentDock memory system. By tracking every significant memory mutation with sub-5ms overhead, it enables data-driven optimization of agent intelligence while providing complete audit trails for debugging and compliance. ## Key Technical Innovations The Memory Evolution Tracker introduces potentially revolutionary approaches to memory observability: - **Complete Lifecycle Tracking**: Every memory mutation tracked from creation to archival with full context - **Pattern Learning Analytics**: Measures effectiveness of discovered patterns and workflows in real-time - **Temporal Evolution Insights**: Understands how agent behavior changes over time through memory analysis - **Cost-Optimized Tracking**: Async event processing with intelligent batching for <5ms overhead - **Progressive Enhancement Integration**: Works seamlessly with existing memory infrastructure These innovations work together to create a comprehensive observability layer that transforms memory debugging from hours to minutes while enabling continuous optimization. ## What is Memory Evolution? Memory evolution in AgentDock represents the **complete lifecycle of memories** as they transform through various states: - **Creation Events**: New memories extracted from conversations or created through consolidation - **Mutation Events**: Changes to importance, resonance, content, or connections - **Access Events**: Recall operations that trigger decay calculations and reinforcement - **Transformation Events**: Episodic to semantic conversion, memory consolidation, pattern learning Each event captures not just what changed, but why it changed, who triggered it, and what impact it had. ## Current Problem Statement Without Memory Evolution Tracking, the AgentDock memory system operates as a **black box** where: ### Visibility Challenges - Memory changes happen without audit trails - Pattern learning effectiveness is unmeasured - Memory consolidation impacts are unknown - Agent behavior evolution is invisible - Performance degradation sources are hard to identify ### Operational Impact - **Debugging Time**: Hours spent tracing memory issues - **Optimization Blindness**: No data to improve algorithms - **User Confusion**: Can't explain how agents learn - **Compliance Risk**: No audit trail for regulated industries - **Performance Mystery**: Unknown bottlenecks and inefficiencies ## Memory Evolution Architecture ```mermaid graph TB subgraph "Memory Operations" A[Memory Creation] --> E[Evolution Tracker] B[Memory Access] --> E C[Memory Decay] --> E D[Memory Consolidation] --> E end subgraph "Evolution Tracking Pipeline" E --> F[Event Creation
< 5ms overhead] F --> G[Async Queue] G --> H[Batch Processor] H --> I[Time-Series Storage] end subgraph "Analytics & Insights" I --> J[Real-time Metrics] I --> K[Historical Analysis] I --> L[Predictive Insights] J --> M[Traceability Dashboard] K --> M L --> M end subgraph "Integration Points" N[WorkflowLearningService] --> E O[TemporalPatternAnalyzer] --> E P[MemoryConnectionManager] --> E Q[PRIMEExtractor] --> E end ``` ## Core Tracking Capabilities ### Evolution Event Structure ```typescript interface MemoryEvolutionEvent { // Core identification id: string; memoryId: string; userId: string; agentId: string; timestamp: number; // Change details changeType: MemoryChangeType; previousValue: any; newValue: any; // Context and reasoning source: string; // Component that triggered change reason: string; // Human-readable explanation // Performance and cost tracking metadata?: { cost?: number; duration?: number; llmUsed?: boolean; modelTier?: 'standard' | 'advanced'; [key: string]: any; }; } ``` ### Comprehensive Change Types - **`creation`**: New memory extracted or manually created - **`update`**: Content or metadata modifications - **`importance`**: Importance score adjustments - **`resonance`**: Decay or reinforcement events - **`consolidation`**: Memories merged or synthesized - **`connection`**: New relationships discovered - **`type_change`**: Episodic → Semantic conversions - **`archival`**: Memory moved to cold storage - **`access`**: Recall events that may trigger changes ## Integration with Existing Systems ### WorkflowLearningService Integration Track how procedural patterns evolve and improve: ```typescript // Automatic tracking when patterns are learned await this.evolutionTracker.trackEvolution(pattern.id, { changeType: 'creation', source: 'WorkflowLearningService', reason: `New ${pattern.sequence.length}-step pattern learned from successful execution`, metadata: { successRate: pattern.successRate, toolSequence: pattern.sequence.map(t => t.tool), averageDuration: pattern.avgDuration } }); ``` ### Temporal Pattern Enhancement Leverage underutilized temporal analysis for richer insights: ```typescript // Track temporal pattern discoveries const patterns = await this.temporalAnalyzer.analyzePatterns(agentId); const activityClusters = await this.temporalAnalyzer.detectActivityClusters(agentId); // Store pattern insights for evolution tracking await this.evolutionTracker.trackBatch(patterns.map(pattern => ({ memoryId: `temporal:${agentId}:${pattern.type}`, changeType: 'update', source: 'TemporalPatternAnalyzer', reason: `${pattern.type} pattern detected with ${pattern.confidence} confidence`, metadata: { patternType: pattern.type, peakHours: pattern.metadata.peakTimes, activityClusters: activityClusters.length } }))); ``` ### Graph Traversal Optimization Enhanced graph utilization for performance: ```typescript // Preload frequently accessed subgraphs await this.evolutionTracker.trackEvolution('graph:preload', { changeType: 'update', source: 'ConnectionGraph', reason: 'Preloaded high-traffic memory subgraph', metadata: { nodeCount: graph.getStats().nodeCount, edgeCount: graph.getStats().edgeCount, preloadDuration: loadTime } }); ``` ## Analytics and Insights ### Real-Time Metrics Dashboard ```typescript interface RealtimeEvolutionMetrics { // Learning velocity memoriesPerHour: number; patternsDiscoveredToday: number; consolidationRate: number; // System health averageDecayRate: number; connectionDensity: number; activeMemoryCount: number; // Cost tracking llmCallsToday: number; embeddingCostToday: number; storageGrowthRate: number; } ``` ### Historical Analysis Reports ```typescript interface AgentEvolutionReport { // Learning patterns knowledgeGrowthTrend: TrendData; topicSpecialization: TopicAnalysis; patternSuccessRates: PatternMetrics; // Memory health decayPatterns: DecayAnalysis; consolidationEffectiveness: number; connectionGraphDensity: GraphMetrics; // Behavioral insights temporalActivityPatterns: ActivityAnalysis; workflowImprovements: WorkflowMetrics; adaptabilityScore: number; } ``` ### Predictive Intelligence ```typescript interface PredictiveInsights { // Forecasting projectedMemoryGrowth: GrowthProjection; decayPredictions: DecayForecast; patternSuccessProbability: PatternPrediction; // Recommendations suggestedConsolidations: ConsolidationSuggestion[]; optimalDecaySettings: DecayConfiguration; connectionDiscoveryOpportunities: ConnectionOpportunity[]; } ``` ## Performance Characteristics ### Tracking Overhead - **Event Creation**: <5ms async operation - **Batch Processing**: 100 events/batch, 5-second intervals - **Storage Impact**: <10% of memory data size - **Query Performance**: <2s for 30-day analytics ### Scalability Design - **Horizontal Scaling**: Partition by user/agent for distributed processing - **Time-Series Optimization**: Automatic rollups for historical data - **Compression**: Event data compressed by 70% on average - **Retention Policies**: Configurable data lifecycle management ## Integration with Traceability Suite The Memory Evolution Tracker seamlessly integrates with the broader **AgentDock Traceability Suite**: ### Unified Observability - **Single Dashboard**: Memory evolution alongside system metrics - **Correlated Insights**: Link memory patterns to performance impacts - **Cost Attribution**: Track memory costs by user, agent, and operation - **Anomaly Detection**: Alert on unusual evolution patterns ### Developer Experience ```typescript // Debugging with full context const evolution = await tracker.getEvolutionHistory(memoryId, { includeRelated: true, timeRange: { start: issueStart, end: now } }); // Generate audit report const auditReport = await tracker.generateAuditReport({ userId: 'user-123', agentId: 'agent-456', changeTypes: ['creation', 'consolidation', 'deletion'], timeRange: { start: auditPeriodStart, end: auditPeriodEnd } }); ``` ## Implementation Roadmap ### Phase 1: Core Infrastructure (Weeks 1-2) - [ ] Implement MemoryEvolutionTracker with async event processing - [ ] Add tracking hooks to all memory mutation points - [ ] Set up time-series storage with partitioning - [ ] Create event batching and compression pipeline ### Phase 2: System Integration (Weeks 3-4) - [ ] Integrate with WorkflowLearningService for pattern tracking - [ ] Enhance TemporalPatternAnalyzer with evolution events - [ ] Add graph traversal optimization tracking - [ ] Implement connection evolution monitoring ### Phase 3: Analytics Engine (Weeks 5-6) - [ ] Build real-time metrics aggregation - [ ] Create historical analysis queries - [ ] Implement predictive insights algorithms - [ ] Add cost tracking and attribution ### Phase 4: Traceability Integration (Weeks 7-8) - [ ] Design unified dashboard UI - [ ] Implement cross-system correlation - [ ] Add alerting and anomaly detection - [ ] Create developer debugging tools ## Success Metrics ### Technical Excellence - **Tracking Overhead**: <5ms for 99.9% of operations - **Zero Data Loss**: 100% event capture with at-least-once delivery - **Query Performance**: <2s for complex analytics queries - **Storage Efficiency**: <10% overhead with compression ### Business Impact - **Debugging Efficiency**: 90% reduction in memory issue resolution time - **Optimization Velocity**: 50% faster algorithm improvements - **User Satisfaction**: 95% positive feedback on transparency - **Compliance Ready**: 100% audit trail coverage ### User Outcomes - **Agent Transparency**: Users understand how their agents learn - **Performance Insights**: Clear visibility into memory health - **Cost Control**: Detailed breakdown of memory operation costs - **Trust Building**: Complete audit trails for sensitive applications ## Security and Privacy ### Data Protection - **User Isolation**: Complete separation of evolution data by user ID - **Encryption**: Event data encrypted at rest and in transit - **Access Control**: Role-based access to evolution analytics - **PII Handling**: Automatic redaction of sensitive information ### Compliance Features - **Audit Trails**: Immutable event log for regulatory compliance - **Data Retention**: Configurable retention with automatic cleanup - **Export Capabilities**: Generate compliance reports on demand - **Right to Erasure**: Support for GDPR data deletion requests ## Future Enhancements ### Advanced Analytics - **Cross-Agent Learning**: Compare evolution patterns across agents - **A/B Testing Framework**: Test memory algorithms with control groups - **ML-Powered Optimization**: Use evolution data to auto-tune parameters - **Behavioral Clustering**: Identify agent personality types ### Integration Expansions - **External Analytics**: Export to Datadog, New Relic, Grafana - **Webhook System**: Real-time notifications for evolution events - **Public API**: Allow custom evolution event tracking - **Mobile SDK**: Track evolution in edge deployments --- **The Memory Evolution Tracker transforms the AgentDock memory system from an opaque intelligence layer into a transparent, optimizable, and debuggable foundation for next-generation AI agents.** ## Memory & Storage Testing System PRD **Product Requirements Document** **Version**: 1.0 **Date**: July 9, 2025 **Status**: Draft **Owner**: AgentDock Core Team ## Executive Summary The Memory & Storage Testing System ensures production-ready reliability, performance, and accuracy of AgentDock's core memory infrastructure. This system validates hybrid vector+text search, cross-adapter compatibility, and real-world performance scenarios across PostgreSQL, SQLite, and vector-enabled variants. ### Business Impact - **Risk Mitigation**: Prevent memory system failures in production deployments - **Performance Assurance**: Guarantee <200ms response times for memory operations - **Compatibility Validation**: Ensure seamless operation across managed and self-hosted databases - **Developer Confidence**: Enable rapid feature development with comprehensive safety nets ## Problem Statement ### Current State - **Incomplete Test Coverage**: PostgreSQL Vector adapter has zero tests - **Missing E2E Validation**: No real embedding pipeline testing - **Performance Unknowns**: No load testing for 10K+ memory scenarios - **Adapter Inconsistency**: Different storage adapters lack unified test suites - **Production Gaps**: Managed service compatibility untested ### Success Metrics - **Test Coverage**: 95% function coverage across all memory operations - **Performance SLA**: <200ms response time for hybrid search operations - **Reliability**: 99.9% uptime in production memory operations - **Accuracy**: ≥85% relevance in hybrid search results vs pure vector search ## Product Overview ### Core Components #### 1. Storage Adapter Test Suite Comprehensive testing for all storage adapters with unified test contracts. **Adapters Covered**: - PostgreSQL (with ts_rank_cd text search) - PostgreSQL Vector (with pgvector + hybrid search) - SQLite (with FTS5) - SQLite Vec (with vec0 + FTS5 BM25) #### 2. Memory Operations Validation End-to-end testing of memory lifecycle operations across all storage types. **Operations Tested**: - Store, Recall, Update, Delete (CRUD) - Batch operations and transactions - Connection discovery and graph traversal - Decay calculations and archival #### 3. Vector & Hybrid Search Testing Validation of vector similarity and hybrid search accuracy. **Search Types**: - Pure vector similarity (cosine, euclidean, dot product) - Pure text search (FTS5 BM25, ts_rank_cd) - Hybrid search (70% vector + 30% text) - Reciprocal Rank Fusion (RRF) algorithms #### 4. Performance & Scale Testing Load testing and performance validation for production scenarios. **Scale Scenarios**: - 10K+ memories with concurrent access - 100+ concurrent users - Large batch operations (1K+ memories) - Connection discovery across large graphs ## User Stories ### Memory System Developer **As a** memory system developer **I want** comprehensive test coverage for all storage adapters **So that** I can confidently deploy new memory features without breaking existing functionality **Acceptance Criteria**: - [ ] All storage adapters pass identical test suites - [ ] Test failures clearly indicate the root cause - [ ] Tests can be run locally with minimal setup - [ ] CI/CD pipeline runs all tests automatically ### DevOps Engineer **As a** DevOps engineer deploying AgentDock **I want** performance and compatibility validation **So that** I can ensure reliable operation in production environments **Acceptance Criteria**: - [ ] Performance tests validate SLA requirements - [ ] Compatibility tests cover managed services (RDS, Supabase) - [ ] Load tests simulate realistic production scenarios - [ ] Resource usage is measured and documented ### AI Application Developer **As an** AI application developer using AgentDock **I want** reliable memory operations **So that** my agents maintain consistent conversational context **Acceptance Criteria**: - [ ] Memory recall accuracy is ≥85% for semantic queries - [ ] Response times are consistently <200ms - [ ] Cross-session memory persistence works reliably - [ ] Memory connections enhance recall relevance ## Functional Requirements ### FR1: Storage Adapter Test Framework **Priority**: P0 (Critical) #### FR1.1: Unified Test Contracts - All storage adapters implement identical test suites - Test isolation prevents cross-contamination - Graceful degradation when extensions unavailable - Error handling validation for all failure modes #### FR1.2: Memory Operations Testing ```typescript // Test contract example interface MemoryOperationsTestSuite { testBasicCRUD(): Promise; testUserIsolation(): Promise; testBatchOperations(): Promise; testConnections(): Promise; testPerformance(): Promise; } ``` ### FR2: Vector Search Validation **Priority**: P0 (Critical) #### FR2.1: Embedding Pipeline Testing - Real OpenAI API integration with text-embedding-3-small - Embedding dimension validation (1536 dimensions) - Cost tracking and API rate limiting - Fallback mechanisms when API unavailable #### FR2.2: Hybrid Search Accuracy - Vector similarity vs text search comparison - 70% vector + 30% text weight validation - Relevance ranking consistency - Cross-adapter result comparison ### FR3: Performance & Scale Testing **Priority**: P1 (High) #### FR3.1: Load Testing - 10K+ memories with concurrent recall operations - 100+ concurrent users performing memory operations - Large batch storage and update operations - Memory connection discovery at scale #### FR3.2: Performance SLA Validation - <200ms response time for hybrid search - <100ms response time for vector-only search - <50ms response time for text-only search - Memory usage and garbage collection impact ### FR4: Production Scenario Testing **Priority**: P1 (High) #### FR4.1: Managed Service Compatibility - PostgreSQL RDS with pgvector extension - Supabase PostgreSQL configuration - Azure Database for PostgreSQL - Google Cloud SQL compatibility #### FR4.2: Self-Hosted Configuration - PostgreSQL with manual pgvector installation - SQLite with vec0 extension compilation - Docker containerized testing environments - Local development setup validation ## Non-Functional Requirements ### Performance Requirements - **Response Time**: <200ms for 95% of hybrid search operations - **Throughput**: Support 1000+ memory operations per second - **Concurrency**: Handle 100+ concurrent users without degradation - **Memory Usage**: <2GB RAM for 100K stored memories ### Reliability Requirements - **Uptime**: 99.9% availability for memory operations - **Data Integrity**: Zero data loss during failures - **Graceful Degradation**: Fallback to text search when vector unavailable - **Error Recovery**: Automatic retry with exponential backoff ### Security Requirements - **User Isolation**: Complete data separation between users - **SQL Injection Protection**: Parameterized queries only - **API Key Security**: Secure handling of OpenAI API keys - **Access Control**: Memory operations require proper authorization ### Compatibility Requirements - **Database Versions**: PostgreSQL 12+, SQLite 3.38+ - **Extension Dependencies**: pgvector 0.5+, sqlite-vec (vec0) latest - **Node.js Versions**: 18.x, 20.x LTS - **Operating Systems**: Linux, macOS, Windows ## Technical Architecture ### Test Infrastructure #### Database Setup ```yaml # Docker Compose for test environment services: postgres-vector: image: pgvector/pgvector:pg16 environment: POSTGRES_DB: agentdock_test POSTGRES_USER: test POSTGRES_PASSWORD: test ports: - "5432:5432" sqlite-vec: build: context: ./test-infrastructure dockerfile: Dockerfile.sqlite-vec volumes: - ./test-data:/data ``` #### Test Data Generation ```typescript // Realistic test data sets interface TestDataSets { smallDataset: { memories: 100; users: 5; agents: 3; connections: 50; }; mediumDataset: { memories: 10000; users: 50; agents: 10; connections: 5000; }; largeDataset: { memories: 100000; users: 500; agents: 50; connections: 50000; }; } ``` ### Test Categories #### Unit Tests - Individual memory operations - Storage adapter implementations - Vector similarity calculations - Text search algorithms #### Integration Tests - Memory system component interactions - Storage adapter compatibility - Embedding service integration - Connection graph operations #### End-to-End Tests - Complete user workflows - Real embedding pipeline - Cross-adapter scenarios - Production configuration testing #### Performance Tests - Load testing scenarios - Stress testing limits - Memory usage profiling - Response time validation ## Implementation Plan ### Phase 1: Foundation (Week 1-2) ✅ COMPLETED **Goal**: Establish core testing infrastructure #### Deliverables - [x] PostgreSQL Vector adapter test suite (535 lines, comprehensive coverage) - [x] SQLite Vec memory operations tests (complete partial implementation) - [x] Unified test contracts for all adapters (test-helpers.ts) - [x] CI/CD pipeline with database setup #### Success Criteria - ✅ All storage adapters have >90% test coverage - ✅ CI/CD pipeline runs successfully (pnpm build passes) - ✅ Local development environment setup documented ### Phase 2: Integration (Week 3-4) ✅ COMPLETED **Goal**: Validate cross-component functionality #### Deliverables - [x] RecallService E2E integration tests (825 lines, comprehensive) - [x] Real embedding pipeline testing with OpenAI API (mock service pattern) - [x] Cross-adapter result comparison validation - [x] Hybrid search accuracy benchmarking (70% vector + 30% text) #### Success Criteria - ✅ RecallService works with all storage adapters - ✅ Embedding pipeline handles API failures gracefully - ✅ Hybrid search accuracy ≥85% vs pure vector search ### Phase 3: Performance (Week 5-6) **Goal**: Ensure production-ready performance #### Deliverables - [ ] Load testing suite for 10K+ memories - [ ] Concurrent user testing (100+ users) - [ ] Performance regression detection - [ ] Resource usage optimization #### Success Criteria - All performance SLAs met - Load tests pass without failures - Resource usage within acceptable limits ### Phase 4: Production Readiness (Week 7-8) **Goal**: Validate production deployment scenarios #### Deliverables - [ ] Managed service compatibility testing - [ ] Production configuration validation - [ ] Disaster recovery testing - [ ] Documentation and runbooks #### Success Criteria - All managed services tested successfully - Production configurations validated - Disaster recovery procedures documented ## Test Specifications ### Memory Operations Test Suite #### Basic CRUD Operations ```typescript describe('Memory CRUD Operations', () => { test('store creates memory with proper isolation'); test('recall filters by user/agent correctly'); test('update modifies memory safely'); test('delete removes memory completely'); test('getById returns correct memory'); test('getStats provides accurate counts'); }); ``` #### Vector Operations Testing ```typescript describe('Vector Operations', () => { test('storeMemoryWithEmbedding stores vector correctly'); test('searchByVector finds similar memories'); test('hybridSearch combines vector + text scores'); test('updateMemoryEmbedding modifies vectors'); test('getMemoryEmbedding retrieves vectors'); }); ``` #### Hybrid Search Validation ```typescript describe('Hybrid Search', () => { test('70% vector + 30% text weight distribution'); test('PostgreSQL ts_rank_cd text scoring'); test('SQLite FTS5 BM25 text scoring'); test('Reciprocal Rank Fusion algorithm'); test('result ranking consistency'); }); ``` ### Performance Test Specifications #### Load Testing ```typescript describe('Performance Tests', () => { test('10K memories storage performance', async () => { const startTime = Date.now(); await storeMemories(10000); const duration = Date.now() - startTime; expect(duration).toBeLessThan(30000); // 30 seconds }); test('concurrent recall operations', async () => { const promises = Array(100).fill(0).map(() => recallMemories('test query') ); const results = await Promise.all(promises); expect(results.every(r => r.length > 0)).toBe(true); }); test('hybrid search response time', async () => { const startTime = Date.now(); await hybridSearch('complex semantic query'); const duration = Date.now() - startTime; expect(duration).toBeLessThan(200); // 200ms SLA }); }); ``` ### E2E Test Scenarios #### User Journey: Learning Session ```typescript describe('E2E: Learning Session', () => { test('complete learning workflow', async () => { // 1. Store working memory during learning const workingId = await storeWorkingMemory( 'Learning about React hooks' ); // 2. Convert to episodic memory after practice const episodicId = await storeEpisodicMemory( 'Successfully built React app with hooks' ); // 3. Extract semantic knowledge const semanticId = await storeSemanticMemory( 'React hooks manage state in functional components' ); // 4. Learn procedural pattern const proceduralId = await learnProceduralPattern( 'need state management', 'use React hooks' ); // 5. Test recall with hybrid search const results = await hybridSearch('React state management'); expect(results).toContainMemories([ workingId, episodicId, semanticId, proceduralId ]); expect(results[0].score).toBeGreaterThan(0.8); }); }); ``` #### Cross-Adapter Compatibility ```typescript describe('E2E: Cross-Adapter Compatibility', () => { test('same results across storage adapters', async () => { const testQuery = 'machine learning algorithms'; const testMemories = generateTestMemories(100); // Store memories in all adapters await Promise.all([ postgresAdapter.batchStore(testMemories), postgresVectorAdapter.batchStore(testMemories), sqliteAdapter.batchStore(testMemories), sqliteVecAdapter.batchStore(testMemories) ]); // Query all adapters const [pgResults, pgvResults, sqliteResults, sqliteVecResults] = await Promise.all([ postgresAdapter.recall(testQuery), postgresVectorAdapter.hybridSearch(testQuery), sqliteAdapter.recall(testQuery), sqliteVecAdapter.hybridSearch(testQuery) ]); // Validate consistency expect(pgvResults.length).toBeGreaterThan(pgResults.length); expect(sqliteVecResults.length).toBeGreaterThan(sqliteResults.length); expect(compareRelevance(pgvResults, sqliteVecResults)).toBeGreaterThan(0.8); }); }); ``` ## Risk Assessment ### High Risk - **PostgreSQL Vector Testing Gap**: Zero tests currently exist - **Performance Unknowns**: No load testing for scale scenarios - **Production Compatibility**: Managed services untested ### Medium Risk - **Embedding API Dependencies**: OpenAI rate limits and costs - **Extension Dependencies**: pgvector and vec0 availability - **Test Environment Complexity**: Multiple database setups ### Low Risk - **Test Maintenance**: New features require test updates - **CI/CD Performance**: Longer build times with comprehensive tests ## Success Criteria ### Functional Success - [ ] All storage adapters pass comprehensive test suites - [ ] Hybrid search accuracy ≥85% vs pure vector search - [ ] Zero data loss or corruption in any test scenario - [ ] Complete user isolation across all operations ### Performance Success - [ ] <200ms response time for 95% of hybrid searches - [ ] Support 1000+ memory operations per second - [ ] Handle 100+ concurrent users without degradation - [ ] Memory usage <2GB for 100K stored memories ### Quality Success - [ ] 95% test coverage across all memory operations - [ ] Zero critical bugs in production deployment - [ ] Successful deployment to all supported platforms - [ ] Developer productivity maintained with fast test execution ## Appendix ### Test Data Samples ```typescript // Realistic memory content for testing const testMemories = [ { content: "The user prefers dark mode in applications", type: "semantic", importance: 0.7, keywords: ["ui", "preferences", "dark-mode"] }, { content: "Successfully debugged authentication issue by checking JWT token expiration", type: "episodic", importance: 0.9, tags: ["debugging", "authentication", "jwt"] }, { content: "When API returns 500 error, check database connection timeout", type: "procedural", importance: 0.8, pattern: "api-error-debugging" } ]; ``` ### Performance Benchmarks ```typescript // Expected performance baselines const performanceBaselines = { vectorSearch: { small: "< 50ms for 1K memories", medium: "< 100ms for 10K memories", large: "< 200ms for 100K memories" }, hybridSearch: { small: "< 100ms for 1K memories", medium: "< 200ms for 10K memories", large: "< 500ms for 100K memories" }, storage: { single: "< 10ms per memory", batch: "< 5ms per memory in batch of 100" } }; ``` --- **Document Control** - **Created**: July 9, 2025 - **Last Updated**: July 9, 2025 - **Next Review**: July 16, 2025 - **Approvers**: Engineering Lead, Product Manager, QA Lead ## Workflow Learning Service - PRD **Author**: AgentDock Team **Date**: July 2025 **Status**: Post-Launch Enhancement **Purpose**: Enhance existing procedural memory with multi-step workflow execution capabilities **Timeline**: After core AgentDock platform priorities complete --- ## Executive Summary Unify and enhance AgentDock's existing workflow learning capabilities by creating a consolidated service that captures, learns, and executes multi-step tool sequences. The system will build upon mature procedural learning infrastructure already in production to enable deterministic replay of complex workflows and support user-submitted workflow definitions. ## Problem Statement **Business Need**: - Agents repeatedly execute the same multi-step tool sequences for similar tasks - Existing tool pattern learning lacks execution capabilities for deterministic replay - Complex workflows (15+ steps) can be learned but not automatically executed - No unified interface for both auto-learned and user-submitted workflow automation **Technical Challenge**: - Need unified workflow learning and execution system for multi-step tool automation - Complex workflows (15+ steps) require deterministic replay capabilities - User-submitted workflows need validation and execution framework - Performance optimization required for large-scale pattern recognition ## Solution Architecture ### Core Concept: Enhanced Workflow Learning & Execution Building on AgentDock's existing procedural learning foundation, the system provides complete workflow automation: 1. **Pattern Detection** (EXISTING) - Already identifies repeated tool sequences and tracks success rates 2. **Workflow Storage** (EXISTING) - Currently stores patterns in procedural memory with user isolation 3. **Smart Execution** (NEW) - Add deterministic replay engine for learned workflows 4. **User Workflows** (NEW) - Add manual workflow definition and submission capabilities 5. **Unified Architecture** (NEW) - Consolidate existing systems into coherent service ### Service Architecture ``` /agentdock-core/src/orchestration/workflow-learning/ ├── WorkflowLearningService.ts # Core learning and execution service ├── types.ts # Workflow data structures and interfaces ├── index.ts # Service exports └── __tests__/ └── WorkflowLearningService.test.ts ``` ### Integration Flow ```typescript // Clean separation of concerns WorkflowLearningService // Service that learns and executes workflows ↓ stores patterns in ProceduralMemory // Memory type that stores trigger→action patterns ↓ uses Storage Layer // Existing storage with user isolation ``` ## Core Features ### Automatic Workflow Learning The service automatically detects and learns tool execution patterns: - **Pattern Recognition** - Identifies successful tool sequences (3+ steps) - **Success Tracking** - Monitors execution outcomes and performance metrics - **Confidence Scoring** - Builds confidence based on repeated successful execution - **Context Awareness** - Associates workflows with execution contexts ### User-Submitted Workflows Support for manually defined workflows: - **Workflow Definition** - Define multi-step tool sequences via API - **Parameter Templates** - Configurable parameters for flexible execution - **Validation** - Ensure workflow steps are valid and executable - **Priority Handling** - User workflows take precedence over auto-learned patterns ### Deterministic Execution Reliable replay of learned workflows: - **Step-by-Step Execution** - Execute workflows in defined order - **Error Handling** - Graceful failure recovery and partial execution - **Progress Tracking** - Real-time execution progress reporting - **Performance Metrics** - Track execution time and success rates ## Implementation ### WorkflowLearningService ```typescript // /orchestration/workflow-learning/WorkflowLearningService.ts export class WorkflowLearningService { constructor( private proceduralMemory: ProceduralMemory, // Uses the actual memory type private config: WorkflowLearningConfig ) {} async learnToolWorkflow(data: ToolExecutionData): Promise { const { userId, agentId, toolSequence, success, context } = data; if (toolSequence.length >= this.config.minStepsToLearn) { const workflowPattern = this.extractWorkflowPattern(toolSequence, context); // Store in ACTUAL procedural memory (not confusing fake memory manager) await this.proceduralMemory.store(userId, agentId, { trigger: workflowPattern.description, action: JSON.stringify(workflowPattern.steps), pattern: workflowPattern.signature, confidence: success ? 0.8 : 0.3, metadata: { category: 'tool-workflow', source: 'auto-learned', toolSequence: workflowPattern.steps.map(s => s.toolName) } }); } } async findWorkflow(userId: string, agentId: string, context: string): Promise { // Query ACTUAL procedural memory for tool workflows const patterns = await this.proceduralMemory.recall(userId, agentId, context, { metadata: { category: 'tool-workflow' }, minConfidence: 0.7 }); return this.selectBestWorkflow(patterns); } async submitUserWorkflow(userId: string, agentId: string, workflow: UserWorkflow): Promise { // Store user workflow in ACTUAL procedural memory await this.proceduralMemory.store(userId, agentId, { trigger: workflow.description, action: JSON.stringify(workflow.steps), pattern: `user-workflow:${workflow.name}`, confidence: 1.0, metadata: { category: 'tool-workflow', source: 'user-submitted', workflowName: workflow.name } }); } } ``` #### Integration with LLMOrchestrationService ```typescript // Clean integration in LLMOrchestrationService export class LLMOrchestrationService { private workflowLearningService: WorkflowLearningService; constructor(/*...*/) { // Initialize workflow learning service with actual procedural memory const proceduralMemory = this.memoryManager.getProceduralMemory(); this.workflowLearningService = new WorkflowLearningService(proceduralMemory, config); } async handleStepFinish(event: StepFinishEvent): Promise { // Existing tool tracking logic... // Add workflow learning if (this.config.workflowLearning?.enabled && this.shouldLearnWorkflow(event)) { const executionData = { userId: this.sessionContext.userId, agentId: this.sessionContext.agentId, toolSequence: this.getSessionToolSequence(), success: this.evaluateExecutionSuccess(event), context: this.extractWorkflowContext() }; // Learn workflow patterns (async, non-blocking) this.workflowLearningService.learnToolWorkflow(executionData).catch(error => { console.warn('Workflow learning failed:', error); }); } } private shouldLearnWorkflow(event: StepFinishEvent): boolean { const toolSequence = this.getSessionToolSequence(); return ( toolSequence.length >= this.config.workflowLearning.minStepsToLearn && // Default: 3 this.allToolsSuccessful(toolSequence) && this.isWithinLearningWindow(toolSequence) // Within 5-minute execution window ); } private evaluateExecutionSuccess(event: StepFinishEvent): boolean { // All tools succeeded AND no exceptions thrown AND task completed return event.success && !this.hasSessionErrors() && this.taskCompleted(); } private extractWorkflowContext(): string { // Combine session context + tool parameters for pattern matching return `${this.sessionContext.taskDescription} | ${this.getToolParameterSummary()}`; } } ``` ### Data Structures (Clean Naming) ```typescript // /orchestration/workflow-learning/types.ts interface ToolWorkflow { id: string; name: string; description: string; steps: WorkflowStep[]; triggerKeywords: string[]; source: 'auto-learned' | 'user-submitted'; confidence: number; successCount: number; totalExecutions: number; createdAt: number; lastUsed: number; } interface WorkflowStep { order: number; toolName: string; parameters: Record; required: boolean; description?: string; } interface UserWorkflow { name: string; description: string; steps: WorkflowStep[]; triggerKeywords: string[]; } interface ToolExecutionData { userId: string; agentId: string; toolSequence: Array<{ toolName: string; parameters: Record; duration: number; success: boolean; }>; success: boolean; context: string; } interface WorkflowLearningConfig { enabled: boolean; // Feature flag for workflow learning minStepsToLearn: number; // Minimum tools to form pattern (Default: 3) minSuccessRate: number; // Minimum success rate for suggestions (Default: 0.6) confidenceThreshold: number; // Minimum confidence for auto-suggestions (Default: 0.8) maxWorkflowsPerAgent: number; // Storage limit per agent (Default: 1000) learningTimeout: number; // Max learning processing time (Default: 100ms) learningWindow: number; // Max time between tools to group as workflow (Default: 300000ms / 5min) autoExecute: boolean; // Enable automatic workflow execution (Default: false) suggestionMode: 'manual' | 'automatic' | 'hybrid'; // How to present suggestions (Default: 'manual') } ``` ### Storage Strategy (Uses Existing System) **NO new storage patterns needed** - uses existing procedural memory: ```typescript // Workflow patterns stored as procedural memory data await proceduralMemory.store(userId, agentId, { trigger: "Code review workflow", action: JSON.stringify([ { order: 1, toolName: "Bash", parameters: { command: "git diff main" } }, { order: 2, toolName: "Grep", parameters: { pattern: "TODO|FIXME" } }, { order: 3, toolName: "Bash", parameters: { command: "npm test" } } ]), pattern: "code-review-workflow", confidence: 0.85, metadata: { category: 'tool-workflow', source: 'auto-learned', toolSequence: ['Bash', 'Grep', 'Bash'] } }); ``` **User isolation** handled by existing procedural memory operations. ### API Design (Clean) ```typescript // POST /api/workflows - User workflow submission export async function POST(request: Request) { const { userId, agentId, workflow } = await request.json(); // User authentication (application responsibility) const authenticatedUserId = await extractUserFromRequest(request); if (!authenticatedUserId || authenticatedUserId !== userId) { return Response.json({ error: 'Unauthorized' }, { status: 401 }); } // Use workflow learning service const workflowLearningService = await getWorkflowLearningService(); await workflowLearningService.submitUserWorkflow(userId, agentId, workflow); return Response.json({ success: true }); } // GET /api/workflows - List workflows export async function GET(request: Request) { const { userId, agentId } = extractParams(request); const workflowLearningService = await getWorkflowLearningService(); const workflows = await workflowLearningService.getWorkflows(userId, agentId); return Response.json({ workflows }); } ``` ## Integration Specifications ### Learning Trigger Conditions The system learns workflows when ALL conditions are met: 1. **Minimum Tool Sequence**: 3+ consecutive successful tool calls 2. **Success Criteria**: All tools return success=true with no exceptions thrown 3. **Execution Window**: Tools executed within 5-minute window (configurable) 4. **Task Completion**: Session indicates successful task completion 5. **Feature Enabled**: `workflowLearning.enabled = true` in configuration ### Context Extraction Strategy Workflow context combines multiple sources for pattern matching: ```typescript WorkflowContext = { taskDescription: session.context.taskDescription, toolParameters: extractedParameterPatterns, executionEnvironment: session.metadata.environment, userIntent: inferredFromToolSequence, successIndicators: taskCompletionSignals } ``` ### Suggestion Integration Points Workflows are suggested at specific decision points: 1. **Pre-Planning**: Before agent begins tool sequence planning 2. **Pattern Recognition**: When current context matches learned patterns 3. **User Request**: When user asks for workflow recommendations 4. **Error Recovery**: When similar workflows succeeded in error scenarios ### Production Safety Controls - **Manual Approval**: All suggestions require explicit user confirmation - **Confidence Gating**: Only suggest workflows above 80% confidence threshold - **Execution Isolation**: Workflow execution separate from normal agent flow - **Rollback Support**: Ability to interrupt and revert partial workflow execution ## Implementation Phases ### Phase 1: Foundation Implementation (COMPLETED) - **✅ IMPLEMENTED**: Created `/orchestration/workflow-learning/WorkflowLearningService.ts` for tool pattern learning - **✅ UNIFIED**: Integrated tool pattern learning with procedural memory type storage - **✅ CLEAN**: Clear separation between memory type and workflow learning service - **✅ STRUCTURED**: Proper module organization with clean imports and exports - **✅ READY**: Foundation prepared for workflow execution engine development ### Phase 2: Learning Integration (IMPLEMENTATION NEEDED) - **✅ READY**: WorkflowLearningService with pattern learning capabilities - **🔧 IMPLEMENT**: Integration with LLMOrchestrationService.handleStepFinish() - **🔧 IMPLEMENT**: Tool sequence capture and success evaluation logic - **🔧 IMPLEMENT**: Learning trigger conditions and workflow context extraction - **🔧 IMPLEMENT**: Configuration system with feature flags and thresholds - **🔧 IMPLEMENT**: Async learning pipeline with error handling ### Phase 3: Execution Engine (PRIMARY DEVELOPMENT) - **🔧 IMPLEMENT**: Deterministic workflow replay with step-by-step execution - **🔧 IMPLEMENT**: User workflow submission API endpoints with validation - **🔧 IMPLEMENT**: Workflow suggestion system integrated with agent planning - **🔧 IMPLEMENT**: Partial execution recovery and error handling mechanisms - **🔧 IMPLEMENT**: Workflow performance tracking and success metrics - **🔧 IMPLEMENT**: Manual approval system for workflow suggestions ### Phase 4: Production Enhancement - **EXISTING**: Performance optimized using memory system capabilities - **NEW**: Add execution testing beyond existing pattern learning tests - **NEW**: Implement workflow execution analytics and reporting - **NEW**: Deploy unified workflow learning and execution system ## Success Metrics ### Learning Effectiveness - **90%** accuracy in workflow pattern recognition - **95%** success rate for learned workflows - **70%** reduction in execution time for repeated tasks - **85%** of multi-step tasks automated through learned workflows ### System Performance - **<5ms** overhead for workflow learning during tool execution - **<100ms** workflow lookup and matching using existing memory operations - **<200ms** workflow execution startup time - **No impact** on existing memory system performance ### User Experience - **80%** of users find workflow suggestions helpful - **60%** adoption rate for suggested workflows - **50%** of agents use learned workflows within 30 days - **95%** reliability score for workflow execution ## Risk Mitigation ### Technical Risks - **Integration complexity**: Minimized by using existing procedural memory infrastructure - **Performance impact**: Controlled through async learning and efficient memory queries - **Storage bloat**: Managed through existing memory decay and importance scoring ### Business Risks - **False workflow triggers**: High confidence thresholds prevent unwanted execution - **Workflow conflicts**: Clear priority system (user-submitted > auto-learned) - **Execution failures**: Graceful degradation and partial execution support ## Conclusion The Workflow Learning Service delivers intelligent automation by learning from successful tool execution patterns and enabling deterministic replay of complex workflows. By building on AgentDock's existing procedural memory infrastructure and proven user isolation patterns, the system provides: - **Automatic Learning** - Captures successful multi-step tool sequences without manual intervention - **Deterministic Execution** - Reliable replay of complex workflows with consistent results - **User Control** - Support for manually defined workflows with priority over auto-learned patterns - **Seamless Integration** - Uses existing memory system for storage with proven performance characteristics The service transforms agents from reactive tool users into proactive workflow executors, building institutional knowledge that improves over time while maintaining the flexibility and reliability that makes AgentDock powerful. ## AgentDock: Build Anything with AI Agents ## 🌐 README Translations [Français](/docs/i18n/french/README.md) • [日本語](/docs/i18n/japanese/README.md) • [한국어](/docs/i18n/korean/README.md) • [中文](/docs/i18n/chinese/README.md) • [Español](/docs/i18n/spanish/README.md) • [Italiano](/docs/i18n/italian/README.md) • [Nederlands](/docs/i18n/dutch/README.md) • [Deutsch](/docs/i18n/deutsch/README.md) • [Polski](/docs/i18n/polish/README.md) • [Türkçe](/docs/i18n/turkish/README.md) • [Українська](/docs/i18n/ukrainian/README.md) • [Ελληνικά](/docs/i18n/greek/README.md) • [Русский](/docs/i18n/russian/README.md) • [العربية](/docs/i18n/arabic/README.md) AgentDock is a framework for building sophisticated AI agents that deliver complex tasks with **configurable determinism**. It consists of two main components: 1. **AgentDock Core**: An open-source, backend-first framework for building and deploying AI agents. It's designed to be *framework-agnostic* and *provider-independent*, giving you complete control over your agent's implementation. 2. **Open Source Client**: A complete Next.js application that serves as a reference implementation and consumer of the AgentDock Core framework. You can see it in action at [https://hub.agentdock.ai](https://hub.agentdock.ai) Built with TypeScript, AgentDock emphasizes *simplicity*, *extensibility*, and ***configurable determinism*** - making it ideal for building reliable and predictable AI systems that can operate with minimal supervision. ## Design Principles AgentDock is built on these core principles: - **Simplicity First**: Minimal code required to create functional agents - **Node-Based Architecture**: All capabilities implemented as nodes - **Tools as Specialized Nodes**: Tools extend the node system for agent capabilities - ****Configurable Determinism****: Control the predictability of agent behavior - **Type Safety**: Comprehensive TypeScript types throughout ### Configurable Determinism ***Configurable determinism*** is a cornerstone of AgentDock's design philosophy, enabling you to balance creative AI capabilities with predictable system behavior: - AgentNodes are inherently non-deterministic as LLMs may generate different responses each time - Workflows can be made more deterministic through *defined tool execution paths* or by connecting sequences of deterministic nodes. - Developers can **control the level of determinism** by configuring which parts of the system use LLM inference versus defined logic. - Even with LLM components, the overall system behavior remains **predictable** through structured interactions and deterministic node execution where specified. - This balanced approach enables both *creativity* and **reliability** in your AI applications #### Deterministic Workflows AgentDock allows you to create fully deterministic processing flows where the execution path and outcomes are predictable. This can be achieved by implementing logic within individual tool nodes or by leveraging the core `BaseNode` architecture to connect multiple deterministic nodes (e.g., data processors, platform integrations): ```mermaid flowchart LR Input[Data Input] --> Prepare[Prepare Data] Prepare --> Process[Process Node] Process --> Database[(Database)] Process --> Format[Format Output] Format --> Output[Data Output] style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Output fill:#f9f9f9,stroke:#333,stroke-width:1px style Process fill:#d4f1f9,stroke:#333,stroke-width:1px style Prepare fill:#d4f1f9,stroke:#333,stroke-width:1px style Format fill:#d4f1f9,stroke:#333,stroke-width:1px style Database fill:#e8e8e8,stroke:#333,stroke-width:1px ``` #### Non-Deterministic Agent Behavior When using AgentNodes with LLMs, the specific outputs may vary, but the overall interaction patterns can be structured: ```mermaid flowchart TD Input[User Query] --> Agent[AgentNode] Agent -->|"LLM Reasoning (Non-Deterministic)"| ToolChoice{Tool Selection} ToolChoice -->|"Option A"| ToolA[Deep Research Tool] ToolChoice -->|"Option B"| ToolB[Data Analysis Tool] ToolChoice -->|"Option C"| ToolC[Direct Response] ToolA --> Response[Final Response] ToolB --> Response ToolC --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style ToolChoice fill:#ffdfba,stroke:#333,stroke-width:1px style ToolA fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolB fill:#d4f1f9,stroke:#333,stroke-width:1px style ToolC fill:#d4f1f9,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` #### Non-Deterministic Agents with Deterministic Sub-Workflows AgentDock gives you the ***best of both worlds*** by combining non-deterministic agent intelligence with deterministic workflow execution: ```mermaid flowchart TD Input[User Query] --> Agent[AgentNode] Agent -->|"LLM Reasoning (Non-Deterministic)"| FlowChoice{Sub-Workflow Selection} FlowChoice -->|"Decision A"| Flow1[Deterministic Workflow 1] FlowChoice -->|"Decision B"| Flow2[Deterministic Workflow 2] FlowChoice -->|"Decision C"| DirectResponse[Generate Response] Flow1 --> |"Step 1 → 2 → 3 → ... → 200"| Flow1Result[Workflow 1 Result] Flow2 --> |"Step 1 → 2 → 3 → ... → 100"| Flow2Result[Workflow 2 Result] Flow1Result --> Response[Final Response] Flow2Result --> Response DirectResponse --> Response style Input fill:#f9f9f9,stroke:#333,stroke-width:1px style Agent fill:#ffdfba,stroke:#333,stroke-width:1px style FlowChoice fill:#ffdfba,stroke:#333,stroke-width:1px style Flow1 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2 fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow1Result fill:#c9e4ca,stroke:#333,stroke-width:1px style Flow2Result fill:#c9e4ca,stroke:#333,stroke-width:1px style DirectResponse fill:#ffdfba,stroke:#333,stroke-width:1px style Response fill:#f9f9f9,stroke:#333,stroke-width:1px ``` This approach enables complex multi-step workflows (potentially involving hundreds of deterministic steps implemented within tools or as node sequences) to be invoked by intelligent agent decisions. While the open-source core provides the foundation for these workflows, [AgentDock Pro](agentdock-pro.md) aims to provide advanced tooling, such as visual builders, to simplify their creation and management. #### TL;DR on Configurable Determinism Think of it like driving. Sometimes you need the AI's creativity (like navigating city streets - non-deterministic), and sometimes you need reliable, step-by-step processes (like following highway signs - deterministic). AgentDock lets you build systems that use *both*, choosing the right approach for each part of a task. You get the AI's smarts *and* predictable results where needed. ## Core Architecture The framework is built around a powerful node-based system: - **BaseNode**: Foundation for all nodes, providing core functionality - **AgentNode**: Specialized node for LLM-powered agents - **Tools as Nodes**: Custom capabilities implemented as specialized nodes - **Node Registry**: Central system for managing and connecting nodes - **Session Management**: State isolation between concurrent conversations - **Orchestration Framework**: Context-aware control of agent behavior - **Evaluation Framework**: Provides tools for systematic agent assessment. Key components include: - `EvaluationRunner`: Orchestrates evaluation execution. - `Evaluators`: A suite of methods (RuleBased, LLMJudge, NLP, Lexical, ToolUsage) to measure different quality aspects. - `EvaluationCriteria`: Defines what to measure. - `EvaluationStorageProvider`: Persists results. Details in the [Evaluation Documentation](./evaluations/README.md). --- ## What You Can Build ### 1. AI-Powered Applications - Custom chatbots with any frontend - Command-line AI assistants - *Automated data processing* pipelines - Backend service integrations ### 2. Integration Capabilities - Any AI provider (OpenAI, Anthropic, etc.) - Any frontend framework - Any backend service - *Custom data sources* and APIs ### 3. Automation Systems - Data processing workflows - Document analysis pipelines - *Automated reporting* systems - Task automation agents ## Key Features | Feature | Description | |---------|-------------| | 🔌 **Framework Agnostic** | AgentDock Core works with *any tech stack* | | 🧩 **Modular Design** | Build complex systems from simple nodes | | 🛠️ **Extensible** | Create custom nodes for any functionality | | 🔒 **Secure** | Built-in security features for API keys and data | | 🔑 **BYOK** | Use your *own API keys* for LLM providers | | 📦 **Self-Contained** | Core framework has minimal dependencies | | ⚙️ **Multi-Step Tool Calls** | Support for *complex reasoning chains* | | 📊 **Structured Logging** | Detailed insights into agent execution | | 🛡️ **Robust Error Handling** | Predictable behavior and simplified debugging | | 📝 **TypeScript First** | Type safety and enhanced developer experience | | 🌐 **Open Source Client** | Complete Next.js reference implementation included | | 🔄 **Orchestration** | *Dynamic control* of agent behavior based on context | | 💾 **Session Management** | Isolated state for concurrent conversations | | 🎮 **Configurable Determinism** | Precise control over agent predictability | | 📊 **Evaluation Framework** | Robust tools to define, run, and analyze agent performance evaluations | ## Getting Started To start building with AgentDock, check out the [Getting Started](getting-started.md) guide, which will walk you through: - Setting up your development environment - Creating your first agent - Implementing custom tools - Deploying your agents For detailed documentation on specific aspects of AgentDock, explore the sections available in the documentation. --- ## 🔒 Security An initial security audit has been performed. See the [Initial Security Audit](./initial-security-audit.md) document for findings and recommendations. ## Contributing Community Agents AgentDock welcomes community contributions for new and interesting agents! This guide explains how to add your agent to the public `/agents` directory so it can be potentially featured in the Open Source Client and shared with others. ## Contribution Goal The `/agents` directory serves as a public repository of pre-configured agent templates. Contributing your agent here allows others to easily discover and use it with the Open Source Client or as inspiration for their own projects. ## Contribution Flow ```mermaid graph LR A(Create Agent Files) --> B(Create PR); B --> C(Review); C -- Approved --> D(Merged); C -- Changes? --> B; D --> E(Available!); ``` ## Steps to Contribute 1. **Create Your Agent Locally:** * Follow the steps outlined in the [Getting Started Guide](../getting-started.md#creating-your-first-agent) to create your agent. * This involves creating a new directory under `/agents//`. * Inside this directory, you **must** include: * `template.json`: The core configuration file defining your agent's LLM, prompt, tools, orchestration, etc. See [Agent Templates](../agent-templates.md) for details. * `README.md`: A clear description of your agent. 2. **Write a Great `README.md`:** * Clearly explain what your agent does and its intended purpose. * Provide example prompts or use cases. * List any required tools (especially custom ones). * Specify any necessary environment variables or API keys the user needs to provide (e.g., `SERPER_API_KEY` for search tools). * Keep it concise and well-formatted. 3. **Add Custom Tools (If Necessary):** * If your agent requires functionality not provided by existing tools, you may need to implement custom tools. * Custom tools are implemented as nodes within the `agentdock-core` framework, typically residing in `agentdock-core/src/nodes` (relative to the core package, often just `/src/nodes` if developing within the main repo). * Refer to the [Node System Overview](../nodes/README.md) and [Custom Tool Development](../nodes/custom-tool-development.md) guides for implementation details. * Ensure any custom tools included in your contribution are well-tested and follow project coding standards. 4. **Submit a Pull Request (PR):** * Fork the main AgentDock repository on GitHub. * Create a new branch for your agent contribution. * Add your agent directory (`/agents//`) and any custom node code (`/src/nodes/...` if applicable) to your branch. * Commit your changes with clear commit messages. * Push your branch to your fork. * Open a Pull Request against the main AgentDock repository. * In the PR description, briefly explain your agent and why it's a valuable addition. ## Acceptance Guidelines To increase the likelihood of your agent contribution being accepted: - **Clear Purpose:** The agent should have a well-defined and useful function. - **Quality README:** The `README.md` must be clear, comprehensive, and accurate. - **Well-Configured Template:** The `template.json` should be correctly formatted and define a sensible agent configuration. - **Functionality:** The agent should work as described (assuming the user provides necessary API keys). - **Uniqueness/Value:** The agent should offer something distinct or demonstrate an interesting use case or configuration pattern. Simple variations of existing agents might be less likely to be accepted unless they showcase a specific technique. - **Code Quality (for Custom Tools):** If custom tools/nodes are included, they must adhere to the project's coding standards, be reasonably tested, and be relevant to the agent's function. - **Clean PR:** The Pull Request should be focused, with clear commit history and a good description. We appreciate your contributions to the AgentDock community! ## RFA-001: AI Code Reviewer Agent ## 1. The Problem Manual code reviews are essential for maintaining code quality, but they are often time-consuming, inconsistent, and prone to human error. Reviewers can miss subtle bugs or security vulnerabilities, and feedback styles can vary widely. Developers spend significant time waiting for reviews or performing repetitive checks, slowing down the development cycle. ## 2. The Agent Solution An AI Code Reviewer agent built with AgentDock that automates the code review process. This agent will: - **Analyze Code:** Accept code snippets or links to code files/PRs (future enhancement). - **Identify Issues:** Detect common bugs, logic errors, performance bottlenecks, and potential security vulnerabilities (like SQL injection, XSS). - **Check Style & Best Practices:** Verify code against configurable style guides (e.g., PEP 8 for Python, standard JavaScript practices) and language-specific best practices. - **Suggest Improvements:** Offer concrete, actionable suggestions for refactoring, improving clarity, and enhancing performance. - **Explain Findings:** Clearly articulate the reasoning behind its suggestions, citing principles or potential consequences. - **Be Constructive:** Deliver feedback in a helpful, objective, and non-confrontational manner. ## 3. Proposed Architecture A clean and powerful implementation uses AgentDock to connect user input directly to a highly capable AI model for analysis. ```mermaid graph TD A[User Input: Code Snippet] --> B(AI Code Analysis); B -- "LLM Analysis & Review" --> C{Review Results}; C --> D[Output: Feedback & Suggestions]; style B fill:#ffdfba,stroke:#333,stroke-width:2px style C fill:#e8f5e9,stroke:#a5d6a7,stroke-width:1px ``` The core logic resides within the configured AI's ability to understand and critique code based on the provided personality and instructions. ## 4. Implementation Guide ### Recommended Nodes - **LLM Node (e.g., `llm.openai`, `llm.anthropic`, `llm.gemini`, `llm.groq`):** The heart of the agent. Choose a provider node corresponding to the AI service you want to use. - **Model Selection:** Crucially, select a **state-of-the-art large language model** known for exceptional performance on coding and code analysis tasks. Model capabilities evolve rapidly, so prioritize using the most advanced models available to you at the time of implementation. ### Example `template.json` Structure ```json { "version": "1.0", "agentId": "code-reviewer", "name": "AI Code Reviewer", "description": "Analyzes code for bugs, style issues, security vulnerabilities, and suggests improvements.", "tags": ["technical", "development", "code-quality", "productivity"], "personality": [ "You are an expert AI Code Reviewer. Your goal is to help developers write high-quality, secure, and maintainable code.", "Analyze the provided code snippet thoroughly.", "Identify potential bugs, style guide violations (mention the specific guide if possible, e.g., PEP 8), security risks, and areas for improvement (performance, readability).", "Provide clear, concise, and constructive feedback.", "For each issue found, explain *why* it's an issue and suggest a specific code improvement or alternative.", "If no major issues are found, confirm that and perhaps offer minor suggestions for best practices.", "Maintain a helpful, objective, and encouraging tone. Avoid overly critical language.", "Structure your review clearly, perhaps using bullet points or numbered lists for different issues.", "If the language isn't specified, try to infer it or ask the user." ], "nodes": [ "llm.openai" // Or your chosen provider node, e.g., "llm.anthropic" ], "nodeConfigurations": { "llm.openai": { // Adjust key based on chosen provider node "model": "YOUR_CHOSEN_STATE_OF_THE_ART_CODING_MODEL", // Specify the best model available to you "temperature": 0.3, // Lower temperature for more deterministic analysis "maxTokens": 4096 // Allow ample space for code and review } }, "chatSettings": { "historyPolicy": "lastN", "historyLength": 10, // Keep context of recent code/review interactions "initialMessages": [ "Hello! I'm the AI Code Reviewer. Please paste the code snippet you'd like me to review. If possible, mention the programming language." ], "chatPrompts": [ "Review this Python function for issues.", "Can you check this JavaScript code for security vulnerabilities?", "Analyze this code snippet and suggest improvements.", "Does this code follow standard best practices?" ] } } ``` ### Key Considerations - **Prompt Engineering:** The `personality` prompt is critical. It needs to guide the LLM to perform a comprehensive review and deliver feedback effectively. - **Model Choice:** Success heavily depends on using a frontier model with strong coding capabilities. - **Temperature:** Use a lower temperature (e.g., 0.2-0.5) for more factual and less creative code analysis. ## 5. Example Conversation **User:** Review this Python code please: ```python def process_data(data_list): results = [] for i in range(len(data_list)): item = data_list[i] if item['value'] > 10: results.append(item['name'] + " processed") return results data = [{'name': 'A', 'value': 5}, {'name': 'B', 'value': 15}, {'name': 'C', 'value': 20}] print(process_data(data)) ``` **Agent:** Okay, I've reviewed the Python code snippet. Here's my analysis: 1. **Iterating by Index:** The code iterates using `range(len(data_list))`. While functional, iterating directly over the list elements is generally considered more Pythonic and readable. * *Suggestion:* Use `for item in data_list:` instead. 2. **String Concatenation:** The line `results.append(item['name'] + " processed")` uses basic string concatenation. For more complex formatting or better readability, f-strings are preferred in modern Python (3.6+). * *Suggestion:* Use `results.append(f"{item['name']} processed")` 3. **Readability:** The code is quite clear, but the direct iteration suggested above would slightly improve it. No major bugs or security issues were detected in this snippet. Here's the revised code incorporating the suggestions: ```python def process_data(data_list): results = [] for item in data_list: # More Pythonic iteration if item['value'] > 10: results.append(f"{item['name']} processed") # Using f-string return results data = [{'name': 'A', 'value': 5}, {'name': 'B', 'value': 15}, {'name': 'C', 'value': 20}] print(process_data(data)) ``` This revised version is slightly cleaner and follows common Python idioms more closely. ## 6. Resources & Contributing - [AgentDock Core Documentation](/docs/) - [Agent Templates Guide](/docs/agent-templates) - [Contributing Agents Guide](/docs/rfa/add-agent) We encourage the community to build this agent! A robust AI Code Reviewer would be a valuable asset for any developer using AgentDock. Submit your implementation for a chance to be featured. ## Request For Agents (RFA) > Build powerful AI agents with AgentDock's node-based architecture ## What are Requests For Agents? Requests For Agents (RFAs) are specifications for AI agents that solve real-world problems using the AgentDock framework. Each RFA provides a clear problem statement, implementation guidance using AgentDock's node system, and resources to help you build an effective agent. ```mermaid graph LR A[Problem Statement] --> B[Agent Architecture] B --> C[Node Configuration] C --> D[Working Agent] style B fill:#e1f5fe,stroke:#81d4fa,stroke-width:2px style C fill:#e8f5e9,stroke:#a5d6a7,stroke-width:2px ``` ## Browse RFAs - [RFA-001: Code Reviewer Agent](/docs/rfa/agents/2025/April/001-code-reviewer) ## Why Build These Agents? - **Solve Real Problems**: Each agent addresses actual user needs - **Showcase Your Skills**: Implemented agents are featured in our showcase - **Join Our Community**: Connect with other builders - **Get Rewarded**: Selected implementations may receive special recognition - **Build Your Portfolio**: Create valuable systems with real-world impact ## For Non-Developers Not a developer? You can still create these agents without code using **AgentDock Pro** - our visual agent builder lets you implement any RFA through an intuitive drag-and-drop interface and natural language instructions. [Learn more about AgentDock Pro →](/docs/agentdock-pro) ## Roadmap This document outlines the planned features and future direction for AgentDock. Most improvements target the core AgentDock framework (`agentdock-core`), which is under active development and will be published as a versioned NPM package upon reaching a stable release. Some items may also involve the open-source client. ## Completed | Feature | Description | |---------|-------------| | [**Storage Abstraction Layer**] | ✅ Flexible storage system with 15 production-ready adapters | | [**Advanced Memory Systems**] | ✅ Four-layer cognitive architecture with PRIME extraction, hybrid search, and memory connections | | [**Vector Storage Integration**] | ✅ Embedding-based retrieval for documents and memory (PostgreSQL + pgvector, SQLite + sqlite-vec fully integrated) | ## In Progress | Feature | Description | |---------|-------------| | [**Evaluation for AI Agents**](./roadmap/evaluation-framework.md) | Comprehensive testing and evaluation framework | ## Planned | Feature | Description | |---------|-------------| | [**Platform Integration**](./roadmap/platform-integration.md) | Support for Telegram, WhatsApp, and other messaging platforms | | [**Multi-Agent Collaboration**](./roadmap/multi-agent-collaboration.md) | Enable agents to work together | | [**Model Context Protocol (MCP) Integration**](./roadmap/mcp-integration.md) | Support for discovering and using external tools via MCP | | [**Voice AI Agents**](./roadmap/voice-agents.md) | AI agents using voice interfaces and phone numbers via AgentNode | | [**Telemetry and Traceability**](./roadmap/telemetry.md) | Advanced logging and performance tracking | ## Advanced Agent Applications | Feature | Description | |---------|-------------| | [**Code Playground**](./roadmap/code-playground.md) | Sandboxed code generation and execution with rich visualization capabilities | ## Workflow System | Feature | Description | |---------|-------------| | [**Workflow Runtime & Nodes**](./roadmap/workflow-nodes.md) | Core runtime, node types, and orchestration logic for complex automations | ## Cloud Deployment | Feature | Description | |---------|-------------| | [**AgentDock Pro**](/docs/agentdock-pro) | Comprehensive enterprise cloud platform for scaling AI agents & workflows, with visual tools and autoscaling | | [**Natural Language AI Agent Builder**](./roadmap/nl-agent-builder.md) | Visual builder + natural language agent and workflow construction | | [**Agent Marketplace**](./roadmap/agent-marketplace.md) | Monetizable agent templates | ## Open Source Client Enhancements - Improved UI/UX for agent management and chat. - Enhanced visualization for orchestration steps. - More robust BYOK (Bring Your Own Key) management. - Multi-modal input/output support (beyond basic image generation). - Example implementations for multi-threading/background tasks (where applicable in Next.js). - Exploration of patterns for multi-tenancy support within the client architecture. ## Community & Ecosystem - Grow the library of community-contributed agents. - Develop more example projects and tutorials. - Establish clearer contribution guidelines. ## AgentDock Repository Improvements - Complete test suite (Unit, Integration, E2E). - Expand core capabilities with workflow node types and runtime enhancements. *This roadmap is indicative and subject to change.* ## Agent Marketplace The Agent Marketplace enables creators to publish, distribute, and monetize their AI agent templates and workflows, while helping users discover high-quality solutions tailored to their needs. ## Current Status **Status: Planned** The Agent Marketplace is currently in the design phase, with implementation planned to follow the Natural Language AI Agent Builder. ## Feature Overview The Agent Marketplace will provide: - **Template Publishing**: Publish agent templates and workflows for others to use - **Perpetual Revenue**: Earn ongoing revenue when others use your templates - **Discovery System**: Find the right templates for specific use cases - **Quality Ratings**: Community-driven rating and feedback system - **Version Management**: Update templates while maintaining backward compatibility - **Integration with NL Builder**: Seamless connection with the Natural Language AI Agent Builder ## Architecture Diagrams ### Marketplace Ecosystem ```mermaid graph TD Creator[Template Creator] -->|Publishes| Marketplace[Agent Marketplace] Marketplace -->|Monetizes| Creator User[End User] -->|Discovers| Marketplace Marketplace -->|Provides| User User -->|Rates & Reviews| Marketplace Marketplace -->|Suggests| NLBuilder[Natural Language Builder] NLBuilder -->|Creates From| Marketplace style Marketplace fill:#0066cc,color:#ffffff,stroke:#0033cc style NLBuilder fill:#e6f2ff,stroke:#99ccff ``` ### Publication Workflow ```mermaid sequenceDiagram participant Creator participant Marketplace participant Verification participant Store Creator->>Marketplace: Submit Template Marketplace->>Verification: Quality Check Verification->>Marketplace: Approval Marketplace->>Store: Publish Store->>Creator: Setup Revenue Share Creator->>Store: Update/Version ``` ## Implementation Details The Agent Marketplace will be implemented through: ### 1. Template Publishing System The system allows creators to prepare and publish their templates: - **Metadata Creation**: Add descriptions, categories, and usage examples - **Version Management**: Control updates while maintaining compatibility - **Documentation Tools**: Provide clear usage instructions for consumers - **Analytics Dashboard**: Monitor usage and earnings ### 2. Discovery Engine The discovery engine helps users find the right templates: - **Smart Search**: Natural language search for template discovery - **Category Navigation**: Browse by use case, industry, or function - **Recommendation System**: AI-powered suggestions based on user needs - **Similar Templates**: Find alternatives to compare functionality - **Filter System**: Narrow results by features, ratings, or popularity ### 3. Monetization Framework The monetization framework enables creators to earn from their work: - **Revenue Share Model**: Earn a percentage of usage fees - **Usage Tracking**: Transparent accounting of template usage - **Flexible Pricing**: Set pricing tiers based on features or volume - **Promotion Tools**: Highlight your templates to potential users - **Usage Analytics**: Understand how your templates are being used ## Benefits to the Ecosystem ### For Template Creators ```mermaid graph LR A[Create Once] --> B[Earn Repeatedly] B --> C[Build Reputation] C --> D[Improve Templates] D --> B style A fill:#e6f2ff,stroke:#99ccff style B fill:#0066cc,color:#ffffff,stroke:#0033cc ``` 1. **Monetize Expertise**: Turn specialized knowledge into recurring revenue 2. **Reach Users**: Access a broader audience than possible independently 3. **Focus on Quality**: Incentive to create better templates for higher earnings 4. **Build Reputation**: Establish yourself as an expert in specific domains 5. **Feedback Loop**: Gain insights from real-world usage to improve offerings ### For End Users ```mermaid graph LR A[Discover Solutions] --> B[Immediate Value] B --> C[Customization] C --> D[Business Results] style B fill:#e6f2ff,stroke:#99ccff style D fill:#0066cc,color:#ffffff,stroke:#0033cc ``` 1. **Specialized Solutions**: Access templates built by domain experts 2. **Time Savings**: Skip building agents from scratch 3. **Quality Assurance**: Use templates vetted by the community 4. **Customization Options**: Adapt templates to specific needs 5. **Consistent Updates**: Benefit from ongoing improvements by creators ### For AgentDock Platform 1. **Expanded Ecosystem**: Growing library of specialized templates 2. **Network Effects**: More creators attract more users and vice versa 3. **Quality Incentives**: Economic rewards for the best templates 4. **Discoverability Solution**: Address the challenge of finding the right agent for specific needs 5. **Ecosystem Growth**: Sustainable model for continuous expansion ## Solving the Discoverability Challenge A key challenge in AI agent ecosystems is helping users find the right agent for their specific needs: ```mermaid graph TD A[Discoverability Challenge] --> B[User Need] B --> C{Agent Marketplace} C -->|Search| D[Natural Language Query] C -->|Browse| E[Categories & Tags] C -->|Analyze| F[Pattern Recognition] D --> G[Relevant Templates] E --> G F --> G G --> H[Value Creation] style C fill:#0066cc,color:#ffffff,stroke:#0033cc ``` The Agent Marketplace addresses this challenge by: 1. **Natural Language Understanding**: Converting user needs into relevant template suggestions 2. **Pattern Analysis**: Identifying which templates work best for specific use cases 3. **Community Curation**: Leveraging ratings and reviews to surface quality options 4. **Usage Analytics**: Understanding which templates deliver results in real-world scenarios 5. **Integration with Builder**: Suggesting templates during natural language agent creation ## Example User Journey ### Template Creator An HR specialist creates an "Employee Onboarding Assistant" template that handles document collection, policy explanations, and IT setup requests. After publishing to the marketplace: 1. The template is discovered by HR departments across multiple organizations 2. Each usage generates revenue for the creator 3. Feedback helps the creator improve the template over time 4. The creator builds a reputation as an HR automation expert 5. The creator develops additional HR templates based on market demand ### Template User A small business owner needs to automate customer support: 1. Searches the marketplace for "customer support automation" 2. Discovers several templates with ratings and reviews 3. Selects a template that matches their specific needs 4. Customizes the template slightly for their brand voice 5. Deploys a production-ready customer support agent in minutes 6. The original template creator receives compensation ## Integration with Natural Language AI Agent Builder The Marketplace and NL Builder work together to enhance the agent creation process: ```mermaid graph TD A[User Description] --> B[NL Builder] B --> C{Pattern Match?} C -->|Yes| D[Suggest Templates] C -->|No| E[Custom Generation] D --> F[Template Selection] F --> G[Customization] E --> G G --> H[Final Agent] style B fill:#e6f2ff,stroke:#99ccff style D fill:#0066cc,color:#ffffff,stroke:#0033cc ``` When a user describes an agent they want to create: 1. The Natural Language Builder analyzes the description 2. Pattern matching identifies relevant marketplace templates 3. The user is offered template suggestions as starting points 4. The user can choose a template and customize it or create a custom solution 5. Template creators earn revenue when their templates are selected ## Timeline | Phase | Description | |-------|-------------| | Design | Create marketplace architecture and economic model | | Alpha | Limited template publishing with manual curation | | Beta | Public template submissions with automated quality checks | | Launch | Full monetization and integration with Natural Language Builder | | Expansion | Advanced analytics and promotional tools for creators | ## Connection to Other Roadmap Items - **Natural Language AI Agent Builder**: Direct integration for template suggestions - **AgentDock Pro**: Enterprise marketplace features and private template repositories - **Multi-Agent Collaboration**: Templates for agent networks and team compositions - **Evaluation Framework**: Quality metrics for marketplace templates ## Code Playground The Code Playground enables AI agents to generate, execute, and visualize code directly within the chat interface, providing a seamless environment for coding, debugging, and demonstration. ## Current Status **Status: Planned** The Code Playground is currently in the design phase, with implementation planned for both OSS and Pro versions. ## Feature Overview The Code Playground will provide: - **In-Chat Code Generation**: Create runnable code directly in agent responses - **Interactive Execution**: Run code and see results without leaving the chat - **Sandboxed Environment**: Secure code execution in an isolated environment - **Multi-Language Support**: JavaScript, TypeScript, Python, and more - **Visual Rendering**: Display charts, tables, and rich visualizations - **Debugging Tools**: Error highlighting and troubleshooting assistance - **Version Control**: Track code changes throughout the conversation - **Custom Node Builder**: Create custom integration nodes for extending platform capabilities ## Architecture Diagrams ### User Experience Flow ```mermaid graph TD A[User Query] --> B[AI Agent] B --> C[Response with Code] C --> D[Code Detection] D --> E[Split View Interface] E --> F[Code Editor] F --> G[Sandbox Execution] G --> H[Results Display] H --> B style B fill:#0066cc,color:#ffffff,stroke:#0033cc style G fill:#e6f2ff,stroke:#99ccff ``` ### System Architecture ```mermaid graph TD A[Chat Interface] --> B[Code Detection] B --> C[Code Parser] C --> D[Editor Integration] D --> E[Sandbox Environment] E --> F[Execution Engine] F --> G[Results Renderer] G --> A subgraph "Core Components" B C end subgraph "UI Components" A D G end subgraph "Execution Layer" E F end style C fill:#0066cc,color:#ffffff,stroke:#0033cc style E fill:#0066cc,color:#ffffff,stroke:#0033cc ``` ## Implementation Details The Code Playground will be implemented through: ### 1. Core Components Code execution and parsing nodes will be added to the AgentDock core: ```typescript // CodeExecutionNode provides secure code execution class CodeExecutionNode extends BaseNode { async execute({ code, language, timeout = 5000 }) { // Execute code in sandbox environment // Return results with output/error } } // CodeParsingNode extracts code blocks from text class CodeParsingNode extends BaseNode { async execute({ text }) { // Parse code blocks from text // Return segmented content } } ``` ### 2. Sandbox Integration The Sandbox provides secure code execution using Sandpack: - **Isolated Environment**: Code runs in a secure iframe - **Resource Limits**: Prevents infinite loops and excessive resource usage - **Multiple Languages**: Supports JavaScript, TypeScript, Python, and more - **Dependency Management**: Enables the use of common libraries and frameworks ### 3. UI Implementation The UI enables seamless code interaction: - **Split View Interface**: Chat and code side-by-side - **Code Editor**: Syntax highlighting and autocomplete - **Results Panel**: Display execution output and visualizations - **Error Handling**: Highlight errors and suggestions for fixing - **Visual Controls**: Run, reset, and version control buttons ## Custom Node Builder A key feature of the Code Playground in AgentDock Pro is the ability to create custom integration nodes, expanding platform capabilities: ```mermaid graph TD A[Code Playground] --> B[Custom Node Builder] B --> C[Node Definition] C --> D[Code Implementation] D --> E[Testing Environment] E --> F[Node Registry] F --> G[Workflow Integration] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style F fill:#e6f2ff,stroke:#99ccff ``` ### Creating Custom Integrations The Custom Node Builder empowers users to: 1. **Build Service Connectors**: Create nodes that connect to any third-party API or service 2. **Define Custom Logic**: Implement specialized business logic for unique use cases 3. **Extend Platform Capabilities**: Add functionality not available in built-in nodes 4. **Develop Organization-Specific Tools**: Create private integrations for internal systems ### Implementation Process ```typescript // Example of a custom integration node created in the Code Playground export class CustomAPINode extends BaseNode { static nodeDefinition = { nodeType: 'custom-api-connector', title: 'My Custom API', description: 'Connects to my organization's API', paramSchema: CustomAPISchema }; async execute(params) { // Connection to custom API // Data transformation // Error handling return processedResults; } } ``` ### Key Benefits - **No External Development Environment**: Build, test, and deploy custom nodes entirely within AgentDock - **Immediate Testing**: Test custom nodes with real data in the sandbox environment - **Simplified Deployment**: Register nodes directly to your workspace - **Version Control**: Track changes and manage versions of custom nodes - **Sharing**: Share custom nodes within your organization or publish to the marketplace ## Use Cases ### 1. Interactive Tutorials Create step-by-step coding tutorials with executable examples: ```mermaid graph LR A[Instruction] --> B[Code Example] B --> C[User Execution] C --> D[Feedback] D --> E[Next Lesson] style B fill:#e6f2ff,stroke:#99ccff ``` ### 2. Data Analysis Analyze data with code execution and visualization: ```mermaid graph TD A[Data Input] --> B[Analysis Code] B --> C[Execution] C --> D[Visualization] D --> E[Insight Generation] style B fill:#e6f2ff,stroke:#99ccff style D fill:#e6f2ff,stroke:#99ccff ``` ### 3. Algorithm Demonstration Explain algorithms with interactive demonstrations: ```mermaid graph TD A[Problem Description] --> B[Algorithm Code] B --> C[User Interaction] C --> D[Step-by-Step Execution] D --> E[Visual Representation] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style E fill:#e6f2ff,stroke:#99ccff ``` ### 4. Custom Integration Development Build and test specialized integration nodes: ```mermaid graph TD A[Integration Need] --> B[Node Template] B --> C[API Integration Code] C --> D[Sandbox Testing] D -->|Refine| C D -->|Complete| E[Deployment to Workflows] style C fill:#0066cc,color:#ffffff,stroke:#0033cc style E fill:#e6f2ff,stroke:#99ccff ``` ## Security Considerations The Code Playground implements several security measures: 1. **Sandboxed Execution**: All code runs in an isolated environment 2. **Resource Limits**: Execution is constrained by time and memory limits 3. **Restricted Access**: No file system or network access by default 4. **Input Validation**: Code is validated before execution 5. **Output Sanitization**: Results are sanitized before display 6. **Permission Controls**: Custom node capabilities restricted by user permissions ## Integration with AgentDock The Code Playground integrates with the existing AgentDock architecture: 1. **Node Integration**: Added as specialized nodes in the NodeRegistry 2. **Agent Template**: Specialized template for code-focused agents 3. **UI Enhancement**: Enhanced chat interface with code detection and rendering 4. **Tool System**: Available as tools for any AgentNode 5. **Custom Node Registry**: Manages and tracks user-created integration nodes ## Timeline | Phase | Description | |-------|-------------| | Design | System architecture and component definitions | | Core Implementation | Build code execution and parsing nodes | | Sandbox Integration | Implement secure code execution environment | | UI Development | Create enhanced chat interface with code execution | | Language Support | Add support for additional programming languages | | Rich Visualization | Implement data visualization capabilities | | Custom Node Builder | Develop tooling for creating custom integrations | ## Benefits 1. **Immediate Execution**: Run code examples directly within the chat 2. **Enhanced Learning**: Interactive coding tutorials and demonstrations 3. **Improved Troubleshooting**: Debug issues with direct code execution 4. **Rapid Prototyping**: Test code snippets quickly in conversation 5. **Live Visualization**: See data and algorithm visualizations in real-time 6. **Platform Extension**: Build custom nodes for specific integration needs 7. **Unified Development**: Create, test, and deploy integrations in one environment ## Connection to Other Roadmap Items - **Evaluation Framework**: Integrates for code quality and performance assessment - **Natural Language AI Agent Builder**: Can generate code-focused agents - **Agent Marketplace**: Enable sharing of code-focused agent templates and custom nodes - **AgentDock Pro**: Enhanced features for collaborative code execution and custom integration development ## Agent Evaluation Framework The Agent Evaluation Framework provides tools for measuring and improving agent performance, ensuring consistent quality across different use cases. ## Current Status **Status: Phase 1 Implemented** Phase 1 of the custom AgentDock Core Evaluation Framework has been implemented. This includes the core runner, evaluator interface, storage provider concept, and a suite of initial evaluators (RuleBased, LLMJudge, NLPAccuracy, ToolUsage, Lexical Suite). ## Overview The framework offers: - **Extensible Architecture**: Based on a core `Evaluator` interface. - **Suite of Built-in Evaluators**: Covering rule-based checks, LLM-as-judge, semantic similarity, tool usage, and lexical analysis. - **Configurable Runs**: Using `EvaluationRunConfig` to select evaluators and criteria. - **Aggregated Results**: Providing detailed outputs with scores, reasoning, and metadata. - **Optional Persistence**: Basic file-based logging (`JsonFileStorageProvider`) implemented, with potential for future integration with a Storage Abstraction Layer. ## Architecture (Phase 1 Implementation) ```mermaid graph TD A[EvaluationInput] --> ER[EvaluationRunner] ARC[EvaluationRunConfig] --> ER subgraph InputComponents A_crit[Criteria] --> A A_resp[Response] --> A A_prom[Prompt] --> A end subgraph ConfigComponents ARC_conf[Evaluator Configs] --> ARC ARC_store[Storage] --> ARC end ER -- uses --> E[Evaluator Interface] E -- produces --> RES[Result] ER -- aggregates --> AGG[Aggregated Results] RES --> AGG subgraph Evaluators RB[RuleBased] -. implements .-> E LLM[LLMJudge] -. implements .-> E NLP[NLPAccuracy] -. implements .-> E end style ER fill:#f9f,stroke:#333,stroke-width:2px style E fill:#ccf,stroke:#333,stroke-width:2px style AGG fill:#9f9,stroke:#333,stroke-width:2px ``` ## Implementation Options A **Custom Implementation** within AgentDock Core was chosen and developed for Phase 1. This provides: - Full control over the evaluation process. - Tight integration with AgentDock types (`AgentMessage`, etc.). - Specific evaluators tailored to agent use cases (e.g., `ToolUsageEvaluator`). - An extensible base for future enhancements. Third-party integrations were deferred to allow for a bespoke foundation matching AgentDock's architecture. ## Key Components (Phase 1) * **`EvaluationInput`**: Data packet including response, prompt, history, ground truth, context, criteria. * **`EvaluationCriteria`**: Defines metrics with name, description, scale, and optional weight. * **`Evaluator` Interface**: Core extensibility point (`type`, `evaluate` method). * **`EvaluationResult`**: Output per criterion (score, reasoning, type). * **`EvaluationRunConfig`**: Specifies evaluators, their configs, optional storage provider, metadata. * **`EvaluationRunner`**: Orchestrates the run via `runEvaluation` function. * **`AggregatedEvaluationResult`**: Final combined output with overall score (if applicable), individual results, snapshots. * **`JsonFileStorageProvider`**: Basic implementation for server-side result logging. ## Key Features (Phase 1) * **Rule-Based Checks**: Length, includes, regex, JSON validity. * **LLM-as-Judge**: Qualitative assessment via LLM call with templating. * **Semantic Similarity**: Cosine similarity using pluggable embedding models (default provided). * **Tool Usage Validation**: Checks tool calls, arguments against expectations. * **Lexical Analysis**: Similarity (Levenshtein, Dice, etc.), keyword coverage, sentiment (VADER), toxicity (blocklist). * **Flexible Input Sourcing**: Evaluators can pull text from `response`, `prompt`, `groundTruth`, or nested `context` fields. * **Score Normalization & Aggregation**: Runner attempts to normalize scores to 0-1 and calculate weighted average. * **Basic Persistence**: Optional JSONL file logging. * **Comprehensive Unit Tests**: Added for core components and evaluators. ## Benefits (Achieved in Phase 1) 1. **Foundational Quality Assurance**: Basic framework for consistent checks. 2. **Extensible Base**: Custom evaluators can be built. 3. **Initial Benchmarking**: Enables comparison of runs via results. 4. **Concrete Metrics**: Moves beyond subjective assessment for core areas. ## Timeline | Phase | Status | Description | |-------|--------|-------------| | ~~Approach Evaluation~~ | ~~In Progress~~ Completed | ~~Comparing third-party vs. custom solutions~~ Custom solution chosen. | | ~~Architecture Design~~ | ~~Planned~~ Completed | Phase 1 architecture designed and implemented. | | Core Implementation | **Completed (Phase 1)** | Basic framework, runner, interface, initial evaluators, storage provider implemented. | | **Phase 2 / Advanced Features** | **Planned** | See PRD for details (e.g., Advanced evaluator configs, UI integration, enhanced storage, etc.). | ## Use Cases ### Agent Development Apply evaluations during development to iteratively improve quality: ```mermaid flowchart LR A[Agent Implementation] --> B[Test Cases/EvaluationInput] B --> C[runEvaluation] C --> D[AggregatedEvaluationResult] D --> E[Analyze Results] E --> F[Agent Refinement] F --> A style C fill:#0066cc,color:#ffffff,stroke:#0033cc style D fill:#e6f2ff,stroke:#99ccff ``` The implemented Phase 1 framework provides the core capabilities for this loop. Refer to the [Evaluation Framework PRD](../prd/evaluation-framework.md) for detailed usage and Phase 2 plans. ## HTTP Adapter Framework Abstraction **Status**: Critical Prerequisite **Priority**: Urgent **Complexity**: Medium ## Overview HTTP adapters provide framework-agnostic HTTP handling for AgentDock Core, enabling a single codebase to work across different HTTP frameworks like NextJS, Hono, Express, and others. This eliminates code duplication and creates the foundation for Platform Integration. ## Current Blocker The open source client contains NextJS-specific logic that must be duplicated for each framework. Without HTTP adapters: - Developers using Hono, Express, or other frameworks must rewrite all HTTP handling logic - Platform Integration (Telegram, WhatsApp, Slack) cannot be implemented - Each new framework deployment requires custom implementations ## Architecture ### Component Structure ``` agentdock-core/src/ ├── adapters/ │ ├── index.ts │ └── http/ │ ├── index.ts # HTTP adapter exports │ ├── base.ts # Base interfaces │ ├── factory.ts # createHTTPAdapter() │ ├── nextjs.ts # NextJS implementation │ ├── hono.ts # Hono implementation │ └── express.ts # Express implementation ``` ### Core Interface ```typescript // Parsed request in framework-agnostic format interface ParsedHTTPRequest { messages: Message[]; agentId: string; sessionId?: string; apiKey?: string; headers: Record; params: Record; body: any; } // Base adapter interface interface HTTPAdapter { parseRequest(request: any): Promise; createStreamResponse(stream: ReadableStream): any; createErrorResponse(error: Error): any; createSuccessResponse(data?: any): any; } ``` ### Factory Function ```typescript export function createHTTPAdapter(type: 'nextjs' | 'hono' | 'express'): HTTPAdapter { switch (type) { case 'nextjs': return new NextJSAdapter(); case 'hono': return new HonoAdapter(); case 'express': return new ExpressAdapter(); } } ``` ## Implementation Plan ### Phase 1: Core Infrastructure - Base interfaces and types - Factory system with adapter registry - Generic HTTP adapter for fallback ### Phase 2: Framework Adapters - NextJS adapter (handle NextRequest/NextResponse) - Hono adapter (handle Context objects) - Express adapter (handle Request/Response) ### Phase 3: Agent Integration - Unified processing pipeline - Integration with AgentNode.handleMessage() - Session and orchestration manager support ### Phase 4: Testing & Migration - Comprehensive testing suite - Open source client migration - Documentation and examples ## Usage Examples ### Open Source Client (Before) ```typescript // src/app/api/chat/[agentId]/route.ts - 120+ lines export async function POST(request: NextRequest) { const body = await request.json(); const agentId = request.nextUrl.pathname.split('/')[3]; // ... complex NextJS-specific logic const agent = new AgentNode(agentId, config); const result = await agent.handleMessage(options); return new Response(result.fullStream); } ``` ### Open Source Client (After) ```typescript // src/app/api/chat/[agentId]/route.ts - 5 lines export async function POST(request: NextRequest) { const adapter = createHTTPAdapter('nextjs'); return processAgentHTTPRequest(adapter, request, { fallbackApiKey: process.env.FALLBACK_API_KEY }); } ``` ### Other Framework Deployments (New) ```typescript // Hono route using same core logic app.post('/chat/:agentId', async (c) => { const adapter = createHTTPAdapter('hono'); return processAgentHTTPRequest(adapter, c, { fallbackApiKey: process.env.FALLBACK_API_KEY }); }); // Express route using same core logic app.post('/chat/:agentId', async (req, res) => { const adapter = createHTTPAdapter('express'); return processAgentHTTPRequest(adapter, { req, res }); }); ``` ## Integration Details ### Unified Processing Pipeline ```typescript export async function processAgentHTTPRequest( adapter: HTTPAdapter, request: any, options?: { fallbackApiKey?: string } ) { // Parse request using framework adapter const parsed = await adapter.parseRequest(request); // Load agent configuration const agentConfig = await loadAgentConfig(parsed.agentId); // Initialize orchestration const orchestrationManager = getOrchestrationManagerInstance(); await orchestrationManager.ensureStateExists(parsed.sessionId); // Create and run agent const agent = new AgentNode(parsed.agentId, { agentConfig, apiKey: parsed.apiKey || options?.fallbackApiKey, provider: agentConfig.provider }); const result = await agent.handleMessage({ messages: parsed.messages, sessionId: parsed.sessionId, orchestrationManager }); return adapter.createStreamResponse(result.fullStream); } ``` ### Framework Implementations **NextJS Adapter:** ```typescript export class NextJSAdapter implements HTTPAdapter { async parseRequest(request: NextRequest): Promise { const body = await request.json(); return { messages: body.messages || [], agentId: request.nextUrl.pathname.split('/').pop() || '', sessionId: body.sessionId, apiKey: request.headers.get('x-api-key') || undefined, headers: Object.fromEntries(request.headers.entries()), params: {}, body }; } createStreamResponse(stream: ReadableStream): Response { return new Response(stream, { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-cache' } }); } } ``` **Hono Adapter:** ```typescript export class HonoAdapter implements HTTPAdapter { async parseRequest(c: Context): Promise { const body = await c.req.json(); return { messages: body.messages || [], agentId: c.req.param('agentId') || '', sessionId: body.sessionId, apiKey: c.req.header('x-api-key'), headers: Object.fromEntries(c.req.raw.headers.entries()), params: c.req.param(), body }; } createStreamResponse(stream: ReadableStream): Response { return new Response(stream, { headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-cache' } }); } } ``` ## Migration Impact ### Open Source Client Changes **Files to Remove:** - `src/lib/agent-adapter.ts` (logic moves to agentdock-core) - `src/lib/orchestration-adapter.ts` (logic moves to agentdock-core) **Files to Update:** - `src/app/api/chat/[agentId]/route.ts` (simplified to 5 lines) - Any remaining imports from removed files **New Capabilities:** - Foundation for platform webhook routes - Consistent behavior across frameworks - Easier testing and debugging ### Framework Flexibility Benefits **Before HTTP Adapters:** - Must rewrite all NextJS logic for each framework - Different error handling and response formats - Separate maintenance burden per framework **After HTTP Adapters:** - Direct reuse of core logic across all frameworks - Identical behavior and error handling - Single codebase works everywhere ## Dependencies ### Blocks These Features - **Platform Integration** - Cannot implement Telegram/WhatsApp/Slack webhooks - **Voice AI Agents** - Requires webhook handling for phone integrations - **Alternative Frameworks** - Hono, Express, and other deployments need abstraction ### Required By These Use Cases - **Platform Integration** - Foundation for webhook handling - **Framework Flexibility** - Support for Hono, Express, and other frameworks - **Open Source Maintenance** - Simplified route updates ## Technical Requirements ### Must Support - Streaming responses for agent messages - Session management integration - Orchestration state handling - Error response formatting - CORS configuration - Header management ### Performance Targets - Zero latency overhead vs current implementation - Memory usage identical to current NextJS routes - Support for concurrent requests ### Compatibility - NextJS 14+ (current open source client) - Hono (for developers preferring Hono) - Express 4+ (for developers preferring Express) - Node.js runtime support ## Success Criteria ### Code Metrics - 80% reduction in framework-specific HTTP code - Single implementation supports 3+ frameworks - 95% test coverage for all adapters ### Development Velocity - New framework support becomes trivial - Platform webhook implementation unblocked - Alternative framework deployments enabled ### Maintenance Benefits - HTTP bugs fixed once, applied everywhere - Consistent error handling across platforms - Unified testing strategy ## Risk Mitigation ### Performance Risk - **Concern**: Additional abstraction layer - **Mitigation**: Benchmark against current implementation - **Fallback**: Direct framework integration if needed ### Compatibility Risk - **Concern**: Framework version changes - **Mitigation**: Comprehensive test suite with CI/CD - **Fallback**: Quick adapter updates ### Migration Risk - **Concern**: Open source client disruption - **Mitigation**: Gradual rollout with extensive testing - **Fallback**: Immediate rollback capability ## Implementation Checklist ### Phase 1: Core Infrastructure - [ ] Create `adapters/http/base.ts` with interfaces - [ ] Implement factory function and registry - [ ] Add comprehensive TypeScript types - [ ] Create generic adapter fallback ### Phase 2: Framework Adapters - [ ] NextJS adapter with streaming support - [ ] Hono adapter with Context handling - [ ] Express adapter with middleware support - [ ] Adapter-specific error handling ### Phase 3: Integration - [ ] Unified `processAgentHTTPRequest()` function - [ ] Session manager integration - [ ] Orchestration manager integration - [ ] Error handling and logging ### Phase 4: Testing & Migration - [ ] Unit tests for all adapters - [ ] Integration tests with AgentDock Core - [ ] Open source client migration - [ ] Documentation and examples ## Model Context Protocol (MCP) Integration ## Status: Planned ## Overview AgentDock Core will integrate the Model Context Protocol (MCP) to enable standardized tool discovery and execution across different AI agents and services. This integration will allow AgentDock agents to leverage external tools while maintaining our core architecture principles. ## Architecture ```mermaid graph TD A[AgentDock Core] --> B[MCP Client Layer] B --> C[Vercel AI SDK] C --> D[External MCP Servers] subgraph "Core Components" E[AgentNode] F[Tool Registry] G[MCP Tool Factory] end A --> E E --> F F --> G G --> B style A fill:#b3e6ff,stroke:#006699 style B fill:#ffe6b3,stroke:#cc8800 style C fill:#d9f2d9,stroke:#006600 style D fill:#ffcccc,stroke:#990000 ``` ## Implementation Strategy ### Phase 1: Core MCP Client Integration 1. **MCP Client Layer** - Utilize Vercel AI SDK's built-in MCP client capabilities - Create a standardized interface for tool discovery and execution - Maintain compatibility with existing node-based architecture 2. **Tool Registry Integration** ```typescript interface MCPToolConfig { transport: { type: 'stdio' | 'sse'; command?: string; args?: string[]; url?: string; }; schemas?: Record; } ``` 3. **Agent Configuration** ```json { "nodes": ["llm.anthropic", "mcp.cursor"], "nodeConfigurations": { "llm.anthropic": { "model": "gpt-4.1" }, "mcp.cursor": { "transport": { "type": "stdio", "command": "cursor-tools" } } } } ``` ### Tool Discovery Flow ```mermaid sequenceDiagram participant Agent as AgentNode participant Registry as Tool Registry participant MCP as MCP Client participant Server as External Server Agent->>Registry: Request tools Registry->>MCP: Initialize client MCP->>Server: Discover tools Server-->>MCP: Tool schemas MCP-->>Registry: Register tools Registry-->>Agent: Available tools ``` ## Core Features 1. **Dynamic Tool Discovery** - Automatic tool registration from MCP servers - Schema validation for tool inputs/outputs - Runtime tool availability checks 2. **Transport Layer Support** - Standard I/O for local tools - Server-Sent Events (SSE) for remote tools - Extensible transport system 3. **Error Handling** - Graceful fallbacks for unavailable tools - Clear error messages for configuration issues - Connection retry mechanisms ## Usage Examples ### Local Tool Integration ```typescript // Example: Using Cursor Tools via MCP const config = { transport: { type: 'stdio', command: 'cursor-tools', args: ['browser', 'open'] } }; await agent.registerMCPTools(config); ``` ### Remote Tool Integration ```typescript // Example: Using Remote MCP Server const config = { transport: { type: 'sse', url: 'https://mcp-server.example.com/sse' }, schemas: { 'get-weather': { parameters: { location: { type: 'string' } } } } }; await agent.registerMCPTools(config); ``` ## Security Considerations 1. **Tool Validation** - Schema validation for all tool inputs - Sanitization of command arguments - Resource usage limits 2. **Transport Security** - TLS for remote connections - Local tool execution sandboxing - Access control for sensitive operations ## Future Enhancements 1. **Tool Caching** - Cache tool schemas for faster startup - Periodic schema refresh - Offline mode support 2. **Advanced Features** - Tool composition and chaining - Custom transport layers - Enhanced error recovery ## Pro Features Preview AgentDock Pro will extend the MCP integration with advanced capabilities: ```mermaid graph TD A[AgentDock Pro] --> B[MCP Client] A --> C[MCP Server] subgraph "Client Capabilities" B --> D[External Tools] B --> E[Remote Services] end subgraph "Server Capabilities" C --> F[Workflow Exposure] C --> G[Resource Management] end style A fill:#b3e6ff,stroke:#006699 style B fill:#ffe6b3,stroke:#cc8800 style C fill:#d9f2d9,stroke:#006600 ``` - **Dual-Role Architecture**: Function as both MCP client and server - **Workflow Exposure**: Share workflows as MCP resources - **Enhanced Resource Management**: Advanced control over exposed capabilities - **Cross-Workflow Integration**: Compose workflows using MCP protocol *(More details coming soon in Pro documentation)* ## Development Timeline 1. **Phase 1: Core Integration** (Current) - [x] Design architecture - [ ] Implement MCP client layer - [ ] Add tool registry support - [ ] Basic transport layers 2. **Phase 2: Enhanced Features** - [ ] Advanced error handling - [ ] Tool caching system - [ ] Security improvements 3. **Phase 3: Optimization** - [ ] Performance improvements - [ ] Extended transport options - [ ] Developer tooling ## Multi-Agent Collaboration ## Current Status **Status: Planned** This document outlines the planned approach for enabling multiple specialized agents or agent personas to collaborate on tasks within a single user session in AgentDock. ## Goal To allow complex tasks to be broken down and handled by different specialized agent configurations (personas) sequentially, managed by the orchestration framework, while maintaining a coherent conversational context. ## Core Concept (V1 - Orchestration-Driven Personas) The initial implementation will leverage the existing **Orchestration Framework**. Instead of just controlling tools, orchestration steps will be used to represent different **agent personas** or **task phases**. - **Personas as Steps:** Each step in an orchestration configuration can represent a different specialist (e.g., a "Researcher" step, a "Planner" step, a "Coder" step). - **Dynamic Configuration:** When a step/persona becomes active (based on [Conditional Transitions](../architecture/orchestration/conditional-transitions.md)), the system will dynamically apply specific configurations associated with that persona for the next interaction. This could include: - A modified or specialized system prompt. - A distinct set of available tools. - Potentially specific LLM model settings (if feasible). - **Sequential Collaboration:** The orchestrator manages the flow, handing off the task context (maintained in the session state) from one persona/step to the next based on predefined conditions. The "collaboration" happens sequentially as the task progresses through different specialist phases. ```mermaid graph TD A[User Request] --> B(Orchestrator); B --> C{Condition Met?}; C -- Yes --> D[Activate Step/Persona X]; C -- No ---> E[Use Current/Default Step/Persona]; D --> F(AgentNode applies Persona X Config); E --> F; F --> G[LLM Interaction]; G --> H{Task Phase Complete?}; H -- Yes --> B; H -- No --> I[Response to User]; style F fill:#ccf,stroke:#333,stroke-width:2px ``` ### Simplified Handoff View ```mermaid graph LR subgraph Session Context direction TB SC[Shared State] end O(Orchestrator) --> P1(Persona 1 / Step 1); P1 --> SC; SC --> P1; P1 -- Task Update --> O; O --> P2(Persona 2 / Step 2); P2 --> SC; SC --> P2; P2 -- Task Update --> O; O --> P3(Persona ...); style O fill:#f9f,stroke:#333,stroke-width:2px ``` ## Architecture & Implementation Approach This approach aims to minimize initial changes to the core framework: 1. **Orchestration Configuration (`template.json`):** Extend the step definition to optionally include persona-specific overrides (e.g., `stepSystemPrompt`, potentially overriding `availableTools` more dynamically). 2. **`AgentNode` Adaptation:** Modify `AgentNode` or the API layer logic that uses it. Before calling `CoreLLM`, it will: - Retrieve the current `OrchestrationState` (including `activeStep`) via `OrchestrationStateManager`. - Check the configuration of the `activeStep`. - Apply any persona overrides from the step config when constructing the prompt and determining the final tool list for the LLM call. 3. **State Management:** The existing `OrchestrationStateManager` and `SessionManager` will be used to persist the `activeStep` and any shared context needed between steps/personas. ## Benefits - Leverages existing orchestration framework. - Enables task decomposition across specialized agent configurations. - Provides structured, sequential workflow management. - Requires relatively minimal initial changes to `agentdock-core`. ## Future Enhancements - **Agent-as-a-Tool:** Allow one `AgentNode` instance to directly invoke another `AgentNode` as a tool, enabling more complex, nested interactions. - **Shared Scratchpad/Memory:** Introduce a dedicated shared memory space within the session state for agents to explicitly pass complex data or intermediate results. - **Concurrent Execution:** Explore models for running multiple agents in parallel for certain tasks. ## Natural Language AI Agent Builder The Natural Language AI Agent Builder allows users to create sophisticated AI agents and workflows using plain language descriptions instead of complex coding or visual programming. ## Current Status **Status: Planned** The Natural Language AI Agent Builder is currently in the design phase, with implementation planned for the Pro version. ## Feature Overview The Natural Language AI Agent Builder will provide: - **Language-Based Creation**: Describe agents and workflows in your own words - **Instant Prototyping**: Test your agents immediately after creation - **Automatic Tool Selection**: Smart configuration of appropriate tools - **Visual Builder Integration**: Seamless transition between natural language and visual editing - **Multi-Language Support**: Create agents using any language, not just English - **Workflow Generation**: Create complex, multi-step workflows through description ## Architecture Diagrams ### Creation Process ```mermaid sequenceDiagram participant User participant NLInterface as Natural Language Interface participant LLM as Large Language Model participant Builder as Visual Builder participant DB as Database User->>NLInterface: Describes agent in natural language NLInterface->>LLM: Sends description with system prompt LLM->>Builder: Generates agent configuration Builder->>DB: Saves agent Builder->>User: Displays visual representation User->>Builder: Makes adjustments (if needed) ``` ### Implementation Architecture ```mermaid graph TD A[User Input] --> B[LLM with System Prompt] B --> C[Generated Agent/Workflow] C --> D[Visual Editor] D --> E[User Refinement] E --> F[Agent Execution] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style C fill:#e6f2ff,stroke:#99ccff ``` ### Agent Example ```mermaid graph TD A[User Input] --> B[Agent Node] B --> C{Tool Selection} C -->|Research| D[Web Search] C -->|Data| E[Database Tool] C -->|Communication| F[Platform Node] F --> G[Telegram] F --> H[Slack] B --> I[Memory System] D --> B E --> B style B fill:#0066cc,color:#ffffff,stroke:#0033cc style F fill:#e6f2ff,stroke:#99ccff style I fill:#e6f2ff,stroke:#99ccff ``` ## Implementation Details The Natural Language AI Agent Builder will be implemented through: ### 1. System Prompt A carefully crafted system prompt provides instructions and context to the LLM: ```typescript const systemPrompt = { instruction: `You are an expert agent builder for AgentDock Pro. Analyze the user's natural language description and create the optimal agent configuration.`, availableTools: { "webSearch": { description: "Searches the web for information", inputs: { "query": "string" }, outputs: { "results": "array" } }, "databaseQuery": { description: "Queries databases", inputs: { "sql": "string" }, outputs: { "results": "array" } }, // More tools... }, outputFormat: { type: "AgentConfiguration", example: { name: "Research Assistant", description: "Helps with research tasks", systemPrompt: "You are a research assistant...", tools: ["webSearch", "fileSummarizer"] } } }; ``` ### 2. LLM Processing The LLM analyzes the description to determine: - Agent's purpose and personality - Required tools and capabilities - System prompt for optimal behavior - Memory requirements - Appropriate connectors to platforms ### 3. Visual Builder Integration The generated agent appears in the visual builder for inspection and refinement: - Node connections automatically created - Tool configurations pre-populated - System prompt displayed for editing - Memory systems attached as needed ## Workflow Examples ### Customer Support Agent **Natural Language Input:** "Create an agent that handles customer support requests, can search our knowledge base, and escalates to human agents when necessary." ```mermaid graph TD A[Platform Node] --> B[Support Agent] B --> C{Query Type} C -->|FAQ| D[Knowledge Base] C -->|Account| E[Customer DB] C -->|Complex| F[Human Escalation] D --> B E --> B B --> G[Memory System] style B fill:#0066cc,color:#ffffff,stroke:#0033cc ``` ### Research Assistant Workflow **Natural Language Input:** "I need a workflow that researches topics, summarizes findings, and sends daily reports by email." ```mermaid graph LR A[Time Trigger] --> B[Research Agent] B --> C[Web Search] C --> B B --> D[Summarization] D --> E[Email Sender] style B fill:#0066cc,color:#ffffff,stroke:#0033cc ``` ### Trading Monitor Workflow **Natural Language Input:** "Build a workflow that monitors stock prices, analyzes market trends, and alerts me on Telegram when specific conditions are met." ```mermaid graph TD A[Market Data] --> B[Analysis Agent] B --> C{Conditions} C -->|Alert| D[Telegram Node] C -->|Record| E[Database] C -->|Normal| F[No Action] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style D fill:#e6f2ff,stroke:#99ccff ``` ## Key Features ### 1. Multi-Language Support Create agents in any language: ``` English: "Create a customer support agent with knowledge base access" Spanish: "Crea un agente de atención al cliente con acceso a la base de conocimientos" Japanese: "ナレッジベースにアクセスできるカスタマーサポートエージェントを作成する" ``` ### 2. Canvas Selection Enhancement Select specific parts of an existing workflow and modify them with natural language: ``` "Add error handling to this section of the workflow" "Improve the response formatting for better readability" "Make this agent more creative in its responses" ``` ### 3. Template Integration The system suggests templates based on your description: ``` Input: "Create an agent that helps with scheduling meetings" System: "I found these templates that match your needs: 1. Calendar Assistant 2. Meeting Coordinator 3. Executive Assistant" ``` ## Integration with AgentDock Core Core users can access Pro-created agents with API keys: ```mermaid graph LR subgraph "AgentDock Pro" A[Natural Language Creation] --> B[Agent Configuration] end subgraph "AgentDock Core" C[API Integration] --> D[Agent Usage] end B --> C style A fill:#0066cc,color:#ffffff,stroke:#0033cc style B fill:#e6f2ff,stroke:#99ccff ``` ## Benefits 1. **Accessibility**: Create agents without coding or technical knowledge 2. **Rapid Prototyping**: Move from idea to working agent in minutes 3. **Iterative Development**: Refine your agent through natural conversation 4. **Reduced Cognitive Load**: Focus on what you want, not implementation details 5. **Enhanced Productivity**: Build complex workflows with simple descriptions ## Timeline | Phase | Status | Description | |-------|--------|-------------| | Design | In Progress | System architecture and prompt design | | Simple Agent Creation | Planned | Basic agent creation from descriptions | | Tool Integration | Planned | Smart tool selection and configuration | | Visual Builder Integration | Planned | Combined natural language and visual editing | | Advanced Workflow Generation | Future | Complex multi-step workflow creation | | Pattern Learning | Future | Improving generation through successful patterns | ## Connection to Other Roadmap Items - **Platform Integration**: Easily configure agent connections to platforms - **Advanced Memory Systems**: Natural language setup of memory requirements - **Multi-Agent Collaboration**: Describe complex agent interactions - **Tool Integration**: Automatic tool selection and configuration ## Platform Integration The Platform Integration feature extends AgentDock agents to interact with users through external messaging platforms such as Telegram, WhatsApp, and Slack. ## Current Status **Status: Blocked - Requires HTTP Adapter Framework** Development of the platform integration system is **blocked** pending implementation of the HTTP Adapter Framework Abstraction. Platform Integration cannot begin until the foundational HTTP adapter infrastructure is completed. **Critical Dependency:** [HTTP Adapter Framework Abstraction](./http-adapter-framework-abstraction.md) **Reason for Dependency:** Platform Integration requires framework-agnostic HTTP handling to support webhooks across NextJS (open source) and Hono (commercial platform). The current NextJS-specific implementation cannot be extended to support platform webhooks without the unified HTTP adapter layer. ## Feature Overview The Platform Integration will provide: - **Framework-Agnostic Design**: Core logic that works across different HTTP frameworks - **Platform Node Abstraction**: Standard interface for implementing platform integrations - **Webhook Handling**: Robust webhook implementation for real-time updates - **Message Transformation**: Conversion between platform-specific and AgentDock message formats - **Conversation Management**: State tracking across user interactions - **HTTP Adapters**: Framework-specific adapters for different deployment environments Beyond standard messaging apps (Telegram, WhatsApp, Slack), the underlying `PlatformNode` abstraction or custom nodes built on `BaseNode` can be leveraged to create integrations with various other platforms, including social media networks like X (formerly Twitter), TikTok, LinkedIn, etc. Interaction can be achieved either through direct API calls (where available and permitted by the platform's terms of service) or potentially by utilizing browser automation tools for platforms lacking suitable APIs or for more complex interactions. ## Architecture Diagrams ### Platform Node Architecture ```mermaid graph LR A[BaseNode] --> B[PlatformNode] B --> C[TelegramNode] B --> D[WhatsAppNode] B --> E[SlackNode] B --> F[DiscordNode] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style C fill:#e6f2ff,stroke:#99ccff ``` ### HTTP Framework Adapters ```mermaid graph LR A[Platform Node] --> B[HTTP Adapter] B --> C[Next.js Adapter] B --> D[Express Adapter] B --> E[Hono Adapter] B --> F[Custom Adapter] style A fill:#0066cc,color:#ffffff,stroke:#0033cc style B fill:#e6f2ff,stroke:#99ccff ``` ### Message Flow ```mermaid graph TD A[User Message] --> B[Platform API] B --> C[Webhook Route] C --> D[HTTP Adapter] D --> E[Platform Node] E --> F[Message Transformer] F --> G[Agent Node] G --> H[generateText] H --> I[Response Transformer] I --> J[Platform API] J --> K[User Interface] style E fill:#0066cc,color:#ffffff,stroke:#0033cc style G fill:#0066cc,color:#ffffff,stroke:#0033cc ``` ## Implementation Details The platform integration system will be implemented with the following components: ```typescript // Base abstract class for all platform integrations abstract class PlatformNode extends BaseNode { // Transform platform message to agent message abstract transformMessageToAgent(message: unknown): Promise; // Transform agent response to platform message abstract transformResponseToPlatform(response: Message): Promise; // Send message to platform abstract sendMessageToPlatform(message: unknown): Promise; // Handle webhook payload async handleWebhookPayload(payload: unknown): Promise; } // HTTP adapter interface for framework-specific handling interface HttpAdapter { parseWebhookRequest(request: unknown): Promise; createSuccessResponse(): unknown; createErrorResponse(error: Error, statusCode?: number): unknown; getParams(request: unknown): Record; } ``` ## Initial Platform Support The first version will include the following platform integrations: 1. **Telegram**: Complete implementation as reference design 2. **WhatsApp**: Basic integration with WhatsApp Business API 3. **Slack**: Integration with Slack Bot API ## Telegram Integration Example The Telegram integration will serve as the reference implementation: ```typescript // Example of creating a Telegram node import { createTelegramNode } from '@/lib/platforms/telegram-factory'; // Create a Telegram node with an existing agent const telegramNode = createTelegramNode('telegram-1', agentNode, { token: process.env.TELEGRAM_BOT_TOKEN! }); // Set up the webhook await telegramNode.setupWebhook(); ``` ## Key Features of Platform Integration ### Framework Agnosticism The core platform logic operates independently of the HTTP framework, allowing for: - Use in Next.js for the reference Open Source Client. - Support for frameworks like Hono or Express.js for custom backend deployments. - Easy extension to other frameworks by implementing the `HttpAdapter` interface. ### Single Message Exchange Platform messaging works with discrete message exchange: ```typescript async handleMessage(chatId: number, message: string): Promise { // Process message with AgentDock Core const response = await this.agentNode.generateText({ messages: [ { role: 'user', content: message } ] }); // Send single complete response back to user await this.sendMessageToPlatform({ chat_id: chatId, text: response, parse_mode: 'Markdown' }); } ``` ### Type Safety Comprehensive TypeScript definitions ensure type safety: ```typescript // Platform-specific types (example for Telegram) interface TelegramMessage { message_id: number; from: TelegramUser; chat: TelegramChat; date: number; text?: string; // Other message properties } // Configuration types interface PlatformConfig { name: string; description?: string; } ``` ## Benefits The platform integration feature delivers several important benefits: 1. **Extended Reach**: Make agents accessible beyond the AgentDock UI 2. **Familiar Interfaces**: Users interact with agents in platforms they already use 3. **Unified Development**: Single agent works across multiple platforms 4. **Framework Flexibility**: Deploy using your preferred HTTP framework 5. **Consistent Experience**: Maintain agent capabilities across platforms ## Timeline | Phase | Status | Description | Dependencies | |-------|--------|-------------|--------------| | **PREREQUISITE: HTTP Adapter Framework** | **Required** | **Must complete first** | **[HTTP Adapter Framework](./http-adapter-framework-abstraction.md)** | | Design & Architecture | Complete | Core architecture design | ✅ Complete | | Platform Node Abstract Class | Blocked | Base class implementation | HTTP Adapter Framework | | HTTP Adapter Interface | Blocked | Framework adapter design | HTTP Adapter Framework | | Telegram Reference | Blocked | First complete implementation | HTTP Adapter Framework | | WhatsApp Integration | Blocked | Business API integration | HTTP Adapter Framework | | Slack Integration | Blocked | Slack Bot implementation | HTTP Adapter Framework | | Additional Platforms | Future | Discord, Teams, etc. | All above phases | **CRITICAL:** All Platform Integration phases are blocked until HTTP Adapter Framework is implemented. ## Connection to Other Roadmap Items The Platform Integration connects with other roadmap items: - **HTTP Adapter Framework Abstraction**: **CRITICAL PREREQUISITE** - Must be implemented first - **Storage Abstraction Layer**: Uses storage for conversation state - **Advanced Memory Systems**: Provides long-term memory across platforms - **Multi-Agent Collaboration**: Enables collaboration via messaging platforms - **Voice AI Agents**: Foundation for voice platform integration ## Impact on Open Source Client **Required Changes After HTTP Adapter Implementation:** 1. **Route Simplification** - `src/app/api/chat/[agentId]/route.ts` - Replace with HTTP adapter usage - Remove `src/lib/agent-adapter.ts` (logic moves to agentdock-core) - Remove `src/lib/orchestration-adapter.ts` (logic moves to agentdock-core) 2. **Platform Webhook Support** - Add new routes: `/api/platforms/telegram/[nodeId]` - Add new routes: `/api/platforms/whatsapp/[nodeId]` - Add new routes: `/api/platforms/slack/[nodeId]` 3. **Configuration Updates** - Update environment variables for platform integrations - Add platform-specific configuration management ## Getting Started (Preview) Once released, getting started will be straightforward: 1. Obtain API credentials for your chosen platform 2. Create a platform node with an existing agent 3. Set up webhook routes in your application 4. Deploy or use tunneling for development ```typescript // Example webhook route in Next.js export async function POST(request: NextRequest, { params }) { const adapter = createHttpAdapter('nextjs'); const nodeId = params.nodeId; const telegramNode = NodeRegistry.getNode(nodeId); const update = await adapter.parseWebhookRequest(request); telegramNode.handleWebhookPayload(update); return adapter.createSuccessResponse(); } ``` ## 🗺️ AgentDock Development Roadmap This document outlines the planned features and future direction for AgentDock. Most improvements target the core AgentDock framework (`agentdock-core`), which is under active development and will be published as a versioned NPM package upon reaching a stable release. Some items may also involve the open-source client. ## Completed | Feature | Description | |---------|-------------| | [**Storage Abstraction Layer**](../storage/storage-abstraction.md) | ✅ Flexible storage system with 15 production-ready adapters | | [**Advanced Memory Systems**](../memory/README.md) | ✅ Four-layer cognitive architecture with PRIME extraction, hybrid search, and memory connections | | [**Vector Storage Integration**](../storage/vector-storage.md) | ✅ Embedding-based retrieval for documents and memory (PostgreSQL + pgvector, SQLite + sqlite-vec fully integrated) | ## In Progress | Feature | Description | |---------|-------------| | [**Evaluation for AI Agents**](./evaluation-framework.md) | Comprehensive testing and evaluation framework | ## Planned | Feature | Description | |---------|-------------| | [**Platform Integration**](./platform-integration.md) | Support for Telegram, WhatsApp, and other messaging platforms | | [**Multi-Agent Collaboration**](./multi-agent-collaboration.md) | Enable agents to work together | | [**Model Context Protocol (MCP) Integration**](./mcp-integration.md) | Support for discovering and using external tools via MCP | | [**Voice AI Agents**](./voice-agents.md) | AI agents using voice interfaces and phone numbers via AgentNode | | [**Telemetry and Traceability**](./telemetry.md) | Advanced logging and performance tracking | ## Advanced Agent Applications | Feature | Description | |---------|-------------| | [**Code Playground**](./code-playground.md) | Sandboxed code generation and execution with rich visualization capabilities | ## Workflow System | Feature | Description | |---------|-------------| | [**Workflow Runtime & Nodes**](./workflow-nodes.md) | Core runtime, node types, and orchestration logic for complex automations | ## Cloud Deployment | Feature | Description | |---------|-------------| | [**AgentDock Pro**](/docs/agentdock-pro) | Comprehensive enterprise cloud platform for scaling AI agents & workflows, with visual tools and autoscaling | | [**Natural Language AI Agent Builder**](./nl-agent-builder.md) | Visual builder + natural language agent and workflow construction | | [**Agent Marketplace**](./agent-marketplace.md) | Monetizable agent templates | ## Open Source Client Enhancements - Improved UI/UX for agent management and chat. - Enhanced visualization for orchestration steps. - More robust BYOK (Bring Your Own Key) management. - Multi-modal input/output support (beyond basic image generation). - Example implementations for multi-threading/background tasks (where applicable in Next.js). - Exploration of patterns for multi-tenancy support within the client architecture. ## Community & Ecosystem - Grow the library of community-contributed agents. - Develop more example projects and tutorials. - Establish clearer contribution guidelines. ## AgentDock Repository Improvements - Complete test suite (Unit, Integration, E2E). - Expand core capabilities with workflow node types and runtime enhancements. ## Release Timeline We follow an iterative development approach, with regular releases focusing on specific feature areas. While we don't provide exact dates for feature availability, our general timeline prioritizes: 1. Core infrastructure improvements (storage, memory) - ✅ **COMPLETED** 2. Integration capabilities (platforms, voice) 3. Advanced tooling (evaluation, telemetry) 4. Cloud and marketplace features *This roadmap is indicative and subject to change.* For the most up-to-date information on our progress, please check our GitHub repository. ## Telemetry & Observability The Telemetry & Observability feature provides monitoring, tracing, and evaluation capabilities for AgentDock agents, enabling developers to gain insights into agent behavior and optimize performance. ## Current Status **Status: Planned** We're exploring different approaches for implementing the Telemetry & Observability system, evaluating both third-party open source solutions and custom implementations. Regardless of which path we choose, the system will deliver comprehensive monitoring and tracing capabilities. ## Feature Overview Key capabilities will include: - **Tracing**: Track agent interactions, LLM calls, and tool executions - **Performance Metrics**: Monitor latency, token usage, and resource utilization - **Cost Tracking**: Measure API usage costs across providers - **Evaluations**: Assess agent output quality with customizable metrics (see [Evaluation Framework](./evaluation-framework.md) for details) - **Session Monitoring**: Group related interactions into sessions for cohesive analysis - **Visualization**: Display trace data in intuitive dashboards ## Architecture Diagrams ### Telemetry Architecture ```mermaid graph TD A[Agent Interaction] --> B[Telemetry Layer] B --> C[Data Collection] C --> D[Export Mechanism] D -->|OpenTelemetry| E[Observability Platform] D -->|Custom Export| F[Custom Solution] B --> G[Performance Metrics] B --> H[Token Usage] B --> I[Tool Execution] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style E fill:#e6f2ff,stroke:#99ccff ``` ### Tracing Pipeline ```mermaid graph TD A[User Input] --> B[AgentNode] B --> C[Telemetry Middleware] subgraph "Tracing Components" C --> D[LLM Calls] C --> E[Tool Execution] C --> F[Message Processing] end D --> G[Trace Export] E --> G F --> G G --> H[Observability Platform] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style C fill:#e6f2ff,stroke:#99ccff ``` ### Evaluation Flow The evaluation system is integrated with telemetry for comprehensive agent assessment. For detailed information on the evaluation architecture and components, please refer to the [Evaluation Framework](./evaluation-framework.md) document. ## Implementation Approaches We're evaluating two main approaches: ### 1. Third-Party Integration Using open source platforms like Laminar or OpenTelemetry-based solutions: - Standardized tracing protocols and formats - Pre-built visualization and analysis tools - Lower development overhead - Community-supported extensions ### 2. Custom Implementation Building a tailored solution specific to AgentDock: - Complete control over data collection and storage - Custom visualization specific to LLM agent needs - Tighter integration with existing AgentDock components - Specialized features for agent evaluation ## Key Features ### Comprehensive Tracing The system will provide detailed visibility into agent operations: - **LLM Call Tracing**: Track prompt construction, model invocation, and response processing - **Tool Execution Monitoring**: Log tool calls, parameters, and results - **Message Flow Visualization**: See the complete conversation flow with timing information - **Error Tracking**: Capture and analyze errors with full context ### Performance Metrics Monitor and optimize agent performance: - **Latency Breakdown**: Identify bottlenecks in the processing pipeline - **Token Usage**: Track token consumption by component and operation - **Resource Utilization**: Monitor CPU, memory, and network usage - **Cost Analysis**: Calculate expenses based on provider-specific pricing ## Timeline | Phase | Status | Description | |-------|--------|-------------| | Approach Evaluation | In Progress | Comparing third-party vs. custom solutions | | Architecture Design | Planned | Core design based on selected approach | | Basic Implementation | Planned | Initial tracing capabilities | | Evaluation Framework | Planned | Tools for assessing agent output quality | | Advanced Features | Future | Enhanced analytics and visualization | ## Connection to Other Roadmap Items The Telemetry & Observability feature connects with other roadmap items: - **Advanced Memory Systems**: Trace memory operations and retrieval effectiveness - **Platform Integration**: Monitor cross-platform interactions and performance - **Voice AI Agents**: Measure voice processing latency and quality - **Evaluation Framework**: Provides data for the [Agent Evaluation Framework](./evaluation-framework.md) ## Use Cases ### Development & Debugging Accelerate agent development with comprehensive tracing: ```mermaid graph TD A[Developer] --> B[Agent Implementation] B --> C[Telemetry Tracing] C --> D[Issue Detection] D --> E[Root Cause Analysis] E --> F[Code Improvement] F --> B style C fill:#0066cc,color:#ffffff,stroke:#0033cc style E fill:#e6f2ff,stroke:#99ccff ``` ### Production Monitoring Ensure reliability and performance in production: ```mermaid graph LR A[Production Agent] --> B[Telemetry Pipeline] B --> C[Real-time Monitoring] C --> D[Alert System] D --> E[Incident Response] B --> F[Performance Dashboard] F --> G[Optimization Opportunities] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style F fill:#e6f2ff,stroke:#99ccff ``` ### Quality Assurance Continuously evaluate and improve agent outputs. This use case is shared with the Evaluation Framework - see the [Evaluation Framework](./evaluation-framework.md) document for more details on assessment criteria and methods. ## Technical Considerations ### Data Privacy and Security Regardless of the implementation approach, the telemetry system will: - Allow sensitive data masking and redaction - Support local-only tracing for development - Provide configurable sampling rates to control data volume - Ensure compliance with privacy regulations ### Performance Impact The telemetry system is designed to have minimal overhead: - Asynchronous processing where possible - Configurable sampling rates to reduce impact - Batched exports to minimize API calls - Memory-efficient trace storage The final architecture will be determined based on further evaluation of existing open source solutions like Laminar, weighing their capabilities against the specific needs of AgentDock agents. Whether we build our own solution or leverage third-party tools, the telemetry system will provide the comprehensive observability needed to optimize agent performance and reliability. ## Voice AI Agents The Voice AI Agents feature enables real-time voice conversations with AgentDock agents through advanced speech-to-speech capabilities, creating natural, interactive experiences through web applications and phone systems. ## Current Status **Status: Planned** Development of the Voice AI Agents system has been designed with a focus on leveraging cutting-edge real-time speech models and integration with the existing AgentDock architecture. ## Feature Overview The Voice AI Agents feature will provide: - **Real-time Voice Interaction**: Near-instantaneous speech-to-speech conversations - **WebRTC Integration**: Low-latency audio streaming for web applications - **Phone Number Access**: Connect agents to traditional phone systems via Twilio - **Multi-provider Support**: Flexibility to use OpenAI Realtime API, ElevenLabs, and other providers - **Voice Node Abstraction**: Standard interface extending the PlatformNode architecture ## Architecture Diagrams ### Voice Node Architecture ```mermaid graph LR A[BaseNode] --> B[PlatformNode] B --> C[VoiceNode] C --> D[WebRTCVoiceNode] C --> E[TwilioVoiceNode] style B fill:#0066cc,color:#ffffff,stroke:#0033cc style C fill:#e6f2ff,stroke:#99ccff ``` ### Speech Processing Pipeline ```mermaid graph TD A[Audio Input] --> B[WebRTC/WebSockets] B --> C[Voice Node] C --> D[Voice AI Provider] D --> E[AgentNode] E --> F[Voice AI Provider] F --> G[Audio Output] style C fill:#0066cc,color:#ffffff,stroke:#0033cc style E fill:#0066cc,color:#ffffff,stroke:#0033cc ``` ### Real-time Voice Communication ```mermaid graph TD A[User Voice] --> B[Audio Stream] B --> C[VoiceNode] C --> D[Voice AI Provider] subgraph "AI Processing" D --> E[Agent Processing] E --> F[Voice Response] end F --> G[Audio Stream] G --> H[User Interface] style C fill:#0066cc,color:#ffffff,stroke:#0033cc style E fill:#e6f2ff,stroke:#99ccff ``` ## Implementation Details The Voice AI Agents system will be implemented with the following components: ```typescript // Abstract class for voice-based interactions abstract class VoiceNode extends PlatformNode { // Process incoming audio stream abstract processAudioStream(audioStream: ReadableStream): Promise; // Generate speech from agent response abstract generateSpeech(response: Message): Promise; // Handle real-time audio session abstract handleAudioSession(sessionId: string): Promise; // Initialize voice provider abstract initializeVoiceProvider(config: VoiceProviderConfig): Promise; } // Configuration for voice providers interface VoiceProviderConfig { provider: 'openai' | 'elevenlabs' | 'sesame'; apiKey: string; modelId?: string; voice?: string; } ``` ## Voice Provider Support The system will integrate with leading voice AI providers: 1. **OpenAI Realtime API**: End-to-end speech-to-speech with GPT-4.1 2. **ElevenLabs**: High-quality voice synthesis and voice-to-voice capabilities 3. **Sesame AI**: Advanced voice models with natural conversational abilities ## Integration Methods ### WebRTC for Browser Applications ```typescript // Example of creating a WebRTC voice node import { createWebRTCVoiceNode } from '@/lib/voice/webrtc-factory'; // Create a WebRTC voice node with an existing agent const voiceNode = createWebRTCVoiceNode('voice-1', agentNode, { provider: 'openai', apiKey: process.env.OPENAI_API_KEY!, modelId: 'gpt-4.1-realtime' }); // Set up audio stream await voiceNode.setupAudioStream(webrtcConnection); ``` ### Twilio for Phone Number Access ```typescript // Example of creating a Twilio voice node import { createTwilioVoiceNode } from '@/lib/voice/twilio-factory'; // Create a Twilio voice node with an existing agent const twilioNode = createTwilioVoiceNode('phone-1', agentNode, { accountSid: process.env.TWILIO_ACCOUNT_SID!, authToken: process.env.TWILIO_AUTH_TOKEN!, phoneNumber: process.env.TWILIO_PHONE_NUMBER!, voiceProvider: { provider: 'elevenlabs', apiKey: process.env.ELEVENLABS_API_KEY!, voice: 'Josh' } }); // Set up webhook for incoming calls await twilioNode.setupWebhook(); ``` ## Key Features ### End-to-End Voice Interaction The system leverages frontier voice AI models for seamless conversations: - **Direct Voice Processing**: Uses provider APIs for speech-to-speech conversion - **Continuous Streaming**: Processes audio in real-time for natural conversation flow - **Low Latency**: Maintains responsive interactions with minimal delay ### Voice Provider Flexibility Select the right voice technology based on your needs: - **OpenAI Realtime**: End-to-end speech model with conversational capabilities - **ElevenLabs**: Superior voice quality and natural-sounding synthesis - **Sesame**: Human-like voice with natural pauses and prosody ### Phone System Integration Connect agents to traditional phone systems: - **Twilio Integration**: Assign phone numbers to agents - **Outbound Calling**: Initiate calls to users - **Inbound Support**: Receive and process incoming calls - **Call Analytics**: Track conversation duration and metrics ## Benefits The Voice AI Agents feature delivers several important benefits: 1. **Natural Interaction**: Voice is the most intuitive human interface 2. **Accessibility**: Provides service to users without technical expertise 3. **Multimodal Support**: Combine with text and visual responses 4. **Global Reach**: Connect through universal phone systems 5. **Enterprise Communication**: Professional voice representation ## Timeline | Phase | Status | Description | |-------|--------|-------------| | Design & Architecture | Planned | Core architecture design | | Voice Node Abstract Class | Planned | Base class implementation | | WebRTC Integration | Planned | Browser-based voice support | | OpenAI Realtime Integration | Planned | Initial voice provider | | ElevenLabs Integration | Planned | Additional voice provider | | Twilio Phone Integration | Planned | Phone number access | | Advanced Voice Features | Future | Voice customization options | ## Connection to Other Roadmap Items The Voice AI Agents feature connects with other roadmap items: - **Platform Integration**: Extends the platform node architecture for voice - **Advanced Memory Systems**: Provides context for personalized voice interactions - **Natural Language AI Agent Builder**: Create voice-enabled agents with natural language - **Agent Marketplace**: Share voice agent templates ## Use Cases ### Customer Service Voice Agent Provide 24/7 voice-based customer service: ```mermaid graph TD A[Phone Call] --> B[Twilio] B --> C[VoiceNode] C --> D[Customer Service Agent] D --> E[Knowledge Base] D --> F[CRM Integration] D --> G[Order System] style C fill:#e6f2ff,stroke:#99ccff style D fill:#0066cc,color:#ffffff,stroke:#0033cc ``` ### Voice Assistant for Applications Enhance applications with conversational voice capabilities: ```mermaid graph LR A[User] --> B[Web Application] B --> C[WebRTC] C --> D[VoiceNode] D --> E[AgentNode] E --> F[Tools & APIs] style D fill:#e6f2ff,stroke:#99ccff style E fill:#0066cc,color:#ffffff,stroke:#0033cc ``` ## AgentDock Workflows & Nodes: Automating Complex Tasks AgentDock is expanding beyond conversational agents to enable the construction of sophisticated, custom automations. The goal is to allow users to orchestrate complex processes, connect diverse tools, and integrate AI logic using a structured, node-based system, reducing the need for extensive custom code for many common automation patterns. This capability relies on a flexible **node-based architecture**. Think of nodes as specialized building blocks: - Some initiate workflows based on **events**. - Others **manage or transform data**. - Some connect to **external services**. - Others perform specific **AI tasks**. The power comes from combining these nodes, particularly **Agent Nodes** (for conversational intelligence) and **AI Inference Nodes** (for specialized AI tasks), into structured workflows. This document outlines the planned node types that form the core of this workflow system, providing a foundation for automating tasks ranging from data processing and customer service flows to complex research and operational decision-making. ## Development Approach: Stability First The advanced workflow capabilities, including the visual builder and the node types detailed below, are currently under active development and refinement. Our priority is ensuring these features are thoroughly tested and proven stable in demanding, real-world production environments before releasing them more broadly. This means we focus on achieving high standards for stability, reliability, and usability first. **AgentDock Pro provides the essential proving ground** where we can rigorously validate these complex features against diverse enterprise use cases. Once these workflow components demonstrate consistent, reliable performance and meet our internal quality benchmarks, we plan to integrate them into the open-source `agentdock-core`. This stability-focused approach ensures that when these features become available in the core library, they are dependable and ready for production use by the open-source community. ## Planned Workflow Node Types Workflows in AgentDock are constructed by connecting various types of nodes. Each node category serves a distinct purpose within the automation process. Here's an overview of the planned categories: ### 1. Event Nodes - **Purpose**: Initiate workflows based on *external triggers*, *schedules*, or *system events*. - **Characteristics**: Act as the starting point for automated workflows. They have outputs but no inputs and are activated by triggers (e.g., webhook, schedule, database change) rather than direct user interaction within the flow. - **Examples**: `Webhook Trigger`, `Time Trigger`, `Database Watcher`. ```mermaid graph TD A[Webhook: New Lead Received] --> B(Parse Lead Data); B --> C(Add to CRM); C --> D(Notify Sales Team); ``` ### 2. Agent Nodes - **Purpose**: Integrate *interactive, conversational AI* capabilities directly into a workflow. - **Characteristics**: Handle bidirectional communication (user input/output), maintain conversation memory/context, utilize tools, and leverage LLMs. These nodes are inherently *non-deterministic*. - **Examples**: `Conversational Agent`, `Customer Support Agent`, `Research Assistant`. ```mermaid graph TD A["User: 'Book flight to NY'"] --> B(Travel Agent); B --> C[API Call: Check Flights]; C --> B; B --> D["Response: 'Found flights...'"]; ``` ### 3. Transform Nodes - **Purpose**: Process and manipulate data as it flows *between other nodes*. - **Characteristics**: Accept input data, perform defined operations (e.g., formatting, parsing, filtering, calculations), and pass the results to the next node. Their effects are internal to the workflow state. Typically *deterministic*. - **Examples**: `Text Formatter`, `JSON Parser`, `Data Filter`, `Math Operations`. ```mermaid graph LR A[Raw User Input] --> B(Format Text: Uppercase Name); B --> C(Filter: Extract Email); C --> D[Processed Contact Info]; ``` ### 4. AI Inference Nodes - **Purpose**: Execute specific, *non-conversational AI tasks* within a workflow. - **Characteristics**: Perform focused AI inference tasks like summarization or classification. Unlike Agent Nodes, they don't manage conversations. Can be *semi-deterministic* depending on configuration (e.g., temperature settings). - **Examples**: `Text Summarization`, `Image Classification`, `Sentiment Analysis`, `Data Extraction`. ```mermaid graph LR A[Product Description Text] --> B(AI Task: Extract Features); B --> C[List of Features]; C --> D(Save Features to DB); ``` ### 5. Connector Nodes - **Purpose**: Interact with *external services and APIs*, primarily for **data retrieval**. - **Characteristics**: Integrate with third-party systems (CRMs, databases, APIs, etc.). Often handle authentication and focus on fetching data *into* the workflow. - **Examples**: `Google Sheets Reader`, `Salesforce Query`, `Weather API Fetcher`, `Database Connector`. ```mermaid graph LR A[Trigger: User Request] --> B(Connector: Fetch Weather API); B --> C[Weather Data Received]; C --> D(Format Weather Report); ``` ### 6. Action Nodes - **Purpose**: Perform operations that produce effects *outside the workflow itself*. - **Characteristics**: Use data from the workflow to modify external systems (e.g., sending emails, updating database records, posting to APIs). Often represent the termination point or side-effect of a workflow branch. - **Examples**: `Email Sender`, `Slack Notifier`, `Database Writer`, `API POST Request`. ```mermaid graph LR A[New Order Data] --> B(Action: Send Confirmation Email); B --> C(Action: Update Order Status in DB); C --> D(Action: Notify Slack Channel); ``` ### 7. Logic Nodes - **Purpose**: Control the *execution flow* and branching within workflows. - **Characteristics**: Determine which path(s) execution should follow based on defined conditions. Implement branching, merging, and looping constructs. Purely *deterministic*. - **Examples**: `Conditional (If/Else)`, `Switch/Case`, `Parallel Branch`, `Loop Construct`. ```mermaid graph TD A[Connector: Get Leads from Google Sheet] --> B(Logic: Loop Through Each Lead); B -- For Each Lead --> C{Logic: Check Status == 'New'?}; C -- Yes --> D[Action: Send Welcome Email]; C -- No --> E[Action: Log as 'Skipped']; D --> B; E --> B; B -- Loop Finished --> F[End Flow]; ``` ## Implementation Status & Roadmap Developing this comprehensive node system and the associated workflow builder is a significant undertaking, currently focused within the AgentDock Pro environment. Our priority is ensuring these features are robust and reliable before wider release. We'll provide updates on the progress towards incorporating these capabilities into the open-source `agentdock-core`. ## Storage Setup Guide ## Quick Start ### Local Development ```bash # Run the application pnpm dev # Storage configuration: # - SQLite adapter auto-registered # - Database created at ./agentdock.db # - Sessions persist across server restarts ``` **No .env.local configuration required for local storage.** ### Production with PostgreSQL/Supabase #### Step 1: Database Setup Choose a PostgreSQL provider: - Supabase (managed PostgreSQL) - Neon - Railway - Self-hosted PostgreSQL 15+ #### Step 2: Configure Environment Add to `.env.local`: ```bash DATABASE_URL=postgresql://postgres:[PASSWORD]@db.[PROJECT-ID].supabase.co:5432/postgres ENABLE_PGVECTOR=true # Optional: for vector operations KV_STORE_PROVIDER=postgresql ``` #### Step 3: Enable Vector Extension (Optional) For vector search capabilities: ```sql CREATE EXTENSION IF NOT EXISTS vector; ``` #### Step 4: Deploy ```bash pnpm build pnpm start ``` **Current capabilities with this setup:** - Session state persistence - Storage API with PostgreSQL backend - Vector operations (if pgvector enabled) **Not yet implemented:** - Server-side message persistence (messages remain in browser localStorage) - User authentication system - AI memory implementation ## Configuration Examples ### Minimal Local Development ```bash # No storage configuration needed # SQLite is automatically enabled in development ``` ### Production with PostgreSQL ```bash # PostgreSQL connection DATABASE_URL=postgresql://postgres:password@host:5432/database ENABLE_PGVECTOR=true KV_STORE_PROVIDER=postgresql ``` ## Common Questions ### Do I need Redis? No. PostgreSQL can handle session storage directly. Redis is optional for caching. ### Do I need MongoDB? No. MongoDB is not recommended for the memory system. Use PostgreSQL or SQLite. ### What about Vercel deployments? Options: - Use external PostgreSQL (Supabase, Neon) - Use Vercel KV (auto-configured when added via Vercel dashboard) ### Data not persisting locally? Ensure you're running `pnpm dev` which enables SQLite automatically. ### Can I use my own PostgreSQL? Yes. Any PostgreSQL 15+ instance works. Add pgvector extension for vector operations. ## Using Additional Storage Adapters Most applications don't need additional adapters. For specific requirements: ### Step 1: Configure Environment ```bash # Example: MongoDB (not recommended for memory) ENABLE_MONGODB=true MONGODB_URI=mongodb://localhost:27017/agentdock ``` ### Step 2: Register in API Route ```typescript // app/api/route.ts import { getStorageFactory } from 'agentdock-core'; import { registerMongoDBAdapter } from 'agentdock-core/storage'; export async function POST(req: Request) { const factory = getStorageFactory(); await registerMongoDBAdapter(factory); const storage = factory.getProvider({ type: 'mongodb' }); // Use storage... } ``` ## Summary - **Local Development**: SQLite auto-configured - **Production**: PostgreSQL recommended - **Additional adapters**: Available but require manual registration ## Message History Management This document explains how AgentDock manages conversation history to optimize context window usage while maintaining conversation coherence. ## History Policies AgentDock supports three history policies: | Policy | Description | |--------|-------------| | `lastN` | Keep the last N user messages and their corresponding assistant responses | | `all` | Keep all messages (no trimming) | | `none` | Remove all history (stateless conversations) | ## Message Trimming Visualization ```mermaid graph TD subgraph "Example: historyLength=3" A[System Message] --> D[User Message 1] D --> E[Assistant Response 1] E --> F[User Message 2] F --> G[Assistant Response 2] G --> H[User Message 3] H --> I[Assistant Response 3] I --> J[User Message 4] J --> K[Assistant Response 4] end subgraph "After Trimming" A2[System Message] -.- H2[User Message 3] H2 --> I2[Assistant Response 3] I2 --> J2[User Message 4] J2 --> K2[Assistant Response 4] end L["User Message 1 + Response"] -.- M["User Message 2 + Response"] -.- N["Trimmed based on historyLength"] N -.-> O["User Message 3 + Response"] -.- P["User Message 4 + Response"] -.- Q["Kept based on historyLength=3"] ``` ## Implementation Details ### Message Trimming Logic The core message trimming is handled by the `applyHistoryPolicy` function: ```typescript export function applyHistoryPolicy( messages: CoreMessage[], options: { historyPolicy?: 'none' | 'lastN' | 'all', historyLength?: number, preserveSystemMessages?: boolean } ): CoreMessage[] { // Implementation details... } ``` When the `historyPolicy` is set to `lastN`, the system: 1. Preserves all system messages (if `preserveSystemMessages` is true). 2. Identifies the conversation messages (excluding system messages). 3. Finds the starting point in the conversation messages that includes exactly the last `N` user messages and any subsequent assistant messages. 4. Keeps only the system messages plus the conversation messages from that calculated starting point onwards. This approach ensures that the context sent to the LLM contains precisely the system prompt(s) and the last N turns of the user-assistant conversation. ### Special Case: historyLength=0 When `historyLength` is set to 0 and `historyPolicy` is `lastN`, the system treats this case as if `historyLength` were set to 1. - This ensures that the last user message and any subsequent assistant responses are kept, along with system messages. - This prevents errors caused by sending only system messages to the LLM and ensures minimal context is always provided. ## Configuration Options AgentDock offers flexible configuration through a layered approach that prioritizes security: ### Agent Template Settings Each agent template can specify history settings: ```typescript { chatSettings: { historyPolicy: 'lastN', // 'none' | 'lastN' | 'all' historyLength: 20, // Number of user messages to keep (default: 20) // Other settings... } } ``` ### Environment Variables Set default history settings using environment variables: ``` NEXT_PUBLIC_DEFAULT_HISTORY_POLICY=lastN NEXT_PUBLIC_DEFAULT_HISTORY_LENGTH=20 ``` ### URL Parameters Control message history settings via URL parameters: | Parameter | Description | Valid Values | Example | |-----------|-------------|--------------|---------| | `historyPolicy` | The message history retention policy | `none`, `lastN`, `all` | `?historyPolicy=lastN` | | `historyLength` | The number of user messages to retain | Any non-negative number | `?historyLength=5` | #### Examples - Keep all messages: `http://localhost:3000/chat?agent=demo&historyPolicy=all` - Keep last 2 user messages: `http://localhost:3000/chat?agent=demo&historyPolicy=lastN&historyLength=2` - Remove all history (keep 1 message): `http://localhost:3000/chat?agent=demo&historyPolicy=lastN&historyLength=0` - Remove all history: `http://localhost:3000/chat?agent=demo&historyPolicy=none` ### Security-First Configuration Precedence AgentDock applies settings in this order of precedence: 1. **Environment Variables** (highest security) 2. **URL Parameters** (only applied if no environment variables are set) 3. **Agent Template Settings** (default fallback) This structure ensures server administrators can enforce security policies through environment variables that cannot be overridden by URL parameters. ## Best Practices ### Message History Optimization - **Start Conservative**: Begin with a smaller `historyLength` (5-20) and increase if needed - **Monitor Token Usage**: Check token counts in development console to optimize settings - **Balance Coherence and Efficiency**: Too few messages can break context, too many waste tokens - **Preserve System Messages**: Always keep system messages to maintain agent personality ### Security Recommendations - **Use Environment Variables in Production**: Set `NEXT_PUBLIC_DEFAULT_HISTORY_POLICY` and `NEXT_PUBLIC_DEFAULT_HISTORY_LENGTH` in production environments to prevent URL parameter overrides - **Set Reasonable Limits**: Excessive history retention can lead to token usage exploitation - **Verify Using Debug Panel**: Add `?debug=true` to check the "Source" field and confirm environment variables are taking precedence - **Consider Authorization Checks**: Implement additional authorization for history modification in sensitive deployments ## Debugging AgentDock provides multiple ways to debug history settings: ### Console Logging When in development mode (`NODE_ENV=development`), the system logs useful information: ``` [History] Agent example-agent history settings: {policy: "lastN", length: 20, messageCount: 22} [History] Trimmed messages from 22 to 12 ``` ### Debug Panel The debug panel (accessible by adding `?debug=true` to your URL) displays current history settings: - **Policy**: The current history policy in use (lastN, all, none) - **Length**: The number of messages to retain - **Source**: Where the settings came from (environment, URL, default) - **Messages**: Current number of messages in the conversation This helps diagnose potential issues with message trimming and verify security precedence. ## Message Persistence in AgentDock This document outlines the current approach to message persistence in the AgentDock reference implementation. ## Current Implementation The current implementation uses a client-side persistence approach with browser localStorage: ```typescript // Inside a React component using useChat from AI SDK const { messages, input, handleInputChange, handleSubmit, isLoading, // ... other hooks } = useChat({ id: agentId, api: `/api/chat/${agentId}`, initialMessages: loadSavedMessages(), // Load from storage onFinish: async (message) => { // Save completed message to storage localStorage.setItem(`chat-${agentId}`, JSON.stringify(messages)); // Update tracking reference prevMessageLengthRef.current = messages.length; }, // ... other options }); // Additional effect to handle saves outside of completion React.useEffect(() => { // Skip if no agent or no messages if (!agentId || messages.length === 0) return; // Only save if message length changed and not currently streaming if (messages.length !== prevMessageLengthRef.current && !isLoading) { localStorage.setItem(`chat-${agentId}`, JSON.stringify(messages)); prevMessageLengthRef.current = messages.length; } }, [agentId, messages, isLoading]); ``` ### Advantages - Simple implementation with direct control - Works without server infrastructure - Provides offline support - Low latency (no network requests) - Easy to debug with browser devtools ### Limitations - Limited to browser localStorage (size limits, browser-specific) - No cross-device synchronization - Limited to client-side storage ## Future Considerations Future versions of AgentDock may implement server-side persistence for more robust message storage, but this is not currently implemented. ## Best Practices for Current Implementation 1. **Strategic Save Points** - Save after message completion (onFinish) - Save before navigation/tab close - Avoid saving during streaming 2. **Proper Error Handling** - Handle storage quota exceeded errors - Provide fallbacks when localStorage is not available - Consider clearing old messages when approaching quota limits 3. **Disconnection Handling** - Implement basic reconnection logic - Consider local backup strategies ## Storage System AgentDock Core provides a comprehensive storage abstraction layer with 15 production-ready adapters for various data persistence needs. This fully-implemented system enables switching between different storage backends without changing application code. ## Core Concepts - **Abstraction:** A primary goal is to abstract the underlying storage mechanism, allowing developers to choose the backend that best fits their deployment needs (e.g., in-memory for development, Redis for scalable deployments, Vercel KV for Vercel hosting). - **Purpose-Driven Configuration:** Different types of data (Key-Value, Vector, Relational) will ideally be configurable with distinct providers based on their requirements (e.g., using Redis for session KV and pgvector for Vector storage). - **Session Scoping:** Much of the core storage usage revolves around managing session-specific data with appropriate isolation and lifecycle management (TTL). - **Security:** Includes components like `SecureStorage` for handling sensitive data client-side. ## Key Components (`agentdock-core/src/storage`) 1. **Storage Abstraction Layer (SAL):** - **Interface (`StorageProvider`):** Defines the standard contract for Key-Value storage operations (`get`, `set`, `delete`, `exists`, etc.). - **Factory (`StorageFactory`, `getStorageFactory`):** Instantiates the configured `StorageProvider` based on environment variables (`KV_STORE_PROVIDER`, `REDIS_URL`, etc.). Manages provider instances. - **Implementations (`/providers` and `/adapters`):** - `MemoryStorageProvider`: Default in-memory KV store. - `RedisStorageProvider`: Uses `@upstash/redis` for Redis/Upstash KV storage. - `VercelKVProvider`: Uses `@vercel/kv` for Vercel KV storage. - Plus 12 additional adapters for various backends (SQLite, PostgreSQL, MongoDB, S3, etc.) - **Vector Support:** PostgreSQL Vector, Pinecone, Qdrant, ChromaDB, and SQLite-vec for AI/embeddings. 2. **Secure Storage (`SecureStorage`):** - A separate utility class designed for **client-side (browser)** secure storage. - Uses the Web Crypto API (AES-GCM) for encryption and HMAC for integrity checking. - Typically used for storing sensitive browser-side data like user-provided API keys in `localStorage`. - **Note:** This is distinct from the server-side Storage Abstraction Layer used by `SessionManager`, etc. ## Integration with Other Subsystems - **Session Management:** `SessionManager` relies *directly* on the SAL (`StorageProvider` via `StorageFactory`) to persist session state. - **Orchestration Framework:** `OrchestrationStateManager` uses `SessionManager`, thus indirectly depending on the SAL for persisting orchestration state. - **Advanced Memory / RAG:** Vector storage adapters (pgvector, Pinecone, etc.) are ready for AI memory implementation. ## Current Status & Usage - The Key-Value part of the Storage Abstraction Layer is implemented and stable, supporting 15 different adapters. - This KV storage is actively used by `SessionManager` and `OrchestrationStateManager` for persistence when configured (defaults to Memory). - `SecureStorage` is available for client-side use cases. - Vector storage abstractions are implemented and ready for AI memory features. ## Further Reading Dive deeper into specific storage aspects: - [Getting Started Guide](./getting-started.md) - [Storage Abstraction Layer](./storage-abstraction.md) - Complete implementation details - [Vector Storage](./vector-storage.md) - AI and embedding storage - [Session Management](../architecture/sessions/session-management.md) (Details usage of storage) # Storage Abstraction Layer AgentDock provides a unified storage interface that allows you to switch between different storage backends without changing your application code. ## Overview The storage abstraction layer enables: - **Unified Interface**: Single API for all storage operations - **Multiple Backends**: Support for 15 storage providers - **Session Management**: Store orchestration state and session data - **TTL Support**: Built-in expiration for all adapters - **Environment Configuration**: Simple setup via environment variables ## Why This Architecture? ### Open Source First, Commercial Ready AgentDock Core is designed with a clear separation between open source and commercial concerns: - **Open Source Core**: The storage abstraction layer and all adapters remain fully open source - **Commercial Independence**: AgentDock's commercial products (Pro, Enterprise) are built ON TOP of the core, not inside it - **No Vendor Lock-in**: Core consumers can use AgentDock without any commercial features interfering - **Clean Architecture**: Commercial features like advanced multi-tenancy, billing, and enterprise auth layer cleanly on top This design ensures that: 1. Open source users get a complete, production-ready storage system 2. Commercial features never pollute or complicate the core 3. Both open source and commercial products can evolve independently 4. The community benefits from enterprise-grade storage patterns without enterprise complexity ### Multi-Tenancy Considerations The storage layer supports multi-tenancy through namespace isolation: - **Open Source**: Single-tenant or simple namespace-based isolation - **Commercial Products**: Advanced multi-tenancy with organization-level isolation - **Same Core**: Both use the exact same storage adapters and patterns ## Storage Architecture ```mermaid graph TD subgraph "Client Browser" A[AgentDock UI] --> B[localStorage
Chat Messages] end subgraph "API Routes" A --> C[Chat API] C --> D[Session Manager] D --> E[Storage Factory] E --> F{Storage Provider} F --> G[Memory
Development] F --> H[Redis/Upstash
Session Cache] F --> I[Vercel KV
Vercel Deployments] F --> J[SQLite
Local Default] F --> K[PostgreSQL/Supabase
Production Data] F --> L[PG Vector
AI Memory] end style A fill:#f9f,stroke:#333,stroke-width:2px style J fill:#9f9,stroke:#333,stroke-width:2px style K fill:#99f,stroke:#333,stroke-width:2px style H fill:#9ff,stroke:#333,stroke-width:2px ``` ## Current Implementation Status ### What's Actually Built - **Storage Abstraction Layer**: Complete with 15 adapters - **Session Management**: Working with any storage backend (requires persistent storage for survival across restarts) - **Orchestration State**: Persisted via SessionManager - **Client-Side Chat History**: Stored in browser localStorage only ### What's NOT Built Yet - **Server-Side Chat Persistence**: Messages are only in localStorage, not persisted server-side - **AI Memory System**: Storage adapters support vectors, but no memory implementation exists - **User Accounts**: No authentication or user management - **Multi-Tenancy**: Basic namespace support exists, but no tenant management - **Automatic Backups**: Depends on your storage provider (e.g., Supabase has backups) ### Architecture for Future Features When these features are built, the architecture would support: ```mermaid graph LR subgraph "Future State - Local Development" A1[AgentDock App] --> B1[SQLite
Everything] B1 --> C1[Sessions
Messages
History] end subgraph "Future State - Production" A2[AgentDock App] --> B2[Redis/Upstash
Sessions] A2 --> B3[PostgreSQL/Supabase
Accounts & Messages] A2 --> B4[PG Vector
AI Memory] B2 --> C2[Fast Session Access] B3 --> C3[Persistent Data] B4 --> C4[Semantic Search] end style A1 fill:#f9f,stroke:#333,stroke-width:2px style A2 fill:#f9f,stroke:#333,stroke-width:2px style B3 fill:#99f,stroke:#333,stroke-width:2px style B2 fill:#9ff,stroke:#333,stroke-width:2px ``` ## Storage Defaults ### Current Implementation - **Default Storage**: Memory (non-persistent, resets on restart) - **Chat Messages**: Browser localStorage only - **Sessions**: Can persist with configured storage backend - **Development**: SQLite auto-enabled for persistence ## Available Storage Adapters ### Core Adapters (Always Available) These three adapters are built into the core and always available: 1. **Memory** - In-memory storage (default, non-persistent) 2. **Redis/Upstash** - Redis-compatible storage via Upstash client 3. **Vercel KV** - Vercel's KV storage (Redis under the hood) ### Auto-Registered Adapters These adapters are automatically registered by the application when conditions are met: 4. **SQLite** - Auto-registered when `NODE_ENV=development` or `ENABLE_SQLITE=true` 5. **SQLite-vec** - Auto-registered when `NODE_ENV=development` or `ENABLE_SQLITE_VEC=true` 6. **PostgreSQL** - Auto-registered when `DATABASE_URL` is set 7. **PostgreSQL Vector** - Auto-registered when `DATABASE_URL` is set and `ENABLE_PGVECTOR=true` ### Additional Adapters (Manual Registration Required) These adapters require manual registration in your API routes: 8. **MongoDB** - Document storage (optional, not recommended for memory systems) 9. **S3** - Object storage for files 10. **DynamoDB** - AWS NoSQL database 11. **Cloudflare KV** - Edge key-value storage 12. **Cloudflare D1** - Edge SQL database 13. **Pinecone** - Vector database 14. **Qdrant** - Vector database 15. **ChromaDB** - Vector database ## Adapter Pattern Compliance ### StorageProvider Interface All storage adapters in AgentDock Core implement the `StorageProvider` interface, ensuring consistent behavior across different backends: ```typescript interface StorageProvider { // Core KV Operations get(key: string, options?: StorageOptions): Promise set(key: string, value: T, options?: StorageOptions): Promise delete(key: string, options?: StorageOptions): Promise exists(key: string, options?: StorageOptions): Promise // Batch Operations getMany(keys: string[], options?: StorageOptions): Promise> setMany(items: Record, options?: StorageOptions): Promise deleteMany(keys: string[], options?: StorageOptions): Promise // List Operations getList(key: string, start?: number, end?: number, options?: StorageOptions): Promise saveList(key: string, values: T[], options?: StorageOptions): Promise deleteList(key: string, options?: StorageOptions): Promise // Management Operations list(prefix: string, options?: ListOptions): Promise clear(prefix?: string): Promise destroy?(): Promise } ``` ### Implementation Standards Every adapter follows these standards: 1. **Namespace Isolation**: All operations respect namespace boundaries for multi-tenancy 2. **TTL Support**: Optional time-to-live for automatic expiration 3. **Type Safety**: Full TypeScript coverage with zero `any` types 4. **Error Handling**: Consistent error patterns and recovery strategies 5. **Performance**: Batch operations for efficiency 6. **Modularity**: Clean separation of concerns, max 250 lines per module ### Adapter Capabilities Matrix | Feature | Memory | Redis | Vercel KV | SQLite | PostgreSQL | MongoDB | S3 | DynamoDB | CF KV | CF D1 | Vector DBs | |---------|--------|-------|-----------|---------|------------|---------|-----|----------|-------|-------|------------| | KV Operations | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | Batch Ops | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | List Storage | Yes | Yes | Yes | Yes | Yes | Yes | Limited* | Yes | Yes | Yes | Limited** | | TTL Support | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | Namespaces | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | Persistence | No | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | | Transactions | No | Partial | Partial | Yes | Yes | Yes | No | Yes | No | Yes | No | *S3 has limited list operations due to object storage nature **Vector databases have limited list operations, optimized for vector search instead ## Quick Start ### 1. Local Development ```bash # Run the app pnpm dev # Automatically enabled: # - SQLite storage adapter registered # - Sessions persist to ./agentdock.db # - SQLite-vec adapter registered (vector operations available) ``` What's actually persisted: - Session state (orchestration state, temporary data) - Any data you explicitly store via the storage API What's NOT persisted yet: - Chat messages (only in browser localStorage) - User accounts (not implemented) - AI memory (storage ready, but memory system not built) ### 2. Production Setup (PostgreSQL/Supabase) For production, you can use any PostgreSQL database. Supabase is a popular choice: **Step 1: Database Setup** 1. Create a PostgreSQL database (Supabase, Neon, Railway, or self-hosted) 2. Get your connection string **Step 2: Configure Storage** ```bash # Add to .env.local DATABASE_URL=postgresql://user:password@host:5432/dbname KV_STORE_PROVIDER=postgresql # Optional: Enable pgvector for future AI features ENABLE_PGVECTOR=true ``` **Step 3: Enable pgvector (Optional)** If you plan to use vector features later: ```sql CREATE EXTENSION IF NOT EXISTS vector; ``` **Step 4: Deploy** ```bash pnpm build pnpm start ``` What this enables: - Session persistence across restarts - Storage API with PostgreSQL backend - Vector operations ready (if pgvector enabled) What still requires implementation: - Server-side chat persistence - User authentication - AI memory system ### 3. Vercel Deployment ```bash # Both work identically (Upstash under the hood) KV_STORE_PROVIDER=redis # Direct Upstash # OR KV_STORE_PROVIDER=vercel-kv # Vercel wrapper ``` ## Production Architecture Patterns ### Current Capabilities ```typescript // What's actually implemented: { sessions: StorageProvider, // Any configured backend orchestration: StorageProvider // Same backend as sessions } // What's NOT implemented yet: { messages: undefined, // Only in browser localStorage memory: undefined, // Storage ready, system not built accounts: undefined // No user management } ``` ### Future Architecture Pattern When these features are implemented, the recommended architecture would be: ```typescript // Development { everything: SQLite // Simple local persistence } // Production { sessions: Redis, // Fast access data: PostgreSQL, // Persistent storage vectors: PostgreSQLVector // AI features } ``` ## Design Decisions Explained ### Why This Architecture? 1. **Separation of Concerns**: Storage is independent of business logic 2. **Flexibility**: Switch backends without code changes 3. **Performance**: Use the right storage for each data type 4. **Scalability**: From local SQLite to distributed systems 5. **Multi-tenancy Ready**: Namespace isolation built-in ### Future-Proofing The storage layer is designed to support: - **Open Source Growth**: Community can add adapters without touching core - **Commercial Features**: Enterprise features layer on top cleanly - **AI Evolution**: Vector storage ready for advanced AI features - **Global Scale**: From single-user to millions of concurrent sessions ## Next Steps ### Future Features - Admin dashboard for multi-tenancy - Traceability and observability - Advanced memory modules - Vertical-specific optimizations ## Configuration Reference ### Environment Variables ```bash # Storage Selection KV_STORE_PROVIDER=sqlite # memory, redis, vercel-kv, sqlite, postgresql, mongodb # SQLite (auto-configured) # No additional config needed # Redis/Upstash REDIS_URL=https://... REDIS_TOKEN=... # PostgreSQL/Supabase DATABASE_URL=postgresql://... ENABLE_POSTGRESQL=true ENABLE_PGVECTOR=true # For AI memory # Session Configuration SESSION_TTL_SECONDS=1800 # 30 minutes default # Optional Adapters ENABLE_MONGODB=true MONGODB_URI=mongodb://... ``` ## Migration Path ### Current → Future 1. **Now**: Browser localStorage for chat UI 2. **Next**: SQLite for local persistence 3. **Production**: Redis + PostgreSQL + PG Vector ### Simple Demo Setup ```bash # One command, everything works KV_STORE_PROVIDER=sqlite # SQLite handles sessions, messages, and history ``` ## Quick Reference: Storage Configuration ### For AI Chat Applications (Character.AI Style) #### Development = Zero Config ```bash # Nothing to configure! pnpm dev # SQLite enabled automatically # Data persists in ./agentdock.db ``` #### Production = 3 Lines in .env.local ```bash # Step 1: Add these to .env.local DATABASE_URL=postgresql://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT].supabase.co:5432/postgres ENABLE_PGVECTOR=true KV_STORE_PROVIDER=postgresql # Step 2: Run pnpm build && pnpm start ``` ### For Basic Applications (No AI Memory) ```bash # Choose one: KV_STORE_PROVIDER=memory # Development only KV_STORE_PROVIDER=redis # With Redis/Upstash KV_STORE_PROVIDER=vercel-kv # For Vercel deployments ``` ### Registering Additional Storage ```typescript // Only if you need S3, DynamoDB, or vector DBs import { registerCloudAdapters, registerVectorAdapters } from 'agentdock-core/storage'; // In your API route const factory = getStorageFactory(); await registerCloudAdapters(factory); // S3, DynamoDB, Cloudflare await registerVectorAdapters(factory); // Pinecone, Qdrant, ChromaDB ``` ## Related Documentation - [Getting Started Guide](./getting-started.md) - [Memory System Documentation](../memory/README.md) - [Session Management](../architecture/sessions/session-management.md) ## Complete .env.local Examples ### For Local Development ```bash # Storage is auto-configured in development # No .env.local changes needed for storage ``` ### For Production ```bash # PostgreSQL/Supabase Configuration DATABASE_URL=postgresql://postgres:[YOUR-PASSWORD]@db.[YOUR-PROJECT].supabase.co:5432/postgres KV_STORE_PROVIDER=postgresql # Optional: Enable vector extension ENABLE_PGVECTOR=true # Alternative: Redis/Upstash for sessions only REDIS_URL=https://[YOUR-URL].upstash.io REDIS_TOKEN=[YOUR-TOKEN] KV_STORE_PROVIDER=redis ``` ## Detailed Configuration Reference ### 1. Environment Variables All storage options you can set in `.env.local`: ```bash # ============================================================================== # OFFICIALLY SUPPORTED STORAGE (Auto-registered in app) # ============================================================================== # SQLite - Local Development (default in development) ENABLE_SQLITE=true # Enable SQLite adapter ENABLE_SQLITE_VEC=true # Enable SQLite with vector search for AI memory SQLITE_PATH=./agentdock.db # Optional: Custom database path # PostgreSQL - Production (enabled when DATABASE_URL is set) DATABASE_URL=postgresql://user:password@localhost:5432/agentdock ENABLE_PGVECTOR=true # Enable pgvector extension for AI memory # Key-Value Storage Provider Selection KV_STORE_PROVIDER=sqlite # Options: memory, redis, vercel-kv, sqlite, postgresql # ============================================================================== # OPTIONAL STORAGE ADAPTERS (Manual registration required) # ============================================================================== # MongoDB (Document storage - not recommended for memory system) ENABLE_MONGODB=true MONGODB_URI=mongodb://localhost:27017/agentdock # Redis/Upstash (Session caching) REDIS_URL=redis://localhost:6379 REDIS_TOKEN=optional-auth-token # Vercel KV (auto-configured on Vercel) KV_URL=https://... KV_REST_API_TOKEN=... # For other adapters (S3, DynamoDB, vector DBs), see full list in .env.example ``` ### 2. Using Auto-Registered Adapters The app automatically registers these adapters based on environment variables: - **SQLite**: When `NODE_ENV=development` or `ENABLE_SQLITE=true` - **SQLite-vec**: When `NODE_ENV=development` or `ENABLE_SQLITE_VEC=true` - **PostgreSQL**: When `DATABASE_URL` is set - **PostgreSQL Vector**: When `DATABASE_URL` is set and `ENABLE_PGVECTOR=true` - **MongoDB**: When `ENABLE_MONGODB=true` and `MONGODB_URI` is set ### 3. Using Additional Storage Adapters (S3, DynamoDB, etc.) These adapters are NOT auto-registered to keep your app fast. Here's how to use them: **Step 1: Set Environment Variables** ```bash # In .env.local, enable what you need: ENABLE_S3=true S3_BUCKET=my-bucket AWS_REGION=us-east-1 AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... ``` **Step 2: Register the Adapter in Your Code** ```typescript // In app/api/your-route/route.ts import { getStorageFactory } from 'agentdock-core'; import { registerCloudAdapters } from 'agentdock-core/storage'; export async function POST(req: Request) { // Step 2a: Get the factory const factory = getStorageFactory(); // Step 2b: Register adapters you need if (process.env.ENABLE_S3 === 'true') { await registerCloudAdapters(factory); } // Step 3: Use the adapter const s3Storage = factory.getProvider({ type: 's3' }); await s3Storage.set('my-file', fileData); } ``` **Available Registration Functions:** - `registerCloudAdapters()` - S3, DynamoDB, Cloudflare - `registerVectorAdapters()` - Pinecone, Qdrant, ChromaDB - `registerMongoDBAdapter()` - MongoDB only ### 3. Storage Selection Logic The system selects storage based on: 1. **Environment Variable**: `KV_STORE_PROVIDER` 2. **Fallback Logic**: - If Redis URL exists → Use Redis - If on Vercel → Use Vercel KV - Otherwise → Use Memory (with warning) ## Usage Examples ### Character.AI Style App (Redis) For a character.ai style app with persistent conversations: ```bash # .env.local KV_STORE_PROVIDER=redis REDIS_URL=redis://localhost:6379 ``` ### Production with PostgreSQL ```bash # .env.local KV_STORE_PROVIDER=postgresql DATABASE_URL=postgresql://user:pass@host:5432/agentdock ``` ### Development with SQLite ```bash # .env.local KV_STORE_PROVIDER=sqlite # No DATABASE_URL needed - uses local file ``` ## Architecture Decision - **Client-side**: Only Memory storage (no direct DB access) - **API Routes**: All storage adapters available - **Edge Functions**: Memory, Redis (Upstash), Vercel KV ## Troubleshooting ### "Module not found" errors - Node.js adapters aren't available client-side - Ensure you're only using them in API routes ### Storage not persisting - Check if you're using Memory storage (default) - Set `KV_STORE_PROVIDER` to a persistent option ### MongoDB not working - Ensure `ENABLE_MONGODB=true` is set - MongoDB adapter is optional to reduce dependencies ## Storage Abstraction ## Overview AgentDock includes a comprehensive storage abstraction layer that provides a unified interface for multiple storage backends, enabling developers to switch between different storage solutions without changing application code. ## Implementation The storage abstraction layer has been fully implemented with: ### Core Features - Unified `StorageProvider` interface for all backends - Factory pattern with environment-based configuration - Essential adapters: Memory, Redis, Vercel KV - Full integration with SessionManager and OrchestrationManager - Built-in TTL support across all providers ### Extended Storage Support - SQLite for local persistence - PostgreSQL for production deployments - PostgreSQL Vector for AI/embeddings - MongoDB as optional document store - Automatic Node.js adapter registration ### Advanced Capabilities - S3, DynamoDB, Cloudflare KV/D1 adapters - Pinecone, Qdrant, ChromaDB for vector operations - SQLite-vec for local vector search - Consistent patterns across all adapters ## Available Adapters (15 Total) ### Always Available (Auto-registered) 1. **Memory** - Default, in-memory storage 2. **Redis/Upstash** - High-performance distributed cache 3. **Vercel KV** - Vercel's Redis-compatible service ### Core Storage (Server-side) 4. **SQLite** - File-based local storage 5. **SQLite-vec** - SQLite with vector search capabilities 6. **PostgreSQL** - Production relational database 7. **PostgreSQL Vector** - pgvector for embeddings 8. **MongoDB** - Document storage (enable with `ENABLE_MONGODB=true`) ### Additional Adapters (Not Auto-registered) To keep build size small: - S3, DynamoDB, Cloudflare KV/D1, Pinecone, Qdrant, ChromaDB ## Implementation Details ### Architecture ```typescript // Unified interface interface StorageProvider { get(key: string): Promise set(key: string, value: any, ttl?: number): Promise delete(key: string): Promise exists(key: string): Promise list(pattern?: string): Promise } ``` ### Configuration ```bash # Simple env-based setup KV_STORE_PROVIDER=redis REDIS_URL=https://your-instance.upstash.io REDIS_TOKEN=your-token ``` ### Usage ```typescript // Automatic adapter selection const storage = getStorageFactory().getProvider(); await storage.set('key', 'value'); ``` ## Key Achievements 1. **Zero Breaking Changes**: Default memory storage maintains compatibility 2. **Simple Configuration**: Environment variables control everything 3. **Production Ready**: Battle-tested adapters for all use cases (15 total) 4. **Developer Friendly**: Single API to learn, works everywhere 5. **Flexible Architecture**: Easy to add new storage backends 6. **Build Optimization**: Non-essential adapters not auto-registered to keep builds small ## Technical Decisions 1. **Factory Pattern**: Centralized adapter management 2. **Dynamic Imports**: Node.js adapters load only when needed 3. **TTL First-class**: Built into core interface 4. **Environment Config**: Simple setup via env vars ## Use Cases ### Current - **Session Management**: Redis for distributed sessions - **Message History**: PostgreSQL for durability - **Vector Search**: pgvector for semantic search - **Development**: SQLite for local persistence ### Future Considerations - Storage migration utilities - Multi-provider sync capabilities - Compression middleware - Encryption at rest ## Documentation - [Storage Overview](../storage/README.md) - [Getting Started Guide](../storage/getting-started.md) - [Architecture Docs](../architecture/sessions/session-management.md) ## Success Metrics - 15 production-ready adapters (including SQLite-vec) - Zero-config memory storage - < 5 min setup for any adapter - No client-side bundling issues - Backward compatible ## Vector Storage Vector storage provides embedding-based retrieval for memories, documents, and semantic search across the AgentDock platform. ## Overview AgentDock includes a complete vector storage system with production-ready adapters fully integrated with the memory system, plus community-supported adapters for specialized use cases. ## Production-Ready Adapters (Memory System Integrated) ### 1. **PostgreSQL + pgvector** ✅ - **Status**: Fully integrated with memory system - **Use Case**: Production deployments - Full vector similarity search - Scales to millions of vectors - HNSW and IVFFlat indexes - Hybrid search capabilities - Native memory operations support ### 2. **SQLite + sqlite-vec** ✅ - **Status**: Fully integrated with memory system - **Use Case**: Development and local testing - Local vector search - Zero external dependencies - Perfect for development - 768-dimension support - Native memory operations support ## Community Extensions The following adapters are available as community extensions for specialized use cases: ### 3. **ChromaDB** - Dedicated vector database - Built-in collections - Metadata filtering - REST API interface ### 4. **Qdrant** - High-performance vector search - Advanced filtering - Batch operations - Clustering support ### 5. **Pinecone** - Managed cloud service - Serverless vector search - Auto-scaling - Global replication ### AI SDK Integration AgentDock exports AI SDK's embedding functions directly: ```typescript import { embed, embedMany } from 'agentdock-core/llm'; import { createOpenAIModel } from 'agentdock-core/llm'; // Create embedding model const embeddingModel = createOpenAIModel({ model: 'text-embedding-3-small', apiKey: process.env.OPENAI_API_KEY }); // Generate single embedding const result = await embed({ model: embeddingModel, value: 'Your text to embed' }); // Generate batch embeddings const results = await embedMany({ model: embeddingModel, values: ['Text 1', 'Text 2', 'Text 3'] }); ``` ## Architecture ### Storage Layer Integration ```typescript // Vector operations are part of storage adapters import { getStorageFactory } from 'agentdock-core'; const factory = getStorageFactory(); const vectorStorage = factory.getProvider({ type: 'postgresql-vector', config: { connectionString: process.env.DATABASE_URL, enableVector: true, defaultDimension: 1536 } }); ``` ### Vector Operations Interface All vector-enabled adapters implement: ```typescript interface VectorOperations { // Collection management createCollection(config: VectorCollectionConfig): Promise; dropCollection(name: string): Promise; // Vector CRUD insertVectors(collection: string, vectors: VectorData[]): Promise; updateVectors(collection: string, vectors: VectorData[]): Promise; deleteVectors(collection: string, ids: string[]): Promise; // Search searchVectors( collection: string, queryVector: number[], options?: VectorSearchOptions ): Promise; } ``` ## Memory System Integration ### 1. Memory Embeddings ```typescript // Generate embeddings for memories const memoryEmbedding = await embed({ model: embeddingModel, value: memory.content }); // Store in vector collection await vectorStorage.insertVectors('memories', [{ id: memory.id, vector: memoryEmbedding.embedding, metadata: { agentId: memory.agentId, type: memory.type, importance: memory.importance } }]); ``` ### 2. Semantic Memory Recall ```typescript // Generate query embedding const queryEmbedding = await embed({ model: embeddingModel, value: userQuery }); // Search similar memories const similarMemories = await vectorStorage.searchVectors( 'memories', queryEmbedding.embedding, { k: 10, filter: { agentId: currentAgentId }, includeScore: true } ); ``` ### 3. Batch Processing ```typescript // Batch embed memories for efficiency const memoryTexts = memories.map(m => m.content); const embeddings = await embedMany({ model: embeddingModel, values: memoryTexts }); // Batch insert const vectorData = memories.map((memory, i) => ({ id: memory.id, vector: embeddings.embeddings[i], metadata: { agentId: memory.agentId, type: memory.type, createdAt: memory.createdAt } })); await vectorStorage.insertVectors('memories', vectorData); ``` ## Production Configurations ### PostgreSQL + pgvector (Recommended) ```typescript // Production setup with pgvector const vectorStorage = factory.getProvider({ type: 'postgresql-vector', config: { connectionString: process.env.DATABASE_URL, enableVector: true, defaultDimension: 1536, defaultMetric: VectorMetric.COSINE, ivfflat: { lists: 100, // For 1M vectors probes: 10 // Query accuracy } } }); ``` ### Embedding Model Selection ```typescript // Cost-optimized embedding const smallModel = createOpenAIModel({ model: 'text-embedding-3-small', // $0.02/1M tokens apiKey: process.env.OPENAI_API_KEY }); // Quality-optimized embedding const largeModel = createOpenAIModel({ model: 'text-embedding-3-large', // $0.13/1M tokens apiKey: process.env.OPENAI_API_KEY }); ``` ## Performance Optimization ### 1. Batch Operations - Process embeddings in batches of 100-1000 - Use `embedMany` for multiple texts - Batch vector insertions ### 2. Caching Strategy ```typescript // Cache embeddings to avoid re-computation const embeddingCache = new Map(); async function getCachedEmbedding(text: string): Promise { const hash = createHash(text); if (embeddingCache.has(hash)) { return embeddingCache.get(hash)!; } const result = await embed({ model, value: text }); embeddingCache.set(hash, result.embedding); return result.embedding; } ``` ### 3. Index Optimization - Use IVFFlat for large datasets (>100K vectors) - Tune `lists` parameter: sqrt(num_vectors) - Increase `probes` for better accuracy ## Cost Management ### Embedding Costs (OpenAI) - text-embedding-3-small: $0.02 per 1M tokens - text-embedding-3-large: $0.13 per 1M tokens - ada-002: $0.10 per 1M tokens (legacy) ### Cost Optimization Strategies 1. Use smaller models for non-critical content 2. Cache embeddings aggressively 3. Batch operations to reduce API calls 4. Filter content before embedding 5. Use dimension reduction when appropriate ## Common Use Cases ### 1. Semantic Memory Search Find memories related to current context ### 2. Document Retrieval RAG implementation for knowledge bases ### 3. Similarity Matching Find similar conversations or patterns ### 4. Concept Clustering Group related memories automatically ### 5. Context Building Retrieve relevant history for agents ## Migration Guide ### From Placeholder to Real Embeddings ```typescript // Before: ChromaDB placeholder const embeddingFunction = new DefaultEmbeddingFunction(); // After: Real embeddings const embeddingFunction = { async generate(documents: string[]): Promise { const result = await embedMany({ model: embeddingModel, values: documents }); return result.embeddings; } }; ``` ## Monitoring and Debugging ### Vector Storage Metrics - Index size and performance - Query latency (p50, p95, p99) - Embedding generation time - Cache hit rates ### Debug Utilities ```typescript // Check vector similarity import { cosineSimilarity } from 'agentdock-core/evaluation'; const similarity = cosineSimilarity(vector1, vector2); console.log(`Similarity: ${similarity}`); ``` ## Next Steps With vector storage fully implemented, the memory system can now: 1. Generate real embeddings for all memory types 2. Perform semantic search at scale 3. Build memory networks with vector similarity 4. Enable hybrid search (vector + metadata) 5. Support multi-modal embeddings (future) ## Testing Strategy This document outlines the testing strategy for the AgentDock project, with a particular focus on the `agentdock-core` framework and its comprehensive unit testing approach. ## Core Principles 1. **Strict Dependency Isolation**: Each unit test must isolate the unit under test from its dependencies using mocks. 2. **Consistent Mocking Patterns**: Use standardized mocking approaches consistently across all tests. 3. **Reusable Test Helpers**: Leverage helper functions to create standardized mocks. 4. **Comprehensive Coverage**: Aim for high test coverage of core functionality. 5. **Clear Test Structure**: Organize tests logically with descriptive names. ## Mocking Strategy ### 1. Direct Dependencies All direct dependencies of a unit under test MUST be mocked. This includes: - Other core classes/components - External clients/APIs - Utility functions with side effects - Storage providers ### 2. Mocking Techniques #### Module Mocking Use `jest.mock()` to mock entire modules: ```typescript // Mock the entire logging module jest.mock('../../logging', () => ({ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() }, LogCategory: { NODE: 'node' } })); ``` #### Function Mocking Use `jest.fn()` to create mock functions: ```typescript const mockFunction = jest.fn().mockReturnValue('mocked result'); // or const mockAsyncFunction = jest.fn().mockResolvedValue({ success: true }); ``` #### Implementation Mocking Use `mockImplementation()` to define complex mock behavior: ```typescript const mockFunction = jest.fn().mockImplementation((arg1, arg2) => { if (arg1 === 'test') { return arg2 * 2; } return arg2; }); ``` #### Standard Mock Objects Use the helper functions in `src/test/setup.ts` to create standardized mock objects: ```typescript import { createMockCoreLLM, createMockOrchestrationManager } from '../../test/setup'; const mockLLM = createMockCoreLLM({ provider: 'openai', modelId: 'gpt-4.1' }); const mockOrchestrationManager = createMockOrchestrationManager(); ``` ### 3. Jest Configuration The Jest configuration for `agentdock-core` is optimized for unit testing: - Tests are run from the root project using the `jest.config.ts` configuration - `clearMocks: true` ensures mocks are automatically cleared between tests - Coverage reporting is enabled to track test coverage ## Test Structure ### File Organization - Tests are located in `__tests__` directories adjacent to the code they test - Test files are named with the `.test.ts` suffix - Helper functions are in `src/test/setup.ts` ### Test Case Structure ```typescript describe('ComponentName', () => { // Setup that applies to all tests beforeEach(() => { jest.clearAllMocks(); // Initialize test objects }); describe('methodName', () => { it('should handle scenario X', () => { // Arrange - set up test conditions // Act - call the method // Assert - verify the results }); it('should handle error case Y', () => { // Test error handling }); }); }); ``` ## Best Practices 1. **Reset Mocks Between Tests**: Use `jest.clearAllMocks()` in `beforeEach` to reset mocks 2. **Mock Minimal Surface Area**: Only mock what's necessary 3. **Verify Mock Interactions**: Check that mocks were called with expected arguments 4. **Test Edge Cases**: Include tests for error conditions and edge cases 5. **Descriptive Test Names**: Use clear, descriptive names for test cases 6. **Use Helper Functions**: Leverage the helper functions in `src/test/setup.ts` for creating consistent mocks ## Module-Specific Testing Guidelines ### Orchestration Module Testing The orchestration module (`OrchestrationManager`, `OrchestrationStateManager`, `StepSequencer`) requires comprehensive testing of: - State transitions and management - Tool filtering and sequencing - Conditional logic for step activation - Error handling and edge cases Use the `createMockOrchestrationManager()` helper function to create standardized mocks for orchestration components. ### Storage Module Testing The storage module requires testing of: - Interface compliance for all provider implementations - CRUD operations and TTL functionality - Provider-specific logic and error handling - Factory instantiation and configuration Use the `createMockStorageProvider()` helper function to create standardized mocks for storage components. ### Node System Testing The core node system requires testing of: - Node registration and retrieval - Tool registration and filtering - Metadata validation and port definitions - Node instantiation and execution Use the `createMockBaseNode()` helper function to create standardized mocks for node components. ## Helper Functions The `src/test/setup.ts` file provides helper functions for creating standardized mocks: - `createMockCoreLLM()`: Creates a mock CoreLLM instance with configurable behavior - `createMockLLMOrchestrationService()`: Creates a mock LLMOrchestrationService instance - `createMockOrchestrationManager()`: Creates a mock OrchestrationManager instance - `createMockStorageProvider()`: Creates a mock StorageProvider instance - `createMockBaseNode()`: Creates a mock BaseNode instance These helper functions ensure consistent behavior across tests and facilitate strict dependency isolation. ## Token Usage Tracking & Smart Context Management AgentDock Core provides mechanisms for tracking LLM token usage and plans for advanced features to manage the context window intelligently. ## Current Implementation: Tracking Actual Usage The current system focuses on tracking the **actual tokens consumed** during an LLM call and accumulating this count within the session state. ### 1. `CoreLLM`: Reporting Usage from AI SDK The `CoreLLM` class interfaces with the Vercel AI SDK. - **Callback Mechanism:** Methods like `streamText` accept an `onUsageAvailable` callback. - **Extraction:** After an LLM interaction completes, `CoreLLM` extracts the `usage` data (`promptTokens`, `completionTokens`) provided by the AI SDK (if available). - **Invocation:** `CoreLLM` invokes the `onUsageAvailable` callback passed to it (typically by `AgentNode`), providing the `TokenUsage` for that specific turn. ```mermaid sequenceDiagram participant AN as AgentNode participant CL as CoreLLM participant AISDK as Vercel AI SDK participant Callback as "onUsageAvailable (in AN)" AN->>+CL: streamText(..., onUsageAvailable) CL->>+AISDK: streamText(...) AISDK-->>-CL: Stream Events & Final Completion (with usage) CL-->>CL: Internal onFinish triggered CL-->>CL: Extracts TokenUsage (Actual) CL-->>Callback: Invoke Callback(actualUsage) Callback-->>AN: (Updates State) Note over AN,CL: CoreLLM reports actual usage via callback CL-->>-AN: Returns Stream Result ``` ### 2. `AgentNode` & State: Storing Cumulative Usage `AgentNode` receives the actual usage report from `CoreLLM` and updates the session state. - **Handling Callback:** `AgentNode` provides an internal method to `CoreLLM` as the `onUsageAvailable` callback. - **State Update:** When the callback is invoked with the actual `TokenUsage` for the turn: 1. `AgentNode` retrieves the current `AIOrchestrationState` via the `OrchestrationManager`. 2. It reads the existing `cumulativeTokenUsage`. 3. It adds the received actual usage to the cumulative totals. 4. It saves the updated state using `OrchestrationManager.updateState()`. - **Stored Data:** The `cumulativeTokenUsage: { promptTokens: number, completionTokens: number, totalTokens: number }` is persisted in the `AIOrchestrationState` (e.g., Redis). ```mermaid sequenceDiagram participant Callback as "_handleUsageCallback (in AN)" participant OM as OrchestrationManager participant Store as "State Store" Callback->>+OM: getState(sessionId) OM->>+Store: GET state Store-->>-OM: Return state OM-->>-Callback: Return state (with current total) Callback->>Callback: Add current turn usage to total Callback->>+OM: updateState(sessionId, newTotal) OM->>+Store: SET state Store-->>-OM: Confirm update OM-->>-Callback: Confirm update ``` ### 3. OSS Client Integration (Current Status) - **Debug Panel Display:** The Open Source client **currently displays** the cumulative token usage (`promptTokens`, `completionTokens`, `totalTokens`) for the active session, typically within a **debug panel** or similar diagnostic view. - **Data Fetching:** This is achieved by the client making an API call (likely similar to a conceptual `GET /api/session/[sessionId]/state`) to the backend. The backend retrieves the `AIOrchestrationState` using the `OrchestrationManager` and returns it, including the `cumulativeTokenUsage` field, which the client then renders. ```mermaid graph LR A[Client UI Debug Panel] -- Fetch State --> B("GET /api/.../state"); B --> C{API Handler}; C -- Get State --> D[OrchestrationManager]; D -- Retrieve --> E[State Store]; E -- State --> D; D -- State --> C; C -- JSON (incl. usage) --> B; B -- Data --> A; style A fill:#ccf,stroke:#333 ``` ## Planned Enhancements: Smart Context Management Building upon the actual usage tracking, the **primary future goal** is to proactively manage context size *before* sending requests to the LLM. ### 1. Token Estimation Strategy (Planned/Conceptual) Accurate token *estimates* are needed for pre-computation *before* an LLM call. Since the AI SDK only provides *actual* usage *after* a call, AgentDock Core must implement its own estimation logic. - **Custom Estimation:** Relies on utilities (like a conceptual `TokenCounter`) to estimate token counts. - **Methods:** This involves: - Using official standalone tokenizers like `tiktoken` (for OpenAI/DeepSeek compatible models) or `@anthropic-ai/tokenizer` when available and applicable. - Employing heuristic methods (based on character/word counts, script analysis for different languages like CJK, etc.) as a fallback or for unsupported models/content (e.g., code snippets, specific data formats). - **Goal:** Get the best possible *estimate* for the prompt payload *before* sending it. ```mermaid graph TD A["Need Token Estimate (Before Send)"] --> B{"Use Custom Estimation Logic"}; B -- "Official Tokenizer Available (tiktoken/Anthropic)?" --> C["Use Official Tokenizer Estimate"]; B -- "No Applicable Official Tokenizer" --> D["Use Heuristic Estimate (Chars/Words/Scripts)"]; C --> E["Estimated Token Count"]; D --> E; E --> F["Inform AgentNode Context Assembly"]; style C fill:#eef,stroke:#333 style D fill:#eee,stroke:#333 ``` ### 2. `AgentNode`: Smart Context Assembly Logic (Planned) `AgentNode` would use these custom token *estimates* to manage the *entire context payload* (including message history, injected memory, etc.) before calling `CoreLLM`. - **Configuration:** Use `ContextManagementOptions` (`maxTokens`, `reserveTokens`, etc.). - **Pre-computation & Pruning:** Before generating a response: 1. Assemble the potential context payload (system prompt, message history, relevant memory chunks, summaries, etc.). 2. Estimate the total tokens for this payload using the custom estimation logic. 3. Calculate the available budget (`maxTokens - reserveTokens`). 4. If `estimatedTokens > budget`: * **Summarization:** Optionally summarize older parts of the history or less critical memory elements (may require internal LLM call). * **Truncation:** Remove the least relevant elements (e.g., oldest messages, lowest priority memory items) until the estimate fits the budget. - **LLM Call:** Send only the managed, fitted context payload to `CoreLLM`. ```mermaid sequenceDiagram participant User participant AN as AgentNode participant TE as "Custom Token Estimator" participant LLM as CoreLLM User->>+AN: handleMessage(newMessage) AN->>AN: Assemble context (History + Memory + NewMsg) AN->>+TE: estimateTokens(fullContextPayload) TE-->>-AN: estimatedTokens AN->>AN: Check budget alt Exceeds Budget AN->>AN: Summarize or Truncate Payload (History/Memory) end AN->>+LLM: streamText(managedContextPayload) LLM-->>-AN: Stream Response (Actual usage reported via callback) AN-->>-User: Stream Response ``` ## Downstream Applications (Enabled by Actual Usage Tracking) While smart context management is the core driver for future development, the **current** persistent tracking of *actual* cumulative usage enables: - **Reporting:** Displaying usage in the client debug panel (as currently implemented). - **Future Cost Estimation:** Mapping actual cumulative tokens to costs. - **Future Budgeting/Limits:** Enforcing limits based on actual cumulative usage. - **Future Analytics:** Aggregating actual usage data. *(Conceptual diagrams for Cost Estimation, Budgeting, Reporting UI remain valid for these applications based on tracked actual usage).* ## Summary AgentDock currently tracks **actual** LLM token usage post-call (reported by `CoreLLM` via SDK data) and accumulates it in the session state, visible in the client's debug panel. The **planned enhancements** focus on using **custom token estimation** logic (like `tiktoken` or heuristics) *before* LLM calls for smart context assembly within `AgentNode`, managing message history and memory to fit model limits. The tracked actual usage provides the data foundation for monitoring and future features like cost tracking and budgeting. - **Internal Callback:** `CoreLLM` now maintains an internal callback (`_onUsageDataAvailable`). This callback can be set by consuming code (like `AgentNode`). - **`generateText` & `streamText` Integration:** Both methods, upon completion (in `onFinish` for streaming or after the call for non-streaming), extract the `usage` data (containing `promptTokens`, `completionTokens`, `totalTokens`) provided by the underlying LLM provider (e.g., OpenAI, Anthropic via Vercel AI SDK). - **Callback Invocation:** If the internal callback is set, `CoreLLM` invokes it immediately after processing a response, passing the `TokenUsage` object. ```typescript // Simplified example from CoreLLM private async _handleCompletion(completionResult: any, options: any) { // ... extract usage data ... const usageData: TokenUsage = { /* ... extracted tokens ... */ }; // Invoke the internal callback if it exists if (this._onUsageDataAvailable) { try { await this._onUsageDataAvailable(usageData); } catch (error) { logger.error(/* ... */); } } // ... handle original onFinish or return result ... } // Method to set the internal callback public setOnUsageDataAvailable(handler: ((usage: TokenUsage) => Promise) | null): void { this._onUsageDataAvailable = handler; } ``` ## Session Persistence: `OrchestrationStateManager` While `CoreLLM` *reports* usage per call, persistent tracking across a session is handled by the `OrchestrationStateManager`. - **`OrchestrationState`:** The state object managed per session includes an optional `cumulativeTokenUsage` field: ```typescript interface OrchestrationState extends SessionState { // ... other fields cumulativeTokenUsage?: { promptTokens: number; completionTokens: number; totalTokens: number; }; } ``` - **Update Handler:** Components like `AgentNode` are responsible for coordinating usage updates. They typically: 1. Define an `updateUsageHandler` function. 2. Set this handler on the `CoreLLM` instance using `setOnUsageDataAvailable` before making an LLM call. 3. The `updateUsageHandler` receives `TokenUsage` data via the callback. 4. Inside the handler, it retrieves the current `OrchestrationState` using `OrchestrationStateManager.getState`. 5. It calculates the *new* cumulative totals by adding the received usage to the existing totals in the state. 6. It calls `OrchestrationStateManager.updateState` to save the updated `cumulativeTokenUsage` back to the session state. 7. Clear the handler from `CoreLLM` after the call using `setOnUsageDataAvailable(null)`. ```typescript // Simplified example from AgentNode or similar async handleInteraction(...) { const stateManager = createOrchestrationStateManager(); // Get configured manager const llm = this.llm; // Get CoreLLM instance const sessionId = /* ... get session ID ... */; const updateUsageHandler = async (usage: TokenUsage) => { const currentState = await stateManager.getState(sessionId); const currentUsage = currentState?.cumulativeTokenUsage || { promptTokens: 0, completionTokens: 0, totalTokens: 0 }; const newCumulativeUsage = { promptTokens: currentUsage.promptTokens + (usage.promptTokens || 0), completionTokens: currentUsage.completionTokens + (usage.completionTokens || 0), totalTokens: currentUsage.totalTokens + (usage.totalTokens || 0), }; await stateManager.updateState(sessionId, { cumulativeTokenUsage: newCumulativeUsage }); logger.debug( LogCategory.USAGE, 'UsageUpdateHandler', 'Updated cumulative session usage', { sessionId, newTotal: newCumulativeUsage.totalTokens } ); }; // Set handler before LLM call llm.setOnUsageDataAvailable(updateUsageHandler); try { // Make the LLM call (e.g., streamText) const result = await llm.streamText(/* ... */); // Process result } finally { // IMPORTANT: Clear the handler afterwards llm.setOnUsageDataAvailable(null); } } ``` ## Tool Usage Tracking This callback mechanism works seamlessly with tools that internally use `CoreLLM` (like `ReflectTool`): 1. The tool execution logic obtains the `CoreLLM` instance and the `updateUsageHandler` (passed down through context or parameters). 2. It sets the handler on its `CoreLLM` instance before making its internal `generateText` or `streamText` call. 3. When the tool's LLM call finishes, the handler updates the *same* session's `cumulativeTokenUsage` via the `OrchestrationStateManager`. 4. The handler is cleared within the tool's scope. This ensures that token usage from both direct agent interactions and tool-invoked LLM calls are aggregated into the session's total. ## Accessing Usage Data - **Session State:** The primary way to access the *cumulative* usage for a session is by retrieving the `OrchestrationState` via `OrchestrationStateManager.getState(sessionId)` and accessing the `cumulativeTokenUsage` property. - **Debugging:** - The `updateUsageHandler` typically logs the incremental updates. - Individual LLM call usage might still be logged by components like `AgentNode` for immediate debugging, but this reflects only the *last* call, not the session total. - **API Responses:** While the previous implementation added usage for the *last* LLM call to headers (`x-token-usage`), a more accurate approach for billing or display would be to retrieve the `cumulativeTokenUsage` from the session state at the end of the request in the API route handler and potentially return *that* value (e.g., in the response body or a different header like `x-session-cumulative-token-usage`). ## Summary Token usage tracking relies on `CoreLLM` callbacks to report usage per LLM call and the `OrchestrationStateManager` to persist the cumulative total for the entire session within the `OrchestrationState`. This provides a robust way to track usage across complex interactions involving multiple LLM calls and tool executions.