VoltAgent Developer & LLM Guide (v1.0.x)

website·Indexed 35 days ago

https://voltagent.dev/docs/

Documentation for the VoltAgent framework (v1.0.x), covering project setup via create-voltagent-app, the @voltagent/core architecture, and the Agent class. Includes details on AgentEventEmitter, SubAgentManager, sub-agent orchestration, execution pipeline hooks, and observability workflows.

Tokens
4.1K
Snippets
12
Records
29
Agent score
22%

What's inside VoltAgent

  1. Build type-safe AI pipelines with Workflows

    Workflows in @voltagent/core enable the creation of multi-step AI pipelines with full TypeScript inference for data flow. They are created using createWorkflowChain and support various step types:

    • andThen: Execute a TypeScript function.
    • andAgent: Run an AI agent for structured output.
    • andWhen: Conditional execution.
    • andAll / andRace: Parallel execution (wait for all vs first win).
    • andTap: Side effects without altering data flow.

    Workflows support Zod schemas for input/output validation and can be paused/resumed for human-in-the-loop interactions. They can be executed via a REST API at POST /workflows/{id}/execute.

  2. Manage runtime context and prompts in agents

    VoltAgent provides dedicated systems for:

    • Context Management: Passing and accessing runtime context throughout the agent's execution lifecycle.
    • Prompt Management: Using dynamic prompt templates to manage agent behavior.
  3. Integrate voice capabilities with @voltagent/voice

    The @voltagent/voice package provides Text-to-Speech (TTS) and Speech-to-Text (STT) capabilities. Supported providers include OpenAI, ElevenLabs, and xsAI. Integration is achieved by passing the voice provider to the Agent constructor via the voice option.
    // Key methods available in @voltagent/voice:
    await voice.speak(text); // TTS: Convert text to audio stream
    await voice.listen(audioStream); // STT: Transcribe audio to text
    await voice.getVoices(); // List available voices
  4. Monitor agents using VoltOps and Langfuse

    Observability is provided through the VoltOps Platform and Langfuse integration.

    • VoltOps Platform: Provides visual execution traces, tool call inspection, memory explorer, and real-time WebSocket updates.
    • Langfuse: Used for advanced analytics and evaluation.
    • Logging: Supports structured logging with configurable levels.
  5. Manage long-running agent operations with Cancellation

    VoltAgent supports the graceful cancellation of long-running agent operations using the standard AbortSignal API.
  6. Create Dynamic Agents with runtime property resolution

    Dynamic Agents allow properties to change at runtime based on user context. Resolution functions receive DynamicValueOptions containing a context Map.

    Dynamic Properties include:

    • instructions: Adjust system prompts based on role or language.
    • model: Select models based on subscription tiers.
    • tools: Provide tool sets based on user permissions.
  7. Handle multi-modal inputs in agent interactions

    VoltAgent agents support multi-modal capabilities, allowing them to process and handle images, audio, and other media types during interactions.
  8. Expose agents via the Agent-to-Agent (A2A) Protocol

    Use the @voltagent/a2a-server package to enable inter-agent communication. The protocol provides a discovery card and a JSON-RPC endpoint.
    GET /.well-known/{agentId}/agent-card.json // Discovery Card
    POST /a2a/{agentId} // JSON-RPC Endpoint

    Supported JSON-RPC Methods:

    • message/send, message/stream, tasks/get, tasks/cancel
  9. Implement Retrieval-Augmented Generation (RAG)

    VoltAgent provides two primary RAG patterns:

    1. Always-On Search: Set a retriever on the Agent to search before every response.
    2. Search When Needed: Add the retriever as a tool, allowing the agent to decide when to search.

    Supported Vector Databases: Chroma, Pinecone, and Qdrant. Custom retrievers can be created by extending the BaseRetriever class.

    Chunking: Supports 17+ chunker types including SemanticChunker, NeuralChunker, RecursiveChunker, MarkdownChunker, HTMLChunker, JSONChunker, CodeChunker, SentenceChunker, TokenChunker, and TableChunker.

  10. Manually set up a VoltAgent project

    For advanced users who prefer manual installation over the CLI tool, follow these steps:

    1. Initialize a Node.js/TypeScript project (npm init, tsc --init).
    2. Install core dependencies: @voltagent/core, ai, and an AI SDK provider (e.g., @ai-sdk/openai or @ai-sdk/anthropic).
    3. Optional dependencies: @voltagent/server-hono (HTTP server) and @voltagent/libsql (persistent memory).
    4. Install dev dependencies: typescript, tsx, @types/node, and optionally @voltagent/cli.
    5. Configure tsconfig.json: Set target to ES2020+ and module to NodeNext.
    6. Configure package.json: Set `
  11. Create custom tools for VoltAgent

    Tools are created using createTool from @voltagent/core. A tool requires a unique name, a description (used by the LLM to determine when to use the tool), a zod schema for parameters (using .describe() for LLM context), and an async execute function. The execute function receives type-safe arguments and optional ToolExecuteOptions (including an AbortSignal for cancellation).
    import { createTool } from "@voltagent/core";
    import { z } from "zod";
    
    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."),
    });
    
    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,
      execute: async (args, options) => {
        const { city, state, unit } = args;
        const location = state ? `${city}, ${state}` : city;
        const signal = options?.signal;
    
        try {
          if (signal?.aborted) throw new Error("Operation cancelled by signal.");
          
          // Simulate API call
          const result = { temp: 25, conditions: "Sunny" };
    
          return {
            location: location,
            temperature: result.temp,
            unit: unit,
            conditions: result.conditions,
          };
        } catch (error) {
          return { error: `Failed to get weather for ${location}. Reason: ${error.message}` };
        }
      },
    });
  12. Initialize a VoltAgent project using create-voltagent-app

    The recommended way to start a VoltAgent project is using the create-voltagent-app CLI tool. This tool sets up the necessary core packages (@voltagent/core, ai SDK providers, and optionally @voltagent/server-hono), TypeScript configuration, and a basic project structure including a .voltagent directory for local SQLite databases.
    # Initialize the project
    npm create voltagent-app@latest my-voltagent-app
    
    cd my-voltagent-app
    
    # Add API keys to the generated .env file
    echo "OPENAI_API_KEY=sk-..." > .env
    
    # Start the development server (uses tsx watch for hot-reloading)
    npm run dev