dspy-ruby
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDSPy.rb Expert
DSPy.rb 专家指南
Overview
概述
DSPy.rb is a Ruby framework that enables developers to program LLMs, not prompt them. Instead of manually crafting prompts, define application requirements through type-safe, composable modules that can be tested, optimized, and version-controlled like regular code.
This skill provides comprehensive guidance on:
- Creating type-safe signatures for LLM operations
- Building composable modules and workflows
- Configuring multiple LLM providers
- Implementing agents with tools
- Testing and optimizing LLM applications
- Production deployment patterns
DSPy.rb 是一款Ruby框架,能让开发者编写LLM程序,而非编写提示词。无需手动编写提示词,而是通过类型安全、可组合的模块定义应用需求,这些模块可以像常规代码一样进行测试、优化和版本控制。
本技能提供以下方面的全面指导:
- 为LLM操作创建类型安全的签名
- 构建可组合的模块和工作流
- 配置多个LLM提供商
- 实现带工具的Agent
- 测试和优化LLM应用
- 生产环境部署模式
Core Capabilities
核心能力
1. Type-Safe Signatures
1. 类型安全签名
Create input/output contracts for LLM operations with runtime type checking.
When to use: Defining any LLM task, from simple classification to complex analysis.
Quick reference:
ruby
class EmailClassificationSignature < DSPy::Signature
description "Classify customer support emails"
input do
const :email_subject, String
const :email_body, String
end
output do
const :category, T.enum(["Technical", "Billing", "General"])
const :priority, T.enum(["Low", "Medium", "High"])
end
endTemplates: See for comprehensive examples including:
assets/signature-template.rb- Basic signatures with multiple field types
- Vision signatures for multimodal tasks
- Sentiment analysis signatures
- Code generation signatures
Best practices:
- Always provide clear, specific descriptions
- Use enums for constrained outputs
- Include field descriptions with parameter
desc: - Prefer specific types over generic String when possible
Full documentation: See sections on Signatures and Type Safety.
references/core-concepts.md为LLM操作创建带运行时类型检查的输入/输出契约。
适用场景:定义任何LLM任务,从简单分类到复杂分析。
快速参考:
ruby
class EmailClassificationSignature < DSPy::Signature
description "Classify customer support emails"
input do
const :email_subject, String
const :email_body, String
end
output do
const :category, T.enum(["Technical", "Billing", "General"])
const :priority, T.enum(["Low", "Medium", "High"])
end
end模板:查看获取完整示例,包括:
assets/signature-template.rb- 包含多种字段类型的基础签名
- 用于多模态任务的视觉签名
- 情感分析签名
- 代码生成签名
最佳实践:
- 始终提供清晰、具体的描述
- 对有限制的输出使用枚举
- 使用参数添加字段描述
desc: - 尽可能使用特定类型而非通用String类型
完整文档:查看中关于签名和类型安全的章节。
references/core-concepts.md2. Composable Modules
2. 可组合模块
Build reusable, chainable modules that encapsulate LLM operations.
When to use: Implementing any LLM-powered feature, especially complex multi-step workflows.
Quick reference:
ruby
class EmailProcessor < DSPy::Module
def initialize
super
@classifier = DSPy::Predict.new(EmailClassificationSignature)
end
def forward(email_subject:, email_body:)
@classifier.forward(
email_subject: email_subject,
email_body: email_body
)
end
endTemplates: See for comprehensive examples including:
assets/module-template.rb- Basic modules with single predictors
- Multi-step pipelines that chain modules
- Modules with conditional logic
- Error handling and retry patterns
- Stateful modules with history
- Caching implementations
Module composition: Chain modules together to create complex workflows:
ruby
class Pipeline < DSPy::Module
def initialize
super
@step1 = Classifier.new
@step2 = Analyzer.new
@step3 = Responder.new
end
def forward(input)
result1 = @step1.forward(input)
result2 = @step2.forward(result1)
@step3.forward(result2)
end
endFull documentation: See sections on Modules and Module Composition.
references/core-concepts.md构建可复用、可链式调用的模块,封装LLM操作。
适用场景:实现任何基于LLM的功能,尤其是复杂的多步骤工作流。
快速参考:
ruby
class EmailProcessor < DSPy::Module
def initialize
super
@classifier = DSPy::Predict.new(EmailClassificationSignature)
end
def forward(email_subject:, email_body:)
@classifier.forward(
email_subject: email_subject,
email_body: email_body
)
end
end模板:查看获取完整示例,包括:
assets/module-template.rb- 带单个预测器的基础模块
- 链式调用模块的多步骤流水线
- 带条件逻辑的模块
- 错误处理和重试模式
- 带历史记录的有状态模块
- 缓存实现
模块组合:将模块链式组合以创建复杂工作流:
ruby
class Pipeline < DSPy::Module
def initialize
super
@step1 = Classifier.new
@step2 = Analyzer.new
@step3 = Responder.new
end
def forward(input)
result1 = @step1.forward(input)
result2 = @step2.forward(result1)
@step3.forward(result2)
end
end完整文档:查看中关于模块和模块组合的章节。
references/core-concepts.md3. Multiple Predictor Types
3. 多种预测器类型
Choose the right predictor for your task:
Predict: Basic LLM inference with type-safe inputs/outputs
ruby
predictor = DSPy::Predict.new(TaskSignature)
result = predictor.forward(input: "data")ChainOfThought: Adds automatic reasoning for improved accuracy
ruby
predictor = DSPy::ChainOfThought.new(TaskSignature)
result = predictor.forward(input: "data")为你的任务选择合适的预测器:
Predict:带类型安全输入/输出的基础LLM推理
ruby
predictor = DSPy::Predict.new(TaskSignature)
result = predictor.forward(input: "data")ChainOfThought:添加自动推理以提升准确性
ruby
predictor = DSPy::ChainOfThought.new(TaskSignature)
result = predictor.forward(input: "data")Returns: { reasoning: "...", output: "..." }
返回: { reasoning: "...", output: "..." }
**ReAct**: Tool-using agents with iterative reasoning
```ruby
predictor = DSPy::ReAct.new(
TaskSignature,
tools: [SearchTool.new, CalculatorTool.new],
max_iterations: 5
)CodeAct: Dynamic code generation (requires gem)
dspy-code_actruby
predictor = DSPy::CodeAct.new(TaskSignature)
result = predictor.forward(task: "Calculate factorial of 5")When to use each:
- Predict: Simple tasks, classification, extraction
- ChainOfThought: Complex reasoning, analysis, multi-step thinking
- ReAct: Tasks requiring external tools (search, calculation, API calls)
- CodeAct: Tasks best solved with generated code
Full documentation: See section on Predictors.
references/core-concepts.md
**ReAct**:支持工具调用的Agent,带迭代推理
```ruby
predictor = DSPy::ReAct.new(
TaskSignature,
tools: [SearchTool.new, CalculatorTool.new],
max_iterations: 5
)CodeAct:动态代码生成(需要 gem)
dspy-code_actruby
predictor = DSPy::CodeAct.new(TaskSignature)
result = predictor.forward(task: "Calculate factorial of 5")各类型适用场景:
- Predict:简单任务、分类、提取
- ChainOfThought:复杂推理、分析、多步骤思考
- ReAct:需要外部工具的任务(搜索、计算、API调用)
- CodeAct:最适合用生成代码解决的任务
完整文档:查看中关于预测器的章节。
references/core-concepts.md4. LLM Provider Configuration
4. LLM提供商配置
Support for OpenAI, Anthropic Claude, Google Gemini, Ollama, and OpenRouter.
Quick configuration examples:
ruby
undefined支持OpenAI、Anthropic Claude、Google Gemini、Ollama和OpenRouter。
快速配置示例:
ruby
undefinedOpenAI
OpenAI
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end
Anthropic Claude
Anthropic Claude
DSPy.configure do |c|
c.lm = DSPy::LM.new('anthropic/claude-3-5-sonnet-20241022',
api_key: ENV['ANTHROPIC_API_KEY'])
end
DSPy.configure do |c|
c.lm = DSPy::LM.new('anthropic/claude-3-5-sonnet-20241022',
api_key: ENV['ANTHROPIC_API_KEY'])
end
Google Gemini
Google Gemini
DSPy.configure do |c|
c.lm = DSPy::LM.new('gemini/gemini-1.5-pro',
api_key: ENV['GOOGLE_API_KEY'])
end
DSPy.configure do |c|
c.lm = DSPy::LM.new('gemini/gemini-1.5-pro',
api_key: ENV['GOOGLE_API_KEY'])
end
Local Ollama (free, private)
本地Ollama(免费、私有)
DSPy.configure do |c|
c.lm = DSPy::LM.new('ollama/llama3.1')
end
**Templates**: See `assets/config-template.rb` for comprehensive examples including:
- Environment-based configuration
- Multi-model setups for different tasks
- Configuration with observability (OpenTelemetry, Langfuse)
- Retry logic and fallback strategies
- Budget tracking
- Rails initializer patterns
**Provider compatibility matrix**:
| Feature | OpenAI | Anthropic | Gemini | Ollama |
|---------|--------|-----------|--------|--------|
| Structured Output | ✅ | ✅ | ✅ | ✅ |
| Vision (Images) | ✅ | ✅ | ✅ | ⚠️ Limited |
| Image URLs | ✅ | ❌ | ❌ | ❌ |
| Tool Calling | ✅ | ✅ | ✅ | Varies |
**Cost optimization strategy**:
- Development: Ollama (free) or gpt-4o-mini (cheap)
- Testing: gpt-4o-mini with temperature=0.0
- Production simple tasks: gpt-4o-mini, claude-3-haiku, gemini-1.5-flash
- Production complex tasks: gpt-4o, claude-3-5-sonnet, gemini-1.5-pro
**Full documentation**: See `references/providers.md` for all configuration options, provider-specific features, and troubleshooting.DSPy.configure do |c|
c.lm = DSPy::LM.new('ollama/llama3.1')
end
**模板**:查看`assets/config-template.rb`获取完整示例,包括:
- 基于环境的配置
- 针对不同任务的多模型设置
- 带可观测性的配置(OpenTelemetry、Langfuse)
- 重试逻辑和回退策略
- 预算跟踪
- Rails初始化器模式
**提供商兼容性矩阵**:
| 功能 | OpenAI | Anthropic | Gemini | Ollama |
|---------|--------|-----------|--------|--------|
| 结构化输出 | ✅ | ✅ | ✅ | ✅ |
| 视觉(图片) | ✅ | ✅ | ✅ | ⚠️ 有限支持 |
| 图片URL | ✅ | ❌ | ❌ | ❌ |
| 工具调用 | ✅ | ✅ | ✅ | 因模型而异 |
**成本优化策略**:
- 开发阶段:Ollama(免费)或gpt-4o-mini(低成本)
- 测试阶段:gpt-4o-mini,temperature=0.0
- 生产环境简单任务:gpt-4o-mini、claude-3-haiku、gemini-1.5-flash
- 生产环境复杂任务:gpt-4o、claude-3-5-sonnet、gemini-1.5-pro
**完整文档**:查看`references/providers.md`获取所有配置选项、提供商特定功能和故障排除方法。5. Multimodal & Vision Support
5. 多模态与视觉支持
Process images alongside text using the unified interface.
DSPy::ImageQuick reference:
ruby
class VisionSignature < DSPy::Signature
description "Analyze image and answer questions"
input do
const :image, DSPy::Image
const :question, String
end
output do
const :answer, String
end
end
predictor = DSPy::Predict.new(VisionSignature)
result = predictor.forward(
image: DSPy::Image.from_file("path/to/image.jpg"),
question: "What objects are visible?"
)Image loading methods:
ruby
undefined使用统一的接口同时处理图片和文本。
DSPy::Image快速参考:
ruby
class VisionSignature < DSPy::Signature
description "Analyze image and answer questions"
input do
const :image, DSPy::Image
const :question, String
end
output do
const :answer, String
end
end
predictor = DSPy::Predict.new(VisionSignature)
result = predictor.forward(
image: DSPy::Image.from_file("path/to/image.jpg"),
question: "What objects are visible?"
)图片加载方法:
ruby
undefinedFrom file
从文件加载
DSPy::Image.from_file("path/to/image.jpg")
DSPy::Image.from_file("path/to/image.jpg")
From URL (OpenAI only)
从URL加载(仅OpenAI支持)
DSPy::Image.from_url("https://example.com/image.jpg")
DSPy::Image.from_url("https://example.com/image.jpg")
From base64
从base64加载
DSPy::Image.from_base64(base64_data, mime_type: "image/jpeg")
**Provider support**:
- OpenAI: Full support including URLs
- Anthropic, Gemini: Base64 or file loading only
- Ollama: Limited multimodal depending on model
**Full documentation**: See `references/core-concepts.md` section on Multimodal Support.DSPy::Image.from_base64(base64_data, mime_type: "image/jpeg")
**提供商支持**:
- OpenAI:完全支持,包括URL
- Anthropic、Gemini:仅支持base64或文件加载
- Ollama:多模态支持有限,取决于模型
**完整文档**:查看`references/core-concepts.md`中关于多模态支持的章节。6. Testing LLM Applications
6. 测试LLM应用
Write standard RSpec tests for LLM logic.
Quick reference:
ruby
RSpec.describe EmailClassifier do
before do
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end
end
it 'classifies technical emails correctly' do
classifier = EmailClassifier.new
result = classifier.forward(
email_subject: "Can't log in",
email_body: "Unable to access account"
)
expect(result[:category]).to eq('Technical')
expect(result[:priority]).to be_in(['High', 'Medium', 'Low'])
end
endTesting patterns:
- Mock LLM responses for unit tests
- Use VCR for deterministic API testing
- Test type safety and validation
- Test edge cases (empty inputs, special characters, long texts)
- Integration test complete workflows
Full documentation: See section on Testing.
references/optimization.md为LLM逻辑编写标准RSpec测试。
快速参考:
ruby
RSpec.describe EmailClassifier do
before do
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end
end
it 'classifies technical emails correctly' do
classifier = EmailClassifier.new
result = classifier.forward(
email_subject: "Can't log in",
email_body: "Unable to access account"
)
expect(result[:category]).to eq('Technical')
expect(result[:priority]).to be_in(['High', 'Medium', 'Low'])
end
end测试模式:
- 为单元测试模拟LLM响应
- 使用VCR进行确定性API测试
- 测试类型安全和验证
- 测试边缘情况(空输入、特殊字符、长文本)
- 集成测试完整工作流
完整文档:查看中关于测试的章节。
references/optimization.md7. Optimization & Improvement
7. 优化与改进
Automatically improve prompts and modules using optimization techniques.
MIPROv2 optimization:
ruby
require 'dspy/mipro'使用优化技术自动改进提示词和模块。
MIPROv2优化:
ruby
require 'dspy/mipro'Define evaluation metric
定义评估指标
def accuracy_metric(example, prediction)
example[:expected_output][:category] == prediction[:category] ? 1.0 : 0.0
end
def accuracy_metric(example, prediction)
example[:expected_output][:category] == prediction[:category] ? 1.0 : 0.0
end
Prepare training data
准备训练数据
training_examples = [
{
input: { email_subject: "...", email_body: "..." },
expected_output: { category: 'Technical' }
},
More examples...
]
training_examples = [
{
input: { email_subject: "...", email_body: "..." },
expected_output: { category: 'Technical' }
},
更多示例...
]
Run optimization
运行优化
optimizer = DSPy::MIPROv2.new(
metric: method(:accuracy_metric),
num_candidates: 10
)
optimized_module = optimizer.compile(
EmailClassifier.new,
trainset: training_examples
)
**A/B testing different approaches**:
```rubyoptimizer = DSPy::MIPROv2.new(
metric: method(:accuracy_metric),
num_candidates: 10
)
optimized_module = optimizer.compile(
EmailClassifier.new,
trainset: training_examples
)
**不同方案的A/B测试**:
```rubyTest ChainOfThought vs ReAct
测试ChainOfThought与ReAct
approach_a_score = evaluate_approach(ChainOfThoughtModule, test_set)
approach_b_score = evaluate_approach(ReActModule, test_set)
**Full documentation**: See `references/optimization.md` section on Optimization.approach_a_score = evaluate_approach(ChainOfThoughtModule, test_set)
approach_b_score = evaluate_approach(ReActModule, test_set)
**完整文档**:查看`references/optimization.md`中关于优化的章节。8. Observability & Monitoring
8. 可观测性与监控
Track performance, token usage, and behavior in production.
OpenTelemetry integration:
ruby
require 'opentelemetry/sdk'
OpenTelemetry::SDK.configure do |c|
c.service_name = 'my-dspy-app'
c.use_all
end在生产环境中跟踪性能、令牌使用情况和行为。
OpenTelemetry集成:
ruby
require 'opentelemetry/sdk'
OpenTelemetry::SDK.configure do |c|
c.service_name = 'my-dspy-app'
c.use_all
endDSPy automatically creates traces
DSPy会自动创建追踪
**Langfuse tracing**:
```ruby
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
c.langfuse = {
public_key: ENV['LANGFUSE_PUBLIC_KEY'],
secret_key: ENV['LANGFUSE_SECRET_KEY']
}
endCustom monitoring:
- Token tracking
- Performance monitoring
- Error rate tracking
- Custom logging
Full documentation: See section on Observability.
references/optimization.md
**Langfuse追踪**:
```ruby
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
c.langfuse = {
public_key: ENV['LANGFUSE_PUBLIC_KEY'],
secret_key: ENV['LANGFUSE_SECRET_KEY']
}
end自定义监控:
- 令牌跟踪
- 性能监控
- 错误率跟踪
- 自定义日志
完整文档:查看中关于可观测性的章节。
references/optimization.mdQuick Start Workflow
快速开始工作流
For New Projects
针对新项目
- Install DSPy.rb and provider gems:
bash
gem install dspy dspy-openai # or dspy-anthropic, dspy-gemini- Configure LLM provider (see ):
assets/config-template.rb
ruby
require 'dspy'
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end- Create a signature (see ):
assets/signature-template.rb
ruby
class MySignature < DSPy::Signature
description "Clear description of task"
input do
const :input_field, String, desc: "Description"
end
output do
const :output_field, String, desc: "Description"
end
end- Create a module (see ):
assets/module-template.rb
ruby
class MyModule < DSPy::Module
def initialize
super
@predictor = DSPy::Predict.new(MySignature)
end
def forward(input_field:)
@predictor.forward(input_field: input_field)
end
end- Use the module:
ruby
module_instance = MyModule.new
result = module_instance.forward(input_field: "test")
puts result[:output_field]- Add tests (see ):
references/optimization.md
ruby
RSpec.describe MyModule do
it 'produces expected output' do
result = MyModule.new.forward(input_field: "test")
expect(result[:output_field]).to be_a(String)
end
end- 安装DSPy.rb和提供商gem:
bash
gem install dspy dspy-openai # 或dspy-anthropic、dspy-gemini- 配置LLM提供商(查看):
assets/config-template.rb
ruby
require 'dspy'
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end- 创建签名(查看):
assets/signature-template.rb
ruby
class MySignature < DSPy::Signature
description "Clear description of task"
input do
const :input_field, String, desc: "Description"
end
output do
const :output_field, String, desc: "Description"
end
end- 创建模块(查看):
assets/module-template.rb
ruby
class MyModule < DSPy::Module
def initialize
super
@predictor = DSPy::Predict.new(MySignature)
end
def forward(input_field:)
@predictor.forward(input_field: input_field)
end
end- 使用模块:
ruby
module_instance = MyModule.new
result = module_instance.forward(input_field: "test")
puts result[:output_field]- 添加测试(查看):
references/optimization.md
ruby
RSpec.describe MyModule do
it 'produces expected output' do
result = MyModule.new.forward(input_field: "test")
expect(result[:output_field]).to be_a(String)
end
endFor Rails Applications
针对Rails应用
- Add to Gemfile:
ruby
gem 'dspy'
gem 'dspy-openai' # or other provider- Create initializer at (see
config/initializers/dspy.rbfor full example):assets/config-template.rb
ruby
require 'dspy'
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end- Create modules in directory:
app/llm/
ruby
undefined- 添加到Gemfile:
ruby
gem 'dspy'
gem 'dspy-openai' # 或其他提供商- 创建初始化器,路径为(查看
config/initializers/dspy.rb获取完整示例):assets/config-template.rb
ruby
require 'dspy'
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end- 在目录创建模块:
app/llm/
ruby
undefinedapp/llm/email_classifier.rb
app/llm/email_classifier.rb
class EmailClassifier < DSPy::Module
Implementation here
end
4. **Use in controllers/services**:
```ruby
class EmailsController < ApplicationController
def classify
classifier = EmailClassifier.new
result = classifier.forward(
email_subject: params[:subject],
email_body: params[:body]
)
render json: result
end
endclass EmailClassifier < DSPy::Module
实现代码
end
4. **在控制器/服务中使用**:
```ruby
class EmailsController < ApplicationController
def classify
classifier = EmailClassifier.new
result = classifier.forward(
email_subject: params[:subject],
email_body: params[:body]
)
render json: result
end
endCommon Patterns
常见模式
Pattern: Multi-Step Analysis Pipeline
模式:多步骤分析流水线
ruby
class AnalysisPipeline < DSPy::Module
def initialize
super
@extract = DSPy::Predict.new(ExtractSignature)
@analyze = DSPy::ChainOfThought.new(AnalyzeSignature)
@summarize = DSPy::Predict.new(SummarizeSignature)
end
def forward(text:)
extracted = @extract.forward(text: text)
analyzed = @analyze.forward(data: extracted[:data])
@summarize.forward(analysis: analyzed[:result])
end
endruby
class AnalysisPipeline < DSPy::Module
def initialize
super
@extract = DSPy::Predict.new(ExtractSignature)
@analyze = DSPy::ChainOfThought.new(AnalyzeSignature)
@summarize = DSPy::Predict.new(SummarizeSignature)
end
def forward(text:)
extracted = @extract.forward(text: text)
analyzed = @analyze.forward(data: extracted[:data])
@summarize.forward(analysis: analyzed[:result])
end
endPattern: Agent with Tools
模式:带工具的Agent
ruby
class ResearchAgent < DSPy::Module
def initialize
super
@agent = DSPy::ReAct.new(
ResearchSignature,
tools: [
WebSearchTool.new,
DatabaseQueryTool.new,
SummarizerTool.new
],
max_iterations: 10
)
end
def forward(question:)
@agent.forward(question: question)
end
end
class WebSearchTool < DSPy::Tool
def call(query:)
results = perform_search(query)
{ results: results }
end
endruby
class ResearchAgent < DSPy::Module
def initialize
super
@agent = DSPy::ReAct.new(
ResearchSignature,
tools: [
WebSearchTool.new,
DatabaseQueryTool.new,
SummarizerTool.new
],
max_iterations: 10
)
end
def forward(question:)
@agent.forward(question: question)
end
end
class WebSearchTool < DSPy::Tool
def call(query:)
results = perform_search(query)
{ results: results }
end
endPattern: Conditional Routing
模式:条件路由
ruby
class SmartRouter < DSPy::Module
def initialize
super
@classifier = DSPy::Predict.new(ClassifySignature)
@simple_handler = SimpleModule.new
@complex_handler = ComplexModule.new
end
def forward(input:)
classification = @classifier.forward(text: input)
if classification[:complexity] == 'Simple'
@simple_handler.forward(input: input)
else
@complex_handler.forward(input: input)
end
end
endruby
class SmartRouter < DSPy::Module
def initialize
super
@classifier = DSPy::Predict.new(ClassifySignature)
@simple_handler = SimpleModule.new
@complex_handler = ComplexModule.new
end
def forward(input:)
classification = @classifier.forward(text: input)
if classification[:complexity] == 'Simple'
@simple_handler.forward(input: input)
else
@complex_handler.forward(input: input)
end
end
endPattern: Retry with Fallback
模式:带回退的重试
ruby
class RobustModule < DSPy::Module
MAX_RETRIES = 3
def forward(input, retry_count: 0)
begin
@predictor.forward(input)
rescue DSPy::ValidationError => e
if retry_count < MAX_RETRIES
sleep(2 ** retry_count)
forward(input, retry_count: retry_count + 1)
else
# Fallback to default or raise
raise
end
end
end
endruby
class RobustModule < DSPy::Module
MAX_RETRIES = 3
def forward(input, retry_count: 0)
begin
@predictor.forward(input)
rescue DSPy::ValidationError => e
if retry_count < MAX_RETRIES
sleep(2 ** retry_count)
forward(input, retry_count: retry_count + 1)
else
# 回退到默认值或抛出异常
raise
end
end
end
endResources
资源
This skill includes comprehensive reference materials and templates:
本技能包含全面的参考资料和模板:
References (load as needed for detailed information)
参考资料(按需加载以获取详细信息)
- core-concepts.md: Complete guide to signatures, modules, predictors, multimodal support, and best practices
- providers.md: All LLM provider configurations, compatibility matrix, cost optimization, and troubleshooting
- optimization.md: Testing patterns, optimization techniques, observability setup, and monitoring
- core-concepts.md:签名、模块、预测器、多模态支持和最佳实践的完整指南
- providers.md:所有LLM提供商配置、兼容性矩阵、成本优化和故障排除
- optimization.md:测试模式、优化技术、可观测性设置和监控
Assets (templates for quick starts)
资源文件(快速开始模板)
- signature-template.rb: Examples of signatures including basic, vision, sentiment analysis, and code generation
- module-template.rb: Module patterns including pipelines, agents, error handling, caching, and state management
- config-template.rb: Configuration examples for all providers, environments, observability, and production patterns
- signature-template.rb:签名示例,包括基础、视觉、情感分析和代码生成签名
- module-template.rb:模块模式,包括流水线、Agent、错误处理、缓存和状态管理
- config-template.rb:所有提供商、环境、可观测性和生产模式的配置示例
When to Use This Skill
何时使用本技能
Trigger this skill when:
- Implementing LLM-powered features in Ruby applications
- Creating type-safe interfaces for AI operations
- Building agent systems with tool usage
- Setting up or troubleshooting LLM providers
- Optimizing prompts and improving accuracy
- Testing LLM functionality
- Adding observability to AI applications
- Converting from manual prompt engineering to programmatic approach
- Debugging DSPy.rb code or configuration issues
在以下场景触发本技能:
- 在Ruby应用中实现基于LLM的功能
- 为AI操作创建类型安全的接口
- 构建带工具调用的Agent系统
- 设置或排查LLM提供商问题
- 优化提示词并提升准确性
- 测试LLM功能
- 为AI应用添加可观测性
- 从手动提示词工程转换为程序化方法
- 调试DSPy.rb代码或配置问题