[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6QEBPA3F2PK3PS7V98EF6H0":3,"skill-same:01M6QEBPA3F2PK3PS7V98EF6H0":113},{"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":31,"publishedAt":51,"linkOnly":52,"markdownContent":53,"markdownBody":54,"frontMatter":55,"refName":62,"commitSha":63,"skillDirectory":64,"forksCount":14,"repositoryHtmlUrl":65,"repositoryHomepageUrl":66,"ownerHtmlUrl":67,"ownerBlogUrl":68,"ownerDescription":69,"updatedAt":70,"install":71,"resources":84},"01M6QEBPA3F2PK3PS7V98EF6H0","dspy",null,"Builds and optimizes language model programs with DSPy (Stanford NLP), using Signatures, modules (Predict, ChainOfThought, ReAct, ProgramOfThought) and optimizers (BootstrapFewShot, MIPRO, BootstrapFinetune). Use when replacing hand-written prompts with declarative signatures, when automatically tuning prompts against training data and a metric, when building multi-stage RAG pipelines or ReAct agents, when building classifiers or structured-output programs, or when saving and evaluating optimized LM programs across providers such as Anthropic, OpenAI, or Ollama. Not for quick prototypes or simple chains; use manual prompting or LangChain instead.","Tashima-Tarsh\u002FDisha6.6","Tashima-Tarsh","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F269906498?v=4","01M6PBH98X03XERH0HFT4PFB1P","NITISH KUMAR","01M6PBH9DA0M6KM3Z12P848F0K",0,"MIT","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-dspy\u002FSKILL.md",[18,23,26],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",{"categoryNo":27,"categoryName":28,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[5,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50],"modules","declarative","predict","automatic","for","quick","as","prompting","signatures","nlp","use","prompt","langchain","programming","applications","training","rag","modular","react","2026-11-10 10:12:30",false,"---\nname: dspy\ndescription: Builds and optimizes language model programs with DSPy (Stanford NLP), using Signatures, modules (Predict, ChainOfThought, ReAct, ProgramOfThought) and optimizers (BootstrapFewShot, MIPRO, BootstrapFinetune). Use when replacing hand-written prompts with declarative signatures, when automatically tuning prompts against training data and a metric, when building multi-stage RAG pipelines or ReAct agents, when building classifiers or structured-output programs, or when saving and evaluating optimized LM programs across providers such as Anthropic, OpenAI, or Ollama. Not for quick prototypes or simple chains; use manual prompting or LangChain instead.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: llm-applications\n  maintainer: Kalaris Labs\n  tags: Prompt Engineering, DSPy, Declarative Programming, RAG, Agents, Prompt Optimization, LM Programming, Stanford NLP, Automatic Optimization, Modular AI\n  dependencies: dspy, openai, anthropic\n---\n\n# DSPy: Declarative Language Model Programming\n\n## When to Use This Skill\n\nUse DSPy when you need to:\n- **Build complex AI systems** with multiple components and workflows\n- **Program LMs declaratively** instead of manual prompt engineering\n- **Optimize prompts automatically** using data-driven methods\n- **Create modular AI pipelines** that are maintainable and portable\n- **Improve model outputs systematically** with optimizers\n- **Build RAG systems, agents, or classifiers** with better reliability\n\n\n## Installation\n\n```bash\n# Stable release\npip install dspy\n\n# Latest development version\npip install git+https:\u002F\u002Fgithub.com\u002Fstanfordnlp\u002Fdspy.git\n\n# With specific LM providers\npip install dspy[openai]        # OpenAI\npip install dspy[anthropic]     # Anthropic Claude\npip install dspy[all]           # All providers\n```\n\n## Quick Start\n\n### Basic Example: Question Answering\n\n```python\nimport dspy\n\n# Configure your language model\nlm = dspy.Claude(model=\"claude-sonnet-4-5-20250929\")\ndspy.settings.configure(lm=lm)\n\n# Define a signature (input → output)\nclass QA(dspy.Signature):\n    \"\"\"Answer questions with short factual answers.\"\"\"\n    question = dspy.InputField()\n    answer = dspy.OutputField(desc=\"often between 1 and 5 words\")\n\n# Create a module\nqa = dspy.Predict(QA)\n\n# Use it\nresponse = qa(question=\"What is the capital of France?\")\nprint(response.answer)  # \"Paris\"\n```\n\n### Chain of Thought Reasoning\n\n```python\nimport dspy\n\nlm = dspy.Claude(model=\"claude-sonnet-4-5-20250929\")\ndspy.settings.configure(lm=lm)\n\n# Use ChainOfThought for better reasoning\nclass MathProblem(dspy.Signature):\n    \"\"\"Solve math word problems.\"\"\"\n    problem = dspy.InputField()\n    answer = dspy.OutputField(desc=\"numerical answer\")\n\n# ChainOfThought generates reasoning steps automatically\ncot = dspy.ChainOfThought(MathProblem)\n\nresponse = cot(problem=\"If John has 5 apples and gives 2 to Mary, how many does he have?\")\nprint(response.rationale)  # Shows reasoning steps\nprint(response.answer)     # \"3\"\n```\n\n## Core Concepts\n\n### 1. Signatures\n\nSignatures define the structure of your AI task (inputs → outputs):\n\n```python\n# Inline signature (simple)\nqa = dspy.Predict(\"question -> answer\")\n\n# Class signature (detailed)\nclass Summarize(dspy.Signature):\n    \"\"\"Summarize text into key points.\"\"\"\n    text = dspy.InputField()\n    summary = dspy.OutputField(desc=\"bullet points, 3-5 items\")\n\nsummarizer = dspy.ChainOfThought(Summarize)\n```\n\n**When to use each:**\n- **Inline**: Quick prototyping, simple tasks\n- **Class**: Complex tasks, type hints, better documentation\n\n### 2. Modules\n\nModules are reusable components that transform inputs to outputs:\n\n#### dspy.Predict\nBasic prediction module:\n\n```python\npredictor = dspy.Predict(\"context, question -> answer\")\nresult = predictor(context=\"Paris is the capital of France\",\n                   question=\"What is the capital?\")\n```\n\n#### dspy.ChainOfThought\nGenerates reasoning steps before answering:\n\n```python\ncot = dspy.ChainOfThought(\"question -> answer\")\nresult = cot(question=\"Why is the sky blue?\")\nprint(result.rationale)  # Reasoning steps\nprint(result.answer)     # Final answer\n```\n\n#### dspy.ReAct\nAgent-like reasoning with tools:\n\n```python\nfrom dspy.predict import ReAct\n\nclass SearchQA(dspy.Signature):\n    \"\"\"Answer questions using search.\"\"\"\n    question = dspy.InputField()\n    answer = dspy.OutputField()\n\ndef search_tool(query: str) -> str:\n    \"\"\"Search Wikipedia.\"\"\"\n    # Your search implementation\n    return results\n\nreact = ReAct(SearchQA, tools=[search_tool])\nresult = react(question=\"When was Python created?\")\n```\n\n#### dspy.ProgramOfThought\nGenerates and executes code for reasoning:\n\n```python\npot = dspy.ProgramOfThought(\"question -> answer\")\nresult = pot(question=\"What is 15% of 240?\")\n# Generates: answer = 240 * 0.15\n```\n\n### 3. Optimizers\n\nOptimizers improve your modules automatically using training data:\n\n#### BootstrapFewShot\nLearns from examples:\n\n```python\nfrom dspy.teleprompt import BootstrapFewShot\n\n# Training data\ntrainset = [\n    dspy.Example(question=\"What is 2+2?\", answer=\"4\").with_inputs(\"question\"),\n    dspy.Example(question=\"What is 3+5?\", answer=\"8\").with_inputs(\"question\"),\n]\n\n# Define metric\ndef validate_answer(example, pred, trace=None):\n    return example.answer == pred.answer\n\n# Optimize\noptimizer = BootstrapFewShot(metric=validate_answer, max_bootstrapped_demos=3)\noptimized_qa = optimizer.compile(qa, trainset=trainset)\n\n# Now optimized_qa performs better!\n```\n\n#### MIPRO (Most Important Prompt Optimization)\nIteratively improves prompts:\n\n```python\nfrom dspy.teleprompt import MIPRO\n\noptimizer = MIPRO(\n    metric=validate_answer,\n    num_candidates=10,\n    init_temperature=1.0\n)\n\noptimized_cot = optimizer.compile(\n    cot,\n    trainset=trainset,\n    num_trials=100\n)\n```\n\n#### BootstrapFinetune\nCreates datasets for model fine-tuning:\n\n```python\nfrom dspy.teleprompt import BootstrapFinetune\n\noptimizer = BootstrapFinetune(metric=validate_answer)\noptimized_module = optimizer.compile(qa, trainset=trainset)\n\n# Exports training data for fine-tuning\n```\n\n### 4. Building Complex Systems\n\n#### Multi-Stage Pipeline\n\n```python\nimport dspy\n\nclass MultiHopQA(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=3)\n        self.generate_query = dspy.ChainOfThought(\"question -> search_query\")\n        self.generate_answer = dspy.ChainOfThought(\"context, question -> answer\")\n\n    def forward(self, question):\n        # Stage 1: Generate search query\n        search_query = self.generate_query(question=question).search_query\n\n        # Stage 2: Retrieve context\n        passages = self.retrieve(search_query).passages\n        context = \"\\n\".join(passages)\n\n        # Stage 3: Generate answer\n        answer = self.generate_answer(context=context, question=question).answer\n        return dspy.Prediction(answer=answer, context=context)\n\n# Use the pipeline\nqa_system = MultiHopQA()\nresult = qa_system(question=\"Who wrote the book that inspired the movie Blade Runner?\")\n```\n\n#### RAG System with Optimization\n\n```python\nimport dspy\nfrom dspy.retrieve.chromadb_rm import ChromadbRM\n\n# Configure retriever\nretriever = ChromadbRM(\n    collection_name=\"documents\",\n    persist_directory=\".\u002Fchroma_db\"\n)\n\nclass RAG(dspy.Module):\n    def __init__(self, num_passages=3):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=num_passages)\n        self.generate = dspy.ChainOfThought(\"context, question -> answer\")\n\n    def forward(self, question):\n        context = self.retrieve(question).passages\n        return self.generate(context=context, question=question)\n\n# Create and optimize\nrag = RAG()\n\n# Optimize with training data\nfrom dspy.teleprompt import BootstrapFewShot\n\noptimizer = BootstrapFewShot(metric=validate_answer)\noptimized_rag = optimizer.compile(rag, trainset=trainset)\n```\n\n## LM Provider Configuration\n\nDetails, code examples and parameter tables: [references\u002Flm-provider-configuration.md](references\u002Flm-provider-configuration.md). Read it when this step applies.\n\n## Common Patterns\n\nDetails, code examples and parameter tables: [references\u002Fcommon-patterns.md](references\u002Fcommon-patterns.md). Read it when this step applies.\n\n## Evaluation and Metrics\n\n### Custom Metrics\n\n```python\ndef exact_match(example, pred, trace=None):\n    \"\"\"Exact match metric.\"\"\"\n    return example.answer.lower() == pred.answer.lower()\n\ndef f1_score(example, pred, trace=None):\n    \"\"\"F1 score for text overlap.\"\"\"\n    pred_tokens = set(pred.answer.lower().split())\n    gold_tokens = set(example.answer.lower().split())\n\n    if not pred_tokens:\n        return 0.0\n\n    precision = len(pred_tokens & gold_tokens) \u002F len(pred_tokens)\n    recall = len(pred_tokens & gold_tokens) \u002F len(gold_tokens)\n\n    if precision + recall == 0:\n        return 0.0\n\n    return 2 * (precision * recall) \u002F (precision + recall)\n```\n\n### Evaluation\n\n```python\nfrom dspy.evaluate import Evaluate\n\n# Create evaluator\nevaluator = Evaluate(\n    devset=testset,\n    metric=exact_match,\n    num_threads=4,\n    display_progress=True\n)\n\n# Evaluate model\nscore = evaluator(qa_system)\nprint(f\"Accuracy: {score}\")\n\n# Compare optimized vs unoptimized\nscore_before = evaluator(qa)\nscore_after = evaluator(optimized_qa)\nprint(f\"Improvement: {score_after - score_before:.2%}\")\n```\n\n## Best Practices\n\n### 1. Start Simple, Iterate\n\n```python\n# Start with Predict\nqa = dspy.Predict(\"question -> answer\")\n\n# Add reasoning if needed\nqa = dspy.ChainOfThought(\"question -> answer\")\n\n# Add optimization when you have data\noptimized_qa = optimizer.compile(qa, trainset=data)\n```\n\n### 2. Use Descriptive Signatures\n\n```python\n# ❌ Bad: Vague\nclass Task(dspy.Signature):\n    input = dspy.InputField()\n    output = dspy.OutputField()\n\n# ✅ Good: Descriptive\nclass SummarizeArticle(dspy.Signature):\n    \"\"\"Summarize news articles into 3-5 key points.\"\"\"\n    article = dspy.InputField(desc=\"full article text\")\n    summary = dspy.OutputField(desc=\"bullet points, 3-5 items\")\n```\n\n### 3. Optimize with Representative Data\n\n```python\n# Create diverse training examples\ntrainset = [\n    dspy.Example(question=\"factual\", answer=\"...).with_inputs(\"question\"),\n    dspy.Example(question=\"reasoning\", answer=\"...\").with_inputs(\"question\"),\n    dspy.Example(question=\"calculation\", answer=\"...\").with_inputs(\"question\"),\n]\n\n# Use validation set for metric\ndef metric(example, pred, trace=None):\n    return example.answer in pred.answer\n```\n\n### 4. Save and Load Optimized Models\n\n```python\n# Save\noptimized_qa.save(\"models\u002Fqa_v1.json\")\n\n# Load\nloaded_qa = dspy.ChainOfThought(\"question -> answer\")\nloaded_qa.load(\"models\u002Fqa_v1.json\")\n```\n\n### 5. Monitor and Debug\n\n```python\n# Enable tracing\ndspy.settings.configure(lm=lm, trace=[])\n\n# Run prediction\nresult = qa(question=\"...\")\n\n# Inspect trace\nfor call in dspy.settings.trace:\n    print(f\"Prompt: {call['prompt']}\")\n    print(f\"Response: {call['response']}\")\n```\n\n## Comparison to Other Approaches\n\n| Feature | Manual Prompting | LangChain | DSPy |\n|---------|-----------------|-----------|------|\n| Prompt Engineering | Manual | Manual | Automatic |\n| Optimization | Trial & error | None | Data-driven |\n| Modularity | Low | Medium | High |\n| Type Safety | No | Limited | Yes (Signatures) |\n| Portability | Low | Medium | High |\n| Learning Curve | Low | Medium | Medium-High |\n\n**When to choose DSPy:**\n- You have training data or can generate it\n- You need systematic prompt improvement\n- You're building complex multi-stage systems\n- You want to optimize across different LMs\n\n**When to choose alternatives:**\n- Quick prototypes (manual prompting)\n- Simple chains with existing tools (LangChain)\n- Custom optimization logic needed\n\n## Resources\n\n- **Documentation**: https:\u002F\u002Fdspy.ai\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fstanfordnlp\u002Fdspy\n- **Discord**: https:\u002F\u002Fdiscord.gg\u002FXCGy2WDCQB\n- **Twitter**: @DSPyOSS\n- **Paper**: \"DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines\"\n\n## See Also\n\n- `references\u002Fmodules.md` - Detailed module guide (Predict, ChainOfThought, ReAct, ProgramOfThought)\n- `references\u002Foptimizers.md` - Optimization algorithms (BootstrapFewShot, MIPRO, BootstrapFinetune)\n- `references\u002Fexamples.md` - Real-world examples (RAG, agents, classifiers)\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm the framework version, model provider, API keys and rate limits.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Test a single call or chain with a known input and inspect raw outputs.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Evaluate on a small labeled set; check structured outputs against their schema; log prompts and responses.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Outputs do not match the expected schema | Add validation and retries, tighten the schema, or simplify the prompt. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Never send private or sensitive data to external APIs without the user's consent.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n","# DSPy: Declarative Language Model Programming\n\n## When to Use This Skill\n\nUse DSPy when you need to:\n- **Build complex AI systems** with multiple components and workflows\n- **Program LMs declaratively** instead of manual prompt engineering\n- **Optimize prompts automatically** using data-driven methods\n- **Create modular AI pipelines** that are maintainable and portable\n- **Improve model outputs systematically** with optimizers\n- **Build RAG systems, agents, or classifiers** with better reliability\n\n\n## Installation\n\n```bash\n# Stable release\npip install dspy\n\n# Latest development version\npip install git+https:\u002F\u002Fgithub.com\u002Fstanfordnlp\u002Fdspy.git\n\n# With specific LM providers\npip install dspy[openai]        # OpenAI\npip install dspy[anthropic]     # Anthropic Claude\npip install dspy[all]           # All providers\n```\n\n## Quick Start\n\n### Basic Example: Question Answering\n\n```python\nimport dspy\n\n# Configure your language model\nlm = dspy.Claude(model=\"claude-sonnet-4-5-20250929\")\ndspy.settings.configure(lm=lm)\n\n# Define a signature (input → output)\nclass QA(dspy.Signature):\n    \"\"\"Answer questions with short factual answers.\"\"\"\n    question = dspy.InputField()\n    answer = dspy.OutputField(desc=\"often between 1 and 5 words\")\n\n# Create a module\nqa = dspy.Predict(QA)\n\n# Use it\nresponse = qa(question=\"What is the capital of France?\")\nprint(response.answer)  # \"Paris\"\n```\n\n### Chain of Thought Reasoning\n\n```python\nimport dspy\n\nlm = dspy.Claude(model=\"claude-sonnet-4-5-20250929\")\ndspy.settings.configure(lm=lm)\n\n# Use ChainOfThought for better reasoning\nclass MathProblem(dspy.Signature):\n    \"\"\"Solve math word problems.\"\"\"\n    problem = dspy.InputField()\n    answer = dspy.OutputField(desc=\"numerical answer\")\n\n# ChainOfThought generates reasoning steps automatically\ncot = dspy.ChainOfThought(MathProblem)\n\nresponse = cot(problem=\"If John has 5 apples and gives 2 to Mary, how many does he have?\")\nprint(response.rationale)  # Shows reasoning steps\nprint(response.answer)     # \"3\"\n```\n\n## Core Concepts\n\n### 1. Signatures\n\nSignatures define the structure of your AI task (inputs → outputs):\n\n```python\n# Inline signature (simple)\nqa = dspy.Predict(\"question -> answer\")\n\n# Class signature (detailed)\nclass Summarize(dspy.Signature):\n    \"\"\"Summarize text into key points.\"\"\"\n    text = dspy.InputField()\n    summary = dspy.OutputField(desc=\"bullet points, 3-5 items\")\n\nsummarizer = dspy.ChainOfThought(Summarize)\n```\n\n**When to use each:**\n- **Inline**: Quick prototyping, simple tasks\n- **Class**: Complex tasks, type hints, better documentation\n\n### 2. Modules\n\nModules are reusable components that transform inputs to outputs:\n\n#### dspy.Predict\nBasic prediction module:\n\n```python\npredictor = dspy.Predict(\"context, question -> answer\")\nresult = predictor(context=\"Paris is the capital of France\",\n                   question=\"What is the capital?\")\n```\n\n#### dspy.ChainOfThought\nGenerates reasoning steps before answering:\n\n```python\ncot = dspy.ChainOfThought(\"question -> answer\")\nresult = cot(question=\"Why is the sky blue?\")\nprint(result.rationale)  # Reasoning steps\nprint(result.answer)     # Final answer\n```\n\n#### dspy.ReAct\nAgent-like reasoning with tools:\n\n```python\nfrom dspy.predict import ReAct\n\nclass SearchQA(dspy.Signature):\n    \"\"\"Answer questions using search.\"\"\"\n    question = dspy.InputField()\n    answer = dspy.OutputField()\n\ndef search_tool(query: str) -> str:\n    \"\"\"Search Wikipedia.\"\"\"\n    # Your search implementation\n    return results\n\nreact = ReAct(SearchQA, tools=[search_tool])\nresult = react(question=\"When was Python created?\")\n```\n\n#### dspy.ProgramOfThought\nGenerates and executes code for reasoning:\n\n```python\npot = dspy.ProgramOfThought(\"question -> answer\")\nresult = pot(question=\"What is 15% of 240?\")\n# Generates: answer = 240 * 0.15\n```\n\n### 3. Optimizers\n\nOptimizers improve your modules automatically using training data:\n\n#### BootstrapFewShot\nLearns from examples:\n\n```python\nfrom dspy.teleprompt import BootstrapFewShot\n\n# Training data\ntrainset = [\n    dspy.Example(question=\"What is 2+2?\", answer=\"4\").with_inputs(\"question\"),\n    dspy.Example(question=\"What is 3+5?\", answer=\"8\").with_inputs(\"question\"),\n]\n\n# Define metric\ndef validate_answer(example, pred, trace=None):\n    return example.answer == pred.answer\n\n# Optimize\noptimizer = BootstrapFewShot(metric=validate_answer, max_bootstrapped_demos=3)\noptimized_qa = optimizer.compile(qa, trainset=trainset)\n\n# Now optimized_qa performs better!\n```\n\n#### MIPRO (Most Important Prompt Optimization)\nIteratively improves prompts:\n\n```python\nfrom dspy.teleprompt import MIPRO\n\noptimizer = MIPRO(\n    metric=validate_answer,\n    num_candidates=10,\n    init_temperature=1.0\n)\n\noptimized_cot = optimizer.compile(\n    cot,\n    trainset=trainset,\n    num_trials=100\n)\n```\n\n#### BootstrapFinetune\nCreates datasets for model fine-tuning:\n\n```python\nfrom dspy.teleprompt import BootstrapFinetune\n\noptimizer = BootstrapFinetune(metric=validate_answer)\noptimized_module = optimizer.compile(qa, trainset=trainset)\n\n# Exports training data for fine-tuning\n```\n\n### 4. Building Complex Systems\n\n#### Multi-Stage Pipeline\n\n```python\nimport dspy\n\nclass MultiHopQA(dspy.Module):\n    def __init__(self):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=3)\n        self.generate_query = dspy.ChainOfThought(\"question -> search_query\")\n        self.generate_answer = dspy.ChainOfThought(\"context, question -> answer\")\n\n    def forward(self, question):\n        # Stage 1: Generate search query\n        search_query = self.generate_query(question=question).search_query\n\n        # Stage 2: Retrieve context\n        passages = self.retrieve(search_query).passages\n        context = \"\\n\".join(passages)\n\n        # Stage 3: Generate answer\n        answer = self.generate_answer(context=context, question=question).answer\n        return dspy.Prediction(answer=answer, context=context)\n\n# Use the pipeline\nqa_system = MultiHopQA()\nresult = qa_system(question=\"Who wrote the book that inspired the movie Blade Runner?\")\n```\n\n#### RAG System with Optimization\n\n```python\nimport dspy\nfrom dspy.retrieve.chromadb_rm import ChromadbRM\n\n# Configure retriever\nretriever = ChromadbRM(\n    collection_name=\"documents\",\n    persist_directory=\".\u002Fchroma_db\"\n)\n\nclass RAG(dspy.Module):\n    def __init__(self, num_passages=3):\n        super().__init__()\n        self.retrieve = dspy.Retrieve(k=num_passages)\n        self.generate = dspy.ChainOfThought(\"context, question -> answer\")\n\n    def forward(self, question):\n        context = self.retrieve(question).passages\n        return self.generate(context=context, question=question)\n\n# Create and optimize\nrag = RAG()\n\n# Optimize with training data\nfrom dspy.teleprompt import BootstrapFewShot\n\noptimizer = BootstrapFewShot(metric=validate_answer)\noptimized_rag = optimizer.compile(rag, trainset=trainset)\n```\n\n## LM Provider Configuration\n\nDetails, code examples and parameter tables: [references\u002Flm-provider-configuration.md](references\u002Flm-provider-configuration.md). Read it when this step applies.\n\n## Common Patterns\n\nDetails, code examples and parameter tables: [references\u002Fcommon-patterns.md](references\u002Fcommon-patterns.md). Read it when this step applies.\n\n## Evaluation and Metrics\n\n### Custom Metrics\n\n```python\ndef exact_match(example, pred, trace=None):\n    \"\"\"Exact match metric.\"\"\"\n    return example.answer.lower() == pred.answer.lower()\n\ndef f1_score(example, pred, trace=None):\n    \"\"\"F1 score for text overlap.\"\"\"\n    pred_tokens = set(pred.answer.lower().split())\n    gold_tokens = set(example.answer.lower().split())\n\n    if not pred_tokens:\n        return 0.0\n\n    precision = len(pred_tokens & gold_tokens) \u002F len(pred_tokens)\n    recall = len(pred_tokens & gold_tokens) \u002F len(gold_tokens)\n\n    if precision + recall == 0:\n        return 0.0\n\n    return 2 * (precision * recall) \u002F (precision + recall)\n```\n\n### Evaluation\n\n```python\nfrom dspy.evaluate import Evaluate\n\n# Create evaluator\nevaluator = Evaluate(\n    devset=testset,\n    metric=exact_match,\n    num_threads=4,\n    display_progress=True\n)\n\n# Evaluate model\nscore = evaluator(qa_system)\nprint(f\"Accuracy: {score}\")\n\n# Compare optimized vs unoptimized\nscore_before = evaluator(qa)\nscore_after = evaluator(optimized_qa)\nprint(f\"Improvement: {score_after - score_before:.2%}\")\n```\n\n## Best Practices\n\n### 1. Start Simple, Iterate\n\n```python\n# Start with Predict\nqa = dspy.Predict(\"question -> answer\")\n\n# Add reasoning if needed\nqa = dspy.ChainOfThought(\"question -> answer\")\n\n# Add optimization when you have data\noptimized_qa = optimizer.compile(qa, trainset=data)\n```\n\n### 2. Use Descriptive Signatures\n\n```python\n# ❌ Bad: Vague\nclass Task(dspy.Signature):\n    input = dspy.InputField()\n    output = dspy.OutputField()\n\n# ✅ Good: Descriptive\nclass SummarizeArticle(dspy.Signature):\n    \"\"\"Summarize news articles into 3-5 key points.\"\"\"\n    article = dspy.InputField(desc=\"full article text\")\n    summary = dspy.OutputField(desc=\"bullet points, 3-5 items\")\n```\n\n### 3. Optimize with Representative Data\n\n```python\n# Create diverse training examples\ntrainset = [\n    dspy.Example(question=\"factual\", answer=\"...).with_inputs(\"question\"),\n    dspy.Example(question=\"reasoning\", answer=\"...\").with_inputs(\"question\"),\n    dspy.Example(question=\"calculation\", answer=\"...\").with_inputs(\"question\"),\n]\n\n# Use validation set for metric\ndef metric(example, pred, trace=None):\n    return example.answer in pred.answer\n```\n\n### 4. Save and Load Optimized Models\n\n```python\n# Save\noptimized_qa.save(\"models\u002Fqa_v1.json\")\n\n# Load\nloaded_qa = dspy.ChainOfThought(\"question -> answer\")\nloaded_qa.load(\"models\u002Fqa_v1.json\")\n```\n\n### 5. Monitor and Debug\n\n```python\n# Enable tracing\ndspy.settings.configure(lm=lm, trace=[])\n\n# Run prediction\nresult = qa(question=\"...\")\n\n# Inspect trace\nfor call in dspy.settings.trace:\n    print(f\"Prompt: {call['prompt']}\")\n    print(f\"Response: {call['response']}\")\n```\n\n## Comparison to Other Approaches\n\n| Feature | Manual Prompting | LangChain | DSPy |\n|---------|-----------------|-----------|------|\n| Prompt Engineering | Manual | Manual | Automatic |\n| Optimization | Trial & error | None | Data-driven |\n| Modularity | Low | Medium | High |\n| Type Safety | No | Limited | Yes (Signatures) |\n| Portability | Low | Medium | High |\n| Learning Curve | Low | Medium | Medium-High |\n\n**When to choose DSPy:**\n- You have training data or can generate it\n- You need systematic prompt improvement\n- You're building complex multi-stage systems\n- You want to optimize across different LMs\n\n**When to choose alternatives:**\n- Quick prototypes (manual prompting)\n- Simple chains with existing tools (LangChain)\n- Custom optimization logic needed\n\n## Resources\n\n- **Documentation**: https:\u002F\u002Fdspy.ai\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fstanfordnlp\u002Fdspy\n- **Discord**: https:\u002F\u002Fdiscord.gg\u002FXCGy2WDCQB\n- **Twitter**: @DSPyOSS\n- **Paper**: \"DSPy: Compiling Declarative Language Model Calls into Self-Improving Pipelines\"\n\n## See Also\n\n- `references\u002Fmodules.md` - Detailed module guide (Predict, ChainOfThought, ReAct, ProgramOfThought)\n- `references\u002Foptimizers.md` - Optimization algorithms (BootstrapFewShot, MIPRO, BootstrapFinetune)\n- `references\u002Fexamples.md` - Real-world examples (RAG, agents, classifiers)\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm the framework version, model provider, API keys and rate limits.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Test a single call or chain with a known input and inspect raw outputs.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Evaluate on a small labeled set; check structured outputs against their schema; log prompts and responses.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Outputs do not match the expected schema | Add validation and retries, tighten the schema, or simplify the prompt. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Never send private or sensitive data to external APIs without the user's consent.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n",{"name":5,"license":15,"metadata":56,"description":7},{"tags":57,"version":58,"category":59,"maintainer":60,"dependencies":61},"Prompt Engineering, DSPy, Declarative Programming, RAG, Agents, Prompt Optimization, LM Programming, Stanford NLP, Automatic Optimization, Modular AI","1.0.0","llm-applications","Kalaris Labs","dspy, openai, anthropic","main","0da4485785ee599388900be50db1635489d53056",".agents\u002Fskills\u002Fkal-dspy","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6","https:\u002F\u002Fdisha6.6.thenitishkr.in\u002F","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh","www.thenitishkr","thenitishkr | AI • Cyber-security • Research\r\n","2026-11-08 03:33:25",{"source":8,"skillName":5,"commands":72,"prompt":82,"zipAvailable":83},[73,76,79],{"tool":74,"command":75},"npx","npx skills add Tashima-Tarsh\u002FDisha6.6 --skill dspy",{"tool":77,"command":78},"bunx","bunx skills add Tashima-Tarsh\u002FDisha6.6 --skill dspy",{"tool":80,"command":81},"pnpm","pnpm dlx skills add Tashima-Tarsh\u002FDisha6.6 --skill dspy","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-dspy\u002FSKILL.md",true,[85,91,95,99,103,107],{"path":86,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Fcommon-patterns.md","REFERENCE","参考文档",2839,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-dspy\u002Freferences\u002Fcommon-patterns.md",{"path":92,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":93,"sourceHtmlUrl":94},"references\u002Fexamples.md",19007,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-dspy\u002Freferences\u002Fexamples.md",{"path":96,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":97,"sourceHtmlUrl":98},"references\u002Flm-provider-configuration.md",996,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-dspy\u002Freferences\u002Flm-provider-configuration.md",{"path":100,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":101,"sourceHtmlUrl":102},"references\u002Fmodules.md",12437,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-dspy\u002Freferences\u002Fmodules.md",{"path":104,"resourceType":87,"resourceTypeDesc":88,"sizeBytes":105,"sourceHtmlUrl":106},"references\u002Foptimizers.md",14933,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-dspy\u002Freferences\u002Foptimizers.md",{"path":108,"resourceType":109,"resourceTypeDesc":110,"sizeBytes":111,"sourceHtmlUrl":112},"scripts\u002Fsafe_arithmetic.py","SCRIPT","脚本",1295,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-dspy\u002Fscripts\u002Fsafe_arithmetic.py",[114,143,167,192,217,241],{"skillNo":115,"name":116,"nameZh":6,"description":117,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":123,"publishedAt":51},"01M6QRD07D4TGNDK6VJ4EHF8BV","youtube-full","Use when the user needs YouTube transcripts, video search, channel browsing, playlist extraction, or content monitoring. Trigger phrases: 'get the transcript for', 'search YouTube for', 'what are the latest videos on', 'list this playlist', 'monitor this channel', or any request involving a YouTube URL, video ID, or @handle. Do NOT use for downloading video or audio files, YouTube engagement data (likes, comments), or private\u002Fage-restricted videos.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fyoutube-full\u002FSKILL.md",[120],{"categoryNo":121,"categoryName":122,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体",[124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,36,140,141,142],"youtube full","youtube","full","transcript","search","monitoring","data","Video","Audio","list","files","do","get","age","trigger","URL","browsing","request","youtube transcripts",{"skillNo":144,"name":145,"nameZh":6,"description":146,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":147,"categories":148,"keywords":149,"publishedAt":51},"01M6QRCJ3112VYPA97YG7KGMC2","x-twitter-growth","X\u002FTwitter growth engine for building audience, crafting viral content, and analyzing engagement. Use when the user wants to grow on X\u002FTwitter, write tweets or threads, analyze their X profile, research competitors on X, plan a posting strategy, or optimize engagement. Complements social-content (generic multi-platform) with X-specific depth: algorithm mechanics, thread engineering, reply strategy, profile optimization, and competitive intelligence via web search.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fx-twitter-growth\u002FSKILL.md",[],[150,151,152,153,128,154,155,156,157,158,159,160,161,162,42,163,164,165,166,36],"twitter","x twitter growth","growth","research","content","engineering","plan","web search","competitors","analyze","engine","write","strategy","platform","grow","posting","competitive",{"skillNo":168,"name":169,"nameZh":6,"description":170,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":171,"categories":172,"keywords":174,"publishedAt":51},"01M6QRBN3EHQNJY42RERP7A149","write-a-skill","Create new agent skills with proper structure, progressive disclosure, and bundled resources. Use when user wants to create, write, build, or author a new skill.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrite-a-skill\u002FSKILL.md",[173],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[175,161,176,177,178,179,180,181,42,182,183,62,184,185,186,187,188,189,190,191],"write a skill","github","create","https","productivity","matt pocock","direct","example","build","new skill","structure","new agent","resources","with","tree","progressive disclosure","author",{"skillNo":193,"name":194,"nameZh":6,"description":195,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":196,"categories":197,"keywords":198,"publishedAt":51},"01M6QRB6G8P33PNGAF9Y69EJ9T","wrap-up","Close out a launched Claude Managed Agent — recap every primitive the founder now owns, regenerate the single-file overview page, and suggest the next 1-2 upgrades. Use when the user says \"wrap up\", \"close this out\", \"what do I own now\", \"give me the summary\", \"recap the agent\", or when the orchestrator routes phase=wrap-up. primitives_inventory.py tables everything owned (agent, environment, session, memory, outcome, deployment); overview_page.py regenerates a self-contained .\u002Fmy-agent\u002Fagent-overview.html; upgrade_suggester.py ranks the next moves from recorded deferrals plus standing hardening steps. Companion to run-without-you; the last stop before phase=done.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrap-up\u002FSKILL.md",[],[199,200,201,202,203,204,205,206,207,42,208,135,209,210,211,212,213,214,215,216],"wrap up","up","wrap","gemini","deployment","run","file","hardening","closeout","stop","upgrade","founder","close","companion","you","tables","directions","phase",{"skillNo":218,"name":219,"nameZh":6,"description":220,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":221,"categories":222,"keywords":224,"publishedAt":51},"01M6QRA5AYC1RBFZ39GTWGS3N8","workflow-builder","Design and write deterministic multi-agent workflow scripts (.js files in .claude\u002Fworkflows\u002F) for Claude Code's Workflow tool. Use when a user wants to build, create, author, scaffold, or run a custom Claude Code workflow, orchestrate sub-agents (fan-out, pipeline, loop, judge-panel), or automate a repeatable multi-step task across fresh-context agents.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkflow-builder\u002FSKILL.md",[223],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[225,226,227,228,229,177,204,230,231,232,233,234,161,235,134,236,237,238,239,240],"workflow","workflow builder","builder","design","workflows","code","orchestrate","pipeline","loop","multi-agent","context","across","fresh","scripts","judge","claude code workflow",{"skillNo":242,"name":243,"nameZh":6,"description":244,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":245,"categories":246,"keywords":247,"publishedAt":51},"01M6QR7QMCZESKQA0ERW1E657M","weekly-review","Use when someone wants to run a weekly review, close open loops, audit stalled projects and commitments, get their system back to trusted, restart a lapsed review habit, or says \"\u002Fcs:weekly-review\". Walks David Allen's three-phase loop — GET CLEAR, GET CURRENT, GET CREATIVE — with deterministic scripts that inventory open loops, gate the checklist with named gaps, and score commitment health 0-100.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fweekly-review\u002FSKILL.md",[],[248,249,250,251,252,253,254,255,256,233,257,258,259,260,261,262,136,263,264,216],"review","weekly review","weekly","deterministic scripts","reflect","feeds","inventory","open","team","projects","project-management","scanner","conversation","back","project","sprint","cadence"]