Claude Code for Haystack: Production RAG Pipelines and Document AI — Claude Skills 360 Blog
Blog / AI / Claude Code for Haystack: Production RAG Pipelines and Document AI
AI

Claude Code for Haystack: Production RAG Pipelines and Document AI

Published: January 10, 2027
Read time: 9 min read
By: Claude Skills 360

Haystack builds production document AI systems through composable Pipeline components. Each component — DocumentSplitter, SentenceTransformersDocumentEmbedder, InMemoryEmbeddingRetriever, PromptBuilder, OpenAIChatGenerator — does one thing and connects to others via typed sockets. Pipeline.connect() links output ports to input ports with type checking. DocumentStores abstract over Elasticsearch, Weaviate, OpenSearch, or in-memory storage. Hybrid retrieval combines BM25 keyword search with dense vector search for production accuracy. Custom components implement the @component decorator with run(). Claude Code generates Haystack indexing pipelines, retrieval-augmented generation chains, custom components, and the FastAPI deployment wrappers for document AI systems.

CLAUDE.md for Haystack Projects

## Haystack Stack
- Version: haystack-ai >= 2.6 (Haystack 2.x — NOT 1.x, breaking API change)
- DocumentStore: InMemoryDocumentStore (dev), WeaviateDocumentStore (prod vector), ElasticsearchDocumentStore (prod BM25)
- Embeddings: SentenceTransformersDocumentEmbedder + SentenceTransformersTextEmbedder
- LLM: OpenAIChatGenerator (GPT-4o), AnthropicChatGenerator (claude-sonnet-4-6)
- Hybrid: JoinDocuments + weighting of BM25 + vector retrieval results
- Custom: @component decorator with InputSocket/OutputSocket type annotation
- Testing: unit test components in isolation, integration test full pipelines

Document Indexing Pipeline

# pipelines/indexing.py — index documents into vector store
from haystack import Pipeline, Document
from haystack.components.converters import TextFileToDocument, PyPDFToDocument
from haystack.components.preprocessors import DocumentSplitter, DocumentCleaner
from haystack.components.embedders import SentenceTransformersDocumentEmbedder
from haystack.components.writers import DocumentWriter
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.document_stores.types import DuplicatePolicy
from pathlib import Path


def build_indexing_pipeline(document_store) -> Pipeline:
    """Build a pipeline to index PDF and text documents."""

    pipeline = Pipeline()

    # Add components
    pipeline.add_component("pdf_converter", PyPDFToDocument())
    pipeline.add_component("text_converter", TextFileToDocument())
    pipeline.add_component("cleaner", DocumentCleaner(
        remove_empty_lines=True,
        remove_extra_whitespaces=True,
        remove_repeated_substrings=False,
    ))
    pipeline.add_component("splitter", DocumentSplitter(
        split_by="sentence",
        split_length=5,
        split_overlap=1,
    ))
    pipeline.add_component("embedder", SentenceTransformersDocumentEmbedder(
        model="sentence-transformers/all-MiniLM-L6-v2",
        batch_size=64,
        progress_bar=True,
    ))
    pipeline.add_component("writer", DocumentWriter(
        document_store=document_store,
        policy=DuplicatePolicy.OVERWRITE,
    ))

    # Connect components: output_socket -> input_socket
    # Note: pdf and text converters both merge into cleaner
    # For single source, connect directly:
    pipeline.connect("pdf_converter", "cleaner")
    pipeline.connect("cleaner", "splitter")
    pipeline.connect("splitter", "embedder")
    pipeline.connect("embedder", "writer")

    return pipeline


def index_documents(file_paths: list[str], document_store) -> dict:
    """Index a list of documents and return stats."""

    pipeline = build_indexing_pipeline(document_store)
    pipeline.warm_up()  # Load embedding model

    # Separate PDFs and text files
    pdf_files = [f for f in file_paths if f.endswith(".pdf")]
    text_files = [f for f in file_paths if not f.endswith(".pdf")]

    results = {}

    if pdf_files:
        result = pipeline.run({
            "pdf_converter": {"sources": [Path(f) for f in pdf_files]}
        })
        results["pdfs"] = result

    if text_files:
        result = pipeline.run({
            "text_converter": {"sources": [Path(f) for f in text_files]}
        })
        results["texts"] = result

    count = document_store.count_documents()
    print(f"Indexed documents. Total in store: {count}")

    return results

