### Quick Start Usage Example Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/data_extraction_agent.md Demonstrates how to use the Resume Extractor Agent to parse a PDF resume and extract structured data. Requires a sample PDF resume. ```ruby require "rails_helper" describe "Resume Extractor Agent - Quick Start Usage" do it "extracts structured data from a PDF resume" do pdf_url = "https://docs.activeagents.ai/sample_resume.pdf" response = ResumeExtractorAgent.with(document: pdf_url).parse.generate_now expect(response.success?).to be true expect(response.message.content).to be_a(Hash) expect(response.message.content).to include("name") expect(response.message.content).to include("email") expect(response.message.content).to include("phone_number") expect(response.message.content).to include("linkedin_url") expect(response.message.content).to include("skills") expect(response.message.content).to include("experience") expect(response.message.content).to include("education") end end ``` -------------------------------- ### Quick Start for Embeddings Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/embeddings.md A quick start example to demonstrate the basic usage of embeddings. ```ruby require "active_agents" # Initialize the agent with an embedding model agent = ActiveAgents::Agent.new(embedding_model: "text-embedding-ada-002") # Generate an embedding for a piece of text response = agent.embed(text: "This is a sample text.") # The response contains the embedding vector puts response.embedding ``` -------------------------------- ### Install Ollama on macOS/Linux Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ollama.md Commands to install the Ollama service, start the server, and pull a model. This is for setting up Ollama on macOS or Linux systems. ```bash # Install Ollama curl -fsSL https://ollama.ai/install.sh | sh # Start Ollama service ollama serve # Pull a model ollama pull llama3 ``` -------------------------------- ### OpenAI Configuration File Setup Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md Example of configuring OpenAI credentials in the `config/active_agent.yml` file. Use `access_token` and optionally `organization_id`. ```yaml openai: access_token: "your-api-key" organization_id: "your-org-id" ``` -------------------------------- ### Quick Example Support Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/agents.md A basic example demonstrating the structure and usage of a support agent. ```ruby class SupportAgent < ApplicationAgent def generate(from:, **args) prompt( "You are a helpful assistant. Respond to the user's query: {from}" ) end end ``` -------------------------------- ### Generate Documentation Examples Source: https://github.com/activeagents/activeagent/blob/main/docs/framework/testing.md Generate example files from test results using `doc_example_output`. This is useful for creating documentation automatically. ```ruby test "help agent example" do VCR.use_cassette("help_agent_example") do result = HelpAgent.with(query: "How do I reset password?").help.generate_now doc_example_output(result) # Creates example file assert result.message.content.present? end end ``` -------------------------------- ### Quick Example: Support Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/framework.md This example demonstrates setting up a basic support agent with its instructions. It includes both the Ruby agent definition and its associated Markdown instructions. ```ruby class SupportAgent < ApplicationAgent def instructions # Load instructions from a Markdown file render_instructions(template: "agents/framework_examples_test/quick_example_test/support/instructions.md") end end ``` ```markdown # Support Agent Instructions Your goal is to assist the user with their query. Ask clarifying questions if needed. ``` -------------------------------- ### Quick Example: Support Agent Usage Source: https://github.com/activeagents/activeagent/blob/main/docs/framework.md This snippet shows how to invoke the SupportAgent and retrieve its response. It's a direct usage example. ```ruby agent = SupportAgent.new response = agent.prompt_now(message: "Hello, I need help with my account.") puts response.message ``` -------------------------------- ### Quick Start Weather Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/mcps.md Demonstrates a basic setup for an agent to access weather information via an MCP server. ```ruby agent = ActiveAgent::Agent.new agent.add_mcp_server( name: "weather_api", url: "https://weather.example.com/mcp", authorization: "YOUR_API_KEY" ) agent.run("What's the weather like in London?") ``` -------------------------------- ### Custom MCP Server Implementation Example Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/mcp-integration-agent.md Example structure for a custom MCP server, demonstrating how to define tools and implement the tool execution logic. ```ruby # lib/mcp_server.rb class McpServer def tools [ { name: "search_database", description: "Search the company database", parameters: { type: "object", properties: { query: { type: "string", description: "Search query" }, limit: { type: "integer", description: "Max results" } }, required: ["query"] } } ] end def execute_tool(name, params) case name when "search_database" Database.search(params["query"], limit: params["limit"]) else { error: "Unknown tool: #{name}" } end end end ``` -------------------------------- ### Basic OpenAI Usage Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md A simple example demonstrating how to instantiate an OpenAI agent and run a query. The default `api_version` is `:responses`. ```ruby agent = OpenAI::Agent.new(model: "gpt-4o", temperature: 0.7) agent.run("Generate a short story about a robot learning to paint.") ``` -------------------------------- ### ActiveAgent Configuration Example Source: https://github.com/activeagents/activeagent/blob/main/docs/framework/rails.md Example configuration for ActiveAgent providers, demonstrating inheritance and environment-specific overrides. ```yaml openai: &openai service: "OpenAI" access_token: <%= Rails.application.credentials.dig(:openai, :access_token) %> model: "gpt-4o" development: openai: <<: *openai model: "gpt-4o-mini" # Cheaper model for development production: openai: <<: *openai ``` -------------------------------- ### Install Dependencies Source: https://github.com/activeagents/activeagent/blob/main/CONTRIBUTING.MD Install project dependencies using Bundler. Ensure Ruby and Bundler are installed. ```bash git clone https://github.com/activeagents/activeagent.git cd activeagent bundle install ``` -------------------------------- ### Configure Ollama in an Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ollama.md Set up the Ollama provider within your agent configuration. This example shows basic agent setup with Ollama. ```ruby agent :ollama, type: :llm do |agent| agent.provider :ollama, model: "llama3" end ``` -------------------------------- ### Quick Example Support Agent Usage Source: https://github.com/activeagents/activeagent/blob/main/docs/agents.md Shows how to invoke the SupportAgent with parameters. ```ruby SupportAgent.with(user: "Alice").generate(from: "How do I reset my password?") ``` -------------------------------- ### Start VitePress dev server Source: https://github.com/activeagents/activeagent/blob/main/docs/contributing/documentation.md Run this command to start the VitePress development server for previewing documentation. The server typically runs at http://localhost:5173. ```bash bin/docs # Starts VitePress dev server at http://localhost:5173 ``` -------------------------------- ### Default Instructions Template Example Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md This example shows the default instructions template loading mechanism. ActiveAgent automatically loads `instructions.md` when `prompt` is called without explicit instructions. ```erb You are a helpful assistant. Available tools: search, analyze, report. ``` -------------------------------- ### Quick Example Usage Source: https://github.com/activeagents/activeagent/blob/main/docs/actions.md Demonstrates how to instantiate and use the 'quick_example_summary' action defined in the agent. It shows calling the action and accessing the generated response. ```ruby agent = QuickExampleSummaryAgent.new response = agent.quick_example_summary("the importance of AI in modern society") puts response.content ``` -------------------------------- ### Tool Configuration Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md Example of configuring built-in tools within the prompt options for the Responses API. This includes enabling web search and setting tool choice to 'required'. ```ruby agent.configure do |c| c.tools = [:web_search_preview] c.tool_choice = :required end ``` -------------------------------- ### Basic Streaming Agent Setup Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/streaming.md Configure an agent to enable streaming by setting `stream: true` in its initialization. ```ruby agent.rb agent = ActiveAgent::Agent.new(stream: true) ``` -------------------------------- ### Custom Instructions Template Example Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md This example demonstrates referencing a specific template by name, optionally passing local variables. It's useful when multiple agents share instruction templates or when different instruction sets are needed for different actions. ```erb #agent.rb generate_with( template: "custom_instructions.text.erb", locals: { tool_list: "search, analyze, report" } ) # custom_instructions.text.erb You are a helpful assistant. Available tools: <%= tool_list %>. ``` -------------------------------- ### Install Dependencies with Bundler Source: https://github.com/activeagents/activeagent/blob/main/docs/contributing/documentation.md Installs project dependencies using Bundler. Ensure you have Ruby and Bundler installed. ```bash bundle install ``` -------------------------------- ### Basic Ollama Usage Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ollama.md Demonstrates a basic generation task using the Ollama provider. This example is suitable for simple text generation prompts. ```ruby agent = :ollama response = agent.generate "What is the capital of France?" puts response.message.content ``` -------------------------------- ### Include Generated Example Output in Docs Source: https://github.com/activeagents/activeagent/blob/main/docs/contributing/documentation.md Embeds a generated example output markdown file into the documentation using VitePress's `::: details` block and the `@include` directive. ```markdown ::: details Response Example ::: ``` -------------------------------- ### Install ActiveAgent Generator Source: https://github.com/activeagents/activeagent/blob/main/AGENTS.md Installs the ActiveAgent generator. This is a prerequisite for generating agents. ```bash # Install generator rails generate active_agent:install ``` -------------------------------- ### Quick Example Agent Definition Source: https://github.com/activeagents/activeagent/blob/main/docs/actions.md Defines a simple agent with a 'quick_example_summary' action that uses prompt() to generate a summary. This is the basic structure for creating agent actions. ```ruby class QuickExampleSummaryAgent < Agent def quick_example_summary(query) prompt("Summarize the following: #{query}") end end ``` -------------------------------- ### Basic RubyLLM Agent Setup Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ruby_llm.md Configure an agent to use the RubyLLM provider with a specified model. ```ruby class MyAgent < ApplicationAgent generate_with :ruby_llm, model: "gpt-4o-mini" end ``` -------------------------------- ### Rate Limiting Example with Generation Callback Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/callbacks.md An example demonstrating rate limiting using a generation callback. This snippet shows how to implement custom logic within the callback. ```ruby agent.before_generation do |params| rate_limit_check(params) end ``` -------------------------------- ### Responses API Web Search Tool Example Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/web-search-agent.md Leverage the Responses API with the `web_search_preview` tool for more granular control over web search parameters. This example shows how to specify the search context size. ```ruby response = WebSearchAgent.with( query: "Latest Ruby on Rails 8 features", context_size: "high" # Options: low, medium, high ).search_with_tools.generate_now puts response.message.content # => Returns comprehensive information about Rails 8 ``` -------------------------------- ### Usage Statistics Example Source: https://github.com/activeagents/activeagent/blob/main/docs/actions.md Shows how to access usage statistics after an action has been executed. This allows tracking token consumption and associated costs. ```ruby response = agent.summarize.generate_now response.usage.total_tokens #=> 125 ``` -------------------------------- ### Install ActiveAgent without Configuration File Source: https://github.com/activeagents/activeagent/blob/main/docs/framework/rails.md Use this flag to skip the creation of the default configuration file. ```bash rails generate active_agent:install --skip-config ``` -------------------------------- ### Install Active Agent Gem Source: https://github.com/activeagents/activeagent/blob/main/README.md Use bundler to add the activeagent gem to your project's Gemfile and install it. ```bash bundle add activeagent ``` -------------------------------- ### Tool Calling Example Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/support-agent.md Illustrates how the agent can call its defined actions, such as `get_cat_image`, in response to a user's request. The output indicates a tool call and a multimodal response. ```ruby message = "Show me a cat" prompt = SupportAgent.prompt(message: message) response = prompt.generate_now # The agent will call the get_cat_image action puts response.message.content # => "Here's a cute cat for you! [image displayed]" ``` -------------------------------- ### MCP Integration Agent Example Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/mcp-integration-agent.md This Ruby code serves as a basic example for an agent implementing the Model Context Protocol (MCP) for integration purposes. ```ruby # Example agent demonstrating MCP (Model Context Protocol) integration ``` -------------------------------- ### Basic OpenRouter Usage Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_router.md Demonstrates a simple text generation request using the OpenRouter provider. It specifies the model and the prompt for the AI. ```ruby response = open_router_agent.generate_content("What is the weather like in San Francisco?") puts response.content ``` -------------------------------- ### Chat API Search Example Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/web-search-agent.md Perform a web search using the Chat Completions API with the `gpt-4o-search-preview` model. This example shows how to retrieve current information based on a query. ```ruby response = WebSearchAgent.with( query: "Latest developments in AI for 2025" ).search_current_events.generate_now puts response.message.content # => Returns current information about AI developments ``` -------------------------------- ### Ollama Advanced Options Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ollama.md Demonstrates advanced configuration options for the Ollama provider, including sampling parameters and system configurations. This is useful for fine-tuning model behavior and connection settings. ```ruby agent = :ollama response = agent.generate "Write a short story about a robot.", temperature: 0.8, top_p: 0.9, num_predict: 100, stop: ["\n\n\n"], seed: 1234 puts response.message.content ``` -------------------------------- ### Agent Tool Usage Example Source: https://github.com/activeagents/activeagent/blob/main/README.md Demonstrates how an agent can be configured to use tools for external service interactions. The response may include results from tool calls. ```ruby # Agent with tool support prompt = SupportAgent.prompt(message: "Show me a cat") response = prompt.generate_now # Response includes tool call results ``` -------------------------------- ### Good Instruction Example Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Provides a clear and specific instruction for a customer support agent, defining role, goal, and verification steps. ```plaintext You are a customer support agent for Acme Corp. Your goal is to resolve customer issues quickly and professionally. Always verify the customer's account before making changes. ``` -------------------------------- ### Rails Credentials Setup Source: https://github.com/activeagents/activeagent/blob/main/docs/framework/testing.md Configure API keys using Rails credentials for secure storage. Alternatively, environment variables can be used as a fallback. ```bash rails credentials:edit ``` ```yaml openai: access_token: your-api-key anthropic: access_token: your-api-key ``` ```bash export OPENAI_ACCESS_TOKEN=your-api-key export ANTHROPIC_ACCESS_TOKEN=your-api-key ``` -------------------------------- ### Instruction Precedence Example Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Demonstrates how instructions are overridden based on their definition location, with per-action instructions having the highest priority. ```ruby agent.rb ``` -------------------------------- ### Provider Configuration Example Source: https://github.com/activeagents/activeagent/blob/main/AGENTS.md Shows how to configure an AI provider, specifically OpenAI, in `config/active_agent.yml` for the development environment. It includes the service name, access token retrieval, and default model. ```yaml development: openai: service: "OpenAI" access_token: <%= Rails.application.credentials.dig(:openai, :access_token) %> model: "gpt-4o-mini" ``` -------------------------------- ### Cross-Provider Tool Usage Examples Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/tools.md Demonstrates how to use the same tool definition across different providers (Anthropic, Ollama, OpenAI, OpenRouter). The common format ensures portability. ```ruby agent = Agent.new(tools: WeatherTool.new) response = agent.prompt( message: "What's the weather like in Boston, MA?", tools: agent.tools ) puts response.content ``` ```ruby agent = Agent.new(tools: WeatherTool.new) response = agent.prompt( message: "What's the weather like in Boston, MA?", tools: agent.tools ) puts response.content ``` ```ruby agent = Agent.new(tools: WeatherTool.new) response = agent.prompt( message: "What's the weather like in Boston, MA?", tools: agent.tools ) puts response.content ``` ```ruby agent = Agent.new(tools: WeatherTool.new) response = agent.prompt( message: "What's the weather like in Boston, MA?", tools: agent.tools ) puts response.content ``` -------------------------------- ### Responses API Agent Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md Demonstrates how to configure and use the Responses API with built-in tools. Set `api_version: :responses` (default) for this functionality. ```ruby agent = OpenAI::Agent.new(api_version: :responses) agent.run("What's the weather like in London?") ``` -------------------------------- ### Actions Interface Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/agents.md An example agent showcasing the actions interface using `prompt` to configure generation context. ```ruby class ActionsInterfaceAgent < ApplicationAgent def generate(query:) prompt("Respond to the user's query: {query}") end end ``` -------------------------------- ### Concise Instruction Example Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Presents a balanced instruction that is neither too vague nor too verbose, defining the agent's role and behavior. ```plaintext You are a product expert for HomeKit devices. Answer questions accurately using the product documentation. If a question is outside your knowledge, direct users to human support. ``` -------------------------------- ### Configure Generation Providers Source: https://github.com/activeagents/activeagent/blob/main/README.md Set up different AI generation providers and their configurations in the `config/active_agent.yml` file. This example shows configurations for OpenAI, Anthropic, and Ollama. ```yaml development: openai: service: "OpenAI" access_token: <%= Rails.application.credentials.dig(:openai, :access_token) %> model: "gpt-4o-mini" anthropic: service: "Anthropic" access_token: <%= Rails.application.credentials.dig(:anthropic, :access_token) %> model: "claude-sonnet-4.5" ollama: service: "Ollama" model: "llama3.2" ruby_llm: service: "RubyLLM" ``` -------------------------------- ### Conversation Example with Message Roles Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/support-agent.md Provides a concrete example of a conversation flow, iterating through messages and displaying their roles and truncated content. This helps visualize the interaction between system, user, assistant, and tool messages. ```ruby response = SupportAgent.prompt(message: "Show me a cat").generate_now response.prompt.messages.each do |message| puts "#{message.role}: #{message.content[0..50]}..." end # Output: # system: You're a support agent. Your job is to help... # user: Show me a cat # assistant: [tool_call: get_cat_image] # tool: https://cataas.com/cat/... # assistant: Here's a cute cat for you! ``` -------------------------------- ### OpenAI Environment Variables Setup Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md Alternative method for setting OpenAI credentials using environment variables. `OPENAI_ACCESS_TOKEN` is required, and `OPENAI_ORGANIZATION_ID` is optional. ```bash export OPENAI_ACCESS_TOKEN=your-api-key export OPENAI_ORGANIZATION_ID=your-org-id ``` -------------------------------- ### Anthropic Configuration File Setup Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/anthropic.md Set up Anthropic credentials in the `config/active_agent.yml` file. This is an alternative to using environment variables. ```yaml anthropic: api_key: "your-api-key" ``` -------------------------------- ### Bad Instruction Example Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Illustrates a vague instruction that lacks specificity and context for the agent. ```plaintext You're helpful. ``` -------------------------------- ### Quick Start: Registering a Weather Agent Tool Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/tools.md Define a method in your agent and register it as a tool. The LLM will call this method when it needs weather data. ```ruby class WeatherAgent < ApplicationAgent # ... other agent code ... # Register the tool using the common format tools [ { name: "get_weather", description: "Get the current weather in a given location", parameters: { type: "object", properties: { location: { type: "string", description: "The city and state, e.g. San Francisco, CA" } }, required: ["location"] } } ] # Method that will be called by the LLM def get_weather(location:) # ... logic to fetch weather data ... "The weather in #{location} is sunny and 25°C." end end ``` ```ruby agent = WeatherAgent.new response = agent.prompt( message: "What's the weather like in Boston, MA?", tools: agent.tools ) puts response.content ``` -------------------------------- ### Install Ollama using Docker Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ollama.md Docker commands to run the Ollama service and pull a model. This is useful for containerized environments. ```bash docker run -d -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama docker exec -it ollama ollama pull llama3 ``` -------------------------------- ### Prompting Callbacks Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/callbacks.md Prompting callbacks are specific to prompt execution. This example shows how to register a callback for prompt execution. ```ruby agent.before_prompt do |prompt, params| # ... end agent.after_prompt do |prompt, params, result| # ... end agent.around_prompt do |prompt, params, &block| # ... result = block.call # ... result end ``` -------------------------------- ### Tool Calling with RubyLLM Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ruby_llm.md Implement tool calling functionality within an agent using the RubyLLM provider. This example shows how to define tools and their parameters for the LLM to use. ```ruby class WeatherAgent < ApplicationAgent generate_with :ruby_llm, model: "gpt-4o-mini" def forecast prompt( message: "What's the weather in Boston?", tools: [{ name: "get_weather", description: "Get weather for a location", parameters: { type: "object", properties: { location: { type: "string", description: "City name" } }, required: ["location"] } }] ) end def get_weather(location:) WeatherService.fetch(location) end end ``` -------------------------------- ### Basic Anthropic Generation Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/anthropic.md Demonstrates a basic usage of the Anthropic provider for generating text. Ensure your API key is set up correctly. ```ruby response = agent.call( "What is the capital of France?", model: "claude-3-haiku-20240307" ) puts response.content ``` -------------------------------- ### Markdown Format Instructions Example Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Use markdown for structured instructions with formatting. The format chosen affects how providers receive instructions, so testing with your specific provider is recommended. ```erb # Technical Support Agent ## Role You provide **technical support** for software issues. ## Guidelines - Always verify the problem before suggesting solutions - Ask clarifying questions when needed - Be patient and encouraging ``` -------------------------------- ### Basic Mock Provider Usage Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/mock.md Demonstrates a basic interaction with the Mock provider, sending a message and receiving a pig latin response. This example highlights the deterministic nature of the mock responses. ```ruby require "active_agent" agent = ActiveAgent::Agent.new({ providers: { mock: { service: "Mock", model: "mock-model" } } }) response = agent.run("Hello world") puts response.message # Output: "Ellohay orldway" ``` -------------------------------- ### Configure GPU Usage for Ollama Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ollama.md Example of configuring GPU usage for the Ollama provider. This requires Ollama to be set up with GPU support. ```ruby agent :ollama, type: :llm do |agent| agent.provider :ollama, model: "llama3", gpu: true end ``` -------------------------------- ### Implement Fallbacks for Production Reliability Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_router.md Configure fallback models for production systems to ensure reliability. This example demonstrates setting up multiple fallbacks for an agent. ```ruby agent :openrouter_best_practice_fallbacks_agent do |agent| agent.model = "openai/gpt-4o" agent.fallback_models = ["openai/gpt-4o-mini", "anthropic/claude-3-opus", "google/gemini-pro"] end ``` -------------------------------- ### Native Formats - OpenAI Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/mcps.md Example of using native formats for OpenAI MCP integration, potentially for provider-specific features. ```ruby agent = ActiveAgent::Agent.new agent.add_mcp_server( name: "openai_native_files", url: "https://openai.mcp.example.com/files", authorization: "OPENAI_FILES_TOKEN" ) agent.run("List files using OpenAI's native format.") ``` -------------------------------- ### Configure OpenRouter Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_router.md Set up the OpenRouter provider within your agent configuration. This example shows the basic structure for agent definition with provider settings. ```ruby agent :open_router_agent do |agent| agent.provider = :open_router agent.settings = { api_key: ENV.fetch("OPEN_ROUTER_API_KEY", "your-api-key") } agent.models = ["openrouter/auto"] end ``` -------------------------------- ### OpenRouter Configuration File Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_router.md Example of how to configure OpenRouter credentials and settings within the `config/active_agent.yml` file. This method is an alternative to environment variables. ```yaml open_router: api_key: "your-api-key" # or # api_key: "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" # models: ["openrouter/auto"] # settings: {} ``` -------------------------------- ### Chat Completions API Agent Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md Demonstrates how to configure and use the traditional Chat Completions API. Set `api_version: :chat` in your agent configuration to use this API. ```ruby agent = OpenAI::Agent.new(api_version: :chat) agent.run("What's the weather like in London?") ``` -------------------------------- ### Run Active Agent Install Generator Source: https://github.com/activeagents/activeagent/blob/main/README.md Execute the Rails generator to create necessary configuration files and the base agent class. ```bash rails generate active_agent:install ``` -------------------------------- ### Enable Custom MCP Servers Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md Configure the Responses API to connect to custom MCP servers. This example demonstrates setting up two custom servers with specific URLs. ```ruby agent.configure do |c| c.tools = [:mcp] c.mcps = [ { url: "https://my.custom.server.com/api", name: "custom_server_1" }, { url: "https://another.server.org/", name: "custom_server_2" } ] end ``` -------------------------------- ### Action-Based Generation Usage Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/generation.md Utilize an agent with defined action methods. This example shows how to call the `summarize` action to get a summary of a given text. ```ruby agent = ActionAgent.new agent.summarize(text: "This is a long piece of text that needs to be summarized.") ``` -------------------------------- ### Install Generation Provider Gems Source: https://github.com/activeagents/activeagent/blob/main/README.md Add gems for specific AI generation providers like OpenAI, Anthropic, Ollama, or a unified API like RubyLLM. ```bash # OpenAI bundle add openai # Anthropic bundle add anthropic # Ollama (uses OpenAI-compatible API) bundle add openai # OpenRouter (uses OpenAI-compatible API) bundle add openai # RubyLLM (unified API for 15+ providers) bundle add ruby_llm ``` -------------------------------- ### Basic OpenAI Configuration Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md Basic setup for the OpenAI provider within an agent configuration. Ensure your API key and organization ID are correctly set. ```ruby OpenAI::Agent.new(model: "gpt-4o", temperature: 0.7) ``` -------------------------------- ### Agent Definitions for Various Providers Source: https://github.com/activeagents/activeagent/blob/main/docs/providers.md Define agents that utilize different AI providers. Each example shows how to specify the provider and model for agent generation. ```ruby class RubyLLMAgent < ApplicationAgent generate_with :ruby_llm, model: "gpt-4o-mini" # Works with any model RubyLLM supports: # generate_with :ruby_llm, model: "claude-sonnet-4-5-20250929" # generate_with :ruby_llm, model: "gemini-2.0-flash" end ``` -------------------------------- ### Chat API Search with Location Context Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/web-search-agent.md Utilize the Chat Completions API for location-aware web searches. This example demonstrates how to provide user location details to get localized search results, such as restaurant recommendations. ```ruby response = WebSearchAgent.with( query: "Best restaurants near me", location: { country: "US", city: "San Francisco", region: "CA" } ).search_current_events.generate_now puts response.message.content # => Returns San Francisco restaurant recommendations ``` -------------------------------- ### Generation Response Usage Example Source: https://github.com/activeagents/activeagent/blob/main/docs/providers.md Demonstrates how to use the generation response object, which includes message content, usage statistics, and raw provider data for debugging. ```ruby generation = agent.generate puts generation.message puts generation.usage puts generation.raw_response ``` -------------------------------- ### Example Usage of Emulated JSON Object Response Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/anthropic.md Demonstrates how to call a method on an agent configured for emulated JSON object responses and retrieve the reconstructed JSON output. ```ruby agent = ResponseFormatJsonObjectAgent.new response = agent.simple_json # response is now the Hash {"message"=>"hello world"} ``` -------------------------------- ### Mock Provider Offline Development Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/mock.md Demonstrates the Mock provider's capability for offline development. This example shows that the provider works without making external API calls, suitable for environments with no network connectivity. ```ruby require "active_agent" agent = ActiveAgent::Agent.new({ providers: { mock: { service: "Mock", model: "mock-model" } } }) # This call will succeed even without an internet connection response = agent.run("Test offline") puts response.message # Output: "Esttay offlineay" ``` -------------------------------- ### Manage Locally Installed Models Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/ollama.md Bash commands to list, pull, and remove models from your local Ollama installation. These commands are used for managing your model library. ```bash # List all locally available models ollama list # Pull a new model ollama pull llama3 # Remove a model ollama rm llama3 ``` -------------------------------- ### Example Rails Endpoint for Receiving Traces Source: https://github.com/activeagents/activeagent/blob/main/docs/framework/telemetry.md An example Rails controller action to receive and process incoming telemetry traces. It requires API key authentication and skips authenticity token verification. ```ruby # app/controllers/api/traces_controller.rb class Api::TracesController < ApplicationController skip_before_action :verify_authenticity_token before_action :authenticate_api_key! def create traces = params[:traces] traces.each do |trace| Trace.create!( trace_id: trace[:trace_id], service_name: trace[:service_name], environment: trace[:environment], spans: trace[:spans], timestamp: trace[:timestamp] ) end head :accepted end private def authenticate_api_key! api_key = request.headers["Authorization"]&.gsub(/^Bearer /, "") head :unauthorized unless ApiKey.exists?(key: api_key) end end ``` -------------------------------- ### Dynamic Context with ERB Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Shows how to use ERB templates in instructions to dynamically include user information and available actions. ```erb You are assisting <%= @user.name %> (<%= @user.email %>). <% if @user.premium? %> Premium features are available to this user. <% end %> Available actions: <% controller.action_methods.each do |action| %> - <%= action %> <% end %> ``` -------------------------------- ### Streaming Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/agents.md An example agent configured to stream responses in real-time. ```ruby class StreamingAgent < ApplicationAgent def generate(query:) stream("Respond to the user's query: {query}") end end ``` -------------------------------- ### Basic Prompt and Response Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/support-agent.md Demonstrates sending a simple message to the Support Agent and generating an immediate response. Shows how to access the message content. ```ruby prompt = SupportAgent.prompt(message: "Hello, I need help") puts prompt.message.content # => "Hello, I need help" response = prompt.generate_now puts response.message.content # => "Hello! I'm here to help you. What can I assist you with today?" ``` -------------------------------- ### Structured Instructions with ERB Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Demonstrates structuring instructions into sections like Role, Capabilities, and Constraints using ERB for dynamic content. ```erb ## Role You are a technical documentation assistant specializing in API documentation. ## Capabilities - Generate code examples in multiple languages - Explain complex technical concepts clearly - Suggest best practices and design patterns ## Constraints - Never expose API keys or secrets in examples - Always validate that code examples would actually work - If unsure about something, say so explicitly ``` -------------------------------- ### Defining Reusable Tools with a Module Source: https://github.com/activeagents/activeagent/blob/main/AGENTS.md Demonstrates how to define reusable tools in a module, like `SEARCH_TOOL`, and include them in an agent. The agent can then use these tools in its prompts. ```ruby module MyTools SEARCH_TOOL = { name: "search", description: "Search for data", parameters: { type: "object", properties: { query: { type: "string" } }, required: ["query"] } } def search(query:) SearchService.find(query) end end class MyAgent < ApplicationAgent include MyTools def find_info prompt(message: "Find X", tools: [SEARCH_TOOL]) end end ``` -------------------------------- ### Agent with JSON Schema Response Source: https://github.com/activeagents/activeagent/blob/main/docs/framework/rails.md Example of an agent configured for JSON schema response validation. ```ruby class DataAgent < ApplicationAgent def parse prompt(params[:message], response_format: :json_schema) end end ``` -------------------------------- ### Before Generation Callback Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/callbacks.md Use before generation callbacks for setup, rate limiting, or validation before any generation executes. ```ruby agent.before_generation do |params| # ... end ``` -------------------------------- ### Configure API Keys for Testing Source: https://github.com/activeagents/activeagent/blob/main/docs/contributing/documentation.md Sets API keys for services like OpenAI, Anthropic, and OpenRouter by creating a `.env.test` file. This is required for re-recording VCR cassettes or running tests against live APIs. ```bash OPENAI_API_KEY=your_key_here ANTHROPIC_API_KEY=your_key_here OPEN_ROUTER_API_KEY=your_key_here ``` -------------------------------- ### Add Provider Gem Source: https://github.com/activeagents/activeagent/blob/main/docs/getting_started.md Install the gem for your chosen AI provider. This allows ActiveAgent to communicate with the AI service. ```bash bundle add openai # Ollama uses OpenAI-compatible API ``` ```bash bundle add anthropic ``` ```bash bundle add openai # Ollama uses OpenAI-compatible API ``` ```bash bundle add openai # OpenRouter uses OpenAI-compatible API ``` ```bash bundle add ruby_llm # Unified API for 15+ providers ``` -------------------------------- ### Native Formats - Anthropic Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/mcps.md Example of using native formats for Anthropic MCP integration, potentially for provider-specific features. ```ruby agent = ActiveAgent::Agent.new agent.add_mcp_server( name: "anthropic_native_tools", url: "https://anthropic.mcp.example.com/tools", authorization: "ANTHROPIC_TOOLS_TOKEN" ) agent.run("Use Anthropic's native format for tool access.") ``` -------------------------------- ### Configuration Precedence for Providers Source: https://github.com/activeagents/activeagent/blob/main/docs/providers.md Illustrates the order of configuration precedence for agent settings, from global to agent-level and runtime overrides. Use this to manage settings like temperature. ```ruby # 1. Global config (config/active_agent.yml) # temperature: 0.7 class MyAgent < ApplicationAgent # 2. Agent-level config generate_with :openai, temperature: 0.5 def analyze # 3. Runtime config (highest precedence) prompt(temperature: 0.9) end end ``` -------------------------------- ### Controller Integration for Agent Generation Source: https://github.com/activeagents/activeagent/blob/main/docs/framework/rails.md Example of integrating agent generation into a Rails controller to handle user requests asynchronously. ```ruby class ChatController < ApplicationController def create generation = ChatAgent .with(message: params[:message], user_id: current_user.id) .respond .generate_later render json: { status: "processing" } end end ``` -------------------------------- ### Ollama Embedding Configuration Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/embeddings.md Configure the Ollama provider for generating embeddings. This example shows how to specify the Ollama model to be used. ```ruby agent = ActiveAgents::Agent.new.embed_with("ollama", model: "nomic-embed-text") response = agent.embed(text: "This is a sample text.") puts response.embedding ``` -------------------------------- ### Generate Schema from ActiveRecord Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/structured_output.md Automatically detect columns and validations when generating JSON schemas from ActiveRecord models. This example excludes timestamps. ```ruby class BlogPost < ApplicationRecord include ActiveAgent::SchemaGenerator end schema = BlogPost.to_json_schema( strict: true, name: "blog_post", exclude: [:created_at, :updated_at] # Omit timestamps ) ``` -------------------------------- ### Enable Web Search Tool Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/open_ai.md Configure the Responses API to use the `web_search_preview` tool for real-time information retrieval. This is useful for questions requiring current information. ```ruby agent.configure do |c| c.tools = [:web_search_preview] end ``` -------------------------------- ### Invocation with Parameters Source: https://github.com/activeagents/activeagent/blob/main/docs/agents.md Demonstrates how to call an agent's action by passing parameters using the `with` method. ```ruby TranslationAgent.with(user: "Bob").translate(text: "Hello world", to: "Spanish") ``` -------------------------------- ### Embedding Callbacks Detailed Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/callbacks.md Embedding callbacks are specific to embedding operations. This example shows detailed usage of before, after, and around embedding callbacks. ```ruby agent.before_embed do |text, params| # ... end agent.after_embed do |text, params, embeddings| # ... end agent.around_embed do |text, params, &block| # ... embeddings = block.call # ... embeddings end ``` -------------------------------- ### OpenAI Pre-built Connectors Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/mcps.md Configures an agent to use OpenAI's pre-built MCP connectors for services like Dropbox and Google Drive. ```ruby agent = ActiveAgent::Agent.new agent.add_mcp_server( name: "openai_dropbox", url: "https://openai.mcp.example.com/dropbox" ) agent.add_mcp_server( name: "openai_google_drive", url: "https://openai.mcp.example.com/google_drive" ) agent.run("List files in my Dropbox and Google Drive.") ``` -------------------------------- ### Anthropic Metadata Configuration Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/anthropic.md Configure custom metadata for request tracking with the Anthropic provider. This example shows how to set a user ID dynamically. ```ruby generate_with :anthropic, metadata: { user_id: -> { Current.user&.id } } ``` -------------------------------- ### System Messages from Instructions Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/messages.md System messages are derived from the `instructions` option provided to the agent. The first snippet shows setting up the agent with instructions, and the second shows how to inspect a system message. ```ruby agent = ActiveAgent::Agent.new(instructions: "You are a helpful assistant.") ``` ```ruby response.messages.find { |m| m.role == :system } ``` -------------------------------- ### Configure Mock Provider in Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/mock.md Set up the Mock provider within your agent's configuration file. Ensure the service is set to 'Mock'. ```ruby agent.rb agent.config.providers.mock = { service: "Mock", model: "mock-model" } ``` -------------------------------- ### Tool Choice Control Examples Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/tools.md Control LLM tool usage with the `tool_choice` parameter. Options include 'auto' (default), 'required', and 'none'. ```ruby # Auto (default) - Let the model decide whether to use tools prompt(message: "...", tools: tools, tool_choice: "auto") ``` ```ruby # Required - Force the model to use at least one tool prompt(message: "...", tools: tools, tool_choice: "required") ``` ```ruby # None - Prevent tool usage entirely prompt(message: "...", tools: tools, tool_choice: "none") ``` -------------------------------- ### Basic Streaming Usage Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/streaming.md Demonstrates how to use an agent configured for streaming. The response will be streamed chunk by chunk. ```ruby usage.rb agent = ActiveAgent::Agent.new(stream: true) agent.run("What is the capital of France?") ``` -------------------------------- ### Multi-Page Navigation Flow with Browser Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/browser-use-agent.md Demonstrates a multi-page navigation sequence using the Browser Agent. This includes navigating to a URL, extracting main content, clicking a link, taking a screenshot, going back, and extracting links. ```ruby agent = BrowserAgent.new # Navigate to main page agent.navigate(url: "https://example.com") # Extract main content content = agent.extract_main_content # Click specific link agent.click(text: "Learn More") # Take screenshot of new page agent.screenshot(main_content_only: true) # Go back agent.go_back # Extract links for further exploration links = agent.extract_links(selector: "#main-content") ``` -------------------------------- ### Dynamic Instructions via Method Reference Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Reference a method that returns instruction text to enable dynamic instructions based on agent state or parameters. This is useful when instructions vary based on user roles, agent state, request context, or other runtime factors. ```ruby def instructions "You are a #{user_role} assistant." end generate_with instructions: :instructions ``` -------------------------------- ### Generate Schema from ActiveModel Source: https://github.com/activeagents/activeagent/blob/main/docs/actions/structured_output.md Generate JSON schemas from Ruby models to ensure consistency and reusability. This example demonstrates generating a schema from a `User` model. ```ruby class User < ApplicationRecord include ActiveAgent::SchemaGenerator end schema = User.to_json_schema ``` -------------------------------- ### Define Instructions in `instructions.text` Template Source: https://github.com/activeagents/activeagent/blob/main/docs/getting_started.md Provide agent instructions using a dedicated ERB template file named `instructions.text` within the agent's view directory. ```erb You are a support agent helping users with their questions. Be concise, friendly, and provide clear solutions. ``` -------------------------------- ### Basic Navigation with Browser Agent Source: https://github.com/activeagents/activeagent/blob/main/docs/examples/browser-use-agent.md Use the Browser Agent to navigate to a URL and retrieve content. Ensure the response message content is present. ```ruby response = BrowserAgent.prompt( message: "Navigate to https://www.example.com and tell me what you see" ).generate_now assert response.message.content.present? ``` -------------------------------- ### Request-Level Overrides Source: https://github.com/activeagents/activeagent/blob/main/docs/framework/configuration.md Demonstrates how request-level settings can override agent-level defaults. In this example, calling `prompt` with a specific temperature overrides the default set in `generate_with` for the `CreativeAgent`. ```ruby class CreativeAgent < ApplicationAgent generate_with :openai, temperature: 0.9 # High creativity by default # Low temperature takes effect def imagine prompt(temperature: 0.3) end end ``` -------------------------------- ### Tool Usage Instructions Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/instructions.md Defines how an agent should use available tools, including a step-by-step workflow and guidelines for a hotel booking assistant. ```md You are a hotel booking assistant helping <%= @user.name %> find and reserve accommodations near their travel destination. ## Available Tools Use these tools in sequence to complete bookings: 1. **search** - Find hotels matching the user's criteria (location, dates, preferences) 2. **book** - Reserve a specific hotel room for the user 3. **confirm** - Finalize the reservation and provide confirmation details ## Booking Workflow 1. Use `search` to find hotels in the requested location with the user's dates and preferences 2. Present options and help the user choose based on their needs (price, amenities, location) 3. Use `book` to reserve the selected hotel room 4. Use `confirm` to finalize the booking and provide the confirmation number ## Guidelines - Always verify the destination, check-in/check-out dates, and number of guests before searching - Present hotel options with key details: price, rating, amenities, distance from destination - Confirm all booking details with the user before calling `book` - After booking, clearly communicate the confirmation number and cancellation policy ``` -------------------------------- ### Handle Errors Gracefully in Callbacks Source: https://github.com/activeagents/activeagent/blob/main/docs/agents/streaming.md Implement error handling within your callbacks to prevent exceptions from interrupting the streaming process. This example uses `ActionCable` for broadcasting. ```ruby def safe_broadcast(chunk) return unless chunk.delta ActionCable.server.broadcast("channel", content: chunk.delta) rescue => e Rails.logger.error("Broadcast failed: #{e.message}") end ``` -------------------------------- ### Basic Anthropic Agent Configuration Source: https://github.com/activeagents/activeagent/blob/main/docs/providers/anthropic.md Configure the Anthropic provider within your agent's setup. This snippet shows the basic structure for integrating Anthropic models. ```ruby agent do # ... provider :anthropic, model: "claude-3-opus-20240229", api_key: "ANTHROPIC_API_KEY" # ... end ```