Skip to main content
skill CX Codex

dspy-haystack-integration — Claude Code skill: setup guide

Optimizes Haystack pipeline prompts using DSPy few-shot compilers. Connects Haystack retrievers into DSPy modules for data-driven prompt tuning.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add OmidZamani/dspy-skills --skill dspy-haystack-integration -a claude-code
Open on GitHub

What dspy-haystack-integration does

This skill connects Haystack components with DSPy optimizers. Instead of editing prompt templates by hand, it wraps a Haystack retriever inside a dspy.Module and optimizes the generator via BootstrapFewShot using a training dataset.

Evaluation relies on custom metric functions. You can pair Haystack evaluators like SASEvaluator with length penalties to balance accuracy and conciseness. Skill metadata targets dspy version 3.2.1.

Converting compiled DSPy demos into Haystack PromptBuilder templates requires manual mapping. Because DSPy and Haystack use different formatting rules, complex pipelines demand custom integration logic.

What it helps with

  • Wrap a Haystack retriever into a dspy.Module for RAG pipelines
  • Optimize generator prompts with DSPy BootstrapFewShot
  • Build combined evaluation metrics using Haystack SASEvaluator
  • Map compiled DSPy demonstrations back into Haystack PromptBuilder templates

Example prompts for the agent

  • Wrap my Haystack retriever in a DSPy RAG module and run BootstrapFewShot optimization.
  • Write an evaluation metric combining Haystack SASEvaluator with a conciseness penalty.
  • Extract the compiled DSPy prompt and apply it to my Haystack PromptBuilder template.

How to install dspy-haystack-integration

1Skills CLI (Vercel)

npx skills add OmidZamani/dspy-skills --skill dspy-haystack-integration -a claude-code

2Manually: put the files in place

~/.claude/skills/dspy-haystack-integration/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/dspy-haystack-integration/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about dspy-haystack-integration

How do I install dspy-haystack-integration in Claude Code?

Run npx skills add OmidZamani/dspy-skills --skill dspy-haystack-integration -a claude-code. The skill file will be placed at ~/.claude/skills/dspy-haystack-integration/SKILL.md.

What does dspy-haystack-integration do?

It provides workflow instructions to tune Haystack generation prompts through DSPy optimizers. It guides wrapping retrievers, compiling few-shot examples, and extracting prompts.

Which DSPy version is supported?

The skill specifies compatibility with DSPy version 3.2.1.

Source text

SKILL.md · MIT
---
name: dspy-haystack-integration
version: "1.0.0"
dspy-compatibility: "3.2.1"
tags: ["retrieval", "optimizer"]
requires-extras: []
description: Use for integrating DSPy with Haystack, optimizing Haystack prompts, improving retrieval pipelines, and extracting DSPy prompts.
allowed-tools:
  - Read
  - Write
  - Glob
  - Grep
---

# DSPy + Haystack Integration

## Goal

Use DSPy's optimization capabilities to automatically improve prompts in Haystack pipelines.

## When to Use

- You have existing Haystack pipelines
- Manual prompt tuning is tedious
- Need data-driven prompt optimization
- Want to combine Haystack components with DSPy optimization

## Inputs

| Input | Type | Description |
|-------|------|-------------|
| `haystack_pipeline` | `Pipeline` | Existing Haystack pipeline |
| `trainset` | `list[dspy.Example]` | Training examples |
| `metric` | `callable` | Evaluation function |

## Outputs

| Output | Type | Description |
|--------|------|-------------|
| `optimized_prompt` | `str` | DSPy-optimized prompt |
| `optimized_pipeline` | `Pipeline` | Updated Haystack pipeline |

## Workflow

### Phase 1: Build Initial Haystack Pipeline

```python
from haystack import Pipeline
from haystack.components.generators import OpenAIGenerator
from haystack.components.builders import PromptBuilder
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.document_stores.in_memory import InMemoryDocumentStore

# Setup document store
doc_store = InMemoryDocumentStore()
doc_store.write_documents(documents)

# Initial generic prompt
initial_prompt = """
Context: {{context}}
Question: {{question}}
Answer:
"""

# Build pipeline
pipeline = Pipeline()
pipeline.add_component("retriever", InMemoryBM25Retriever(document_store=doc_store))
pipeline.add_component("prompt_builder", PromptBuilder(template=initial_prompt))
pipeline.add_component("generator", OpenAIGenerator(model="gpt-4o-mini"))

pipeline.connect("retriever", "prompt_builder.context")
pipeline.connect("prompt_builder", "generator")
```

### Phase 2: Create DSPy RAG Module