RAG Query Pipeline

# pipelines/rag.py — retrieval-augmented generation pipeline
from haystack import Pipeline
from haystack.components.embedders import SentenceTransformersTextEmbedder
from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever
from haystack.components.builders import PromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
import os


RAG_PROMPT = """
You are a helpful assistant that answers questions based on the provided documents.
If the documents don't contain enough information to answer confidently, say so.

Documents:
{% for doc in documents %}
---
Source: {{ doc.meta.get('file_path', 'unknown') }}
{{ doc.content }}
{% endfor %}
---

Question: {{ question }}

Answer:
"""


def build_rag_pipeline(document_store) -> Pipeline:
    """Build an end-to-end RAG pipeline."""

    pipeline = Pipeline()

    pipeline.add_component("embedder", SentenceTransformersTextEmbedder(
        model="sentence-transformers/all-MiniLM-L6-v2",
    ))
    pipeline.add_component("retriever", InMemoryEmbeddingRetriever(
        document_store=document_store,
        top_k=5,
    ))
    pipeline.add_component("prompt_builder", PromptBuilder(
        template=RAG_PROMPT,
    ))
    pipeline.add_component("llm", OpenAIChatGenerator(
        model="gpt-4o",
        api_key=os.environ["OPENAI_API_KEY"],
        generation_kwargs={
            "temperature": 0.1,
            "max_tokens": 1024,
        },
    ))

    # Connect the pipeline
    pipeline.connect("embedder.embedding", "retriever.query_embedding")
    pipeline.connect("retriever.documents", "prompt_builder.documents")
    pipeline.connect("prompt_builder.prompt", "llm.messages")

    return pipeline


def answer_question(question: str, pipeline: Pipeline) -> dict:
    """Run a question through the RAG pipeline."""

    result = pipeline.run({
        "embedder": {"text": question},
        "prompt_builder": {"question": question},
    })

    response = result["llm"]["replies"][0].content
    retrieved_docs = result["retriever"]["documents"]

    return {
        "answer": response,
        "sources": [
            {
                "content": doc.content[:200],
                "source": doc.meta.get("file_path", "unknown"),
                "score": doc.score,
            }
            for doc in retrieved_docs
        ],
    }

Hybrid Retrieval (BM25 + Vector)

# pipelines/hybrid_rag.py — combine keyword and semantic search
from haystack import Pipeline
from haystack.components.retrievers.in_memory import (
    InMemoryEmbeddingRetriever,
    InMemoryBM25Retriever,
)
from haystack.components.joiners import DocumentJoiner
from haystack.components.rankers import MetaFieldRanker
from haystack.components.embedders import SentenceTransformersTextEmbedder
from haystack.components.builders import PromptBuilder
from haystack.components.generators.chat import OpenAIChatGenerator


def build_hybrid_rag_pipeline(document_store) -> Pipeline:
    """Hybrid RAG: combine BM25 keyword + dense vector retrieval."""

    pipeline = Pipeline()

    # Embedder for vector retrieval
    pipeline.add_component("embedder", SentenceTransformersTextEmbedder(
        model="sentence-transformers/all-MiniLM-L6-v2"
    ))

    # BM25 retriever: good for exact keyword matches
    pipeline.add_component("bm25_retriever", InMemoryBM25Retriever(
        document_store=document_store,
        top_k=10,
    ))

    # Vector retriever: good for semantic similarity
    pipeline.add_component("vector_retriever", InMemoryEmbeddingRetriever(
        document_store=document_store,
        top_k=10,
    ))

    # Join and deduplicate results — reciprocal rank fusion
    pipeline.add_component("joiner", DocumentJoiner(
        join_mode="reciprocal_rank_fusion",
        top_k=7,
    ))

    pipeline.add_component("prompt_builder", PromptBuilder(template=RAG_PROMPT))
    pipeline.add_component("llm", OpenAIChatGenerator(model="gpt-4o"))

    # BM25 doesn't need embedding
    pipeline.connect("bm25_retriever.documents", "joiner.documents")

    # Vector path
    pipeline.connect("embedder.embedding", "vector_retriever.query_embedding")
    pipeline.connect("vector_retriever.documents", "joiner.documents")

    # Joined → prompt → LLM
    pipeline.connect("joiner.documents", "prompt_builder.documents")
    pipeline.connect("prompt_builder.prompt", "llm.messages")

    return pipeline


