{"id":32932905,"url":"https://github.com/raaf-ai/raaf","last_synced_at":"2026-06-14T21:32:34.522Z","repository":{"id":305186669,"uuid":"1020190141","full_name":"raaf-ai/raaf","owner":"raaf-ai","description":null,"archived":false,"fork":false,"pushed_at":"2025-12-03T21:33:31.000Z","size":10524,"stargazers_count":1,"open_issues_count":47,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-12-07T03:19:31.983Z","etag":null,"topics":["agent","agentic-ai","ai","ruby","ruby-on-rails"],"latest_commit_sha":null,"homepage":"http://guides.raaf-ai.dev/","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/raaf-ai.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-07-15T13:31:48.000Z","updated_at":"2025-12-03T21:33:36.000Z","dependencies_parsed_at":null,"dependency_job_id":"a983d22a-93cd-4b8f-a48f-dcab2f45f73f","html_url":"https://github.com/raaf-ai/raaf","commit_stats":null,"previous_names":["raaf-ai/raaf"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/raaf-ai/raaf","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raaf-ai%2Fraaf","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raaf-ai%2Fraaf/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raaf-ai%2Fraaf/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raaf-ai%2Fraaf/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/raaf-ai","download_url":"https://codeload.github.com/raaf-ai/raaf/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/raaf-ai%2Fraaf/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34339194,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-14T02:00:07.365Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agent","agentic-ai","ai","ruby","ruby-on-rails"],"created_at":"2025-11-11T18:20:26.137Z","updated_at":"2026-06-14T21:32:34.516Z","avatar_url":"https://github.com/raaf-ai.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Ruby AI Agents Factory (RAAF)\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Version](https://img.shields.io/badge/Version-0.1.0-blue.svg)](https://rubygems.org/gems/ruby-ai-agents-factory)\n[![Ruby](https://img.shields.io/badge/Ruby-3.0%2B-red.svg)](https://www.ruby-lang.org/)\n \n\nA comprehensive Ruby framework for building sophisticated multi-agent AI workflows. Ruby AI Agents Factory (RAAF) is a Ruby implementation inspired by OpenAI's Swarm framework, providing 100% feature parity with the Python OpenAI Agents library, plus additional enterprise-grade capabilities.\n\n\u003e 🤖 **Built with AI**: This codebase was developed using AI assistance, demonstrating AI-assisted software development at scale.\n\n## ✅ Build Status\n\nCI:\n\n[![Docs Link Check](https://github.com/raaf-ai/raaf/actions/workflows/docs-link-check.yml/badge.svg)](https://github.com/raaf-ai/raaf/actions/workflows/docs-link-check.yml)\n[![Core CI](https://github.com/raaf-ai/raaf/actions/workflows/core-ci.yml/badge.svg)](https://github.com/raaf-ai/raaf/actions/workflows/core-ci.yml)\n[![DSL CI](https://github.com/raaf-ai/raaf/actions/workflows/dsl-ci.yml/badge.svg)](https://github.com/raaf-ai/raaf/actions/workflows/dsl-ci.yml)\n[![Providers CI](https://github.com/raaf-ai/raaf/actions/workflows/providers-ci.yml/badge.svg)](https://github.com/raaf-ai/raaf/actions/workflows/providers-ci.yml)\n[![Guides Build \u0026 Deploy](https://github.com/raaf-ai/raaf/actions/workflows/guides-build-deploy.yml/badge.svg)](https://github.com/raaf-ai/raaf/actions/workflows/guides-build-deploy.yml)\n\nWeekly:\n\n[![Core Weekly](https://github.com/raaf-ai/raaf/actions/workflows/core-weekly.yml/badge.svg)](https://github.com/raaf-ai/raaf/actions/workflows/core-weekly.yml)\n[![DSL Weekly](https://github.com/raaf-ai/raaf/actions/workflows/dsl-weekly.yml/badge.svg)](https://github.com/raaf-ai/raaf/actions/workflows/dsl-weekly.yml)\n[![Providers Weekly](https://github.com/raaf-ai/raaf/actions/workflows/providers-weekly.yml/badge.svg)](https://github.com/raaf-ai/raaf/actions/workflows/providers-weekly.yml)\n\n## 🎯 About RAAF and OpenAI Swarm\n\nRAAF is a Ruby implementation of multi-agent orchestration patterns inspired by [OpenAI's Swarm framework](https://github.com/openai/swarm). While Swarm provides an experimental, educational framework for exploring ergonomic interfaces for multi-agent systems in Python, RAAF brings these concepts to the Ruby ecosystem with production-ready features and enterprise-grade capabilities.\n\n### Key Concepts from Swarm\n\nLike Swarm, RAAF implements:\n- **Lightweight Agents**: Agents are simple, stateless entities defined by instructions and tools\n- **Handoffs**: Agents can seamlessly transfer conversations to other specialized agents\n- **Function Calling**: Natural integration of Ruby methods as agent tools\n- **Context Variables**: Thread-safe context passing between agents and tool calls\n\n### Beyond Swarm: Enterprise Features\n\nRAAF extends the Swarm concepts with:\n- **Multi-Provider Support**: Not just OpenAI, but Anthropic, Google, Cohere, and more.\n- **Production Safety**: Advanced guardrails, PII detection, and security filtering\n- **Memory Management**: Token-aware context management with vector search\n- **Compliance**: GDPR/SOC2/HIPAA compliance tracking and audit trails\n- **Rails Integration**: Full Rails engine with web UI and database persistence\n- **Comprehensive Tracing**: OpenTelemetry support and AI-powered analytics\n\n## 🌟 Key Features\n\n### Core Agent Capabilities\n- **🤖 Multi-Agent Workflows** - Specialized agents with intelligent routing and handoffs\n- **🔧 Advanced Tool Integration** - 15+ built-in tools including file search, web search, computer automation, code interpreter, document generation, and more\n- **📡 Real-time Streaming** - Live response streaming with comprehensive event handling\n- **🎯 Multi-Provider Support** - OpenAI, Anthropic, Gemini, Cohere, Groq, Ollama, and more\n- **📋 Universal Structured Output** - JSON schema enforcement across ALL providers\n- **♻️ Automatic Continuation** - Seamless handling of large responses with intelligent format merging (CSV 95%, Markdown 85-95%, JSON 60-70% success rates)\n\n### Memory \u0026 Intelligence\n- **🧠 Memory Management** - Token-aware context management with auto-pruning and summarization\n- **🔍 Vector Search** - Semantic search with PostgreSQL/pgvector, hybrid search, and query expansion\n- **📚 Document Processing** - Generate PDFs, Word docs, Excel sheets, and reports\n- **🤖 MCP Integration** - Model Context Protocol support for external tool servers\n\n### Enterprise \u0026 Production\n- **🛡️ Advanced Guardrails** - PII detection, security filtering, tripwire rules, parallel execution\n- **📊 Compliance \u0026 Audit** - GDPR/SOC2/HIPAA compliance tracking with integrity hashing\n- **🛤️ Rails Integration** - Complete mountable engine with database storage and web UI\n- **📈 Comprehensive Tracing** - OpenAI dashboard integration, AI-powered analysis, anomaly detection\n- **💰 Cost Management** - Token usage tracking, budget controls, and cost analytics\n- **🔍 Advanced Debugging** - Interactive debugger with breakpoints, step-through, and performance profiling\n\n### Communication \u0026 Integration\n- **🎤 Voice Workflows** - Complete speech-to-text and text-to-speech pipeline\n- **🌐 External Integrations** - Confluence, local shell, computer control tools\n- **📊 Business Analytics** - Usage monitoring, resource tracking, and insights\n- **💻 Developer Experience** - Interactive REPL, natural language queries, export capabilities\n\n## 🚀 Quick Start\n\n### Installation\n\n```bash\ngem install raaf\n```\n\nOr add to your Gemfile:\n```ruby\ngem 'raaf'\n```\n\n### Basic Example\n\n```ruby\nrequire 'raaf'\n\n# Set your API key\nENV['OPENAI_API_KEY'] = 'your-api-key'\n\n# Define a tool function with proper documentation\n# @param city [String] The city to get weather for\n# @return [String] Weather information for the city\ndef get_weather(city:)\n  \"The weather in #{city} is sunny with 22°C\"\nend\n\n# Create an agent with comprehensive configuration\nagent = RAAF::Agent.new(\n  name: \"WeatherAssistant\",\n  instructions: \"You are a helpful weather assistant. Use tools when needed.\",\n  model: \"gpt-4o\"  # Uses ResponsesProvider by default for Python SDK compatibility\n)\n\n# Add tools to extend agent capabilities\nagent.add_tool(method(:get_weather))\n\n# Create runner (automatically uses ResponsesProvider with built-in retry)\nrunner = RAAF::Runner.new(agent: agent)\n\n# Run conversation and get result\nresult = runner.run(\"What's the weather in Paris?\")\n\n# Access the assistant's response\nputs result.messages.last[:content]\n# =\u003e \"I'll check the weather in Paris for you...\"\n```\n\n### Structured Output Example\n\n```ruby\n# Universal structured output across ALL providers with smart field mapping\nagent = RAAF::Agent.new(\n  name: \"DataExtractor\",\n  instructions: \"Extract user information as JSON.\",\n  model: \"gpt-4o\",\n  response_format: {\n    type: \"json_schema\",\n    json_schema: {\n      name: \"user_info\",\n      strict: true,\n      schema: {\n        type: \"object\",\n        properties: {\n          name: { type: \"string\" },\n          age: { type: \"integer\" },\n          email: { type: \"string\" }\n        },\n        required: [\"name\", \"age\"],\n        additionalProperties: false\n      }\n    }\n  }\n)\n\n# Works with ANY provider - OpenAI, Anthropic, Cohere, Groq, etc.\nrunner = RAAF::Runner.new(agent: agent)\nresult = runner.run(\"I'm Alice, 25, alice@example.com\")\n\n# Guaranteed JSON output matching your schema\nuser_data = JSON.parse(result.messages.last[:content])\nputs \"Hello #{user_data['name']}, age #{user_data['age']}!\"\n```\n\n### Advanced Schema Validation with Smart Key Mapping\n\nRAAF agents include powerful schema validation with automatic key normalization:\n\n```ruby\n# Create a DSL agent with flexible schema validation\nclass CompanyExtractor \u003c RAAF::DSL::Agent\n  agent_name \"CompanyExtractor\"\n  model \"gpt-4o\"\n  \n  # Define schema with snake_case fields\n  schema do\n    field :company_name, type: :string, required: true\n    field :market_sector, type: :string, required: true\n    field :employee_count, type: :integer\n    field :annual_revenue, type: :number\n    \n    # Configure validation mode for flexible field mapping\n    validate_mode :tolerant  # :strict, :tolerant, or :partial\n  end\n  \n  instructions \"Extract company information from the text\"\nend\n\n# LLM can use natural language field names that get automatically mapped\nagent = CompanyExtractor.new\nresult = agent.run(\u003c\u003c~TEXT\n  ACME Corporation is a technology company in the software sector.\n  They have around 500 employees and $50M annual revenue.\nTEXT)\n\n# Even if LLM returns fields like \"Company Name\", \"Market Sector\", \"Employee Count\"\n# They get automatically normalized to :company_name, :market_sector, :employee_count\nputs result[:company_name]    # \"ACME Corporation\"\nputs result[:market_sector]   # \"software\"\nputs result[:employee_count]  # 500\n```\n\n**Key Features:**\n\n- **Smart Key Normalization**: `\"Company Name\"` → `:company_name`, `\"API-Key\"` → `:api_key`\n- **Three Validation Modes**:\n  - `:strict` - All fields must match exactly (default)\n  - `:tolerant` - Required fields strict, others flexible\n  - `:partial` - Use whatever validates, ignore invalid fields\n- **JSON Repair**: Handles malformed JSON, markdown-wrapped responses, trailing commas\n- **Nested Schema Support**: Works with complex nested objects and arrays\n- **Comprehensive Metrics**: Track parsing success rates and common failures\n\n### JSON Handling and Repair\n\nRAAF agents automatically handle malformed JSON responses from LLMs:\n\n```ruby\n# The JsonRepair module handles common LLM output issues automatically\nclass DataProcessor \u003c RAAF::DSL::Agent\n  agent_name \"DataProcessor\"\n  model \"gpt-4o\"\n  \n  schema do\n    field :processed_data, type: :object\n    field :summary, type: :string\n    validate_mode :tolerant\n  end\nend\n\n# These malformed responses are automatically repaired:\n\n# 1. JSON with trailing commas\n# LLM Output: '{\"name\": \"John\", \"age\": 25,}'\n# Auto-repaired to: {\"name\": \"John\", \"age\": 25}\n\n# 2. JSON wrapped in markdown\n# LLM Output: '```json\\n{\"valid\": true}\\n```'  \n# Auto-extracted: {\"valid\": true}\n\n# 3. Mixed content with JSON\n# LLM Output: 'Here is the data: {\"name\": \"Alice\"} as requested.'\n# Auto-extracted: {\"name\": \"Alice\"}\n\n# 4. Single quotes instead of double quotes  \n# LLM Output: \"{'name': 'Bob', 'active': true}\"\n# Auto-repaired to: {\"name\": \"Bob\", \"active\": true}\n\nagent = DataProcessor.new\nresult = agent.run(\"Process this data and return as JSON\")\n\n# All repairs happen automatically - you always get clean, parsed data\nputs result[:processed_data]  # Hash with symbolized keys\n```\n\n## Core vs DSL Agents: JSON Handling\n\n**Great News**: JSON repair and schema validation features are now available in **both Core and DSL agents**!\n\n### Core Agents (RAAF::Agent)\n- **Configurable JSON parsing**: Enable fault-tolerant parsing with `json_repair: true`\n- **Smart key normalization**: Enable with `normalize_keys: true`\n- **Multiple validation modes**: Choose `:strict`, `:tolerant`, or `:partial`\n- **Backward compatible**: Default behavior remains strict for existing code\n\n```ruby\n# Core agent with JSON repair and key normalization\nagent = RAAF::Agent.new(\n  name: \"DataExtractor\", \n  instructions: \"Extract company data\",\n  model: \"gpt-4o\",\n  json_repair: true,      # Enable fault-tolerant JSON parsing\n  normalize_keys: true,   # Enable automatic key normalization\n  validation_mode: :tolerant,  # Allow flexible validation\n  response_format: { \n    type: \"json_schema\",\n    json_schema: {\n      properties: {\n        company_name: { type: \"string\" },\n        employee_count: { type: \"integer\" }\n      }\n    }\n  }\n)\n```\n\n### DSL Agents (RAAF::DSL::Agent)\n- **Automatic JSON repair**: Enabled by default in DSL context\n- **Built-in key normalization**: Seamlessly maps natural language field names\n- **Schema DSL**: Declarative schema definition with validation modes\n- **Best for**: Rapid development and complex data extraction workflows\n\n```ruby\n# DSL agent - enhanced with declarative syntax\nclass FlexibleExtractor \u003c RAAF::DSL::Agent\n  schema do\n    field :company_name, type: :string, required: true\n    field :employee_count, type: :integer\n    validate_mode :tolerant  # Built into schema DSL\n  end\nend\n```\n\n**Choose Core agents** for maximum control and configuration flexibility.  \n**Choose DSL agents** for rapid development with declarative schemas.\n\n### Multi-Agent Example\n\n```ruby\n# Create specialized agents with clear roles and handoff logic\nsupport_agent = RAAF::Agent.new(\n  name: \"CustomerSupport\",\n  instructions: \"Handle general customer inquiries. Transfer technical issues to TechnicalSupport.\",\n  model: \"gpt-4o\"\n)\n\ntech_agent = RAAF::Agent.new(\n  name: \"TechnicalSupport\", \n  instructions: \"Handle technical troubleshooting and API integration issues.\",\n  model: \"gpt-4o\"\n)\n\n# Configure agent handoffs (creates transfer_to_TechnicalSupport tool automatically)\nsupport_agent.add_handoff(tech_agent)\n\n# Create runner with the initial agent\nrunner = RAAF::Runner.new(agent: support_agent)\n\n# The agent will automatically handoff when detecting technical issues\nresult = runner.run(\"My API integration is failing with 500 errors\")\n\n# Check which agent handled the final response\nputs \"Final agent: #{result.last_agent.name}\"\nputs \"Response: #{result.messages.last[:content]}\"\n```\n\n### Memory Management Example\n\n```ruby\n# Create agent with memory\nagent = RAAF::Agent.new(\n  name: \"Assistant\",\n  instructions: \"You are a helpful assistant with memory.\",\n  model: \"gpt-4o\"\n)\n\n# Add memory manager with token limits\nmemory_manager = RAAF::Memory::MemoryManager.new(\n  store: RAAF::Memory::VectorStore.new,\n  token_limit: 4000,\n  pruning_strategy: :sliding_window\n)\n\n# Run with memory context\nrunner = RAAF::Runner.new(\n  agent: agent,\n  memory_manager: memory_manager\n)\n\n# Conversations are automatically stored and retrieved\nresult = runner.run(\"Remember that my favorite color is blue\")\n# Later...\nresult = runner.run(\"What's my favorite color?\")\n# =\u003e \"Your favorite color is blue\"\n```\n\n### Pipeline DSL Example\n\nTransform complex multi-step workflows from 66+ lines to just 3 lines:\n\n```ruby\n# Define agents using RAAF DSL\nclass DataAnalyzer \u003c RAAF::DSL::Agent\n  instructions \"Analyze the provided data and extract key insights\"\n  model \"gpt-4o\"\n  \n  result_transform do\n    field :insights\n    field :summary\n  end\nend\n\nclass ReportGenerator \u003c RAAF::DSL::Agent\n  instructions \"Generate a professional report from the analysis\"\n  model \"gpt-4o\"\n  \n  result_transform do\n    field :report\n  end\nend\n\n# Create elegant pipeline - just 3 lines!\nclass DataProcessingPipeline \u003c RAAF::Pipeline\n  flow DataAnalyzer \u003e\u003e ReportGenerator\nend\n\n# Run the pipeline\npipeline = DataProcessingPipeline.new(\n  raw_data: \"Sales data: Q1: $100k, Q2: $150k, Q3: $120k, Q4: $180k\"\n)\nresult = pipeline.run\nputs result[:report]\n```\n\n**Parallel Processing:**\n```ruby\n# Execute multiple agents simultaneously\nclass ParallelAnalysisPipeline \u003c RAAF::Pipeline\n  flow DataInput \u003e\u003e \n       (SentimentAnalyzer | KeywordExtractor | EntityRecognizer) \u003e\u003e \n       ResultMerger\nend\n```\n\n**Advanced Features:**\n- **Automatic Field Mapping** - Context flows intelligently between agents\n- **Error Handling** - Built-in retry and fallback mechanisms  \n- **Performance Optimization** - Parallel execution where possible\n- **Testing Support** - Comprehensive RSpec integration\n- **Field Validation** - Compile-time compatibility checking\n\n👉 **[Complete Pipeline DSL Guide](docs/PIPELINE_DSL_GUIDE.md)** - Comprehensive documentation with patterns, troubleshooting, and best practices\n\n### Pipeline Schema Validation\n\nRAAF pipelines support unified schema validation across all agents, ensuring consistent data structures throughout your workflow:\n\n```ruby\nclass DataProcessingPipeline \u003c RAAF::Pipeline\n  flow DataAnalyzer \u003e\u003e ReportGenerator \u003e\u003e SummaryCreator\n  \n  # Define shared schema for all agents in this pipeline\n  pipeline_schema do\n    field :company_name, type: :string, required: true\n    field :analysis_data, type: :object, required: true\n    field :confidence_score, type: :number\n    field :metadata, type: :object\n    \n    # Choose validation mode for all agents\n    validate_mode :tolerant  # :strict, :tolerant, or :partial\n  end\n  \n  context do\n    default :analysis_depth, \"standard\"\n  end\nend\n\n# Usage - all agents automatically inherit the pipeline schema\npipeline = DataProcessingPipeline.new(\n  raw_data: \"Tesla Inc automotive data...\",\n  analysis_depth: \"detailed\"\n)\nresult = pipeline.run\n\n# All agents return consistently structured data\nputs result[:company_name]      # \"Tesla Inc\" (normalized from any variant)\nputs result[:analysis_data]     # Structured analysis object  \nputs result[:confidence_score]  # Numeric confidence value\n```\n\n**Key Features:**\n\n- **Unified Schema**: Single schema definition shared across all pipeline agents\n- **Automatic JSON Repair**: Handles malformed JSON, trailing commas, markdown wrapping\n- **Smart Key Normalization**: `\"Company Name\"` → `:company_name` automatically\n- **Schema Priority**: Agents can override pipeline schema with their own if needed\n- **Flexible Validation**: Choose strict, tolerant, or partial validation modes\n- **Nested Objects**: Support for complex data structures and arrays\n\n**Schema Inheritance:**\n```ruby\n# Agent can override pipeline schema when needed\nclass SpecializedAnalyzer \u003c RAAF::DSL::Agent\n  # This agent uses its own schema instead of pipeline schema\n  schema do\n    field :specialized_result, type: :array, required: true\n    field :analysis_method, type: :string, required: true\n    validate_mode :strict  # Can use different validation mode\n  end\nend\n\n# Priority order: Agent schema \u003e Pipeline schema \u003e No schema\n```\n\n### Vector Search Example\n\n```ruby\n# Create vector store for semantic search\nvector_store = RAAF::VectorStore.new(\n  adapter: :postgresql,  # or :in_memory for development\n  connection_string: ENV['DATABASE_URL']\n)\n\n# Add documents\nvector_store.add_documents([\n  { content: \"Ruby is a dynamic programming language\", metadata: { topic: \"languages\" } },\n  { content: \"Rails is a web framework for Ruby\", metadata: { topic: \"frameworks\" } }\n])\n\n# Create agent with vector search tool\nagent = RAAF::Agent.new(\n  name: \"ResearchAssistant\",\n  instructions: \"Help users find relevant information.\",\n  model: \"gpt-4o\"\n)\n\n# Add vector search capability\nagent.add_tool(RAAF::Tools::VectorSearchTool.new(vector_store: vector_store))\n\nrunner = RAAF::Runner.new(agent: agent)\nresult = runner.run(\"Tell me about Ruby frameworks\")\n```\n\n### Document Generation Example\n\n```ruby\n# Create agent with document generation tools\nagent = RAAF::Agent.new(\n  name: \"ReportGenerator\",\n  instructions: \"Generate professional reports and documents.\",\n  model: \"gpt-4o\"\n)\n\n# Add document generation capabilities\nagent.add_tool(RAAF::Tools::DocumentTool.new)\nagent.add_tool(RAAF::Tools::ReportTool.new)\n\nrunner = RAAF::Runner.new(agent: agent)\n\n# Generate various document types\nresult = runner.run(\"Create a PDF report summarizing Q4 sales data\")\nresult = runner.run(\"Generate an Excel spreadsheet with financial projections\")\nresult = runner.run(\"Create a Word document with meeting minutes\")\n```\n\n### Advanced Guardrails Example\n\n```ruby\n# Configure multiple guardrails with parallel execution\nguardrails = RAAF::ParallelGuardrails.new([\n  RAAF::Guardrails::PIIDetector.new(\n    action: :redact,\n    sensitivity: :high\n  ),\n  RAAF::Guardrails::SecurityGuardrail.new(\n    block_patterns: [/password/, /api_key/],\n    action: :block\n  ),\n  RAAF::Guardrails::Tripwire.new(\n    patterns: [/delete.*production/, /drop.*table/],\n    action: :terminate\n  )\n])\n\nagent = RAAF::Agent.new(\n  name: \"SecureAssistant\",\n  instructions: \"Process user requests safely.\",\n  model: \"gpt-4o\",\n  guardrails: guardrails\n)\n\n# Guardrails automatically filter inputs and outputs\nrunner = RAAF::Runner.new(agent: agent)\nresult = runner.run(\"My SSN is 123-45-6789\")  # PII will be redacted\n```\n\n### Debugging Example\n\n```ruby\n# Enable interactive debugging\ndebugger = RAAF::Debugging::Debugger.new\nagent = RAAF::Agent.new(\n  name: \"DebugAssistant\",\n  instructions: \"Help debug issues.\",\n  model: \"gpt-4o\"\n)\n\n# Run with debugging enabled\nrunner = RAAF::DebugRunner.new(\n  agent: agent,\n  debugger: debugger\n)\n\n# Set breakpoints and watch variables\ndebugger.set_breakpoint(:before_tool_call)\ndebugger.watch(:token_usage)\n\n# Step through execution\nresult = runner.run(\"Debug this workflow\")\n\n# Export debug session\ndebugger.export_session(\"debug_session.json\")\n```\n\n### Logging Configuration\n\n```ruby\n# Configure unified logging system\nRAAF.logger.configure do |config|\n  config.log_level = :debug\n  config.log_format = :json\n  config.log_output = :rails  # or :console, :file, :auto\n  config.debug_categories = [:api, :tracing, :http]\nend\n\n# Use in your classes\nclass MyAgent\n  include RAAF::Logger\n  \n  def process\n    log_info(\"Processing started\", agent: \"MyAgent\", task_id: 123)\n    log_debug_api(\"API call\", url: \"https://api.openai.com\")\n    log_debug_tracing(\"Span created\", span_id: \"abc123\")\n  end\nend\n\n# Environment configuration\nENV['RAAF_LOG_LEVEL'] = 'debug'\nENV['RAAF_LOG_FORMAT'] = 'json'\nENV['RAAF_DEBUG_CATEGORIES'] = 'api,tracing,http'\n```\n\n**Debug Categories:**\n- `tracing` - Span lifecycle, trace processing\n- `api` - API calls, responses, HTTP details  \n- `tools` - Tool execution, function calls\n- `handoff` - Agent handoffs, delegation\n- `context` - Context management, memory\n- `http` - HTTP debug output\n- `general` - General debug messages\n\n\u003e 📋 **Complete Environment Variables Guide**: For a comprehensive list of all environment variables, their functions, formats, and examples, see **[ENVIRONMENT_VARIABLES.md](ENVIRONMENT_VARIABLES.md)**.\n\n### Rails Integration Example\n\n```bash\n# Add to Gemfile and install\ngem 'raaf'\nbundle install\n\n# Generate Rails integration\nrails generate raaf:tracing:install\nrails db:migrate\n\n# Visit /tracing in your browser for web interface\n```\n\n```ruby\n# config/initializers/raaf_tracing.rb\nRAAF::Tracing.configure do |config|\n  config.auto_configure = true  # Automatically store traces in database\n  config.mount_path = '/tracing'\nend\n\n# app/jobs/application_job.rb\nclass ApplicationJob \u003c ActiveJob::Base\n  include RAAF::Tracing::RailsIntegrations::JobTracing\nend\n\n# Now all agent calls are automatically traced and visible at /tracing\nagent = RAAF::Agent.new(name: \"Assistant\", model: \"gpt-4o\")\nrunner = RAAF::Runner.new(agent: agent)\nresult = runner.run(\"Hello from Rails!\")\n```\n\n## 📚 Documentation\n\n### Getting Started\n- dsl/README.md — DSL quick start and core concepts\n- examples/ — Example workflows and tool usage\n- docs/PIPELINE_DSL_GUIDE.md — End-to-end Pipeline DSL guide\n\n### Continuation Feature (NEW)\n- **[docs/CONTINUATION_GUIDE.md](docs/CONTINUATION_GUIDE.md)** — User guide for automatic continuation (configuration, best practices)\n- **[docs/API_DOCUMENTATION.md](docs/API_DOCUMENTATION.md)** — Complete API reference for continuation classes\n- **[docs/EXAMPLES.md](docs/EXAMPLES.md)** — Working code examples for CSV, Markdown, and JSON\n- **[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** — Common issues and solutions\n\n**Continuation Feature Overview:**\n- Automatically handles responses that exceed token limits\n- Supports CSV (95% success), Markdown (85-95% success), and JSON (60-70% success)\n- Zero configuration required - works by default with optional tuning\n- Includes format detection, intelligent merging, and error recovery\n\n### API References\n- dsl/API_REFERENCE.md — DSL classes, agents, pipeline APIs\n- docs/TOOL_API_REFERENCE.md — Tool DSL and unified tool API\n- docs/API_DOCUMENTATION.md — Continuation APIs (Config, Mergers, Format Detection)\n- tracing/API_REFERENCE.md — Tracing APIs and integrations\n- memory/API_REFERENCE.md — Memory and vector store APIs\n- guardrails/API_REFERENCE.md — Guardrails and safety APIs\n- tools/API_REFERENCE.md — Toolkits and adapters\n- analytics/API_REFERENCE.md — Analytics and usage tracking APIs\n\n### Production\n- SECURITY.md — Security practices and guidelines\n- rails/ — Rails engine and integration (see gem README)\n\nIf you can’t find a doc at the root, look for it under the relevant gem folder (e.g., dsl/, tracing/, memory/) or in docs/.\n\n### Development\n- **[Contributing Guide](CONTRIBUTING.md)** - How to contribute to the project\n- **[Troubleshooting](TROUBLESHOOTING.md)** - Common issues and solutions\n- **[Changelog](CHANGELOG.md)** - Version history and updates\n\n## 📦 Mono-repo Architecture\n\nRAAF is organized as a mono-repo containing multiple independent gems, allowing you to use only the features you need:\n\n### Core Gems\n- raaf — Meta-gem that includes all components\n- raaf-core — Essential agent runtime (see core/README.md)\n- raaf-dsl — Declarative DSL for agents/pipelines (see dsl/README.md)\n- raaf-providers — Multi-provider support (see providers/)\n\n### Tool Ecosystems\n- raaf-tools — Basic tools (see tools/)\n- raaf-tools-advanced — Enterprise tools (see tools/)\n\n### Safety \u0026 Compliance\n- raaf-guardrails — Content filtering, PII detection (see guardrails/)\n- raaf-compliance — Compliance and audit (see compliance/)\n\n### Advanced Features\n- raaf-memory — Memory/vector search (see memory/)\n- raaf-streaming — Streaming and async (see core/ and tracing/)\n- raaf-tracing — Monitoring/observability (see tracing/)\n- raaf-rails — Rails integration and UI (see rails/)\n\n### Development Tools\n- raaf-debug — Debugger and REPL (see debug/)\n- raaf-testing — RSpec matchers/test utils (see testing/)\n- raaf-visualization — Workflow visualization (see analytics/)\n\n### Quick Map\n- Core runtime: core/\n- DSL and pipelines: dsl/\n- Providers: providers/\n- Tools: tools/\n- Guardrails: guardrails/\n- Memory: memory/\n- Tracing: tracing/\n- Rails engine: rails/\n- Testing helpers: testing/\n\n### Modular Installation\n\nInstall only what you need:\n\n```ruby\n# Minimal setup\ngem 'raaf-core'\n\n# Standard setup with tools\ngem 'raaf-core'\ngem 'raaf-tools'\ngem 'raaf-guardrails'\n\n# Full enterprise setup\ngem 'raaf' # Includes everything\n```\n\n## 🏗️ Core Architecture\n\n### Agents\nAI systems that can use tools, make decisions, and collaborate with other agents to complete complex workflows.\n\n### Tools\nExtensive tool ecosystem extending agent capabilities:\n\n**Search \u0026 Information**\n- **File Search** - Search through codebases and documentation\n- **Web Search** - Access real-time information with domain filtering\n- **Vector Search** - Semantic search with hybrid capabilities\n\n**Automation \u0026 Control**\n- **Computer Control** - Automate UI interactions\n- **Local Shell** - Execute system commands safely\n- **Code Interpreter** - Execute code in sandboxed environment\n\n**Document \u0026 Content**\n- **Document Tool** - Generate PDFs, Word docs, Excel sheets\n- **Report Tool** - Create professional reports with templates\n- **Confluence Tool** - Integrate with Confluence wikis\n\n**External Integration**\n- **MCP Tool** - Connect to Model Context Protocol servers\n- **Function Tool** - Wrap any Ruby method as a tool\n\n### Memory System\n- **Memory Manager** - Token-aware context management\n- **Memory Stores** - In-memory, file-based, and vector storage\n- **Auto-pruning** - Intelligent memory management strategies\n\n### Multi-Agent Workflows\nSpecialized agents working together with intelligent handoffs based on context and capabilities.\n\n### Guardrails System\n- **PII Detection** - Automatic PII identification and redaction\n- **Security Filtering** - Block sensitive patterns\n- **Tripwire Rules** - Immediate termination on critical patterns\n- **Parallel Execution** - High-performance guardrail processing\n\n### Tracing \u0026 Monitoring\n- **OpenAI Dashboard** - Native integration with OpenAI platform\n- **Rails Web UI** - Full-featured analytics dashboard\n- **AI Analysis** - Automatic trace analysis and insights\n- **Anomaly Detection** - Identify unusual patterns\n- **Cost Tracking** - Token usage and spend analytics\n\n### Compliance \u0026 Audit\n- **Audit Logger** - Comprehensive event tracking with integrity hashing\n- **Policy Manager** - Enforce data retention and access policies\n- **Compliance Monitor** - Real-time GDPR/SOC2/HIPAA compliance\n- **Export Capabilities** - JSON, CSV, SIEM format exports\n\n## 🎯 Use Cases\n\n- **Customer Service** - Automated support with specialist handoffs\n- **Research \u0026 Analysis** - Information gathering and synthesis\n- **Code Assistance** - Development help and code review\n- **Data Processing** - Automated analysis and reporting\n- **Voice Interfaces** - Speech-enabled applications\n\n## 🌐 Provider Support\n\n- **OpenAI** - GPT-4, GPT-3.5, and other OpenAI models\n- **Anthropic** - Claude 3.5 Sonnet, Claude 3 Opus, and Haiku\n- **Google** - Gemini 1.5 Pro and Flash\n- **Cohere** - Command and Chat models\n- **Groq** - High-speed inference\n- **Ollama** - Local model serving\n- **100+ More** - Via compatible APIs\n\n## 🛡️ Enterprise Features\n\n- **Safety Guardrails** - Content filtering and input validation\n- **Rate Limiting** - Prevent abuse and control costs\n- **Usage Tracking** - Comprehensive analytics and reporting\n- **Cost Controls** - Budget limits and alerts\n- **Audit Logging** - Complete activity trails\n- **Configuration Management** - Environment-based settings\n\n## 💻 Development Experience\n\n```ruby\n# Ruby-idiomatic agent configuration\nagent = RAAF::Agent.new(name: \"Assistant\") do |config|\n  config.instructions = \"You are a helpful assistant\"\n  config.model = \"gpt-4o\"\n  config.add_tool(calculator_tool)\nend\n\n# Dynamic tool execution\nresult = agent.get_weather(city: \"Tokyo\")  # Direct method calls\n\n# Comprehensive tracing\ntracer = RAAF.tracer\nrunner = RAAF::Runner.new(agent: agent, tracer: tracer)\n\n# Interactive debugging\ndebugger = RAAF::Debugging::Debugger.new\ndebugger.set_breakpoint(:before_tool_call)\ndebug_runner = RAAF::DebugRunner.new(agent: agent, debugger: debugger)\n\n# Natural language trace queries\nquery = RAAF::Tracing::NaturalLanguageQuery.new(tracer)\nresults = query.search(\"Show me slow API calls from yesterday\")\n\n# Streaming with events\nrunner.run_streaming(\"Tell me a story\") do |event|\n  case event\n  when RAAF::StreamingEvents::ResponseTextDeltaEvent\n    print event.text_delta\n  when RAAF::StreamingEvents::ResponseCompletedEvent\n    puts \"\\nCompleted: #{event.response.status}\"\n  end\nend\n```\n\n## 🧪 Testing\n\nThe project includes a comprehensive RSpec test suite. Coverage is tracked in CI; see workflow summaries for current figures.\n\n### Running Tests\n\n```bash\n# Run all tests\nbundle exec rspec\n\n# Run specific test file\nbundle exec rspec spec/raaf/agent_spec.rb\n\n# Run with coverage report\nCOVERAGE=true bundle exec rspec\n\n# Run tests in parallel for speed\nbundle exec parallel_rspec spec/\n```\n\n### Writing Tests for Your Agents\n\n```ruby\n# spec/agents/my_agent_spec.rb\nrequire 'spec_helper'\n\nRSpec.describe \"MyAgent\" do\n  let(:agent) do\n    RAAF::Agent.new(\n      name: \"TestAgent\",\n      instructions: \"You are a test assistant.\",\n      model: \"gpt-4o\"\n    )\n  end\n  \n  let(:runner) { RAAF::Runner.new(agent: agent) }\n  \n  it \"responds to basic queries\" do\n    VCR.use_cassette(\"agent_basic_query\") do\n      result = runner.run(\"Hello\")\n      expect(result.messages.last[:content]).to include(\"Hello\")\n    end\n  end\n  \n  it \"uses tools correctly\" do\n    agent.add_tool(method(:calculator_tool))\n    \n    VCR.use_cassette(\"agent_tool_use\") do\n      result = runner.run(\"What is 25 * 4?\")\n      expect(result.messages.last[:content]).to include(\"100\")\n    end\n  end\n  \n  it \"handles errors gracefully\" do\n    expect {\n      runner.run(\"Trigger an error\")\n    }.to raise_error(RAAF::APIError)\n  end\nend\n```\n\n### Test Helpers\n\n```ruby\n# spec/support/agent_helpers.rb\nmodule AgentHelpers\n  def create_test_agent(name: \"TestAgent\", **options)\n    RAAF::Agent.new(\n      name: name,\n      instructions: \"Test agent\",\n      model: \"gpt-4o\",\n      **options\n    )\n  end\n  \n  def stub_openai_response(content)\n    allow_any_instance_of(RAAF::Runner)\n      .to receive(:run)\n      .and_return(double(messages: [{ role: \"assistant\", content: content }]))\n  end\nend\n\nRSpec.configure do |config|\n  config.include AgentHelpers\nend\n```\n\n### Testing Best Practices\n\n- Use VCR to record and replay API interactions\n- Test both successful and error scenarios\n- Mock external dependencies appropriately\n- Test guardrails and security features\n- Verify token usage and cost tracking\n- Test streaming responses with proper event handling\n\n## ⚙️ Supported Ruby Versions\n\nRAAF targets modern Ruby versions tested in CI. Current baseline: Ruby 3.2 and 3.3. Other versions may work but are not part of the official test matrix.\n\n## ⚡ Concurrency Notes\n\nParallel pipeline steps and iterators use Ruby threads. For IO‑bound workloads this improves throughput. For very large data sets, consider adding concurrency limits or batching to avoid creating excessive threads. See docs/PIPELINE_DSL_GUIDE.md for patterns.\n\n## 🤝 Contributing\n\nWe welcome contributions from developers of all experience levels! Here's how to get involved:\n\n### 🏷️ Find Work to Do\n\n- **[Good First Issues](https://github.com/raaf-ai/raaf/labels/good%20first%20issue)** - Perfect for newcomers\n- **[Help Wanted](https://github.com/raaf-ai/raaf/labels/help%20wanted)** - Issues where we need community help\n- **[Documentation](https://github.com/raaf-ai/raaf/labels/documentation)** - Help improve our guides\n- **[Bug Reports](https://github.com/raaf-ai/raaf/labels/bug)** - Fix issues and improve stability\n\n### 🔍 Browse by Component\n\n- **[Core](https://github.com/raaf-ai/raaf/labels/core)** - Agent execution and runners\n- **[Tools](https://github.com/raaf-ai/raaf/labels/tools)** - Web search, files, and custom tools\n- **[Providers](https://github.com/raaf-ai/raaf/labels/providers)** - AI provider integrations\n- **[Memory](https://github.com/raaf-ai/raaf/labels/memory)** - Context persistence and vector storage\n- **[Rails](https://github.com/raaf-ai/raaf/labels/rails)** - Rails integration and dashboard\n\n### 📋 Contribution Resources\n\n- **[Contributing Guide](CONTRIBUTING.md)** - Detailed contribution guidelines\n- **[Project Boards](https://github.com/raaf-ai/raaf/projects)** - Current roadmap and priorities\n- **[GitHub Discussions](https://github.com/raaf-ai/raaf/discussions)** - Ideas, questions, and collaboration\n\n### 🚀 Quick Contribution Steps\n\n1. **Fork** the repository\n2. **Create** a feature branch (`git checkout -b feature/amazing-feature`)\n3. **Make** your changes with tests\n4. **Commit** with a descriptive message\n5. **Push** to your branch (`git push origin feature/amazing-feature`)\n6. **Open** a Pull Request\n\n### 💡 Contribution Ideas\n\n- **Add new tools** - Web scraping, databases, APIs\n- **Improve documentation** - Examples, guides, API docs\n- **Enhance testing** - Unit tests, integration tests, examples\n- **Provider integrations** - New AI providers and models\n- **Performance optimization** - Memory usage, speed improvements\n- **Security enhancements** - Guardrails, compliance features\n\nEvery contribution makes RAAF better for the entire community!\n\n## 🤝 Community \u0026 Support\n\n- **GitHub Issues** - Bug reports and feature requests\n- **Documentation** - Comprehensive guides and examples\n- **GitHub Discussions** - Community conversations and support\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🙏 Acknowledgments\n\n- Inspired by [OpenAI's Swarm framework](https://github.com/openai/swarm) - An experimental framework for multi-agent orchestration\n- Based on concepts from the [OpenAI Agents Python SDK](https://github.com/openai/openai-agents-python)\n- Built with ❤️ for the Ruby community\n- Thanks to all contributors and users\n\n### Relationship to Swarm\n\nRAAF began as a Ruby port of OpenAI's Swarm framework, maintaining the core philosophy of lightweight, composable agents while adding production-ready features. Where Swarm focuses on educational simplicity, RAAF provides the additional layers needed for enterprise deployment including compliance, monitoring, and multi-provider support.\n\n---\n\n**Ready to build intelligent AI workflows?** Start with the DSL guide in dsl/README.md, dive deeper with docs/PIPELINE_DSL_GUIDE.md, or explore examples in examples/.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fraaf-ai%2Fraaf","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fraaf-ai%2Fraaf","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fraaf-ai%2Fraaf/lists"}