A comprehensive collection of examples demonstrating the power of DSPy.rb - the Ruby framework for programming language models.
Library repo: https://github.com/vicentereig/dspy.rb
- Ruby 3.3.5 (specified in Gemfile)
- OpenAI API key (recommended) or Anthropic API key
- Bundler for dependency management
- Internet connection for API calls
-
Install dependencies:
bundle install
-
Configure API key:
cp .env.example .env # Edit .env and add your OpenAI API key
-
Run examples:
# Interactive mode ruby main.rb # List all examples ruby main.rb --list # Run specific example ruby main.rb --run 1 # Run all examples ruby main.rb --all
- Pattern:
DSPy::Predict
- Description: Demonstrates simple structured prediction with sentiment classification
- Features: Custom enum types, structured output, confidence scoring
- Use Cases: Text classification, sentiment analysis, basic categorization
- Pattern:
DSPy::ChainOfThought
- Description: Shows reasoning capabilities with math problems and general Q&A
- Features: Automatic reasoning field injection, detailed explanations
- Use Cases: Complex problem solving, educational content, step-by-step analysis
- Pattern:
DSPy::ReAct
- Description: Intelligent agent that can use tools to solve complex problems
- Features: Custom tool definitions, multi-step reasoning, tool selection
- Tools Included: Calculator, unit converter, datetime utilities
- Use Cases: Mathematical calculations, data conversion, multi-step workflows
- Pattern:
DSPy::Module
with composed workflows - Description: Complex article writing pipeline with outline generation, section writing, and review
- Features: Multi-step workflows, content generation, automated review
- Use Cases: Content creation, document generation, quality assurance workflows
- Pattern: Advanced type system usage
- Description: Task analysis, project planning, and recipe optimization with complex types
- Features: Custom enums, structs, arrays, optional fields
- Use Cases: Data modeling, structured analysis, complex business logic
dspyrb-examples/
βββ Gemfile # Ruby dependencies and version
βββ setup.rb # Shared DSPy configuration
βββ main.rb # Interactive runner with CLI options
βββ run_example.rb # Quick runner for individual examples
βββ .env.example # Environment variables template
βββ .env # Your actual environment variables (create this)
βββ examples/ # Individual example files
β βββ 01_basic_predict.rb # Basic prediction patterns
β βββ 02_chain_of_thought.rb # Reasoning with CoT
β βββ 03_react_agent.rb # Tool-using agents
β βββ 04_multi_stage_pipeline.rb # Complex workflows
β βββ 05_custom_types.rb # Advanced type usage
βββ README.md # This file
Define input/output schemas using Sorbet types:
class MySignature < DSPy::Signature
description "What this signature does"
input do
const :field_name, String
end
output do
const :result, String
end
end
- Predict: Basic LLM completion with structured output
- ChainOfThought: Adds automatic reasoning steps
- ReAct: Tool-using agents for complex problem solving
Create custom tools for ReAct agents:
class MyTool < DSPy::Tools::Base
tool_name 'my_tool'
tool_description 'What this tool does'
def call(param:)
# Tool implementation
end
end
Define structured data with enums and custom types:
class Priority < T::Enum
enums do
Low = new('low')
High = new('high')
end
end
class Task < T::Struct
const :title, String
const :priority, Priority
end
# Start interactive mode
ruby main.rb
# Follow the prompts to:
# - List available examples (l)
# - Run specific example (1-5)
# - Run all examples (a)
# - Quit (q)
# List all available examples
ruby main.rb --list
# Run specific example by number
ruby main.rb --run 1
ruby main.rb --run 3
# Run all examples in sequence
ruby main.rb --all
# Show help
ruby main.rb --help
# Fast way to run individual examples
ruby run_example.rb 1 # Basic prediction
ruby run_example.rb 2 # Chain of thought
ruby run_example.rb 3 # ReAct agent
ruby run_example.rb 4 # Multi-stage pipeline
ruby run_example.rb 5 # Complex types
# Run example files directly
ruby examples/01_basic_predict.rb
ruby examples/02_chain_of_thought.rb
ruby examples/03_react_agent.rb
ruby examples/04_multi_stage_pipeline.rb
ruby examples/05_custom_types.rb
API Key Issues:
- Ensure your
.env
file exists and containsOPENAI_API_KEY=your_actual_key
- Verify the API key is valid and has sufficient credits
- Check that the
.env
file is in the project root directory
Ruby Version Issues:
- Ensure you're using Ruby 3.3.5 (check with
ruby --version
) - Use a Ruby version manager like rbenv or RVM if needed
Gem Installation Issues:
# If bundle install fails, try:
gem install bundler
bundle install --verbose
# If DSPy.rb fails to install:
bundle update
Type Errors:
- DSPy.rb uses Sorbet for runtime type checking
- Ensure your inputs match the expected types in signatures
- Check enum values are properly defined
Network/API Errors:
- Verify internet connection
- Check API service status
- Ensure API key has proper permissions
Enable debug output by setting environment variable:
DEBUG=true ruby main.rb --run 1
Required:
OPENAI_API_KEY
: Your OpenAI API key
Optional:
ANTHROPIC_API_KEY
: Anthropic API key (alternative to OpenAI)DEBUG
: Enable debug loggingAUTO_RUN
: Skip pauses in --all mode
- Create a new file in
examples/
directory - Follow the existing pattern with
require_relative '../setup'
- Add example to
EXAMPLES
hash inmain.rb
andrun_example.rb
- Update this README
class MyCustomTool < DSPy::Tools::Base
tool_name 'my_tool'
tool_description 'Description of what this tool does'
sig { params(param1: String, param2: Integer).returns(String) }
def call(param1:, param2:)
# Your tool logic here
"Result: #{param1} processed with #{param2}"
end
end
class ComplexSignature < DSPy::Signature
description "A complex signature example"
class Status < T::Enum
enums do
Active = new('active')
Inactive = new('inactive')
end
end
class Item < T::Struct
const :name, String
const :value, Float
const :status, Status
end
input do
const :data, T::Array[String]
const :options, T::Hash[String, T.any(String, Integer)]
end
output do
const :items, T::Array[Item]
const :summary, String
const :confidence, Float
end
end
-
Start with Basic Prediction (
01_basic_predict.rb
)- Understand DSPy signatures and basic prediction
- Learn about type safety and structured outputs
-
Explore Chain of Thought (
02_chain_of_thought.rb
)- See how reasoning improves output quality
- Understand automatic reasoning injection
-
Try ReAct Agents (
03_react_agent.rb
)- Learn about tool-using agents
- Understand multi-step problem solving
-
Build Complex Workflows (
04_multi_stage_pipeline.rb
)- Compose multiple LLM calls
- Create end-to-end content generation
-
Master Type System (
05_custom_types.rb
)- Advanced enum and struct usage
- Complex data modeling
Try modifying the examples to:
- Add new signature types for your use case
- Create custom tools for your domain
- Build multi-stage pipelines for your workflows
- Experiment with different LLM providers
- Integrate with your existing Ruby applications