[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6H91PPY6H74CW8J14KF96T1":3,"skill-same:01M6H91PPY6H74CW8J14KF96T1":101},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":14,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":6,"ownerDescription":49,"updatedAt":50,"install":51,"resources":64},"01M6H91PPY6H74CW8J14KF96T1","dspy-ruby",null,"Build type-safe LLM applications with DSPy.rb — Ruby's programmatic prompt framework with signatures, modules, agents, and optimization. Use when implementing predictable AI features, creating LLM signatures and modules, configuring language model providers, building agent systems with tools, optimizing prompts, or testing LLM-powered functionality in Ruby applications.","drhazemibclc\u002Fplate","drhazemibclc","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F153584232?v=4","01M6H8X67MYG903V4N92MKWKYK","Hazem Ali Abd Elraouf","01M6H8X6C5TSX21P7HJVZVNFNQ",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"ruby","dspy ruby","dspy","prompt","implementing","programmatic","LLM Applications","type","signatures","Optimizing Prompts","modules","use","testing","model","applications","Providers","Tools","Optimization","framework","safe","2026-11-10 10:12:30",false,"---\nname: dspy-ruby\ndescription: Build type-safe LLM applications with DSPy.rb — Ruby's programmatic prompt framework with signatures, modules, agents, and optimization. Use when implementing predictable AI features, creating LLM signatures and modules, configuring language model providers, building agent systems with tools, optimizing prompts, or testing LLM-powered functionality in Ruby applications.\n---\n\n# DSPy.rb\n\n> Build LLM apps like you build software. Type-safe, modular, testable.\n\nDSPy.rb brings software engineering best practices to LLM development. Instead of tweaking prompts, define what you want with Ruby types and let DSPy handle the rest.\n\n## Overview\n\nDSPy.rb is a Ruby framework for building language model applications with programmatic prompts. It provides:\n\n- **Type-safe signatures** — Define inputs\u002Foutputs with Sorbet types\n- **Modular components** — Compose and reuse LLM logic\n- **Automatic optimization** — Use data to improve prompts, not guesswork\n- **Production-ready** — Built-in observability, testing, and error handling\n\n## Core Concepts\n\n### 1. Signatures\n\nDefine interfaces between your app and LLMs using Ruby types:\n\n```ruby\nclass EmailClassifier \u003C DSPy::Signature\n  description \"Classify customer support emails by category and priority\"\n\n  class Priority \u003C T::Enum\n    enums do\n      Low = new('low')\n      Medium = new('medium')\n      High = new('high')\n      Urgent = new('urgent')\n    end\n  end\n\n  input do\n    const :email_content, String\n    const :sender, String\n  end\n\n  output do\n    const :category, String\n    const :priority, Priority  # Type-safe enum with defined values\n    const :confidence, Float\n  end\nend\n```\n\n### 2. Modules\n\nBuild complex workflows from simple building blocks:\n\n- **Predict** — Basic LLM calls with signatures\n- **ChainOfThought** — Step-by-step reasoning\n- **ReAct** — Tool-using agents\n- **CodeAct** — Dynamic code generation agents (install the `dspy-code_act` gem)\n\n### 3. Tools & Toolsets\n\nCreate type-safe tools for agents with comprehensive Sorbet support:\n\n```ruby\n# Enum-based tool with automatic type conversion\nclass CalculatorTool \u003C DSPy::Tools::Base\n  tool_name 'calculator'\n  tool_description 'Performs arithmetic operations with type-safe enum inputs'\n\n  class Operation \u003C T::Enum\n    enums do\n      Add = new('add')\n      Subtract = new('subtract')\n      Multiply = new('multiply')\n      Divide = new('divide')\n    end\n  end\n\n  sig { params(operation: Operation, num1: Float, num2: Float).returns(T.any(Float, String)) }\n  def call(operation:, num1:, num2:)\n    case operation\n    when Operation::Add then num1 + num2\n    when Operation::Subtract then num1 - num2\n    when Operation::Multiply then num1 * num2\n    when Operation::Divide\n      return \"Error: Division by zero\" if num2 == 0\n      num1 \u002F num2\n    end\n  end\nend\n\n# Multi-tool toolset with rich types\nclass DataToolset \u003C DSPy::Tools::Toolset\n  toolset_name \"data_processing\"\n\n  class Format \u003C T::Enum\n    enums do\n      JSON = new('json')\n      CSV = new('csv')\n      XML = new('xml')\n    end\n  end\n\n  tool :convert, description: \"Convert data between formats\"\n  tool :validate, description: \"Validate data structure\"\n\n  sig { params(data: String, from: Format, to: Format).returns(String) }\n  def convert(data:, from:, to:)\n    \"Converted from #{from.serialize} to #{to.serialize}\"\n  end\n\n  sig { params(data: String, format: Format).returns(T::Hash[String, T.any(String, Integer, T::Boolean)]) }\n  def validate(data:, format:)\n    { valid: true, format: format.serialize, row_count: 42, message: \"Data validation passed\" }\n  end\nend\n```\n\n### 4. Type System & Discriminators\n\nDSPy.rb uses sophisticated type discrimination for complex data structures:\n\n- **Automatic `_type` field injection** — DSPy adds discriminator fields to structs for type safety\n- **Union type support** — `T.any()` types automatically disambiguated by `_type`\n- **Reserved field name** — Avoid defining your own `_type` fields in structs\n- **Recursive filtering** — `_type` fields filtered during deserialization at all nesting levels\n\n### 5. Optimization\n\nImprove accuracy with real data:\n\n- **MIPROv2** — Advanced multi-prompt optimization with bootstrap sampling and Bayesian optimization\n- **GEPA** — Genetic-Pareto Reflective Prompt Evolution with feedback maps, experiment tracking, and telemetry\n- **Evaluation** — Comprehensive framework with built-in and custom metrics, error handling, and batch processing\n\n## Quick Start\n\n```ruby\n# Install\ngem 'dspy'\n\n# Configure\nDSPy.configure do |c|\n  c.lm = DSPy::LM.new('openai\u002Fgpt-4o-mini', api_key: ENV['OPENAI_API_KEY'])\nend\n\n# Define a task\nclass SentimentAnalysis \u003C DSPy::Signature\n  description \"Analyze sentiment of text\"\n\n  input do\n    const :text, String\n  end\n\n  output do\n    const :sentiment, String  # positive, negative, neutral\n    const :score, Float       # 0.0 to 1.0\n  end\nend\n\n# Use it\nanalyzer = DSPy::Predict.new(SentimentAnalysis)\nresult = analyzer.call(text: \"This product is amazing!\")\nputs result.sentiment  # => \"positive\"\nputs result.score      # => 0.92\n```\n\n## Provider Adapter Gems\n\nTwo strategies for connecting to LLM providers:\n\n### Per-provider adapters (direct SDK access)\n\n```ruby\n# Gemfile\ngem 'dspy'\ngem 'dspy-openai'    # OpenAI, OpenRouter, Ollama\ngem 'dspy-anthropic' # Claude\ngem 'dspy-gemini'    # Gemini\n```\n\nEach adapter gem pulls in the official SDK (`openai`, `anthropic`, `gemini-ai`).\n\n### Unified adapter via RubyLLM (recommended for multi-provider)\n\n```ruby\n# Gemfile\ngem 'dspy'\ngem 'dspy-ruby_llm'  # Routes to any provider via ruby_llm\ngem 'ruby_llm'\n```\n\nRubyLLM handles provider routing based on the model name. Use the `ruby_llm\u002F` prefix:\n\n```ruby\nDSPy.configure do |c|\n  c.lm = DSPy::LM.new('ruby_llm\u002Fgemini-2.5-flash', structured_outputs: true)\n  # c.lm = DSPy::LM.new('ruby_llm\u002Fclaude-sonnet-4-20250514', structured_outputs: true)\n  # c.lm = DSPy::LM.new('ruby_llm\u002Fgpt-4o-mini', structured_outputs: true)\nend\n```\n\n## Events System\n\nDSPy.rb ships with a structured event bus for observing runtime behavior.\n\n### Module-Scoped Subscriptions (preferred for agents)\n\n```ruby\nclass MyAgent \u003C DSPy::Module\n  subscribe 'lm.tokens', :track_tokens, scope: :descendants\n\n  def track_tokens(_event, attrs)\n    @total_tokens += attrs.fetch(:total_tokens, 0)\n  end\nend\n```\n\n### Global Subscriptions (for observability\u002Fintegrations)\n\n```ruby\nsubscription_id = DSPy.events.subscribe('score.create') do |event, attrs|\n  Langfuse.export_score(attrs)\nend\n\n# Wildcards supported\nDSPy.events.subscribe('llm.*') { |name, attrs| puts \"[#{name}] tokens=#{attrs[:total_tokens]}\" }\n```\n\nEvent names use dot-separated namespaces (`llm.generate`, `react.iteration_complete`). Every event includes module metadata (`module_path`, `module_leaf`, `module_scope.ancestry_token`) for filtering.\n\n## Lifecycle Callbacks\n\nRails-style lifecycle hooks ship with every `DSPy::Module`:\n\n- **`before`** — Runs ahead of `forward` for setup (metrics, context loading)\n- **`around`** — Wraps `forward`, calls `yield`, and lets you pair setup\u002Fteardown logic\n- **`after`** — Fires after `forward` returns for cleanup or persistence\n\n```ruby\nclass InstrumentedModule \u003C DSPy::Module\n  before :setup_metrics\n  around :manage_context\n  after :log_metrics\n\n  def forward(question:)\n    @predictor.call(question: question)\n  end\n\n  private\n\n  def setup_metrics\n    @start_time = Time.now\n  end\n\n  def manage_context\n    load_context\n    result = yield\n    save_context\n    result\n  end\n\n  def log_metrics\n    duration = Time.now - @start_time\n    Rails.logger.info \"Prediction completed in #{duration}s\"\n  end\nend\n```\n\nExecution order: before → around (before yield) → forward → around (after yield) → after. Callbacks are inherited from parent classes and execute in registration order.\n\n## Fiber-Local LM Context\n\nOverride the language model temporarily using fiber-local storage:\n\n```ruby\nfast_model = DSPy::LM.new(\"openai\u002Fgpt-4o-mini\", api_key: ENV['OPENAI_API_KEY'])\n\nDSPy.with_lm(fast_model) do\n  result = classifier.call(text: \"test\")  # Uses fast_model inside this block\nend\n# Back to global LM outside the block\n```\n\n**LM resolution hierarchy**: Instance-level LM → Fiber-local LM (`DSPy.with_lm`) → Global LM (`DSPy.configure`).\n\nUse `configure_predictor` for fine-grained control over agent internals:\n\n```ruby\nagent = DSPy::ReAct.new(MySignature, tools: tools)\nagent.configure { |c| c.lm = default_model }\nagent.configure_predictor('thought_generator') { |c| c.lm = powerful_model }\n```\n\n## Evaluation Framework\n\nSystematically test LLM application performance with `DSPy::Evals`:\n\n```ruby\nmetric = DSPy::Metrics.exact_match(field: :answer, case_sensitive: false)\nevaluator = DSPy::Evals.new(predictor, metric: metric)\nresult = evaluator.evaluate(test_examples, display_table: true)\nputs \"Pass Rate: #{(result.pass_rate * 100).round(1)}%\"\n```\n\nBuilt-in metrics: `exact_match`, `contains`, `numeric_difference`, `composite_and`. Custom metrics return `true`\u002F`false` or a `DSPy::Prediction` with `score:` and `feedback:` fields.\n\nUse `DSPy::Example` for typed test data and `export_scores: true` to push results to Langfuse.\n\n## GEPA Optimization\n\nGEPA (Genetic-Pareto Reflective Prompt Evolution) uses reflection-driven instruction rewrites:\n\n```ruby\ngem 'dspy-gepa'\n\nteleprompter = DSPy::Teleprompt::GEPA.new(\n  metric: metric,\n  reflection_lm: DSPy::ReflectionLM.new('openai\u002Fgpt-4o-mini', api_key: ENV['OPENAI_API_KEY']),\n  feedback_map: feedback_map,\n  config: { max_metric_calls: 600, minibatch_size: 6 }\n)\n\nresult = teleprompter.compile(program, trainset: train, valset: val)\noptimized_program = result.optimized_program\n```\n\nThe metric must return `DSPy::Prediction.new(score:, feedback:)` so the reflection model can reason about failures. Use `feedback_map` to target individual predictors in composite modules.\n\n## Typed Context Pattern\n\nReplace opaque string context blobs with `T::Struct` inputs. Each field gets its own `description:` annotation in the JSON schema the LLM sees:\n\n```ruby\nclass NavigationContext \u003C T::Struct\n  const :workflow_hint, T.nilable(String),\n        description: \"Current workflow phase guidance for the agent\"\n  const :action_log, T::Array[String], default: [],\n        description: \"Compact one-line-per-action history of research steps taken\"\n  const :iterations_remaining, Integer,\n        description: \"Budget remaining. Each tool call costs 1 iteration.\"\nend\n\nclass ToolSelectionSignature \u003C DSPy::Signature\n  input do\n    const :query, String\n    const :context, NavigationContext  # Structured, not an opaque string\n  end\n\n  output do\n    const :tool_name, String\n    const :tool_args, String, description: \"JSON-encoded arguments\"\n  end\nend\n```\n\nBenefits: type safety at compile time, per-field descriptions in the LLM schema, easy to test as value objects, extensible by adding `const` declarations.\n\n## Schema Formats (BAML \u002F TOON)\n\nControl how DSPy describes signature structure to the LLM:\n\n- **JSON Schema** (default) — Standard format, works with `structured_outputs: true`\n- **BAML** (`schema_format: :baml`) — 84% token reduction for Enhanced Prompting mode. Requires `sorbet-baml` gem.\n- **TOON** (`schema_format: :toon, data_format: :toon`) — Table-oriented format for both schemas and data. Enhanced Prompting mode only.\n\nBAML and TOON apply only when `structured_outputs: false`. With `structured_outputs: true`, the provider receives JSON Schema directly.\n\n## Storage System\n\nPersist and reload optimized programs with `DSPy::Storage::ProgramStorage`:\n\n```ruby\nstorage = DSPy::Storage::ProgramStorage.new(storage_path: \".\u002Fdspy_storage\")\nstorage.save_program(result.optimized_program, result, metadata: { optimizer: 'MIPROv2' })\n```\n\nSupports checkpoint management, optimization history tracking, and import\u002Fexport between environments.\n\n## Rails Integration\n\n### Directory Structure\n\nOrganize DSPy components using Rails conventions:\n\n```\napp\u002F\n  entities\u002F          # T::Struct types shared across signatures\n  signatures\u002F        # DSPy::Signature definitions\n  tools\u002F             # DSPy::Tools::Base implementations\n    concerns\u002F        # Shared tool behaviors (error handling, etc.)\n  modules\u002F           # DSPy::Module orchestrators\n  services\u002F          # Plain Ruby services that compose DSPy modules\nconfig\u002F\n  initializers\u002F\n    dspy.rb          # DSPy + provider configuration\n    feature_flags.rb # Model selection per role\nspec\u002F\n  signatures\u002F        # Schema validation tests\n  tools\u002F             # Tool unit tests\n  modules\u002F           # Integration tests with VCR\n  vcr_cassettes\u002F     # Recorded HTTP interactions\n```\n\n### Initializer\n\n```ruby\n# config\u002Finitializers\u002Fdspy.rb\nRails.application.config.after_initialize do\n  next if Rails.env.test? && ENV[\"DSPY_ENABLE_IN_TEST\"].blank?\n\n  RubyLLM.configure do |config|\n    config.gemini_api_key = ENV[\"GEMINI_API_KEY\"] if ENV[\"GEMINI_API_KEY\"].present?\n    config.anthropic_api_key = ENV[\"ANTHROPIC_API_KEY\"] if ENV[\"ANTHROPIC_API_KEY\"].present?\n    config.openai_api_key = ENV[\"OPENAI_API_KEY\"] if ENV[\"OPENAI_API_KEY\"].present?\n  end\n\n  model = ENV.fetch(\"DSPY_MODEL\", \"ruby_llm\u002Fgemini-2.5-flash\")\n  DSPy.configure do |config|\n    config.lm = DSPy::LM.new(model, structured_outputs: true)\n    config.logger = Rails.logger\n  end\n\n  # Langfuse observability (optional)\n  if ENV[\"LANGFUSE_PUBLIC_KEY\"].present? && ENV[\"LANGFUSE_SECRET_KEY\"].present?\n    DSPy::Observability.configure!\n  end\nend\n```\n\n### Feature-Flagged Model Selection\n\nUse different models for different roles (fast\u002Fcheap for classification, powerful for synthesis):\n\n```ruby\n# config\u002Finitializers\u002Ffeature_flags.rb\nmodule FeatureFlags\n  SELECTOR_MODEL = ENV.fetch(\"DSPY_SELECTOR_MODEL\", \"ruby_llm\u002Fgemini-2.5-flash-lite\")\n  SYNTHESIZER_MODEL = ENV.fetch(\"DSPY_SYNTHESIZER_MODEL\", \"ruby_llm\u002Fgemini-2.5-flash\")\nend\n```\n\nThen override per-tool or per-predictor:\n\n```ruby\nclass ClassifyTool \u003C DSPy::Tools::Base\n  def call(query:)\n    predictor = DSPy::Predict.new(ClassifyQuery)\n    predictor.configure { |c| c.lm = DSPy::LM.new(FeatureFlags::SELECTOR_MODEL, structured_outputs: true) }\n    predictor.call(query: query)\n  end\nend\n```\n\n## Schema-Driven Signatures\n\n**Prefer typed schemas over string descriptions.** Let the type system communicate structure to the LLM rather than prose in the signature description.\n\n### Entities as Shared Types\n\nDefine reusable `T::Struct` and `T::Enum` types in `app\u002Fentities\u002F` and reference them across signatures:\n\n```ruby\n# app\u002Fentities\u002Fsearch_strategy.rb\nclass SearchStrategy \u003C T::Enum\n  enums do\n    SingleSearch = new(\"single_search\")\n    DateDecomposition = new(\"date_decomposition\")\n  end\nend\n\n# app\u002Fentities\u002Fscored_item.rb\nclass ScoredItem \u003C T::Struct\n  const :id, String\n  const :score, Float, description: \"Relevance score 0.0-1.0\"\n  const :verdict, String, description: \"relevant, maybe, or irrelevant\"\n  const :reason, String, default: \"\"\nend\n```\n\n### Schema vs Description: When to Use Each\n\n**Use schemas (T::Struct\u002FT::Enum)** for:\n- Multi-field outputs with specific types\n- Enums with defined values the LLM must pick from\n- Nested structures, arrays of typed objects\n- Outputs consumed by code (not displayed to users)\n\n**Use string descriptions** for:\n- Simple single-field outputs where the type is `String`\n- Natural language generation (summaries, answers)\n- Fields where constraint guidance helps (e.g., `description: \"YYYY-MM-DD format\"`)\n\n**Rule of thumb**: If you'd write a `case` statement on the output, it should be a `T::Enum`. If you'd call `.each` on it, it should be `T::Array[SomeStruct]`.\n\n## Tool Patterns\n\n### Tools That Wrap Predictions\n\nA common pattern: tools encapsulate a DSPy prediction, adding error handling, model selection, and serialization:\n\n```ruby\nclass RerankTool \u003C DSPy::Tools::Base\n  tool_name \"rerank\"\n  tool_description \"Score and rank search results by relevance\"\n\n  MAX_ITEMS = 200\n  MIN_ITEMS_FOR_LLM = 5\n\n  sig { params(query: String, items: T::Array[T::Hash[Symbol, T.untyped]]).returns(T::Hash[Symbol, T.untyped]) }\n  def call(query:, items: [])\n    return { scored_items: items, reranked: false } if items.size \u003C MIN_ITEMS_FOR_LLM\n\n    capped_items = items.first(MAX_ITEMS)\n    predictor = DSPy::Predict.new(RerankSignature)\n    predictor.configure { |c| c.lm = DSPy::LM.new(FeatureFlags::SYNTHESIZER_MODEL, structured_outputs: true) }\n\n    result = predictor.call(query: query, items: capped_items)\n    { scored_items: result.scored_items, reranked: true }\n  rescue => e\n    Rails.logger.warn \"[RerankTool] LLM rerank failed: #{e.message}\"\n    { error: \"Rerank failed: #{e.message}\", scored_items: items, reranked: false }\n  end\nend\n```\n\n**Key patterns:**\n- Short-circuit LLM calls when unnecessary (small data, trivial cases)\n- Cap input size to prevent token overflow\n- Per-tool model selection via `configure`\n- Graceful error handling with fallback data\n\n### Error Handling Concern\n\n```ruby\nmodule ErrorHandling\n  extend ActiveSupport::Concern\n\n  private\n\n  def safe_predict(signature_class, **inputs)\n    predictor = DSPy::Predict.new(signature_class)\n    yield predictor if block_given?\n    predictor.call(**inputs)\n  rescue Faraday::Error, Net::HTTPError => e\n    Rails.logger.error \"[#{self.class.name}] API error: #{e.message}\"\n    nil\n  rescue JSON::ParserError => e\n    Rails.logger.error \"[#{self.class.name}] Invalid LLM output: #{e.message}\"\n    nil\n  end\nend\n```\n\n## Observability\n\n### Tracing with DSPy::Context\n\nWrap operations in spans for Langfuse\u002FOpenTelemetry visibility:\n\n```ruby\nresult = DSPy::Context.with_span(\n  operation: \"tool_selector.select\",\n  \"dspy.module\" => \"ToolSelector\",\n  \"tool_selector.tools\" => tool_names.join(\",\")\n) do\n  @predictor.call(query: query, context: context, available_tools: schemas)\nend\n```\n\n### Setup for Langfuse\n\n```ruby\n# Gemfile\ngem 'dspy-o11y'\ngem 'dspy-o11y-langfuse'\n\n# .env\nLANGFUSE_PUBLIC_KEY=pk-...\nLANGFUSE_SECRET_KEY=sk-...\nDSPY_TELEMETRY_BATCH_SIZE=5\n```\n\nEvery `DSPy::Predict`, `DSPy::ReAct`, and tool call is automatically traced when observability is configured.\n\n### Score Reporting\n\nReport evaluation scores to Langfuse:\n\n```ruby\nDSPy.score(name: \"relevance\", value: 0.85, trace_id: current_trace_id)\n```\n\n## Testing\n\n### VCR Setup for Rails\n\n```ruby\nVCR.configure do |config|\n  config.cassette_library_dir = \"spec\u002Fvcr_cassettes\"\n  config.hook_into :webmock\n  config.configure_rspec_metadata!\n  config.filter_sensitive_data('\u003CGEMINI_API_KEY>') { ENV['GEMINI_API_KEY'] }\n  config.filter_sensitive_data('\u003COPENAI_API_KEY>') { ENV['OPENAI_API_KEY'] }\nend\n```\n\n### Signature Schema Tests\n\nTest that signatures produce valid schemas without calling any LLM:\n\n```ruby\nRSpec.describe ClassifyResearchQuery do\n  it \"has required input fields\" do\n    schema = described_class.input_json_schema\n    expect(schema[:required]).to include(\"query\")\n  end\n\n  it \"has typed output fields\" do\n    schema = described_class.output_json_schema\n    expect(schema[:properties]).to have_key(:search_strategy)\n  end\nend\n```\n\n### Tool Tests with Mocked Predictions\n\n```ruby\nRSpec.describe RerankTool do\n  let(:tool) { described_class.new }\n\n  it \"skips LLM for small result sets\" do\n    expect(DSPy::Predict).not_to receive(:new)\n    result = tool.call(query: \"test\", items: [{ id: \"1\" }])\n    expect(result[:reranked]).to be false\n  end\n\n  it \"calls LLM for large result sets\", :vcr do\n    items = 10.times.map { |i| { id: i.to_s, title: \"Item #{i}\" } }\n    result = tool.call(query: \"relevant items\", items: items)\n    expect(result[:reranked]).to be true\n  end\nend\n```\n\n## Resources\n\n- [core-concepts.md](.\u002Freferences\u002Fcore-concepts.md) — Signatures, modules, predictors, type system deep-dive\n- [toolsets.md](.\u002Freferences\u002Ftoolsets.md) — Tools::Base, Tools::Toolset DSL, type safety, testing\n- [providers.md](.\u002Freferences\u002Fproviders.md) — Provider adapters, RubyLLM, fiber-local LM context, compatibility matrix\n- [optimization.md](.\u002Freferences\u002Foptimization.md) — MIPROv2, GEPA, evaluation framework, storage system\n- [observability.md](.\u002Freferences\u002Fobservability.md) — Event system, dspy-o11y gems, Langfuse, score reporting\n- [signature-template.rb](.\u002Fassets\u002Fsignature-template.rb) — Signature scaffold with T::Enum, Date\u002FTime, defaults, union types\n- [module-template.rb](.\u002Fassets\u002Fmodule-template.rb) — Module scaffold with .call(), lifecycle callbacks, fiber-local LM\n- [config-template.rb](.\u002Fassets\u002Fconfig-template.rb) — Rails initializer with RubyLLM, observability, feature flags\n\n## Key URLs\n\n- Homepage: https:\u002F\u002Foss.vicente.services\u002Fdspy.rb\u002F\n- GitHub: https:\u002F\u002Fgithub.com\u002Fvicentereig\u002Fdspy.rb\n- Documentation: https:\u002F\u002Foss.vicente.services\u002Fdspy.rb\u002Fgetting-started\u002F\n\n## Guidelines for Claude\n\nWhen helping users with DSPy.rb:\n\n1. **Schema over prose** — Define output structure with `T::Struct` and `T::Enum` types, not string descriptions\n2. **Entities in `app\u002Fentities\u002F`** — Extract shared types so signatures stay thin\n3. **Per-tool model selection** — Use `predictor.configure { |c| c.lm = ... }` to pick the right model per task\n4. **Short-circuit LLM calls** — Skip the LLM for trivial cases (small data, cached results)\n5. **Cap input sizes** — Prevent token overflow by limiting array sizes before sending to LLM\n6. **Test schemas without LLM** — Validate `input_json_schema` and `output_json_schema` in unit tests\n7. **VCR for integration tests** — Record real HTTP interactions, never mock LLM responses by hand\n8. **Trace with spans** — Wrap tool calls in `DSPy::Context.with_span` for observability\n9. **Graceful degradation** — Always rescue LLM errors and return fallback data\n\n### Signature Best Practices\n\n**Keep description concise** — The signature `description` should state the goal, not the field details:\n\n```ruby\n# Good — concise goal\nclass ParseOutline \u003C DSPy::Signature\n  description 'Extract block-level structure from HTML as a flat list of skeleton sections.'\n\n  input do\n    const :html, String, description: 'Raw HTML to parse'\n  end\n\n  output do\n    const :sections, T::Array[Section], description: 'Block elements: headings, paragraphs, code blocks, lists'\n  end\nend\n```\n\n**Use defaults over nilable arrays** — For OpenAI structured outputs compatibility:\n\n```ruby\n# Good — works with OpenAI structured outputs\nclass ASTNode \u003C T::Struct\n  const :children, T::Array[ASTNode], default: []\nend\n```\n\n### Recursive Types with `$defs`\n\nDSPy.rb supports recursive types in structured outputs using JSON Schema `$defs`:\n\n```ruby\nclass TreeNode \u003C T::Struct\n  const :value, String\n  const :children, T::Array[TreeNode], default: []  # Self-reference\nend\n```\n\nThe schema generator automatically creates `#\u002F$defs\u002FTreeNode` references for recursive types, compatible with OpenAI and Gemini structured outputs.\n\n### Field Descriptions for T::Struct\n\nDSPy.rb extends T::Struct to support field-level `description:` kwargs that flow to JSON Schema:\n\n```ruby\nclass ASTNode \u003C T::Struct\n  const :node_type, NodeType, description: 'The type of node (heading, paragraph, etc.)'\n  const :text, String, default: \"\", description: 'Text content of the node'\n  const :level, Integer, default: 0  # No description — field is self-explanatory\n  const :children, T::Array[ASTNode], default: []\nend\n```\n\n**When to use field descriptions**: complex field semantics, enum-like strings, constrained values, nested structs with ambiguous names. **When to skip**: self-explanatory fields like `name`, `id`, `url`, or boolean flags.\n\n## Version\n\nCurrent: 0.34.3\n","# DSPy.rb\n\n> Build LLM apps like you build software. Type-safe, modular, testable.\n\nDSPy.rb brings software engineering best practices to LLM development. Instead of tweaking prompts, define what you want with Ruby types and let DSPy handle the rest.\n\n## Overview\n\nDSPy.rb is a Ruby framework for building language model applications with programmatic prompts. It provides:\n\n- **Type-safe signatures** — Define inputs\u002Foutputs with Sorbet types\n- **Modular components** — Compose and reuse LLM logic\n- **Automatic optimization** — Use data to improve prompts, not guesswork\n- **Production-ready** — Built-in observability, testing, and error handling\n\n## Core Concepts\n\n### 1. Signatures\n\nDefine interfaces between your app and LLMs using Ruby types:\n\n```ruby\nclass EmailClassifier \u003C DSPy::Signature\n  description \"Classify customer support emails by category and priority\"\n\n  class Priority \u003C T::Enum\n    enums do\n      Low = new('low')\n      Medium = new('medium')\n      High = new('high')\n      Urgent = new('urgent')\n    end\n  end\n\n  input do\n    const :email_content, String\n    const :sender, String\n  end\n\n  output do\n    const :category, String\n    const :priority, Priority  # Type-safe enum with defined values\n    const :confidence, Float\n  end\nend\n```\n\n### 2. Modules\n\nBuild complex workflows from simple building blocks:\n\n- **Predict** — Basic LLM calls with signatures\n- **ChainOfThought** — Step-by-step reasoning\n- **ReAct** — Tool-using agents\n- **CodeAct** — Dynamic code generation agents (install the `dspy-code_act` gem)\n\n### 3. Tools & Toolsets\n\nCreate type-safe tools for agents with comprehensive Sorbet support:\n\n```ruby\n# Enum-based tool with automatic type conversion\nclass CalculatorTool \u003C DSPy::Tools::Base\n  tool_name 'calculator'\n  tool_description 'Performs arithmetic operations with type-safe enum inputs'\n\n  class Operation \u003C T::Enum\n    enums do\n      Add = new('add')\n      Subtract = new('subtract')\n      Multiply = new('multiply')\n      Divide = new('divide')\n    end\n  end\n\n  sig { params(operation: Operation, num1: Float, num2: Float).returns(T.any(Float, String)) }\n  def call(operation:, num1:, num2:)\n    case operation\n    when Operation::Add then num1 + num2\n    when Operation::Subtract then num1 - num2\n    when Operation::Multiply then num1 * num2\n    when Operation::Divide\n      return \"Error: Division by zero\" if num2 == 0\n      num1 \u002F num2\n    end\n  end\nend\n\n# Multi-tool toolset with rich types\nclass DataToolset \u003C DSPy::Tools::Toolset\n  toolset_name \"data_processing\"\n\n  class Format \u003C T::Enum\n    enums do\n      JSON = new('json')\n      CSV = new('csv')\n      XML = new('xml')\n    end\n  end\n\n  tool :convert, description: \"Convert data between formats\"\n  tool :validate, description: \"Validate data structure\"\n\n  sig { params(data: String, from: Format, to: Format).returns(String) }\n  def convert(data:, from:, to:)\n    \"Converted from #{from.serialize} to #{to.serialize}\"\n  end\n\n  sig { params(data: String, format: Format).returns(T::Hash[String, T.any(String, Integer, T::Boolean)]) }\n  def validate(data:, format:)\n    { valid: true, format: format.serialize, row_count: 42, message: \"Data validation passed\" }\n  end\nend\n```\n\n### 4. Type System & Discriminators\n\nDSPy.rb uses sophisticated type discrimination for complex data structures:\n\n- **Automatic `_type` field injection** — DSPy adds discriminator fields to structs for type safety\n- **Union type support** — `T.any()` types automatically disambiguated by `_type`\n- **Reserved field name** — Avoid defining your own `_type` fields in structs\n- **Recursive filtering** — `_type` fields filtered during deserialization at all nesting levels\n\n### 5. Optimization\n\nImprove accuracy with real data:\n\n- **MIPROv2** — Advanced multi-prompt optimization with bootstrap sampling and Bayesian optimization\n- **GEPA** — Genetic-Pareto Reflective Prompt Evolution with feedback maps, experiment tracking, and telemetry\n- **Evaluation** — Comprehensive framework with built-in and custom metrics, error handling, and batch processing\n\n## Quick Start\n\n```ruby\n# Install\ngem 'dspy'\n\n# Configure\nDSPy.configure do |c|\n  c.lm = DSPy::LM.new('openai\u002Fgpt-4o-mini', api_key: ENV['OPENAI_API_KEY'])\nend\n\n# Define a task\nclass SentimentAnalysis \u003C DSPy::Signature\n  description \"Analyze sentiment of text\"\n\n  input do\n    const :text, String\n  end\n\n  output do\n    const :sentiment, String  # positive, negative, neutral\n    const :score, Float       # 0.0 to 1.0\n  end\nend\n\n# Use it\nanalyzer = DSPy::Predict.new(SentimentAnalysis)\nresult = analyzer.call(text: \"This product is amazing!\")\nputs result.sentiment  # => \"positive\"\nputs result.score      # => 0.92\n```\n\n## Provider Adapter Gems\n\nTwo strategies for connecting to LLM providers:\n\n### Per-provider adapters (direct SDK access)\n\n```ruby\n# Gemfile\ngem 'dspy'\ngem 'dspy-openai'    # OpenAI, OpenRouter, Ollama\ngem 'dspy-anthropic' # Claude\ngem 'dspy-gemini'    # Gemini\n```\n\nEach adapter gem pulls in the official SDK (`openai`, `anthropic`, `gemini-ai`).\n\n### Unified adapter via RubyLLM (recommended for multi-provider)\n\n```ruby\n# Gemfile\ngem 'dspy'\ngem 'dspy-ruby_llm'  # Routes to any provider via ruby_llm\ngem 'ruby_llm'\n```\n\nRubyLLM handles provider routing based on the model name. Use the `ruby_llm\u002F` prefix:\n\n```ruby\nDSPy.configure do |c|\n  c.lm = DSPy::LM.new('ruby_llm\u002Fgemini-2.5-flash', structured_outputs: true)\n  # c.lm = DSPy::LM.new('ruby_llm\u002Fclaude-sonnet-4-20250514', structured_outputs: true)\n  # c.lm = DSPy::LM.new('ruby_llm\u002Fgpt-4o-mini', structured_outputs: true)\nend\n```\n\n## Events System\n\nDSPy.rb ships with a structured event bus for observing runtime behavior.\n\n### Module-Scoped Subscriptions (preferred for agents)\n\n```ruby\nclass MyAgent \u003C DSPy::Module\n  subscribe 'lm.tokens', :track_tokens, scope: :descendants\n\n  def track_tokens(_event, attrs)\n    @total_tokens += attrs.fetch(:total_tokens, 0)\n  end\nend\n```\n\n### Global Subscriptions (for observability\u002Fintegrations)\n\n```ruby\nsubscription_id = DSPy.events.subscribe('score.create') do |event, attrs|\n  Langfuse.export_score(attrs)\nend\n\n# Wildcards supported\nDSPy.events.subscribe('llm.*') { |name, attrs| puts \"[#{name}] tokens=#{attrs[:total_tokens]}\" }\n```\n\nEvent names use dot-separated namespaces (`llm.generate`, `react.iteration_complete`). Every event includes module metadata (`module_path`, `module_leaf`, `module_scope.ancestry_token`) for filtering.\n\n## Lifecycle Callbacks\n\nRails-style lifecycle hooks ship with every `DSPy::Module`:\n\n- **`before`** — Runs ahead of `forward` for setup (metrics, context loading)\n- **`around`** — Wraps `forward`, calls `yield`, and lets you pair setup\u002Fteardown logic\n- **`after`** — Fires after `forward` returns for cleanup or persistence\n\n```ruby\nclass InstrumentedModule \u003C DSPy::Module\n  before :setup_metrics\n  around :manage_context\n  after :log_metrics\n\n  def forward(question:)\n    @predictor.call(question: question)\n  end\n\n  private\n\n  def setup_metrics\n    @start_time = Time.now\n  end\n\n  def manage_context\n    load_context\n    result = yield\n    save_context\n    result\n  end\n\n  def log_metrics\n    duration = Time.now - @start_time\n    Rails.logger.info \"Prediction completed in #{duration}s\"\n  end\nend\n```\n\nExecution order: before → around (before yield) → forward → around (after yield) → after. Callbacks are inherited from parent classes and execute in registration order.\n\n## Fiber-Local LM Context\n\nOverride the language model temporarily using fiber-local storage:\n\n```ruby\nfast_model = DSPy::LM.new(\"openai\u002Fgpt-4o-mini\", api_key: ENV['OPENAI_API_KEY'])\n\nDSPy.with_lm(fast_model) do\n  result = classifier.call(text: \"test\")  # Uses fast_model inside this block\nend\n# Back to global LM outside the block\n```\n\n**LM resolution hierarchy**: Instance-level LM → Fiber-local LM (`DSPy.with_lm`) → Global LM (`DSPy.configure`).\n\nUse `configure_predictor` for fine-grained control over agent internals:\n\n```ruby\nagent = DSPy::ReAct.new(MySignature, tools: tools)\nagent.configure { |c| c.lm = default_model }\nagent.configure_predictor('thought_generator') { |c| c.lm = powerful_model }\n```\n\n## Evaluation Framework\n\nSystematically test LLM application performance with `DSPy::Evals`:\n\n```ruby\nmetric = DSPy::Metrics.exact_match(field: :answer, case_sensitive: false)\nevaluator = DSPy::Evals.new(predictor, metric: metric)\nresult = evaluator.evaluate(test_examples, display_table: true)\nputs \"Pass Rate: #{(result.pass_rate * 100).round(1)}%\"\n```\n\nBuilt-in metrics: `exact_match`, `contains`, `numeric_difference`, `composite_and`. Custom metrics return `true`\u002F`false` or a `DSPy::Prediction` with `score:` and `feedback:` fields.\n\nUse `DSPy::Example` for typed test data and `export_scores: true` to push results to Langfuse.\n\n## GEPA Optimization\n\nGEPA (Genetic-Pareto Reflective Prompt Evolution) uses reflection-driven instruction rewrites:\n\n```ruby\ngem 'dspy-gepa'\n\nteleprompter = DSPy::Teleprompt::GEPA.new(\n  metric: metric,\n  reflection_lm: DSPy::ReflectionLM.new('openai\u002Fgpt-4o-mini', api_key: ENV['OPENAI_API_KEY']),\n  feedback_map: feedback_map,\n  config: { max_metric_calls: 600, minibatch_size: 6 }\n)\n\nresult = teleprompter.compile(program, trainset: train, valset: val)\noptimized_program = result.optimized_program\n```\n\nThe metric must return `DSPy::Prediction.new(score:, feedback:)` so the reflection model can reason about failures. Use `feedback_map` to target individual predictors in composite modules.\n\n## Typed Context Pattern\n\nReplace opaque string context blobs with `T::Struct` inputs. Each field gets its own `description:` annotation in the JSON schema the LLM sees:\n\n```ruby\nclass NavigationContext \u003C T::Struct\n  const :workflow_hint, T.nilable(String),\n        description: \"Current workflow phase guidance for the agent\"\n  const :action_log, T::Array[String], default: [],\n        description: \"Compact one-line-per-action history of research steps taken\"\n  const :iterations_remaining, Integer,\n        description: \"Budget remaining. Each tool call costs 1 iteration.\"\nend\n\nclass ToolSelectionSignature \u003C DSPy::Signature\n  input do\n    const :query, String\n    const :context, NavigationContext  # Structured, not an opaque string\n  end\n\n  output do\n    const :tool_name, String\n    const :tool_args, String, description: \"JSON-encoded arguments\"\n  end\nend\n```\n\nBenefits: type safety at compile time, per-field descriptions in the LLM schema, easy to test as value objects, extensible by adding `const` declarations.\n\n## Schema Formats (BAML \u002F TOON)\n\nControl how DSPy describes signature structure to the LLM:\n\n- **JSON Schema** (default) — Standard format, works with `structured_outputs: true`\n- **BAML** (`schema_format: :baml`) — 84% token reduction for Enhanced Prompting mode. Requires `sorbet-baml` gem.\n- **TOON** (`schema_format: :toon, data_format: :toon`) — Table-oriented format for both schemas and data. Enhanced Prompting mode only.\n\nBAML and TOON apply only when `structured_outputs: false`. With `structured_outputs: true`, the provider receives JSON Schema directly.\n\n## Storage System\n\nPersist and reload optimized programs with `DSPy::Storage::ProgramStorage`:\n\n```ruby\nstorage = DSPy::Storage::ProgramStorage.new(storage_path: \".\u002Fdspy_storage\")\nstorage.save_program(result.optimized_program, result, metadata: { optimizer: 'MIPROv2' })\n```\n\nSupports checkpoint management, optimization history tracking, and import\u002Fexport between environments.\n\n## Rails Integration\n\n### Directory Structure\n\nOrganize DSPy components using Rails conventions:\n\n```\napp\u002F\n  entities\u002F          # T::Struct types shared across signatures\n  signatures\u002F        # DSPy::Signature definitions\n  tools\u002F             # DSPy::Tools::Base implementations\n    concerns\u002F        # Shared tool behaviors (error handling, etc.)\n  modules\u002F           # DSPy::Module orchestrators\n  services\u002F          # Plain Ruby services that compose DSPy modules\nconfig\u002F\n  initializers\u002F\n    dspy.rb          # DSPy + provider configuration\n    feature_flags.rb # Model selection per role\nspec\u002F\n  signatures\u002F        # Schema validation tests\n  tools\u002F             # Tool unit tests\n  modules\u002F           # Integration tests with VCR\n  vcr_cassettes\u002F     # Recorded HTTP interactions\n```\n\n### Initializer\n\n```ruby\n# config\u002Finitializers\u002Fdspy.rb\nRails.application.config.after_initialize do\n  next if Rails.env.test? && ENV[\"DSPY_ENABLE_IN_TEST\"].blank?\n\n  RubyLLM.configure do |config|\n    config.gemini_api_key = ENV[\"GEMINI_API_KEY\"] if ENV[\"GEMINI_API_KEY\"].present?\n    config.anthropic_api_key = ENV[\"ANTHROPIC_API_KEY\"] if ENV[\"ANTHROPIC_API_KEY\"].present?\n    config.openai_api_key = ENV[\"OPENAI_API_KEY\"] if ENV[\"OPENAI_API_KEY\"].present?\n  end\n\n  model = ENV.fetch(\"DSPY_MODEL\", \"ruby_llm\u002Fgemini-2.5-flash\")\n  DSPy.configure do |config|\n    config.lm = DSPy::LM.new(model, structured_outputs: true)\n    config.logger = Rails.logger\n  end\n\n  # Langfuse observability (optional)\n  if ENV[\"LANGFUSE_PUBLIC_KEY\"].present? && ENV[\"LANGFUSE_SECRET_KEY\"].present?\n    DSPy::Observability.configure!\n  end\nend\n```\n\n### Feature-Flagged Model Selection\n\nUse different models for different roles (fast\u002Fcheap for classification, powerful for synthesis):\n\n```ruby\n# config\u002Finitializers\u002Ffeature_flags.rb\nmodule FeatureFlags\n  SELECTOR_MODEL = ENV.fetch(\"DSPY_SELECTOR_MODEL\", \"ruby_llm\u002Fgemini-2.5-flash-lite\")\n  SYNTHESIZER_MODEL = ENV.fetch(\"DSPY_SYNTHESIZER_MODEL\", \"ruby_llm\u002Fgemini-2.5-flash\")\nend\n```\n\nThen override per-tool or per-predictor:\n\n```ruby\nclass ClassifyTool \u003C DSPy::Tools::Base\n  def call(query:)\n    predictor = DSPy::Predict.new(ClassifyQuery)\n    predictor.configure { |c| c.lm = DSPy::LM.new(FeatureFlags::SELECTOR_MODEL, structured_outputs: true) }\n    predictor.call(query: query)\n  end\nend\n```\n\n## Schema-Driven Signatures\n\n**Prefer typed schemas over string descriptions.** Let the type system communicate structure to the LLM rather than prose in the signature description.\n\n### Entities as Shared Types\n\nDefine reusable `T::Struct` and `T::Enum` types in `app\u002Fentities\u002F` and reference them across signatures:\n\n```ruby\n# app\u002Fentities\u002Fsearch_strategy.rb\nclass SearchStrategy \u003C T::Enum\n  enums do\n    SingleSearch = new(\"single_search\")\n    DateDecomposition = new(\"date_decomposition\")\n  end\nend\n\n# app\u002Fentities\u002Fscored_item.rb\nclass ScoredItem \u003C T::Struct\n  const :id, String\n  const :score, Float, description: \"Relevance score 0.0-1.0\"\n  const :verdict, String, description: \"relevant, maybe, or irrelevant\"\n  const :reason, String, default: \"\"\nend\n```\n\n### Schema vs Description: When to Use Each\n\n**Use schemas (T::Struct\u002FT::Enum)** for:\n- Multi-field outputs with specific types\n- Enums with defined values the LLM must pick from\n- Nested structures, arrays of typed objects\n- Outputs consumed by code (not displayed to users)\n\n**Use string descriptions** for:\n- Simple single-field outputs where the type is `String`\n- Natural language generation (summaries, answers)\n- Fields where constraint guidance helps (e.g., `description: \"YYYY-MM-DD format\"`)\n\n**Rule of thumb**: If you'd write a `case` statement on the output, it should be a `T::Enum`. If you'd call `.each` on it, it should be `T::Array[SomeStruct]`.\n\n## Tool Patterns\n\n### Tools That Wrap Predictions\n\nA common pattern: tools encapsulate a DSPy prediction, adding error handling, model selection, and serialization:\n\n```ruby\nclass RerankTool \u003C DSPy::Tools::Base\n  tool_name \"rerank\"\n  tool_description \"Score and rank search results by relevance\"\n\n  MAX_ITEMS = 200\n  MIN_ITEMS_FOR_LLM = 5\n\n  sig { params(query: String, items: T::Array[T::Hash[Symbol, T.untyped]]).returns(T::Hash[Symbol, T.untyped]) }\n  def call(query:, items: [])\n    return { scored_items: items, reranked: false } if items.size \u003C MIN_ITEMS_FOR_LLM\n\n    capped_items = items.first(MAX_ITEMS)\n    predictor = DSPy::Predict.new(RerankSignature)\n    predictor.configure { |c| c.lm = DSPy::LM.new(FeatureFlags::SYNTHESIZER_MODEL, structured_outputs: true) }\n\n    result = predictor.call(query: query, items: capped_items)\n    { scored_items: result.scored_items, reranked: true }\n  rescue => e\n    Rails.logger.warn \"[RerankTool] LLM rerank failed: #{e.message}\"\n    { error: \"Rerank failed: #{e.message}\", scored_items: items, reranked: false }\n  end\nend\n```\n\n**Key patterns:**\n- Short-circuit LLM calls when unnecessary (small data, trivial cases)\n- Cap input size to prevent token overflow\n- Per-tool model selection via `configure`\n- Graceful error handling with fallback data\n\n### Error Handling Concern\n\n```ruby\nmodule ErrorHandling\n  extend ActiveSupport::Concern\n\n  private\n\n  def safe_predict(signature_class, **inputs)\n    predictor = DSPy::Predict.new(signature_class)\n    yield predictor if block_given?\n    predictor.call(**inputs)\n  rescue Faraday::Error, Net::HTTPError => e\n    Rails.logger.error \"[#{self.class.name}] API error: #{e.message}\"\n    nil\n  rescue JSON::ParserError => e\n    Rails.logger.error \"[#{self.class.name}] Invalid LLM output: #{e.message}\"\n    nil\n  end\nend\n```\n\n## Observability\n\n### Tracing with DSPy::Context\n\nWrap operations in spans for Langfuse\u002FOpenTelemetry visibility:\n\n```ruby\nresult = DSPy::Context.with_span(\n  operation: \"tool_selector.select\",\n  \"dspy.module\" => \"ToolSelector\",\n  \"tool_selector.tools\" => tool_names.join(\",\")\n) do\n  @predictor.call(query: query, context: context, available_tools: schemas)\nend\n```\n\n### Setup for Langfuse\n\n```ruby\n# Gemfile\ngem 'dspy-o11y'\ngem 'dspy-o11y-langfuse'\n\n# .env\nLANGFUSE_PUBLIC_KEY=pk-...\nLANGFUSE_SECRET_KEY=sk-...\nDSPY_TELEMETRY_BATCH_SIZE=5\n```\n\nEvery `DSPy::Predict`, `DSPy::ReAct`, and tool call is automatically traced when observability is configured.\n\n### Score Reporting\n\nReport evaluation scores to Langfuse:\n\n```ruby\nDSPy.score(name: \"relevance\", value: 0.85, trace_id: current_trace_id)\n```\n\n## Testing\n\n### VCR Setup for Rails\n\n```ruby\nVCR.configure do |config|\n  config.cassette_library_dir = \"spec\u002Fvcr_cassettes\"\n  config.hook_into :webmock\n  config.configure_rspec_metadata!\n  config.filter_sensitive_data('\u003CGEMINI_API_KEY>') { ENV['GEMINI_API_KEY'] }\n  config.filter_sensitive_data('\u003COPENAI_API_KEY>') { ENV['OPENAI_API_KEY'] }\nend\n```\n\n### Signature Schema Tests\n\nTest that signatures produce valid schemas without calling any LLM:\n\n```ruby\nRSpec.describe ClassifyResearchQuery do\n  it \"has required input fields\" do\n    schema = described_class.input_json_schema\n    expect(schema[:required]).to include(\"query\")\n  end\n\n  it \"has typed output fields\" do\n    schema = described_class.output_json_schema\n    expect(schema[:properties]).to have_key(:search_strategy)\n  end\nend\n```\n\n### Tool Tests with Mocked Predictions\n\n```ruby\nRSpec.describe RerankTool do\n  let(:tool) { described_class.new }\n\n  it \"skips LLM for small result sets\" do\n    expect(DSPy::Predict).not_to receive(:new)\n    result = tool.call(query: \"test\", items: [{ id: \"1\" }])\n    expect(result[:reranked]).to be false\n  end\n\n  it \"calls LLM for large result sets\", :vcr do\n    items = 10.times.map { |i| { id: i.to_s, title: \"Item #{i}\" } }\n    result = tool.call(query: \"relevant items\", items: items)\n    expect(result[:reranked]).to be true\n  end\nend\n```\n\n## Resources\n\n- [core-concepts.md](.\u002Freferences\u002Fcore-concepts.md) — Signatures, modules, predictors, type system deep-dive\n- [toolsets.md](.\u002Freferences\u002Ftoolsets.md) — Tools::Base, Tools::Toolset DSL, type safety, testing\n- [providers.md](.\u002Freferences\u002Fproviders.md) — Provider adapters, RubyLLM, fiber-local LM context, compatibility matrix\n- [optimization.md](.\u002Freferences\u002Foptimization.md) — MIPROv2, GEPA, evaluation framework, storage system\n- [observability.md](.\u002Freferences\u002Fobservability.md) — Event system, dspy-o11y gems, Langfuse, score reporting\n- [signature-template.rb](.\u002Fassets\u002Fsignature-template.rb) — Signature scaffold with T::Enum, Date\u002FTime, defaults, union types\n- [module-template.rb](.\u002Fassets\u002Fmodule-template.rb) — Module scaffold with .call(), lifecycle callbacks, fiber-local LM\n- [config-template.rb](.\u002Fassets\u002Fconfig-template.rb) — Rails initializer with RubyLLM, observability, feature flags\n\n## Key URLs\n\n- Homepage: https:\u002F\u002Foss.vicente.services\u002Fdspy.rb\u002F\n- GitHub: https:\u002F\u002Fgithub.com\u002Fvicentereig\u002Fdspy.rb\n- Documentation: https:\u002F\u002Foss.vicente.services\u002Fdspy.rb\u002Fgetting-started\u002F\n\n## Guidelines for Claude\n\nWhen helping users with DSPy.rb:\n\n1. **Schema over prose** — Define output structure with `T::Struct` and `T::Enum` types, not string descriptions\n2. **Entities in `app\u002Fentities\u002F`** — Extract shared types so signatures stay thin\n3. **Per-tool model selection** — Use `predictor.configure { |c| c.lm = ... }` to pick the right model per task\n4. **Short-circuit LLM calls** — Skip the LLM for trivial cases (small data, cached results)\n5. **Cap input sizes** — Prevent token overflow by limiting array sizes before sending to LLM\n6. **Test schemas without LLM** — Validate `input_json_schema` and `output_json_schema` in unit tests\n7. **VCR for integration tests** — Record real HTTP interactions, never mock LLM responses by hand\n8. **Trace with spans** — Wrap tool calls in `DSPy::Context.with_span` for observability\n9. **Graceful degradation** — Always rescue LLM errors and return fallback data\n\n### Signature Best Practices\n\n**Keep description concise** — The signature `description` should state the goal, not the field details:\n\n```ruby\n# Good — concise goal\nclass ParseOutline \u003C DSPy::Signature\n  description 'Extract block-level structure from HTML as a flat list of skeleton sections.'\n\n  input do\n    const :html, String, description: 'Raw HTML to parse'\n  end\n\n  output do\n    const :sections, T::Array[Section], description: 'Block elements: headings, paragraphs, code blocks, lists'\n  end\nend\n```\n\n**Use defaults over nilable arrays** — For OpenAI structured outputs compatibility:\n\n```ruby\n# Good — works with OpenAI structured outputs\nclass ASTNode \u003C T::Struct\n  const :children, T::Array[ASTNode], default: []\nend\n```\n\n### Recursive Types with `$defs`\n\nDSPy.rb supports recursive types in structured outputs using JSON Schema `$defs`:\n\n```ruby\nclass TreeNode \u003C T::Struct\n  const :value, String\n  const :children, T::Array[TreeNode], default: []  # Self-reference\nend\n```\n\nThe schema generator automatically creates `#\u002F$defs\u002FTreeNode` references for recursive types, compatible with OpenAI and Gemini structured outputs.\n\n### Field Descriptions for T::Struct\n\nDSPy.rb extends T::Struct to support field-level `description:` kwargs that flow to JSON Schema:\n\n```ruby\nclass ASTNode \u003C T::Struct\n  const :node_type, NodeType, description: 'The type of node (heading, paragraph, etc.)'\n  const :text, String, default: \"\", description: 'Text content of the node'\n  const :level, Integer, default: 0  # No description — field is self-explanatory\n  const :children, T::Array[ASTNode], default: []\nend\n```\n\n**When to use field descriptions**: complex field semantics, enum-like strings, constrained values, nested structs with ambiguous names. **When to skip**: self-explanatory fields like `name`, `id`, `url`, or boolean flags.\n\n## Version\n\nCurrent: 0.34.3\n",{"name":5,"description":7},"main","2af107c35457ccaaa2c99d5478745496095d3cf7",".codex\u002Fskills\u002Fdspy-ruby","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc","Certified Pediatrician and IBCLC","2026-03-22 21:33:09",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add drhazemibclc\u002Fplate --skill dspy-ruby",{"tool":57,"command":58},"bunx","bunx skills add drhazemibclc\u002Fplate --skill dspy-ruby",{"tool":60,"command":61},"pnpm","pnpm dlx skills add drhazemibclc\u002Fplate --skill dspy-ruby","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002FSKILL.md",true,[65,71,75,79,85,89,93,97],{"path":66,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":69,"sourceHtmlUrl":70},"assets\u002Fconfig-template.rb","SCRIPT","脚本",6858,"https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002Fassets\u002Fconfig-template.rb",{"path":72,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":73,"sourceHtmlUrl":74},"assets\u002Fmodule-template.rb",7982,"https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002Fassets\u002Fmodule-template.rb",{"path":76,"resourceType":67,"resourceTypeDesc":68,"sizeBytes":77,"sourceHtmlUrl":78},"assets\u002Fsignature-template.rb",6636,"https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002Fassets\u002Fsignature-template.rb",{"path":80,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":83,"sourceHtmlUrl":84},"references\u002Fcore-concepts.md","REFERENCE","参考文档",17911,"https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002Freferences\u002Fcore-concepts.md",{"path":86,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":87,"sourceHtmlUrl":88},"references\u002Fobservability.md",12881,"https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002Freferences\u002Fobservability.md",{"path":90,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":91,"sourceHtmlUrl":92},"references\u002Foptimization.md",18800,"https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002Freferences\u002Foptimization.md",{"path":94,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":95,"sourceHtmlUrl":96},"references\u002Fproviders.md",14681,"https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002Freferences\u002Fproviders.md",{"path":98,"resourceType":81,"resourceTypeDesc":82,"sizeBytes":99,"sourceHtmlUrl":100},"references\u002Ftoolsets.md",15970,"https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fdspy-ruby\u002Freferences\u002Ftoolsets.md",[102,120,136,150,163,174],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":39},"01M6H97EF29WFNJJJH91670GQ1","workflows-work","[DEPRECATED] Use \u002Fce:work instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-work\u002FSKILL.md",[],[109,110,111,112,113,114,115,116,117,30,118,119],"workflows","work","workflows work","file","for","path","true","todo","specification","clarity","plan",{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":39},"01M6H97C6CZMYST83WEJN87CVS","workflows-review","[DEPRECATED] Use \u002Fce:review instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-review\u002FSKILL.md",[],[127,128,109,118,129,130,131,113,132,115,133,134,135,30],"workflows review","review","pr","github","branch","latest","number","URL","name",{"skillNo":137,"name":138,"nameZh":6,"description":139,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":140,"categories":141,"keywords":142,"publishedAt":39},"01M6H97A2P4ZE58BKMVQBYAK3M","workflows-plan","[DEPRECATED] Use \u002Fce:plan instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-plan\u002FSKILL.md",[],[109,143,119,144,145,113,115,146,147,118,148,149,30],"workflows plan","bug","improvement","feature","idea","report","bug report",{"skillNo":151,"name":152,"nameZh":6,"description":153,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":154,"categories":155,"keywords":156,"publishedAt":39},"01M6H9780WX39EB980F69WFHEQ","workflows-compound","[DEPRECATED] Use \u002Fce:compound instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-compound\u002FSKILL.md",[],[157,158,109,115,159,113,160,30,161,118,162],"workflows compound","compound","context","about","fix","brief",{"skillNo":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":169,"publishedAt":39},"01M6H9761C1HS173TW6P4ZMCY2","workflows-brainstorm","[DEPRECATED] Use \u002Fce:brainstorm instead — renamed for clarity.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fworkflows-brainstorm\u002FSKILL.md",[],[170,109,171,118,172,30,113,115,173,146,147],"brainstorm","workflows brainstorm","explore","problem",{"skillNo":175,"name":176,"nameZh":6,"description":177,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":178,"categories":179,"keywords":180,"publishedAt":39},"01M6H971R100F94DW8NGC93KQ6","vercel-react-best-practices","React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React\u002FNext.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.","https:\u002F\u002Fgithub.com\u002Fdrhazemibclc\u002Fplate\u002Fblob\u002Fmain\u002F.codex\u002Fskills\u002Fvercel-react-best-practices\u002FSKILL.md",[],[181,182,183,184,185,186,187,188,189,190,191,192,36,193,194,195,196,197,198,199],"vercel","react best practices","best practices","vercel react best practices","react","Next.js","data fetching","triggers","pages","next","performance optimization","refactoring","code","tasks","guidelines","react components","components","performance","writing"]