dspy-haystack-integration

Tool for integrating DSPy with Haystack, focused on optimizing Haystack prompts, improving retrieval pipelines, and extracting DSPy prompts so DSPy prompt strategies can be used within the Haystack environment.

Last repository push
GitHub Stars
126
Forks
13
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "dspy-haystack-integration" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-ffc80ccdf7fc290c53afb7aa09a190323a8aceff8461f538afd316aa06f240da. Verify the upstream source and version against https://github.com/OmidZamani/dspy-skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Tool for integrating DSPy with Haystack, focused on optimizing Haystack prompts, improving retrieval pipelines, and extracting DSPy prompts so DSPy prompt strategies can be used within the Haystack environment.

0 Downloads

Introduction source: third_party · OmidZamani · 1.0.0 Reference

SkillPi interpretation

Tasks
Use for integrating DSPy with Haystack, optimizing Haystack prompts, improving retrieval pipelines, and extracting DSPy prompts.
Audience
You have existing Haystack pipelines Manual prompt tuning is tedious Need data-driven prompt optimization Want to combine Haystack components with DSPy optimization
Inputs and outputs
| Input | Type | Description | |-------|------|-------------| | `haystack_pipeline` | `Pipeline` | Existing Haystack pipeline | | `trainset` | `list[dspy.Example]` | Training examples | | `metric` | `callable` | Evaluation function |
Software, accounts and paid services
doc_store = InMemoryDocumentStore() doc_store.write_documents(documents)
Limits and differences
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
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
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

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

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

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

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 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.

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

Current listing version

1.0.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value85/100

Highlights

  • 提供 DSPy 与 Haystack 集成的完整解决方案,解决实际工程痛点
  • 覆盖提示优化、检索管道改进、DSPy 提示提取等多个实用场景
Trigger Precision95/100

Highlights

  • 触发描述精准完整,明确说明集成、优化、改进、提取四大核心功能
  • frontmatter description 字段完整,边界清晰无歧义
Structure and Standards95/100

Highlights

  • 结构完整,包含目标、使用场景、输入输出、分阶段工作流、生产示例、最佳实践和限制说明
  • 提供端到端代码示例,单文件长度适中,符合规范要求
Execution Reliability75/100

Areas to improve

  • 引用文件缺失 Reported severity: Major

    SKILL.md 引用了 references/prompt-extraction.md 和 examples/haystack-dspy-optimizer.py 两个文件,但未在传入内容中提供

    Recommendation: 请补充缺失的引用文件,或移除相关引用说明

Highlights

  • 工具来源明确(Haystack、DSPy),参数使用合理,代码示例完整
Evidence Verifiability (mean of the first four)88/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • docs.haystack.deepset.ai
  • dspy.ai
  • github.com

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

doc_store = InMemoryDocumentStore() doc_store.write_documents(documents)

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.