def run_hybrid_query(question: str, pipeline: Pipeline) -> dict:
    result = pipeline.run({
        "embedder": {"text": question},
        "bm25_retriever": {"query": question},
        "prompt_builder": {"question": question},
    })

    return {
        "answer": result["llm"]["replies"][0].content,
        "n_docs": len(result["joiner"]["documents"]),
    }

Custom Component

# components/query_expander.py — custom Haystack component
from haystack import component, default_from_dict, default_to_dict
from haystack.dataclasses import ChatMessage
from haystack.components.generators.chat import OpenAIChatGenerator
from typing import List
import os


@component
class QueryExpander:
    """Expand a query into multiple rephrased variants for better recall."""

    def __init__(self, n_variants: int = 3):
        self.n_variants = n_variants
        self.generator = OpenAIChatGenerator(
            model="gpt-4o-mini",
            api_key=os.environ["OPENAI_API_KEY"],
        )

    @component.output_types(queries=List[str])
    def run(self, query: str) -> dict:
        """Expand query into N rephrased variants."""

        messages = [ChatMessage.from_user(
            f"""Generate {self.n_variants} different phrasings of this question.
            Return only the rephrased questions, one per line, no numbering.
            
            Original: {query}"""
        )]

        result = self.generator.run(messages=messages)
        response_text = result["replies"][0].content

        variants = [line.strip() for line in response_text.strip().split("\n") if line.strip()]
        all_queries = [query] + variants[:self.n_variants]

        return {"queries": all_queries}

    def to_dict(self) -> dict:
        return default_to_dict(self, n_variants=self.n_variants)

    @classmethod
    def from_dict(cls, data: dict):
        return default_from_dict(cls, data)

FastAPI Deployment

# api/main.py — serve Haystack pipeline via FastAPI
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from haystack.document_stores.in_memory import InMemoryDocumentStore
from pipelines.hybrid_rag import build_hybrid_rag_pipeline
from pipelines.indexing import index_documents
import os

app = FastAPI(title="Document QA API")

# Shared state
document_store = InMemoryDocumentStore()
rag_pipeline = None


@app.on_event("startup")
async def startup():
    global rag_pipeline

    # Index documents on startup
    docs_dir = os.environ.get("DOCS_DIR", "./documents")
    if os.path.exists(docs_dir):
        files = [str(f) for f in Path(docs_dir).glob("**/*") if f.is_file()]
        if files:
            index_documents(files, document_store)

    rag_pipeline = build_hybrid_rag_pipeline(document_store)
    rag_pipeline.warm_up()


class QuestionRequest(BaseModel):
    question: str
    top_k: int = 5


class AnswerResponse(BaseModel):
    answer: str
    sources: list[dict]


@app.post("/ask", response_model=AnswerResponse)
async def ask_question(request: QuestionRequest):
    if not rag_pipeline:
        raise HTTPException(503, "Pipeline not initialized")

    result = run_hybrid_query(request.question, rag_pipeline)

    return AnswerResponse(
        answer=result["answer"],
        sources=result.get("sources", []),
    )


@app.post("/index")
async def index_new_documents(file_paths: list[str]):
    """Index new documents at runtime."""
    global rag_pipeline
    index_documents(file_paths, document_store)
    rag_pipeline = build_hybrid_rag_pipeline(document_store)
    rag_pipeline.warm_up()
    return {"indexed": len(file_paths), "total": document_store.count_documents()}

For the LlamaIndex alternative that focuses on knowledge graph construction and multi-index routing rather than Haystack’s component pipeline model, see the LlamaIndex guide for ingestion pipelines and query engines. For the DSPy optimizer that treats RAG as a compiled program and auto-optimizes prompts and retrieval, the DSPy guide covers declarative LLM programs. The Claude Skills 360 bundle includes Haystack skill sets covering indexing pipelines, hybrid retrieval, and custom components. Start with the free tier to try Haystack pipeline generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free