dspy
БесплатноБез исполняемых скриптовНе проверенDSPy 2.5+ for programming (not prompting) LMs. Covers Signatures, Modules (Predict, ChainOfThought, ReAct, Retrieve), compilers/optimizers (BootstrapFewShot…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
DSPy
Philosophy
DSPy treats LLM programs like neural networks: you declare the computation (Modules + Signatures) and a compiler optimizes the prompts (few-shot demos, instructions, even weights) against a metric. You never write brittle prompt strings - you declare the I/O contract and let the optimizer tune it.
Installation
pip install -U dspy
Configure LM and Retriever
import dspy
lm = dspy.LM("anthropic/claude-sonnet-4-20250514", api_key=ANTHROPIC_API_KEY, max_tokens=2048)
dspy.configure(lm=lm)
# Optional: OpenAI, Azure, Ollama, HuggingFace TGI, vLLM, Databricks...
# dspy.LM("openai/gpt-4o")
# dspy.LM("ollama/llama3.1:8b", api_base="http://localhost:11434")
Signatures
# Inline
qa = dspy.Predict("question -> answer")
# Class-based with descriptions + types
class GenerateAnswer(dspy.Signature):
"""Answer questions using the provided context."""
context: list[str] = dspy.InputField(desc="retrieved passages")
question: str = dspy.InputField()
answer: str = dspy.OutputField(desc="concise answer with citations")
pred = dspy.Predict(GenerateAnswer)
out = pred(context=["Paris is the capital of France."], question="What is France's capital?")
print(out.answer)
Modules
# Predict - single-shot
predict = dspy.Predict(GenerateAnswer)
# ChainOfThought - adds a reasoning field
cot = dspy.ChainOfThought(GenerateAnswer)
# ProgramOfThought - code reasoning
pot = dspy.ProgramOfThought("question -> answer")
# ReAct - tool use
def search_web(query: str) -> str:
"""Search the web."""
return "..."
react = dspy.ReAct("question -> answer", tools=[search_web])
# MultiChainComparison - sample N chains, pick best
compare = dspy.MultiChainComparison(GenerateAnswer, M=5)
RAG Module (custom)
class RAG(dspy.Module):
def __init__(self, num_passages: int = 5):
super().__init__()
self.retrieve = dspy.Retrieve(k=num_passages)
self.generate = dspy.ChainOfThought(GenerateAnswer)
def forward(self, question: str):
passages = self.retrieve(question).passages
return self.generate(context=passages, question=question)
rag = RAG(num_passages=5)
result = rag("Who wrote the Python language?")
print(result.answer)
Retrievers
# ColBERTv2 (hosted example from DSPy docs)
colbert = dspy.ColBERTv2(url="http://20.102.90.50:2017/wiki17_abstracts")
dspy.configure(rm=colbert)
# Chroma
from dspy.retrieve.chromadb_rm import ChromadbRM
chroma = ChromadbRM(collection_name="docs", persist_directory="./chroma", k=5)
# Qdrant
from dspy.retrieve.qdrant_rm import QdrantRM
qdrant = QdrantRM(qdrant_collection_name="docs", qdrant_client=client, k=5)
# Pinecone, Weaviate, Milvus, FAISS - similar adapters under dspy.retrieve
Compilation (Optimization)
BootstrapFewShot
from dspy.teleprompt import BootstrapFewShot
trainset = [
dspy.Example(question="What is 2+2?", answer="4").with_inputs("question"),
dspy.Example(question="Capital of Spain?", answer="Madrid").with_inputs("question"),
# ... ~20-200 examples
]
def em_metric(example, pred, trace=None) -> bool:
return pred.answer.strip().lower() == example.answer.strip().lower()
optimizer = BootstrapFewShot(metric=em_metric, max_bootstrapped_demos=4, max_labeled_demos=8)
compiled_rag = optimizer.compile(RAG(), trainset=trainset)
MIPROv2 (joint instruction + few-shot optimization)
from dspy.teleprompt import MIPROv2
miprov2 = MIPROv2(
metric=em_metric,
auto="medium", # light | medium | heavy
num_threads=16,
)
compiled_rag = miprov2.compile(
RAG(),
trainset=trainset,
valset=valset,
max_bootstrapped_demos=4,
max_labeled_demos=4,
requires_permission_to_run=False,
)
BootstrapFinetune (weights, not prompts)
from dspy.teleprompt import BootstrapFinetune
finetuner = BootstrapFinetune(metric=em_metric)
finetuned = finetuner.compile(RAG(), trainset=trainset, target="meta-llama/Llama-3.1-8B-Instruct")
Evaluation
from dspy.evaluate import Evaluate
evaluate = Evaluate(
devset=devset,
num_threads=8,
display_progress=True,
display_table=5,
)
def f1_metric(example, pred, trace=None) -> float:
gold = set(example.answer.lower().split())
got = set(pred.answer.lower().split())
if not gold or not got:
return 0.0
precision = len(gold & got) / len(got)
recall = len(gold & got) / len(gold)
return 2 * precision * recall / (precision + recall) if (precision + recall) else 0.0
score = evaluate(compiled_rag, metric=f1_metric)
print("F1:", score)
Multi-Stage Program (Query Rewrite + Retrieve + Answer)
class RewriteQuery(dspy.Signature):
"""Rewrite the user question to maximize retrieval recall."""
question: str = dspy.InputField()
rewritten: str = dspy.OutputField(desc="expanded query with synonyms")
class MultiStageRAG(dspy.
Установить dspy в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл dspy?
DSPy 2.5+ for programming (not prompting) LMs. Covers Signatures, Modules (Predict, ChainOfThought, ReAct, Retrieve), compilers/optimizers (BootstrapFewShot, MIPROv2, BootstrapFinetune), retrievers, evaluation, and production deployment of compiled programs. USE WHEN: user mentions "DSPy", "dspy.Module", "dspy.Signature", "MIPROv2", "BootstrapFewShot", "ChainOfThought optimization", "program > prompt" DO NOT USE FOR: manual prompt templates - use `langchain`; LlamaIndex query engines - use `llamaindex`; generic RAG architecture - use `rag-patterns`
Как установить скилл dspy?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл dspy запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic