dspy-ruby
RubyでLLMアプリを開発するDSPy.rbフレームワークを使い、予測可能なAI機能の実装やプロンプト最適化を行うSkill。
📜 元の英語説明(参考)
This skill should be used when working with DSPy.rb, a Ruby framework for building type-safe, composable LLM applications. Use this when implementing predictable AI features, creating LLM signatures and modules, configuring language model providers (OpenAI, Anthropic, Gemini, Ollama), building agent systems with tools, optimizing prompts, or testing LLM-powered functionality in Ruby applications.
🇯🇵 日本人クリエイター向け解説
RubyでLLMアプリを開発するDSPy.rbフレームワークを使い、予測可能なAI機能の実装やプロンプト最適化を行うSkill。
※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。
⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。
🎯 このSkillでできること
下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。
📦 インストール方法 (3ステップ)
- 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
- 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
- 3. 展開してできたフォルダを、ホームフォルダの
.claude/skills/に置く- · macOS / Linux:
~/.claude/skills/ - · Windows:
%USERPROFILE%\.claude\skills\
- · macOS / Linux:
Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。
詳しい使い方ガイドを見る →- 最終更新
- 2026-05-17
- 取得日時
- 2026-05-17
- 同梱ファイル
- 1
📖 Skill本文(日本語訳)
※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。
[Skill 名] dspy-ruby
DSPy.rb エキスパート
概要
DSPy.rb は、開発者が「プロンプトを記述するのではなく、LLM をプログラミングする」ことを可能にする Ruby フレームワークです。手動でプロンプトを作成する代わりに、通常のコードのようにテスト、最適化、バージョン管理が可能な、型安全で構成可能なモジュールを通じてアプリケーション要件を定義します。
このスキルは、以下の包括的なガイダンスを提供します。
- LLM 操作のための型安全なシグネチャの作成
- 構成可能なモジュールとワークフローの構築
- 複数の LLM プロバイダーの構成
- ツールを使用したエージェントの実装
- LLM アプリケーションのテストと最適化
- 本番デプロイメントパターン
コア機能
1. 型安全なシグネチャ
ランタイム型チェックを備えた LLM 操作の入出力契約を作成します。
使用する場面: 単純な分類から複雑な分析まで、あらゆる LLM タスクを定義する場合。
クイックリファレンス:
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 に、以下を含む包括的な例があります。
- 複数のフィールド型を持つ基本的なシグネチャ
- マルチモーダルタスク用のビジョンシグネチャ
- 感情分析シグネチャ
- コード生成シグネチャ
ベストプラクティス:
- 常に明確で具体的な説明を提供してください
- 制約のある出力には enum を使用してください
desc:パラメータでフィールドの説明を含めてください- 可能な場合は、汎用的な String よりも特定の型を優先してください
完全なドキュメント: シグネチャと型安全に関する references/core-concepts.md のセクションを参照してください。
2. 構成可能なモジュール
LLM 操作をカプセル化する、再利用可能で連結可能なモジュールを構築します。
使用する場面: あらゆる LLM 駆動機能、特に複雑な多段階ワークフローを実装する場合。
クイックリファレンス:
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 に、以下を含む包括的な例があります。
- 単一の予測器を持つ基本的なモジュール
- モジュールを連結する多段階パイプライン
- 条件ロジックを持つモジュール
- エラー処理とリトライパターン
- 履歴を持つステートフルモジュール
- キャッシングの実装
モジュール構成: モジュールを連結して複雑なワークフローを作成します。
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.md のセクションを参照してください。
3. 複数の予測器タイプ
タスクに適した予測器を選択してください。
Predict: 型安全な入出力を備えた基本的な LLM 推論
predictor = DSPy::Predict.new(TaskSignature)
result = predictor.forward(input: "data")
ChainOfThought: 精度向上のための自動推論を追加
predictor = DSPy::ChainOfThought.new(TaskSignature)
result = predictor.forward(input: "data")
# Returns: { reasoning: "...", output: "..." }
ReAct: 反復推論を備えたツール使用エージェント
predictor = DSPy::ReAct.new(
TaskSignature,
tools: [SearchTool.new, CalculatorTool.new],
max_iterations: 5
)
CodeAct: 動的なコード生成(dspy-code_act gem が必要)
predictor = DSPy::CodeAct.new(TaskSignature)
result = predictor.forward(task: "Calculate factorial of 5")
それぞれの使用する場面:
- Predict: 単純なタスク、分類、抽出
- ChainOfThought: 複雑な推論、分析、多段階思考
- ReAct: 外部ツール(検索、計算、API 呼び出し)を必要とするタスク
- CodeAct: 生成されたコードで最もよく解決されるタスク
完全なドキュメント: 予測器に関する references/core-concepts.md のセクションを参照してください。
4. LLM プロバイダー構成
OpenAI、Anthropic Claude、Google Gemini、Ollama、OpenRouter をサポートしています。
クイック構成例:
# OpenAI
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end
# Anthropic Claude
DSPy.configure do |c|
c.lm = DSPy::LM.new('anthropic/claude-3-5-sonnet-20241022',
api_key: ENV['ANTHROPIC_API_KEY'])
end
# Google Gemini
DSPy.configure do |c|
c.lm = DSPy::LM.new('gemini/gemini-1.5-pro',
api_key: ENV['GOOGLE_API_KEY'])
end
# Local Ollama (無料、プライベート)
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. マルチモーダル & ビジョンサポート
統一された DSPy::Image インターフェースを使用して、テキストと画像を一緒に処理します。
クイックリファレンス:
class VisionSignature < DS 📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開
DSPy.rb Expert
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
Core Capabilities
1. Type-Safe Signatures
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:
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
Templates: See assets/signature-template.rb for comprehensive examples including:
- 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
desc:parameter - Prefer specific types over generic String when possible
Full documentation: See references/core-concepts.md sections on Signatures and Type Safety.
2. Composable Modules
Build reusable, chainable modules that encapsulate LLM operations.
When to use: Implementing any LLM-powered feature, especially complex multi-step workflows.
Quick reference:
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
Templates: See assets/module-template.rb for comprehensive examples including:
- 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:
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
Full documentation: See references/core-concepts.md sections on Modules and Module Composition.
3. Multiple Predictor Types
Choose the right predictor for your task:
Predict: Basic LLM inference with type-safe inputs/outputs
predictor = DSPy::Predict.new(TaskSignature)
result = predictor.forward(input: "data")
ChainOfThought: Adds automatic reasoning for improved accuracy
predictor = DSPy::ChainOfThought.new(TaskSignature)
result = predictor.forward(input: "data")
# Returns: { reasoning: "...", output: "..." }
ReAct: Tool-using agents with iterative reasoning
predictor = DSPy::ReAct.new(
TaskSignature,
tools: [SearchTool.new, CalculatorTool.new],
max_iterations: 5
)
CodeAct: Dynamic code generation (requires dspy-code_act gem)
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 references/core-concepts.md section on Predictors.
4. LLM Provider Configuration
Support for OpenAI, Anthropic Claude, Google Gemini, Ollama, and OpenRouter.
Quick configuration examples:
# OpenAI
DSPy.configure do |c|
c.lm = DSPy::LM.new('openai/gpt-4o-mini',
api_key: ENV['OPENAI_API_KEY'])
end
# Anthropic Claude
DSPy.configure do |c|
c.lm = DSPy::LM.new('anthropic/claude-3-5-sonnet-20241022',
api_key: ENV['ANTHROPIC_API_KEY'])
end
# Google Gemini
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)
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.
5. Multimodal & Vision Support
Process images alongside text using the unified DSPy::Image interface.
Quick reference:
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:
# From file
DSPy::Image.from_file("path/to/image.jpg")
# From URL (OpenAI only)
DSPy::Image.from_url("https://example.com/image.jpg")
# From 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.
6. Testing LLM Applications
Write standard RSpec tests for LLM logic.
Quick reference:
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
Testing 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 references/optimization.md section on Testing.
7. Optimization & Improvement
Automatically improve prompts and modules using optimization techniques.
MIPROv2 optimization:
require 'dspy/mipro'
# Define evaluation metric
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...
]
# 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:
# Test ChainOfThought vs 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.
8. Observability & Monitoring
Track performance, token usage, and behavior in production.
OpenTelemetry integration:
require 'opentelemetry/sdk'
OpenTelemetry::SDK.configure do |c|
c.service_name = 'my-dspy-app'
c.use_all
end
# DSPy automatically creates traces
Langfuse tracing:
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
Custom monitoring:
- Token tracking
- Performance monitoring
- Error rate tracking
- Custom logging
Full documentation: See references/optimization.md section on Observability.
Quick Start Workflow
For New Projects
-
Install DSPy.rb and provider gems:
gem install dspy dspy-openai # or dspy-anthropic, dspy-gemini -
Configure LLM provider (see
assets/config-template.rb):require 'dspy'
DSPy.configure do |c| c.lm = DSPy::LM.new('openai/gpt-4o-mini', api_key: ENV['OPENAI_API_KEY']) end
3. **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):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
5. **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):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
For Rails Applications
-
Add to Gemfile:
gem 'dspy' gem 'dspy-openai' # or other provider -
Create initializer at
config/initializers/dspy.rb(seeassets/config-template.rbfor full example):require 'dspy'
DSPy.configure do |c| c.lm = DSPy::LM.new('openai/gpt-4o-mini', api_key: ENV['OPENAI_API_KEY']) end
3. **Create modules in** `app/llm/` directory:
```ruby
# app/llm/email_classifier.rb
class EmailClassifier < DSPy::Module
# Implementation here
end
- Use in controllers/services:
class EmailsController < ApplicationController def classify classifier = EmailClassifier.new result = classifier.forward( email_subject: params[:subject], email_body: params[:body] ) render json: result end end
Common Patterns
Pattern: Multi-Step Analysis Pipeline
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
end
Pattern: Agent with Tools
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
end
Pattern: Conditional Routing
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
end
Pattern: Retry with Fallback
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
end
Resources
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
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
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