```python
import dspy

class HaystackRAG(dspy.Module):
    """DSPy module wrapping Haystack retriever."""
    
    def __init__(self, retriever, k=3):
        super().__init__()
        self.retriever = retriever
        self.k = k
        self.generate = dspy.ChainOfThought("context, question -> answer")
    
    def forward(self, question):
        # Use Haystack retriever
        results = self.retriever.run(query=question, top_k=self.k)
        context = [doc.content for doc in results['documents']]
        
        # Use DSPy for generation
        pred = self.generate(context=context, question=question)
        return dspy.Prediction(context=context, answer=pred.answer)
```

### Phase 3: Define Custom Metric

```python
from haystack.components.evaluators import SASEvaluator

# Haystack semantic evaluator
sas_evaluator = SASEvaluator(model="sentence-transformers/all-MiniLM-L6-v2")

def mixed_metric(example, pred, trace=None):
    """Combine semantic accuracy with conciseness."""
    
    # Semantic similarity (Haystack SAS)
    sas_result = sas_evaluator.run(
        ground_truth_answers=[example.answer],
        predicted_answers=[pred.answer]
    )
    semantic_score = sas_result['score']
    
    # Conciseness penalty
    word_count = len(pred.answer.split())
    conciseness = 1.0 if word_count <= 20 else max(0, 1 - (word_count - 20) / 50)
    
    return 0.7 * semantic_score + 0.3 * conciseness
```

### Phase 4: Optimize with DSPy

```python
from dspy.teleprompt import BootstrapFewShot

lm = dspy.LM("openai/gpt-4o-mini")
dspy.configure(lm=lm)

# Create DSPy module with Haystack retriever
rag_module = HaystackRAG(retriever=pipeline.get_component("retriever"))

# Optimize
optimizer = BootstrapFewShot(
    metric=mixed_metric,
    max_bootstrapped_demos=4,
    max_labeled_demos=4
)

compiled = optimizer.compile(rag_module, trainset=trainset)
```

### Phase 5: Extract and Apply Optimized Prompt

After optimization, extract the optimized prompt and apply it to your Haystack pipeline.

See [Prompt Extraction Guide](references/prompt-extraction.md) for detailed steps on:
- Extracting prompts from compiled DSPy modules
- Mapping DSPy demos to Haystack templates
- Building optimized Haystack pipelines

## Production Example

For a complete production-ready implementation, see [HaystackDSPyOptimizer](examples/haystack-dspy-optimizer.py).

This class provides:
- Wrapper for Haystack retrievers in DSPy modules
- Automatic optimization with BootstrapFewShot
- Prompt extraction and Haystack pipeline rebuilding
- Complete usage example with document store setup

## Best Practices

1. **Match retrievers** - Use same retriever in DSPy module as Haystack pipeline
2. **Custom metrics** - Combine Haystack evaluators with DSPy optimization
3. **Prompt extraction** - Carefully map DSPy demos to Haystack template format
4. **Test both** - Validate DSPy module AND final Haystack pipeline

## Limitations

- Prompt template conversion can be tricky
- Some Haystack features don't map directly to DSPy
- Requires maintaining two codebases initially
- Complex pipelines may need custom integration

## Official Documentation

- **DSPy Documentation**: https://dspy.ai/
- **DSPy GitHub**: https://github.com/stanfordnlp/dspy
- **Haystack Documentation**: https://docs.haystack.deepset.ai/

© OmidZamani · MIT · OmidZamani/dspy-skills

Similar skills

All skills for AI and ML →

From the same set23

dspy-optimizer-selection Helps you pick a DSPy optimizer that fits your data and budget, from LabeledFewShot up to GEPA and BetterTogether. Useful when you don't know where to start compiling. CX Codex +1 ★ 124repo stars dspy-optimize-anything Guides AI agents through GEPA reflective evolutionary search for code, prompts, configs, and text artifacts using diagnostic feedback. CX Codex +1 ★ 124repo stars dspy-miprov2-optimizer This skill guides MIPROv2 optimization of DSPy programs, searching for instruction and few-shot demo combinations with Bayesian optimization. Use it to tune a program against training data. CX Codex +1 ★ 124repo stars dspy-mcp-tool-integration A skill that walks through wiring an MCP server into DSPy: turning its tools into dspy.Tool and calling them from an async agent. CX Codex +1 ★ 124repo stars dspy-gepa-reflective Guides GEPA optimization of DSPy agents using written feedback and execution traces. Useful for ReAct systems with tools and multi-step workflows. CX Codex +1 ★ 124repo stars dspy-finetune-bootstrap Turns a working DSPy program into fine-tuned weights for a smaller model, cutting inference cost and speeding up responses. CX Codex +1 ★ 124repo stars dspy-evaluation-suite Tests and benchmarks DSPy modules against evaluation datasets using multi-threaded execution and custom scoring functions. CX Codex +1 ★ 124repo stars dspy-embedding-retrieval Build semantic retrieval over an application-owned text corpus with DSPy embeddings, local or hosted models, and optional FAISS indexing. CX Codex +1 ★ 124repo stars

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor