### Minimal Agent Initialization Source: https://voltagent.dev/llms.txt Demonstrates the basic setup for creating an Agent instance with essential configuration like name, LLM provider, and model. ```typescript import { Agent, VoltAgent } from "@voltagent/core"; import { VercelAIProvider } from "@voltagent/vercel-ai"; import { openai } from "@ai-sdk/openai"; const simpleAgent = new Agent({ name: "simple-assistant", description: "You answer questions directly.", llm: new VercelAIProvider(), model: openai("gpt-4o-mini"), }); new VoltAgent({ agents: { main: simpleAgent } }); ``` -------------------------------- ### Initialize VoltAgent Project with CLI Source: https://voltagent.dev/llms.txt Use the create-voltagent-app CLI to quickly set up a new VoltAgent project. Follow prompts for package manager and add API keys to the .env file. ```bash # Installs necessary dependencies and sets up the basic structure npm create voltagent-app@latest my-voltagent-app # Follow prompts for package manager selection (npm/yarn/pnpm) cd my-voltagent-app # Add API keys to the generated .env file echo "OPENAI_API_KEY=sk-..." > .env # Example for OpenAI # Start the development server npm run dev ``` -------------------------------- ### Create VoltAgent App with Assistant UI Source: https://voltagent.dev/llms.txt Use this command to scaffold a new VoltAgent application integrated with Assistant UI. ```bash npm create voltagent-app@latest -- --example with-assistant-ui ``` -------------------------------- ### Create VoltAgent App with Next.js Source: https://voltagent.dev/llms.txt Use this command to scaffold a new VoltAgent application integrated with Next.js. ```bash npm create voltagent-app@latest -- --example with-nextjs ``` -------------------------------- ### Configure LibSQLStorage with Turso for Production Source: https://voltagent.dev/llms.txt Sets up LibSQLStorage to use Turso for production environments. Ensures required environment variables are set and configures optional table prefix and debug logging. ```typescript import { LibSQLStorage } from "@voltagent/core"; if (!process.env.TURSO_DATABASE_URL || !process.env.TURSO_AUTH_TOKEN) { throw new Error("TURSO_DATABASE_URL and TURSO_AUTH_TOKEN environment variables are required."); } export const productionMemory = new LibSQLStorage({ url: process.env.TURSO_DATABASE_URL, authToken: process.env.TURSO_AUTH_TOKEN, tablePrefix: "prod_chats", // Optional: Namespace tables debug: process.env.NODE_ENV === 'development', // Enable debug logs in dev }); ``` -------------------------------- ### Create VoltAgent App with CopilotKit Source: https://voltagent.dev/llms.txt Use this command to scaffold a new VoltAgent application integrated with CopilotKit. ```bash npm create voltagent-app@latest -- --example with-copilotkit ``` -------------------------------- ### Initialize Agent with Production Memory Source: https://voltagent.dev/llms.txt Initializes an Agent instance using the configured production memory provider (LibSQLStorage with Turso). Interactions with this agent will be persisted in the Turso database. ```typescript import { Agent } from "@voltagent/core"; import { productionMemory } from "./config/memory"; // ... other imports const productionAgent = new Agent({ name: "prod-assistant", llm: new VercelAIProvider(), model: openai("gpt-4o"), memory: productionMemory, // Use the configured Turso instance }); // ... Initialize VoltAgent ... // Interactions now persist in the Turso database // await productionAgent.generateText("Remember this code: XYZ", { userId: "dev1", conversationId: "projectA" }); ``` -------------------------------- ### Define and Configure Supervisor and Sub-agent Source: https://voltagent.dev/llms.txt Set up a supervisor agent that delegates tasks to a specialized sub-agent like a WebResearcher. Ensure the supervisor has a good reasoning model and the sub-agent has necessary tools. ```typescript import { Agent, VoltAgent } from "@voltagent/core"; import { VercelAIProvider } from "@voltagent/vercel-ai"; import { openai } from "@ai-sdk/openai"; // Assume 'webSearchTool' is defined elsewhere // 1. Define Researcher Sub-agent const researcher = new Agent({ name: "WebResearcher", description: "Efficiently searches the web for information on a given topic and provides a concise summary.", llm: new VercelAIProvider(), model: openai("gpt-4o-mini"), // tools: [webSearchTool], // This agent needs a web search tool }); // 2. Define Supervisor Agent const supervisor = new Agent({ name: "ResearchCoordinator", description: `You are a coordinator. When asked to research a topic, delegate the task to the WebResearcher agent using the delegate_task tool. Present the summary provided by the researcher. Available agents: WebResearcher.`, llm: new VercelAIProvider(), model: openai("gpt-4o"), // Needs good reasoning subAgents: [researcher], // List the sub-agent }); // 3. Initialize Framework new VoltAgent({ agents: { coordinator: supervisor } }); // Interaction Flow: // User -> coordinator: "Research the impact of AI on climate change." // Coordinator LLM -> delegate_task({ task: "Research AI impact on climate change", targetAgents: ["WebResearcher"] }) // -> SubAgentManager.handoffTask(target=researcher, task=..., parentId='coordinator', parentHistoryId='...') // -> researcher Agent receives task, uses its 'webSearchTool' // -> researcher Agent returns summary // -> SubAgentManager.handoffTask returns result to delegate_task // Coordinator LLM -> Receives summary from tool result, formats final answer // Coordinator -> User: "Here is a summary of AI's impact on climate change: [summary]" ``` -------------------------------- ### Default VoltAgent Project Structure Source: https://voltagent.dev/llms.txt The standard directory layout generated by `create-voltagent-app`, including source files, configuration, and environment variables. ```text my-voltagent-app/ ├── src/ │ └── index.ts # Main agent definition and framework initialization ├── .voltagent/ # Default directory for local SQLite databases (memory/observability) ├── .env # Environment variables (API keys) ├── .gitignore ├── package.json # Project metadata, dependencies, scripts ├── tsconfig.json # TypeScript configuration └── README.md # Basic project README ``` -------------------------------- ### Create dynamic prompts with createPrompt utility Source: https://voltagent.dev/llms.txt Use the `createPrompt` utility to generate dynamic prompt strings from templates and variables. This function helps manage complex prompt structures and allows for default variable values. ```typescript import { createPrompt } from "@voltagent/core"; const myPrompt = createPrompt({ template: "Analyze sentiment for: {{text}}. Focus on {{aspect}}.", variables: { aspect: "overall tone" } // Default variable }); const specificPrompt = myPrompt({ text: "This product is amazing!" }); // -> "Analyze sentiment for: This product is amazing!. Focus on overall tone." const specificPrompt2 = myPrompt({ text: "Service was slow.", aspect: "service speed" }); // -> "Analyze sentiment for: Service was slow.. Focus on service speed." ``` -------------------------------- ### List Available Tools Source: https://voltagent.dev/llms.txt Retrieves a list of all available tools. ```APIDOC ## GET /tools ### Description Retrieves a list of all available tools. ### Method GET ### Endpoint /tools ### Response #### Success Response (200) - **tools** (array) - A list of available tools. - **name** (string) - The tool name. - **description** (string) - The tool description. #### Response Example { "tools": [ { "name": "calculator", "description": "Performs mathematical calculations." } ] } ``` -------------------------------- ### Integrate with OpenAI/compatible APIs using XSAIProvider Source: https://voltagent.dev/llms.txt Use XSAIProvider for lightweight integration with OpenAI and compatible APIs, suitable for edge environments. Specify API keys and optionally a custom base URL for local models. ```typescript import { XSAIProvider } from "@voltagent/xsai"; const provider = new XSAIProvider({ apiKey: process.env.OPENAI_API_KEY!, // Or other compatible key // baseURL: "http://localhost:11434/v1" // Optional: for local models }); const agent = new Agent({ // ... name, description ... llm: provider, model: "gpt-4o-mini", // Pass model name as string }); ``` -------------------------------- ### Integrate with Vercel AI SDK using VercelAIProvider Source: https://voltagent.dev/llms.txt Use VercelAIProvider to access a wide range of models through the Vercel AI SDK. Configuration is often handled via environment variables. ```typescript import { VercelAIProvider } from "@voltagent/vercel-ai"; import { openai } from "@ai-sdk/openai"; // Import specific model functions const provider = new VercelAIProvider(); // Config often handled by env vars const agent = new Agent({ // ... name, description ... llm: provider, model: openai("gpt-4o-mini"), // Pass the AI SDK model object }); ``` -------------------------------- ### Agent Class Constructor Signature Source: https://voltagent.dev/llms.txt Defines the structure for configuring an Agent instance, including LLM provider, model, memory, tools, and other capabilities. ```typescript import { AgentHooks } from './hooks'; import { LLMProvider } from './providers'; import { Memory, MemoryOptions } from '../memory'; import { AgentTool } from '../tool'; import { BaseRetriever } from '../retriever'; import { Voice } from '../voice'; class Agent }> { constructor(options: { id?: string; name: string; description?: string; llm: ProviderInstance; // e.g., new VercelAIProvider() model: ModelType; // e.g., openai("gpt-4o-mini") memory?: Memory | false; memoryOptions?: MemoryOptions; tools?: AgentTool[]; subAgents?: Agent[]; hooks?: AgentHooks; retriever?: BaseRetriever; voice?: Voice; maxHistoryEntries?: number; }); // ... methods like generateText, streamText, etc. } ``` -------------------------------- ### Create a Detailed Weather Tool Source: https://voltagent.dev/llms.txt Defines a weather tool with type-safe parameters using Zod and includes logging and AbortSignal support in its execution logic. Use this for fetching weather data with clear input validation and cancellation capabilities. ```typescript import { createTool, ToolExecuteOptions } from "@voltagent/core"; import { z } from "zod"; // 1. Define clear parameters with descriptions for the LLM const weatherParams = z.object({ city: z.string().describe("The name of the city."), state: z.string().optional().describe("The state or region (e.g., CA, TX). Optional."), unit: z.enum(["celsius", "fahrenheit"]).default("celsius").describe("Temperature unit."), }); // 2. Create the tool instance export const detailedWeatherTool = createTool({ name: "get_detailed_weather", description: "Provides the current temperature and weather conditions for a specific city, optionally including the state.", parameters: weatherParams, // 3. Implement the execute function (args are type-safe) execute: async (args: z.infer, options?: ToolExecuteOptions) => { // Type of args: { city: string; state?: string; unit: "celsius" | "fahrenheit" } const { city, state, unit } = args; const location = state ? `${city}, ${state}` : city; const signal = options?.signal; // Access AbortSignal if provided console.log(`[Tool: Weather] Executing for ${location}, Unit: ${unit}`); // Simulate API call with potential cancellation try { // Check if aborted before starting if (signal?.aborted) throw new Error("Operation cancelled by signal."); // --- Placeholder for API call --- const apiCallPromise = new Promise<{ temp: number; conditions: string }>(resolve => setTimeout(() => { // Simulate different weather based on location const temp = location.toLowerCase().includes("london") ? 15 : 28; const conditions = location.toLowerCase().includes("london") ? "Rainy" : "Sunny"; resolve({ temp, conditions }); }, 1000) // Simulate 1 second delay ); // Handle potential abort during the simulated delay const result = await Promise.race([ apiCallPromise, new Promise((_, reject) => { if (signal) { signal.addEventListener('abort', () => reject(new Error("Weather API call aborted."))); } }) ]); // --- End Placeholder --- console.log(`[Tool: Weather] Success for ${location}`); // Return structured result return { location: location, temperature: (result as any).temp, unit: unit, conditions: (result as any).conditions, }; } catch (error) { console.error(`[Tool: Weather] Failed for ${location}:`, error.message); // Provide a structured error for the LLM return { error: `Failed to get weather for ${location}. Reason: ${error.message}` }; } }, }); ``` -------------------------------- ### Execute Workflow Source: https://voltagent.dev/llms.txt Executes a specified workflow. ```APIDOC ## POST /workflows/{id}/execute ### Description Executes a specified workflow. ### Method POST ### Endpoint /workflows/{id}/execute ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the workflow to execute. ### Request Body - **inputs** (object) - Optional - Inputs for the workflow. ### Request Example { "inputs": { "param1": "value1" } } ### Response #### Success Response (200) - **result** (any) - The result of the workflow execution. #### Response Example { "result": "Workflow completed successfully." } ``` -------------------------------- ### Agent Object Generation Source: https://voltagent.dev/llms.txt Generates a structured object using a specified agent. ```APIDOC ## POST /agents/{id}/object ### Description Generates a structured object using a specified agent. ### Method POST ### Endpoint /agents/{id}/object ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the agent to use. ### Request Body - **prompt** (string) - Required - The input prompt for the agent. - **schema** (object) - Required - The JSON schema for the desired output object. ### Request Example { "prompt": "Extract user information.", "schema": { "type": "object", "properties": { "name": {"type": "string"}, "email": {"type": "string"} } } } ### Response #### Success Response (200) - **object** (object) - The generated structured object. #### Response Example { "object": { "name": "John Doe", "email": "john.doe@example.com" } } ``` -------------------------------- ### Agent Text Generation Source: https://voltagent.dev/llms.txt Generates text using a specified agent. ```APIDOC ## POST /agents/{id}/text ### Description Generates text using a specified agent. ### Method POST ### Endpoint /agents/{id}/text ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the agent to use. ### Request Body - **prompt** (string) - Required - The input prompt for the agent. ### Request Example { "prompt": "What is the weather today?" } ### Response #### Success Response (200) - **response** (string) - The generated text response from the agent. #### Response Example { "response": "The weather today is sunny." } ``` -------------------------------- ### List Registered Agents Source: https://voltagent.dev/llms.txt Retrieves a list of all registered agents. ```APIDOC ## GET /agents ### Description Retrieves a list of all registered agents. ### Method GET ### Endpoint /agents ### Response #### Success Response (200) - **agents** (array) - A list of registered agents. - **id** (string) - The agent ID. - **name** (string) - The agent name. #### Response Example { "agents": [ { "id": "agent-123", "name": "Customer Support Bot" } ] } ``` -------------------------------- ### Agent Text Streaming Source: https://voltagent.dev/llms.txt Streams text generated by a specified agent. ```APIDOC ## POST /agents/{id}/stream ### Description Streams text generated by a specified agent. ### Method POST ### Endpoint /agents/{id}/stream ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the agent to use. ### Request Body - **prompt** (string) - Required - The input prompt for the agent. ### Request Example { "prompt": "Tell me a story." } ### Response #### Success Response (200) - **stream** (ReadableStream) - A stream of text chunks generated by the agent. #### Response Example (Stream of text chunks) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.