skills/dspy-haystack-integration/SKILL.md
This skill should be used when the user asks to "integrate DSPy with Haystack", "optimize Haystack prompts using DSPy", "use DSPy to improve Haystack pipeline", mentions "Haystack pipeline optimization", "combining DSPy and Haystack", "extract DSPy prompt for Haystack", or wants to use DSPy's optimization capabilities to automatically improve prompts in existing Haystack pipelines.
npx skillsauth add omidzamani/dspy-skills dspy-haystack-integrationInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Use DSPy's optimization capabilities to automatically improve prompts in Haystack pipelines.
| Input | Type | Description |
|-------|------|-------------|
| haystack_pipeline | Pipeline | Existing Haystack pipeline |
| trainset | list[dspy.Example] | Training examples |
| metric | callable | Evaluation function |
| Output | Type | Description |
|--------|------|-------------|
| optimized_prompt | str | DSPy-optimized prompt |
| optimized_pipeline | Pipeline | Updated Haystack pipeline |
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")
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)
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
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)
After optimization, extract the optimized prompt and apply it to your Haystack pipeline.
See Prompt Extraction Guide for detailed steps on:
For a complete production-ready implementation, see HaystackDSPyOptimizer.
This class provides:
tools
This skill should be used when the user asks to "optimize with SIMBA", "use mini-batch introspective optimization", "generate self-reflective rules", mentions "SIMBA optimizer", "stochastic mini-batch ascent", "output variability", or needs an alternative to MIPROv2/GEPA that evolves rules and demonstrations from numeric metrics.
data-ai
This skill should be used when the user asks to "create a DSPy signature", "define inputs and outputs", "design a signature", "use InputField or OutputField", "add type hints to DSPy", mentions "signature class", "type-safe DSPy", "Pydantic models in DSPy", or needs to define what a DSPy module should do with structured inputs and outputs.
development
This skill should be used when the user asks to "use DSPy RLM", "process a very long context", "use ProgramOfThought", "use CodeAct", "run DSPy modules in parallel", mentions Recursive Language Models, sandboxed Python execution, Deno, `dspy.RLM`, `dspy.ProgramOfThought`, `dspy.CodeAct`, or `dspy.Parallel`, or needs to choose a DSPy reasoning module beyond Predict, ChainOfThought, and ReAct.
tools
This skill should be used when the user asks to "create a ReAct agent", "build an agent with tools", "implement tool-calling agent", "use dspy.ReAct", mentions "agent with tools", "reasoning and acting", "multi-step agent", "agent optimization with GEPA", or needs to build production agents that use tools to solve complex tasks.