### Environment Variable Setup for AxCrew Examples Source: https://github.com/amitdeshmukh/ax-crew/blob/main/examples/README.md Example of how to configure necessary API keys and credentials in a .env file for running AxCrew examples. This includes keys for Anthropic, OpenAI, Gemini, and WordPress. ```env ANTHROPIC_API_KEY=your_anthropic_key OPENAI_API_KEY=your_openai_key GEMINI_API_KEY=your_gemini_key # Add other provider keys as needed WORDPRESS_URL=your_wordpress_site_url WORDPRESS_USERNAME=your_username WORDPRESS_APP_PASSWORD=your_application_password GOOGLE_MAPS_API_KEY=your_google_maps_key ``` -------------------------------- ### Agent Configuration with Examples - JavaScript Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Demonstrates how to define an agent's configuration, including its name, description, signature, provider, AI model, and providing specific examples to guide its behavior. These examples match the input/output signature and show desired response formats. ```javascript { "name": "MathTeacher", "description": "Solves math problems with step by step explanations", "signature": "problem:string \"a math problem to solve\" -> solution:string \"step by step solution with final answer\"", "provider": "google-gemini", "providerKeyName": "GEMINI_API_KEY", "ai": { "model": "gemini-1.5-pro", "temperature": 0 }, "examples": [ { "problem": "what is the square root of 144?", "solution": "Let's solve this step by step:\n1. The square root of a number is a value that, when multiplied by itself, gives the original number\n2. For 144, we need to find a number that when multiplied by itself equals 144\n3. 12 × 12 = 144\nTherefore, the square root of 144 is 12" }, { "problem": "what is the cube root of 27?", "solution": "Let's solve this step by step:\n1. The cube root of a number is a value that, when multiplied by itself twice, gives the original number\n2. For 27, we need to find a number that when cubed equals 27\n3. 3 × 3 × 3 = 27\nTherefore, the cube root of 27 is 3" } ] } ``` -------------------------------- ### Installing npm Dependencies for AxCrew Examples Source: https://github.com/amitdeshmukh/ax-crew/blob/main/examples/README.md Bash commands to install npm dependencies required for specific AxCrew examples, such as those involving WordPress or Google Maps integrations. ```bash # For WordPress example npm install node-fetch https # For Math Problem example npm install mathjs # For MCP Agent with Google Maps example npm install @modelcontextprotocol/server-google-maps ``` -------------------------------- ### AxCrew Quickstart with TypeScript Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md A comprehensive TypeScript example demonstrating how to set up an AxCrew, define a typed configuration, create custom functions, manage shared state, add agents, and execute agent actions. It also shows how to access agent and crew metrics. ```typescript import { AxCrew, AxCrewFunctions, FunctionRegistryType, StateInstance } from '@amitdeshmukh/ax-crew'; import type { AxFunction } from '@ax-llm/ax'; // Type-safe configuration const config = { crew: [{ name: "Planner", description: "Creates a plan to complete a task", signature: "task:string \"a task to be completed\" -> plan:string \"a plan to execute the task\"", provider: "google-gemini", providerKeyName: "GEMINI_API_KEY", ai: { model: "gemini-1.5-pro", temperature: 0 } }] }; // Create custom functions with type safety class MyCustomFunction { constructor(private state: Record) {} toFunction(): AxFunction { return { name: 'MyCustomFunction', description: 'Does something useful', parameters: { type: 'object', properties: { inputParam: { type: 'string', description: "input to the function" } } }, func: async ({ inputParam }) => { // Implementation return inputParam; } }; } } // Type-safe function registry const myFunctions: FunctionRegistryType = { MyCustomFunction }; // Create crew with type checking const crew = new AxCrew(config, myFunctions); // Set and get state crew.state.set('key', 'value'); const value: string = crew.state.get('key'); // Add agents to the crew await crew.addAgentsToCrew(['Planner']); const planner = crew.agents?.get('Planner'); if (planner) { const response = await planner.forward({ task: "Plan something" }); // Sub-agent usage - when used by another agent (AI is ignored and agent's own config is used) const subAgentResponse = await planner.forward(ai, { task: "Plan something" }); // Metrics (per-agent and per-crew) const agentMetrics = (planner as any).getMetrics?.(); const crewMetrics = crew.getCrewMetrics(); console.log('Agent metrics:', agentMetrics); console.log('Crew metrics:', crewMetrics); } ``` -------------------------------- ### Basic Researcher-Writer Crew Setup with AxCrew Source: https://github.com/amitdeshmukh/ax-crew/blob/main/examples/README.md Demonstrates the creation of a simple AxCrew with two agents: a researcher for information gathering and a writer for content creation. This example requires no additional dependencies beyond the core AxCrew package. ```typescript import { AxCrew } from "@amitdeshmukh/ax-crew"; const crew = new AxCrew({ crew: [ { name: "researcher", // ... configuration }, { name: "writer", // ... configuration } ] }); // Usage example in the file ``` -------------------------------- ### Running AxCrew Examples with ts-node or built code Source: https://github.com/amitdeshmukh/ax-crew/blob/main/examples/README.md Instructions on how to execute AxCrew examples, either directly using `ts-node` or after building the project and running the compiled JavaScript files. ```bash # Using ts-node npx ts-node examples/basic-researcher-writer.ts # Or after building npm run build node dist/examples/basic-researcher-writer.js ``` -------------------------------- ### Write and Publish to WordPress with AxCrew Source: https://github.com/amitdeshmukh/ax-crew/blob/main/examples/README.md Shows how to generate content using AI, format it for WordPress, and publish it directly to a WordPress site. This example requires `@wordpress/api-fetch` and `@wordpress/url` npm packages, along with WordPress site credentials configured in `.env`. -------------------------------- ### Azure OpenAI Provider Configuration Example Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Demonstrates a JSON configuration for an agent using Azure OpenAI. It includes provider-specific arguments like `resourceName`, `deploymentName`, and `version` for detailed Azure setup. ```json { "name": "Writer", "description": "Writes concise summaries", "signature": "topic:string -> summary:string", "provider": "azure-openai", "providerKeyName": "AZURE_OPENAI_API_KEY", "ai": { "model": "gpt-4o-mini", "temperature": 0 }, "apiURL": "https://your-resource.openai.azure.com", "providerArgs": { "resourceName": "your-resource", "deploymentName": "gpt-4o-mini", "version": "api-version=2024-02-15-preview" } } ``` -------------------------------- ### Example Agent Task Execution (JavaScript) Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Provides a complete example of initializing an AX Crew, adding specific agents, and executing a user query through the Planner and Manager agents. Demonstrates the flow of information and task execution. ```javascript import { AxCrew, AxCrewFunctions } from '@amitdeshmukh/ax-crew'; // Create a new instance of AxCrew const crew = new AxCrew('./agentConfig.json', AxCrewFunctions); crew.addAgentsToCrew(['Planner', 'Calculator', 'Manager']); // Get agent instances const Planner = crew.agents.get("Planner"); const Manager = crew.agents.get("Manager"); // User query const userQuery = "whats the square root of the number of days between now and Christmas"; console.log(`\n\nQuestion: ${userQuery}`); // Forward the user query to the agents const planResponse = await Planner.forward({ task: userQuery }); const managerResponse = await Manager.forward({ question: userQuery, plan: planResponse.plan }); // Get and print the plan and answer from the agents const plan = planResponse.plan; const answer = managerResponse.answer; console.log(`\n\nPlan: ${plan}`); console.log(`\n\nAnswer: ${answer}`); ``` -------------------------------- ### Initializing AxCrew with Built-in Functions - JavaScript Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Shows how to initialize the AxCrew with the built-in functions provided by the `@amitdeshmukh/ax-crew` package. This is a convenient way to get started with pre-defined tools. ```javascript import { AxCrewFunctions } from '@amitdeshmukh/ax-crew'; const crew = new AxCrew(configFilePath, AxCrewFunctions); ``` -------------------------------- ### Agent Learning from Examples with Ax-Crew Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt Demonstrates how to configure an agent within Ax-Crew to learn from provided few-shot examples. This improves the agent's ability to generate consistent and high-quality output in a specific format. It requires the '@amitdeshmukh/ax-crew' package and an OpenAI API key. ```typescript import { AxCrew } from '@amitdeshmukh/ax-crew'; const config = { crew: [{ name: "CodeReviewer", description: "Reviews code and suggests improvements", signature: "code:string -> review:string", provider: "openai", providerKeyName: "OPENAI_API_KEY", ai: { model: "gpt-4o-mini", temperature: 0 }, examples: [ { code: "function add(a, b) { return a + b; }", review: "✓ LGTM: Simple, clear function. Consider:\n- Add JSDoc comments\n- Add type annotations (TypeScript)\n- Add input validation for edge cases" }, { code: "const data = await fetch(url).then(r => r.json()).catch(e => console.log(e))", review: "⚠ Issues found:\n1. Silent error handling - errors should be propagated or logged properly\n2. Missing error context - log should include url and error details\n3. No timeout handling\n\nSuggestion:\ntry { const response = await fetch(url, { timeout: 5000 }); if (!response.ok) throw new Error(`HTTP ${response.status}`); return await response.json(); } catch (error) { logger.error(`Fetch failed for ${url}:`, error); throw error; }" }, { code: "for(var i=0;i console.log(item));\n// or\nfor (const item of arr) { console.log(item); }" } ] }] }; const crew = new AxCrew(config); await crew.addAgent('CodeReviewer'); const reviewer = crew.agents?.get('CodeReviewer'); const review = await reviewer?.forward({ code: "function calc(x,y){return x/y}" }); console.log(review?.review); ``` -------------------------------- ### Solve Math Problem with Gemini Pro and AxCrew Source: https://github.com/amitdeshmukh/ax-crew/blob/main/examples/README.md Illustrates using AxCrew with Gemini Pro for solving mathematical problems, including step-by-step explanations and cost tracking. This example requires the 'mathjs' npm package. ```typescript const userQuery = "who is considered as the father of the iphone and what is the 7th root of their year of birth?"; // See file for implementation ``` -------------------------------- ### AxCrew Cost Tracking and Management Source: https://github.com/amitdeshmukh/ax-crew/blob/main/examples/README.md Provides code examples for monitoring API usage costs within AxCrew. It shows how to retrieve individual agent costs, aggregated crew costs, and how to reset cost tracking. ```typescript // Get individual agent costs const cost = agent.getUsageCost(); console.log("Usage cost:", cost); // Get aggregated costs for all agents in the crew const totalCosts = crew.getAggregatedCosts(); console.log("Total costs:", totalCosts); // Reset cost tracking if needed crew.resetCosts(); ``` -------------------------------- ### Install AxCrew and Dependencies Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Installs the AxCrew package and its peer dependencies, AxLLM and AxLLM tools, using npm. Requires Node.js version 21 or higher. ```bash npm install @amitdeshmukh/ax-crew npm install @ax-llm/ax @ax-llm/ax-tools ``` -------------------------------- ### MCP Agent with Google Maps Integration using AxCrew Source: https://github.com/amitdeshmukh/ax-crew/blob/main/examples/README.md Demonstrates integrating external APIs like Google Maps through Model Context Protocol (MCP) servers within AxCrew. It showcases agent dependencies, location-based queries, and cost tracking across multiple agents. Requires `@modelcontextprotocol/server-google-maps` and Google Maps API key. ```typescript const userQuery = "Are there any cool bars around the Eiffel Tower within 5 min walking distance"; ``` -------------------------------- ### Agent Persona Configuration using Prompt Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Shows an example of configuring an agent's persona using the 'prompt' field within a JSON configuration. The 'prompt' acts as an alias for 'definition' and is used as the agent's system prompt. ```json { "name": "Planner", "description": "Creates a plan to complete a task", "prompt": "You are a meticulous planning assistant. Produce concise, executable step-by-step plans with clear justifications, constraints, and assumptions. Prefer brevity, avoid fluff, and ask for missing critical details before proceeding when necessary.", "signature": "task:string -> plan:string", "provider": "google-gemini", "providerKeyName": "GEMINI_API_KEY", "ai": { "model": "gemini-1.5-flash", "temperature": 0 } } ``` -------------------------------- ### Track Agent and Crew Usage Costs Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Provides JavaScript code examples for tracking API usage costs per agent and for the entire crew. It demonstrates how to retrieve metrics like total requests, tokens used, and estimated costs, and how to reset these metrics. ```javascript // After running an agent's forward method await Planner.forward({ task: userQuery }); // Per-agent metrics const agentMetrics = (Planner as any).getMetrics?.(); console.log(agentMetrics); /* Example: { provider: "anthropic", model: "claude-3-haiku-20240307", requests: { totalRequests, totalErrors, errorRate, totalStreamingRequests, durationMsSum, durationCount }, tokens: { promptTokens, completionTokens, totalTokens }, estimatedCostUSD: 0.00091, // rounded to 5 decimals functions: { totalFunctionCalls, totalFunctionLatencyMs } } */ // Crew metrics const crewMetrics = crew.getCrewMetrics(); console.log(crewMetrics); /* Example: { requests: { ... }, tokens: { promptTokens, completionTokens, totalTokens }, estimatedCostUSD: 0.00255, // rounded to 5 decimals functions: { ... } } */ // Reset tracked metrics crew.resetCosts(); ``` -------------------------------- ### Stream Agent Responses in Real-Time with Ax Crew Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt Explains how to enable real-time streaming of agent responses using the `streamingForward` method in Ax Crew. This provides immediate token-level feedback for long-running tasks. The example demonstrates processing streamed chunks and coordinating streaming across sub-agents. ```typescript import { AxCrew } from '@amitdeshmukh/ax-crew'; const config = { crew: [{ name: "Writer", description: "Generates long-form content", signature: "topic:string -> article:string", provider: "google-gemini", providerKeyName: "GEMINI_API_KEY", ai: { model: "gemini-2.0-flash", temperature: 0.7, maxTokens: 4000 } }] }; const crew = new AxCrew(config); await crew.addAgent('Writer'); const writer = crew.agents?.get('Writer'); // Stream response tokens in real-time const stream = writer?.streamingForward({ topic: "The future of renewable energy" }); if (stream) { try { for await (const chunk of stream) { // Each chunk contains delta with partial field updates if (chunk.delta && typeof chunk.delta === 'object' && 'article' in chunk.delta) { process.stdout.write(chunk.delta.article); } } console.log('\n--- Streaming complete ---'); } catch (error) { console.error('Streaming error:', error); } } // Streaming with sub-agent coordination const managerStream = manager?.streamingForward({ question: "Write article and summarize it" }); if (managerStream) { let fullResponse = ''; for await (const chunk of managerStream) { if (chunk.delta?.answer) { fullResponse += chunk.delta.answer; process.stdout.write(chunk.delta.answer); } } } ``` -------------------------------- ### Add Agents with Automatic Dependency Resolution | TypeScript Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt Shows how to add agents to an AxCrew instance, highlighting the automatic dependency resolution and initialization in the correct order. It also includes an example of detecting circular dependencies. ```typescript import { AxCrew } from '@amitdeshmukh/ax-crew'; const crew = new AxCrew(config); // Adds agents in dependency order automatically // Calculator → Planner → Manager (even if specified differently) await crew.addAgentsToCrew(['Manager', 'Planner', 'Calculator']); // Or add all agents from config await crew.addAllAgents(); // Access initialized agents const manager = crew.agents?.get('Manager'); const planner = crew.agents?.get('Planner'); // Detect circular dependencies try { await crew.addAgentsToCrew(['AgentA']); // If AgentA depends on AgentB which depends on AgentA } catch (error) { console.error(error.message); // Error: "Circular dependency detected or missing dependencies for agents: AgentA" } ``` -------------------------------- ### Ax-Crew Agent Configuration for STDIO MCP Transport Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Configuration example for an Ax-Crew agent using the Model Context Protocol (MCP) with the STDIO transport type. This allows agents to communicate with local tools or services via standard input/output. It includes details for specifying the command, arguments, and environment variables for the MCP server. ```json { "name": "DataAnalyst", "description": "Analyzes data using MCP tools", "signature": "data:string -> analysis:string", "provider": "openai", "providerKeyName": "OPENAI_API_KEY", "ai": { "model": "gpt-4", "temperature": 0 }, "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"], "env": { "NODE_ENV": "production" } }, "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"] } } } ``` -------------------------------- ### Set and Get Crew State (JavaScript) Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Demonstrates how to manage shared state within an AX Crew instance using `crew.state.set()` and `crew.state.get()`. State is accessible by all agents and functions within the crew. ```javascript // Set some state (key/value) for this crew crew.state.set('name', 'Crew1'); crew.state.set('location', 'Earth'); // Get the state for the crew crew.state.get('name'); // 'Crew1' crew.state.getAll(); // { name: 'Crew1', location: 'Earth' } ``` -------------------------------- ### Integrate Agents with MCP Servers (TypeScript) Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt This example shows how to connect AX Crew agents to Model Context Protocol (MCP) servers for accessing external tools. It configures an agent to use different MCP transports, including STDIO for local filesystem access, HTTP SSE for web searches (using Brave Search), and Streamable HTTP for custom API interactions. The agent automatically utilizes these configured MCP servers to fulfill its tasks. ```typescript import { AxCrew } from '@amitdeshmukh/ax-crew'; const config = { crew: [{ name: "DataAnalyst", description: "Analyzes files and searches web", signature: "query:string -> analysis:string", provider: "anthropic", providerKeyName: "ANTHROPIC_API_KEY", ai: { model: "claude-3-5-sonnet-latest", temperature: 0, maxTokens: 2000 }, mcpServers: { // STDIO transport - local filesystem access "filesystem": { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "/workspace/data"], env: { NODE_ENV: "production" } }, // HTTP SSE transport - web search "brave-search": { command: "npx", args: ["-y", "@modelcontextprotocol/server-brave-search"], env: { BRAVE_API_KEY: process.env.BRAVE_API_KEY } }, // Streamable HTTP transport - custom API "data-processor": { mcpEndpoint: "http://localhost:3002/stream", options: { authorization: "Bearer token-xyz", timeout: 30000, headers: { "X-Custom-Header": "custom-value" } } } } }] }; const crew = new AxCrew(config); await crew.addAgent('DataAnalyst'); const analyst = crew.agents?.get('DataAnalyst'); // Agent automatically uses MCP tools const result = await analyst?.forward({ query: "Analyze sales data in /workspace/data/sales.csv and search for market trends" }); console.log(result?.analysis); // Agent uses filesystem MCP to read CSV, brave-search MCP for trends, // and data-processor MCP for analysis // Output: "Sales data shows 23% growth. Market trends indicate..." ``` -------------------------------- ### Ax-Crew Agent Configuration for Streamable HTTP MCP Transport Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Configuration example for an Ax-Crew agent using the Model Context Protocol (MCP) with the Streamable HTTP transport type. This is used for MCP servers that support streaming HTTP communication. The configuration includes the `mcpEndpoint` and optional `options` like authorization headers. ```json { "name": "StreamAnalyst", "description": "Processes streaming data using MCP tools", "signature": "stream:string -> results:string", "provider": "google-gemini", "providerKeyName": "GEMINI_API_KEY", "ai": { "model": "gemini-1.5-pro", "temperature": 0 }, "mcpServers": { "stream-processor": { "mcpEndpoint": "http://localhost:3002/stream", "options": { "authorization": "Bearer ey.JhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0..-1234567890.1234567890", "headers": { "X-Custom-Header": "custom-value" } } } } } ``` -------------------------------- ### Ax-Crew Agent Configuration for Mixed MCP Transports Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md An example of an Ax-Crew agent configuration that utilizes multiple Model Context Protocol (MCP) transport types simultaneously. This demonstrates flexibility by combining STDIO, HTTP SSE, and Streamable HTTP transports within a single agent definition to access diverse external tools and services. ```json { "name": "MultiModalAgent", "description": "Uses multiple MCP servers with different transports", "signature": "task:string -> result:string", "provider": "openai", "providerKeyName": "OPENAI_API_KEY", "ai": { "model": "gpt-4", "temperature": 0 }, "mcpServers": { "local-files": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/workspace"] }, "web-search": { "sseUrl": "http://localhost:3001/sse" }, "data-stream": { "mcpEndpoint": "http://localhost:3002/stream" } } } ``` -------------------------------- ### Manage Shared State Across Agents with Ax Crew Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt Demonstrates how to set, get, and reset key-value state accessible by all agents within an Ax Crew. This enables seamless data sharing and persistence across agent interactions. It covers crew-level state, agent-level state modification, and state persistence. ```typescript import { AxCrew, AxCrewFunctions } from '@amitdeshmukh/ax-crew'; const crew = new AxCrew(config, AxCrewFunctions); await crew.addAllAgents(); // Set state at crew level crew.state.set('projectName', 'QuantumAI'); crew.state.set('budget', 50000); crew.state.set('userPreferences', { theme: 'dark', language: 'en' }); // Get state values const project = crew.state.get('projectName'); // "QuantumAI" const allState = crew.state.getAll(); // { projectName: "QuantumAI", budget: 50000, userPreferences: {...} } // Agents can access and modify shared state const planner = crew.agents?.get('Planner'); planner?.state.set('currentPhase', 'research'); const manager = crew.agents?.get('Manager'); const phase = manager?.state.get('currentPhase'); // "research" // State persists across agent calls await planner?.forward({ task: "Create research plan" }); planner?.state.set('planCreated', true); await manager?.forward({ question: "Execute plan" }); const planStatus = manager?.state.get('planCreated'); // true // Reset state when needed crew.state.reset(); console.log(crew.state.getAll()); // {} ``` -------------------------------- ### Ax-Crew Agent Configuration for HTTP SSE MCP Transport Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Configuration example for an Ax-Crew agent using the Model Context Protocol (MCP) with the HTTP SSE (Server-Sent Events) transport type. This enables agents to connect to external HTTP services that push data using SSE. The configuration specifies the `sseUrl` for the MCP server. ```json { "name": "WebAnalyst", "description": "Analyzes web content using MCP tools", "signature": "url:string -> analysis:string", "provider": "anthropic", "providerKeyName": "ANTHROPIC_API_KEY", "ai": { "model": "claude-3-haiku", "temperature": 0 }, "mcpServers": { "api-server": { "sseUrl": "https://api.example.com/mcp/sse" } } } ``` -------------------------------- ### Initialize AxCrew with Configuration File Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Demonstrates how to import and instantiate the AxCrew class using a configuration file path. This method is suitable for separating configuration from code and for version control. ```javascript import { AxCrew } from '@amitdeshmukh/ax-crew'; const configFilePath = './agentConfig.json'; const crew = new AxCrew(configFilePath); ``` -------------------------------- ### Initialize AxCrew with Direct Configuration Object Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Illustrates how to import and instantiate the AxCrew class by directly providing a configuration object. This is useful for dynamic configuration generation or runtime modifications. ```javascript import { AxCrew } from '@amitdeshmukh/ax-crew'; const config = { crew: [ { name: "Planner", description: "Creates a plan to complete a task", signature: "task:string \"a task to be completed\" -> plan:string \"a plan to execute the task in 5 steps or less\"", provider: "google-gemini", providerKeyName: "GEMINI_API_KEY", ai: { model: "gemini-1.5-flash", temperature: 0 }, options: { debug: false } } // ... more agents ] }; const crew = new AxCrew(config); ``` -------------------------------- ### Initialize AxCrew with Configuration Object | TypeScript Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt Demonstrates how to initialize an AxCrew instance using a configuration object, including defining agents, their providers, AI settings, and functions. It shows how to add all agents, execute tasks sequentially, and retrieve results. ```typescript import { AxCrew, AxCrewFunctions } from '@amitdeshmukh/ax-crew'; import type { AxCrewConfig } from '@amitdeshmukh/ax-crew'; // Define crew configuration const config: AxCrewConfig = { crew: [ { name: "Planner", description: "Creates execution plans", signature: "task:string -> plan:string", provider: "google-gemini", providerKeyName: "GEMINI_API_KEY", ai: { model: "gemini-1.5-pro", temperature: 0, maxTokens: 2000 }, options: { debug: false } }, { name: "Calculator", description: "Performs mathematical calculations", signature: "problem:string -> solution:string", provider: "openai", providerKeyName: "OPENAI_API_KEY", ai: { model: "gpt-4o-mini", temperature: 0 }, functions: ["CurrentDateTime", "DaysBetweenDates"] }, { name: "Manager", description: "Orchestrates task execution", signature: "question:string, plan:string -> answer:string", provider: "anthropic", providerKeyName: "ANTHROPIC_API_KEY", ai: { model: "claude-3-haiku-20240307", temperature: 0 }, agents: ["Planner", "Calculator"] // Sub-agents } ] }; // Create crew with built-in functions const crew = new AxCrew(config, AxCrewFunctions); // Initialize all agents with dependency resolution await crew.addAllAgents(); // Execute task with agents const planner = crew.agents?.get("Planner"); const manager = crew.agents?.get("Manager"); const planResponse = await planner?.forward({ task: "Calculate days until Christmas and find square root" }); const result = await manager?.forward({ question: "Complete the task", plan: planResponse?.plan }); console.log(result?.answer); // Output: "Christmas is in 68 days. The square root of 68 is approximately 8.25." ``` -------------------------------- ### Configure GitHub MCP Server Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Sets up a GitHub MCP server using npx. It requires a GITHUB_PERSONAL_ACCESS_TOKEN environment variable for authentication. This server enables agents to interact with GitHub repositories. ```json { "github": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-github"], "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "your-github-token" } } } ``` -------------------------------- ### Initialize AxCrew and Add MCP-Enabled Agent Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Demonstrates how to initialize an AxCrew instance with agent configurations and add an agent that utilizes MCP servers. The agent can then automatically use configured MCP functions for tasks like reading files. ```javascript import { AxCrew } from '@amitdeshmukh/ax-crew'; // Create crew with MCP-enabled agents const crew = new AxCrew('./agentConfig.json'); await crew.addAgent('DataAnalyst'); // Agent with MCP servers configured const analyst = crew.agents.get('DataAnalyst'); // The agent can now use MCP functions automatically const response = await analyst.forward({ data: "Please analyze the sales data in /workspace/sales.csv" }); // The agent will automatically use the filesystem MCP server to read the file // and any other configured MCP tools for analysis ``` -------------------------------- ### Configure Filesystem MCP Server Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Sets up a Filesystem MCP server using npx. It requires specifying an allowed path for file operations. This server enables agents to interact with the local filesystem securely. ```json { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"] } } ``` -------------------------------- ### Adding Multiple Agents with Dependencies - JavaScript Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Explains how to add a subset of agents to the crew while still leveraging automatic dependency management. Agents are initialized in the correct order, even if added in multiple steps or out of dependency order. ```javascript // Add multiple agents - dependencies will be handled automatically await crew.addAgentsToCrew(['Manager', 'Planner', 'Calculator']); // Or add them in multiple steps - order doesn't matter as dependencies are handled await crew.addAgentsToCrew(['Calculator']); // Will be initialized first await crew.addAgentsToCrew(['Manager']); // Will initialize Planner first if it's a dependency ``` -------------------------------- ### Configure Environment Variables for LLM Providers Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Sets up necessary API keys for different LLM providers in the environment. These keys are referenced in agent configurations via `providerKeyName`. ```bash GEMINI_API_KEY=... ANTHROPIC_API_KEY=... OPENAI_API_KEY=... AZURE_OPENAI_API_KEY=... ``` -------------------------------- ### Adding All Agents Automatically - JavaScript Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Demonstrates the simplest method to add all agents defined in the configuration to the crew. This approach automatically handles agent dependencies and initialization order. ```javascript // Initialize all agents defined in the config await crew.addAllAgents(); // Get agent instances const planner = crew.agents?.get("Planner"); const manager = crew.agents?.get("Manager"); ``` -------------------------------- ### Configure Brave Search MCP Server Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Configures a Brave Search MCP server using npx. This server requires a BRAVE_API_KEY environment variable for authentication. It allows agents to perform searches using Brave Search. ```json { "brave-search": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-brave-search"], "env": { "BRAVE_API_KEY": "your-brave-api-key" } } } ``` -------------------------------- ### Add Agents Individually with Manual Dependency Management (JavaScript) Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Allows granular control over agent initialization by adding them one by one. Developers must manually manage dependencies to avoid errors. Suitable for complex scenarios requiring precise control over the agent loading order. ```javascript await crew.addAgent('Calculator'); // Add base agent first await crew.addAgent('Planner'); // Then its dependent await crew.addAgent('Manager'); // Then agents that depend on both ``` -------------------------------- ### Tracking Usage Metrics and Costs with Ax-Crew Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt Shows how to retrieve detailed usage metrics (token count, request counts, errors, costs) for individual agents and the entire crew using the Ax-Crew library. It also demonstrates resetting these metrics. Requires the '@amitdeshmukh/ax-crew' package. ```typescript import { AxCrew, AxCrewFunctions } from '@amitdeshmukh/ax-crew'; const crew = new AxCrew(config, AxCrewFunctions); await crew.addAgentsToCrew(['Planner', 'Calculator', 'Manager']); const planner = crew.agents?.get('Planner'); const calculator = crew.agents?.get('Calculator'); const manager = crew.agents?.get('Manager'); // Execute multiple operations await planner?.forward({ task: "Plan a deployment" }); await calculator?.forward({ problem: "Calculate server capacity" }); await manager?.forward({ question: "Execute deployment plan", plan: "..." }); // Get per-agent metrics const plannerMetrics = (planner as any)?.getMetrics?.(); console.log(JSON.stringify(plannerMetrics, null, 2)); const calculatorMetrics = (calculator as any)?.getMetrics?.(); console.log(calculatorMetrics); // Get crew-level aggregated metrics const crewMetrics = crew.getCrewMetrics(); console.log(JSON.stringify(crewMetrics, null, 2)); // Reset metrics for new measurement window crew.resetCosts(); // Execute new operations await manager?.forward({ question: "Status check" }); const newMetrics = crew.getCrewMetrics(); console.log(newMetrics.estimatedCostUSD); // Only includes operations after reset ``` -------------------------------- ### Configure PostgreSQL MCP Server Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Configures a PostgreSQL MCP server using npx. It requires a POSTGRES_CONNECTION_STRING environment variable for database connectivity. This server allows agents to interact with PostgreSQL databases. ```json { "postgres": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-postgres"], "env": { "POSTGRES_CONNECTION_STRING": "postgresql://user:pass@localhost/db" } } } ``` -------------------------------- ### Configure New Streamable HTTP MCP Server Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Illustrates the configuration for a new streamable HTTP MCP server. It specifies the MCP endpoint URL and allows for additional options like connection timeouts, enabling efficient real-time data streams. ```json { "mcpServers": { "my-stream-server": { "mcpEndpoint": "http://localhost:3002/stream", "options": { "timeout": 30000 } } } } ``` -------------------------------- ### Configure Provider Arguments for AI Agents (TypeScript) Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt Demonstrates how to configure provider-specific parameters for different AI services like Azure OpenAI, Google Gemini, and Ollama. This allows for customization of API endpoints, deployment names, project IDs, and other service-specific settings. ```typescript import { AxCrew } from '@amitdeshmukh/ax-crew'; const config = { crew: [ { name: "AzureAgent", description: "Uses Azure OpenAI deployment", signature: "query:string -> response:string", provider: "azure-openai", providerKeyName: "AZURE_OPENAI_API_KEY", ai: { model: "gpt-4o-mini", temperature: 0 }, apiURL: "https://my-resource.openai.azure.com", providerArgs: { resourceName: "my-resource", deploymentName: "gpt-4o-mini-deployment", version: "2024-02-15-preview" } }, { name: "GeminiAgent", description: "Uses Gemini with Vertex AI", signature: "task:string -> result:string", provider: "google-gemini", providerKeyName: "GEMINI_API_KEY", ai: { model: "gemini-1.5-pro", temperature: 0 }, providerArgs: { projectId: "my-gcp-project", region: "us-central1", endpointId: "custom-endpoint-id" } }, { name: "OllamaAgent", description: "Uses local Ollama instance", signature: "input:string -> output:string", provider: "ollama", ai: { model: "llama3.2", temperature: 0.7 }, providerArgs: { url: "http://localhost:11434" } } ] }; const crew = new AxCrew(config); await crew.addAllAgents(); const azureAgent = crew.agents?.get('AzureAgent'); const result = await azureAgent?.forward({ query: "Explain quantum entanglement" }); console.log(result?.response); // Uses Azure deployment specified in providerArgs ``` -------------------------------- ### Initializing AxCrew with Custom Functions - TypeScript Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Illustrates how to initialize AxCrew with your own custom functions. This involves creating a `FunctionRegistryType` object mapping function names to their instances, allowing for tailored agent capabilities. ```typescript import { FunctionRegistryType } from '@amitdeshmukh/ax-crew'; const myFunctions: FunctionRegistryType = { GoogleSearch: googleSearchInstance.toFunction() }; const crew = new AxCrew(configFilePath, myFunctions); ``` -------------------------------- ### Stream Agent Responses in JavaScript Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Demonstrates how to stream responses from Ax-Crew agents in real-time using the `forward` method. This is useful for long-running tasks and provides immediate feedback. It supports both direct and sub-agent usage, with customizable stream handling. ```javascript import { AxCrew, AxCrewFunctions } from '@amitdeshmukh/ax-crew'; // Create and initialize crew as shown above const crew = new AxCrew('./agentConfig.json', AxCrewFunctions); await crew.addAgentsToCrew(['Planner']); const planner = crew.agents.get("Planner"); // Stream responses using the forward method await planner.forward( { task: "Create a detailed plan for a website" }, { onStream: (chunk) => { // Process each chunk of the response as it arrives console.log('Received chunk:', chunk); } } ); // You can also use streaming with sub-agents await planner.forward( ai, { task: "Create a detailed plan for a website" }, { onStream: (chunk) => { process.stdout.write(chunk); } } ); ``` -------------------------------- ### Execute Agents and Sub-Agents with `forward` in Ax Crew Source: https://context7.com/amitdeshmukh/ax-crew/llms.txt Illustrates how to execute agents directly or as sub-agents using the `forward` method in Ax Crew. This method supports passing input values, receiving structured outputs, and injecting AI services for sub-agent calls. It also covers advanced usage like streaming callbacks and error handling. ```typescript import { AxCrew } from '@amitdeshmukh/ax-crew'; import type { AxAI } from '@ax-llm/ax'; const crew = new AxCrew(config); await crew.addAgentsToCrew(['Researcher', 'Writer']); const researcher = crew.agents?.get('Researcher'); const writer = crew.agents?.get('Writer'); // Direct agent execution const researchResult = await researcher?.forward({ query: "Latest developments in quantum computing" }); console.log(researchResult?.research); // Output: "Recent breakthroughs include 1000-qubit processors..." // Sub-agent execution (when Writer uses Researcher as sub-agent) // The AI parameter is injected by the parent agent const article = await writer?.forward({ topic: "Quantum Computing in 2025" }); console.log(article?.article); // Output: "Quantum computing has revolutionized... [uses researcher internally]" // Forward with options (streaming callbacks, etc.) const result = await researcher?.forward( { query: "AI safety protocols" }, { onStream: (chunk) => process.stdout.write(chunk), maxRetries: 3 } ); // Error handling try { await researcher?.forward({ invalidInput: "test" }); } catch (error) { console.error("Agent execution failed:", error.message); } ``` -------------------------------- ### Enable Debug Mode for MCP Servers Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Shows how to enable debug mode within the AX-Crew configuration. This setting provides detailed logs for MCP server initialization and inter-process communication, aiding in troubleshooting. ```json { "debug": true, "mcpServers": { ... } } ``` -------------------------------- ### Define Agent Dependencies in Configuration (JSON) Source: https://github.com/amitdeshmukh/ax-crew/blob/main/README.md Specifies dependencies for an agent within its configuration object using the 'agents' field. This allows the crew system to automatically manage the initialization order based on these explicit relationships. ```json { name: "Manager", // ... other config ... agents: ["Planner", "Calculator"] // Manager depends on these agents } ```