{"id":10302,"date":"2025-12-09T02:13:28","date_gmt":"2025-12-09T10:13:28","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/"},"modified":"2025-12-09T02:13:28","modified_gmt":"2025-12-09T10:13:28","slug":"openai-haystack-rag-with-search-vector-index","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/","title":{"rendered":"RAG with OpenAI, Haystack, and Couchbase Search Vector Index"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/couchbase-examples\/vector-search-cookbook\/tree\/main\/haystack\/search_based\/RAG_with_Couchbase_Capella_and_OpenAI.ipynb\">View Source<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This notebook demonstrates how to build a Retrieval Augmented Generation (RAG) system using:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The BBC News dataset containing real-time news articles<\/li>\n\n\n<li>Couchbase Capella Search Vector Index for low-latency vector retrieval<\/li>\n\n\n<li>Haystack framework for the RAG pipeline<\/li>\n\n\n<li>OpenAI for embeddings and text generation<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The system allows users to ask questions about current events and get AI-generated answers based on the latest news articles.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To build our RAG system, we need a set of libraries. The libraries we install handle everything from connecting to databases to performing AI tasks. Each library has a specific role: Couchbase libraries manage database operations, Haystack handles AI model integrations and pipeline management, and we will use the OpenAI SDK for generating embeddings and calling OpenAI&#8217;s language models.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>%pip install datasets haystack-ai couchbase-haystack openai pandas\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>[Output too long, omitted for brevity]\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The script starts by importing a series of libraries required for various tasks, including handling JSON, logging, time tracking, Couchbase connections, Haystack components for RAG pipeline, embedding generation, and dataset loading.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import getpass\nimport base64\nimport logging\nimport sys\nimport time\nimport pandas as pd\nfrom datetime import timedelta\n\nfrom couchbase.auth import PasswordAuthenticator\nfrom couchbase.cluster import Cluster\nfrom couchbase.exceptions import CouchbaseException\nfrom couchbase.options import ClusterOptions\nfrom datasets import load_dataset\nfrom haystack import Pipeline, GeneratedAnswer\nfrom haystack.components.embedders import OpenAIDocumentEmbedder, OpenAITextEmbedder\nfrom haystack.components.preprocessors import DocumentCleaner\nfrom haystack.components.writers import DocumentWriter\nfrom haystack.components.builders.answer_builder import AnswerBuilder\nfrom haystack.components.builders.prompt_builder import PromptBuilder\nfrom haystack.components.generators import OpenAIGenerator\nfrom haystack.utils import Secret\nfrom haystack.dataclasses import Document\n\nfrom couchbase_haystack import (\n    CouchbaseSearchDocumentStore,\n    CouchbasePasswordAuthenticator,\n    CouchbaseClusterOptions,\n    CouchbaseSearchEmbeddingRetriever,\n)\nfrom couchbase.options import KnownConfigProfiles\n\n# Configure logging\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>\/Users\/viraj.agarwal\/Tasks\/Task16.5\/.venv\/lib\/python3.13\/site-packages\/tqdm\/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https:\/\/ipywidgets.readthedocs.io\/en\/stable\/user_install.html\n  from .autonotebook import tqdm as notebook_tqdm\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-create-and-deploy-your-operational-cluster-on-capella\" class=\"wp-block-heading\">Create and Deploy Your Operational cluster on Capella<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To get started with Couchbase Capella, create an account and use it to deploy an operational cluster.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To know more, please follow the <a href=\"https:\/\/docs.couchbase.com\/cloud\/get-started\/create-account.html\">instructions<\/a>.<\/p>\n\n\n\n<h4 id=\"h-couchbase-capella-configuration\" class=\"wp-block-heading\">Couchbase Capella Configuration<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">When running Couchbase using <a href=\"https:\/\/cloud.couchbase.com\/sign-in\">Capella<\/a>, the following prerequisites need to be met:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Have a multi-node Capella cluster running the Data, Query, Index, and Search services.<\/li>\n\n\n<li>Create the <a href=\"https:\/\/docs.couchbase.com\/cloud\/clusters\/manage-database-users.html\">database credentials<\/a> to access the travel-sample bucket (Read and Write) used in the application.<\/li>\n\n\n<li><a href=\"https:\/\/docs.couchbase.com\/cloud\/clusters\/allow-ip-address.html\">Allow access<\/a> to the Cluster from the IP on which the application is running.<\/li>\n\n<\/ul>\n\n\n\n<h4 id=\"h-openai-models-setup\" class=\"wp-block-heading\">OpenAI Models Setup<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In order to create the RAG application, we need an embedding model to ingest the documents for Vector Search and a large language model (LLM) for generating the responses based on the context.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For this implementation, we&#8217;ll use OpenAI&#8217;s models which provide state-of-the-art performance for both embeddings and text generation:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Embedding Model<\/strong>: We&#8217;ll use OpenAI&#8217;s <code>text-embedding-3-large<\/code> model, which provides high-quality embeddings with 3,072 dimensions for semantic search capabilities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Large Language Model<\/strong>: We&#8217;ll use OpenAI&#8217;s <code>gpt-4o<\/code> model for generating responses based on the retrieved context. This model offers excellent reasoning capabilities and can handle complex queries effectively.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Prerequisites for OpenAI Integration<\/strong>:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Create an OpenAI account at <a href=\"https:\/\/platform.openai.com\">platform.openai.com<\/a><\/li>\n\n\n<li>Generate an API key from your OpenAI dashboard<\/li>\n\n\n<li>Ensure you have sufficient credits or a valid payment method set up<\/li>\n\n\n<li>Set up your API key as an environment variable or input it securely in the notebook<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For more details about OpenAI&#8217;s models and pricing, please refer to the <a href=\"https:\/\/platform.openai.com\/docs\/models\">OpenAI documentation<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Enter your Couchbase and OpenAI credentials:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>OPENAI_API_KEY<\/strong> is your OpenAI API key which can be obtained from your OpenAI dashboard at <a href=\"https:\/\/platform.openai.com\/api-keys\">platform.openai.com<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>INDEX_NAME<\/strong> is the name of the Search Vector Index used for vector search operations.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>CB_CONNECTION_STRING = input(&quot;Couchbase Cluster URL (default: localhost): &quot;) or &quot;localhost&quot;\nCB_USERNAME = input(&quot;Couchbase Username (default: admin): &quot;) or &quot;admin&quot;\nCB_PASSWORD = input(&quot;Couchbase password (default: Password@12345): &quot;) or &quot;Password@12345&quot;\nCB_BUCKET_NAME = input(&quot;Couchbase Bucket: &quot;)\nCB_SCOPE_NAME = input(&quot;Couchbase Scope: &quot;)\nCB_COLLECTION_NAME = input(&quot;Couchbase Collection: &quot;)\nCB_INDEX_NAME = input(&quot;Vector Search Index: &quot;)\nOPENAI_API_KEY = input(&quot;OpenAI API Key: &quot;)\n\n# Check if the variables are correctly loaded\nif not all([CB_CONNECTION_STRING, CB_USERNAME, CB_PASSWORD, CB_BUCKET_NAME, CB_SCOPE_NAME, CB_COLLECTION_NAME, CB_INDEX_NAME, OPENAI_API_KEY]):\n    raise ValueError(&quot;All configuration variables must be provided.&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>from couchbase.cluster import Cluster \nfrom couchbase.options import ClusterOptions\nfrom couchbase.auth import PasswordAuthenticator\nfrom couchbase.management.buckets import CreateBucketSettings\nfrom couchbase.management.collections import CollectionSpec\nfrom couchbase.management.search import SearchIndex\nimport json\n\n# Connect to Couchbase cluster\ncluster = Cluster(CB_CONNECTION_STRING, ClusterOptions(\n    PasswordAuthenticator(CB_USERNAME, CB_PASSWORD)))\n\n# Create bucket if it does not exist\nbucket_manager = cluster.buckets()\ntry:\n    bucket_manager.get_bucket(CB_BUCKET_NAME)\n    print(f&quot;Bucket &#039;{CB_BUCKET_NAME}&#039; already exists.&quot;)\nexcept Exception as e:\n    print(f&quot;Bucket &#039;{CB_BUCKET_NAME}&#039; does not exist. Creating bucket...&quot;)\n    bucket_settings = CreateBucketSettings(name=CB_BUCKET_NAME, ram_quota_mb=500)\n    bucket_manager.create_bucket(bucket_settings)\n    print(f&quot;Bucket &#039;{CB_BUCKET_NAME}&#039; created successfully.&quot;)\n\n# Create scope and collection if they do not exist\ncollection_manager = cluster.bucket(CB_BUCKET_NAME).collections()\nscopes = collection_manager.get_all_scopes()\nscope_exists = any(scope.name == CB_SCOPE_NAME for scope in scopes)\n\nif scope_exists:\n    print(f&quot;Scope &#039;{CB_SCOPE_NAME}&#039; already exists.&quot;)\nelse:\n    print(f&quot;Scope &#039;{CB_SCOPE_NAME}&#039; does not exist. Creating scope...&quot;)\n    collection_manager.create_scope(CB_SCOPE_NAME)\n    print(f&quot;Scope &#039;{CB_SCOPE_NAME}&#039; created successfully.&quot;)\n\ncollections = [collection.name for scope in scopes if scope.name == CB_SCOPE_NAME for collection in scope.collections]\ncollection_exists = CB_COLLECTION_NAME in collections\n\nif collection_exists:\n    print(f&quot;Collection &#039;{CB_COLLECTION_NAME}&#039; already exists in scope &#039;{CB_SCOPE_NAME}&#039;.&quot;)\nelse:\n    print(f&quot;Collection &#039;{CB_COLLECTION_NAME}&#039; does not exist in scope &#039;{CB_SCOPE_NAME}&#039;. Creating collection...&quot;)\n    collection_manager.create_collection(collection_name=CB_COLLECTION_NAME, scope_name=CB_SCOPE_NAME)\n    print(f&quot;Collection &#039;{CB_COLLECTION_NAME}&#039; created successfully.&quot;)\n\n# Create Search Vector Index from search_vector_index.json file at scope level\nwith open(&#039;search_vector_index.json&#039;, &#039;r&#039;) as search_file:\n    search_index_definition = SearchIndex.from_json(json.load(search_file))\n    \n       # Update search index definition with user inputs\n    search_index_definition.name = CB_INDEX_NAME\n    search_index_definition.source_name = CB_BUCKET_NAME\n    \n    # Update types mapping\n    old_type_key = next(iter(search_index_definition.params[&#039;mapping&#039;][&#039;types&#039;].keys()))\n    type_obj = search_index_definition.params[&#039;mapping&#039;][&#039;types&#039;].pop(old_type_key)\n    search_index_definition.params[&#039;mapping&#039;][&#039;types&#039;][f&quot;{CB_SCOPE_NAME}.{CB_COLLECTION_NAME}&quot;] = type_obj\n    \n    search_index_name = search_index_definition.name\n    \n    # Get scope-level search manager\n    scope_search_manager = cluster.bucket(CB_BUCKET_NAME).scope(CB_SCOPE_NAME).search_indexes()\n    \n    try:\n        # Check if index exists at scope level\n        existing_index = scope_search_manager.get_index(search_index_name)\n        print(f&quot;Search Vector Index &#039;{search_index_name}&#039; already exists at scope level.&quot;)\n    except Exception as e:\n        print(f&quot;Search Vector Index &#039;{search_index_name}&#039; does not exist at scope level. Creating index from search_vector_index.json...&quot;)\n        with open(&#039;search_vector_index.json&#039;, &#039;r&#039;) as search_file:\n            scope_search_manager.upsert_index(search_index_definition)\n            print(f&quot;Search Vector Index &#039;{search_index_name}&#039; created successfully at scope level.&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Bucket &#039;b&#039; already exists.\nScope &#039;s&#039; already exists.\nCollection &#039;c&#039; already exists in scope &#039;s&#039;.\nSearch Vector Index &#039;vector_search&#039; already exists at scope level.\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Load the TMDB movie dataset and prepare documents for indexing:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Load TMDB dataset\nprint(&quot;Loading TMDB dataset...&quot;)\ndataset = load_dataset(&quot;AiresPucrs\/tmdb-5000-movies&quot;)\nmovies_df = pd.DataFrame(dataset[&#039;train&#039;])\nprint(f&quot;Total movies found: {len(movies_df)}&quot;)\n\n# Create documents from movie data\ndocs_data = []\nfor _, row in movies_df.iterrows():\n    if pd.isna(row[&#039;overview&#039;]):\n        continue\n        \n    try:\n        docs_data.append({\n            &#039;id&#039;: str(row[&quot;id&quot;]),\n            &#039;content&#039;: f&quot;Title: {row[&#039;title&#039;]}nGenres: {&#039;, &#039;.join([genre[&#039;name&#039;] for genre in eval(row[&#039;genres&#039;])])}nOverview: {row[&#039;overview&#039;]}&quot;,\n            &#039;metadata&#039;: {\n                &#039;title&#039;: row[&#039;title&#039;],\n                &#039;genres&#039;: row[&#039;genres&#039;],\n                &#039;original_language&#039;: row[&#039;original_language&#039;],\n                &#039;popularity&#039;: float(row[&#039;popularity&#039;]),\n                &#039;release_date&#039;: row[&#039;release_date&#039;],\n                &#039;vote_average&#039;: float(row[&#039;vote_average&#039;]),\n                &#039;vote_count&#039;: int(row[&#039;vote_count&#039;]),\n                &#039;budget&#039;: int(row[&#039;budget&#039;]),\n                &#039;revenue&#039;: int(row[&#039;revenue&#039;])\n            }\n        })\n    except Exception as e:\n        logger.error(f&quot;Error processing movie {row[&#039;title&#039;]}: {e}&quot;)\n\nprint(f&quot;Created {len(docs_data)} documents with valid overviews&quot;)\ndocuments = [Document(id=doc[&#039;id&#039;], content=doc[&#039;content&#039;], meta=doc[&#039;metadata&#039;]) \n            for doc in docs_data]\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Loading TMDB dataset...\n\n\nGenerating train split: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 4803\/4803 [00:00&lt;00:00, 123144.70 examples\/s]\n\n\nTotal movies found: 4803\nCreated 4800 documents with valid overviews\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Set up the Couchbase document store for storing movie data and embeddings:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Initialize document store\ndocument_store = CouchbaseSearchDocumentStore(\n    cluster_connection_string=Secret.from_token(CB_CONNECTION_STRING),\n    authenticator=CouchbasePasswordAuthenticator(\n        username=Secret.from_token(CB_USERNAME),\n        password=Secret.from_token(CB_PASSWORD)\n    ),\n    cluster_options=CouchbaseClusterOptions(\n        profile=KnownConfigProfiles.WanDevelopment,\n    ),\n    bucket=CB_BUCKET_NAME,\n    scope=CB_SCOPE_NAME,\n    collection=CB_COLLECTION_NAME,\n    vector_search_index=CB_INDEX_NAME,\n)\n\nprint(&quot;Couchbase document store initialized successfully.&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Couchbase document store initialized successfully.\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Configure the document embedder using Capella AI&#8217;s endpoint and the E5 Mistral model. This component will generate embeddings for each movie overview to enable semantic search<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>embedder = OpenAIDocumentEmbedder(\n    api_key=Secret.from_token(OPENAI_API_KEY),\n    model=&quot;text-embedding-3-large&quot;,\n)\n\nrag_embedder = OpenAITextEmbedder(\n    api_key=Secret.from_token(OPENAI_API_KEY),\n    model=&quot;text-embedding-3-large&quot;,\n)\n\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Configure the LLM generator using Capella AI&#8217;s endpoint and Llama 3.1 model. This component will generate natural language responses based on the retrieved documents.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>llm = OpenAIGenerator(\n    api_key=Secret.from_token(OPENAI_API_KEY),\n    model=&quot;gpt-4o&quot;,\n)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Build the pipeline for processing and indexing movie documents:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Create indexing pipeline\nindex_pipeline = Pipeline()\nindex_pipeline.add_component(&quot;cleaner&quot;, DocumentCleaner())\nindex_pipeline.add_component(&quot;embedder&quot;, embedder)\nindex_pipeline.add_component(&quot;writer&quot;, DocumentWriter(document_store=document_store))\n\n# Connect indexing components\nindex_pipeline.connect(&quot;cleaner.documents&quot;, &quot;embedder.documents&quot;)\nindex_pipeline.connect(&quot;embedder.documents&quot;, &quot;writer.documents&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>&lt;haystack.core.pipeline.pipeline.Pipeline object at 0x124121550&gt;\n\ud83d\ude85 Components\n  - cleaner: DocumentCleaner\n  - embedder: OpenAIDocumentEmbedder\n  - writer: DocumentWriter\n\ud83d\udee4\ufe0f Connections\n  - cleaner.documents -&gt; embedder.documents (list[Document])\n  - embedder.documents -&gt; writer.documents (list[Document])\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Execute the pipeline for processing and indexing movie documents:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Run indexing pipeline\n\nif documents:\n    # Process documents in batches for better performance\n    batch_size = 100\n    total_docs = len(documents[:200])\n    \n    for i in range(0, total_docs, batch_size):\n        batch = documents[i:i + batch_size]\n        result = index_pipeline.run({&quot;cleaner&quot;: {&quot;documents&quot;: batch}})\n        print(f&quot;Processed batch {i\/\/batch_size + 1}: {len(batch)} documents&quot;)\n    \n    print(f&quot;nSuccessfully processed {total_docs} documents&quot;)\n    print(f&quot;Sample document metadata: {documents[0].meta}&quot;)\nelse:\n    print(&quot;No documents created. Skipping indexing.&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>Calculating embeddings: 4it [00:06,  1.73s\/it]\n\n\nProcessed batch 1: 100 documents\n\n\nCalculating embeddings: 4it [00:06,  1.66s\/it]\n\nProcessed batch 2: 100 documents\n\nSuccessfully processed 200 documents\nSample document metadata: {&#039;title&#039;: &#039;Four Rooms&#039;, &#039;genres&#039;: &#039;[{&quot;id&quot;: 80, &quot;name&quot;: &quot;Crime&quot;}, {&quot;id&quot;: 35, &quot;name&quot;: &quot;Comedy&quot;}]&#039;, &#039;original_language&#039;: &#039;en&#039;, &#039;popularity&#039;: 22.87623, &#039;release_date&#039;: &#039;1995-12-09&#039;, &#039;vote_average&#039;: 6.5, &#039;vote_count&#039;: 530, &#039;budget&#039;: 4000000, &#039;revenue&#039;: 4300000}\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Set up the Retrieval Augmented Generation pipeline for answering questions about movies:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Define RAG prompt template\nprompt_template = &quot;&quot;&quot;\nGiven these documents, answer the question.nDocuments:\n{% for doc in documents %}\n    {{ doc.content }}\n{% endfor %}\n\nnQuestion: {{question}}\nnAnswer:\n&quot;&quot;&quot;\n\n# Create RAG pipeline\nrag_pipeline = Pipeline()\n\n# Add components\nrag_pipeline.add_component(\n    &quot;query_embedder&quot;,\n    rag_embedder,\n)\nrag_pipeline.add_component(&quot;retriever&quot;, CouchbaseSearchEmbeddingRetriever(document_store=document_store))\nrag_pipeline.add_component(&quot;prompt_builder&quot;, PromptBuilder(template=prompt_template))\nrag_pipeline.add_component(&quot;llm&quot;,llm)\nrag_pipeline.add_component(&quot;answer_builder&quot;, AnswerBuilder())\n\n# Connect RAG components\nrag_pipeline.connect(&quot;query_embedder&quot;, &quot;retriever.query_embedding&quot;)\nrag_pipeline.connect(&quot;retriever.documents&quot;, &quot;prompt_builder.documents&quot;)\nrag_pipeline.connect(&quot;prompt_builder.prompt&quot;, &quot;llm.prompt&quot;)\nrag_pipeline.connect(&quot;llm.replies&quot;, &quot;answer_builder.replies&quot;)\nrag_pipeline.connect(&quot;llm.meta&quot;, &quot;answer_builder.meta&quot;)\nrag_pipeline.connect(&quot;retriever&quot;, &quot;answer_builder.documents&quot;)\n\nprint(&quot;RAG pipeline created successfully.&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>PromptBuilder has 2 prompt variables, but `required_variables` is not set. By default, all prompt variables are treated as optional, which may lead to unintended behavior in multi-branch pipelines. To avoid unexpected execution, ensure that variables intended to be required are explicitly set in `required_variables`.\n\n\nRAG pipeline created successfully.\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use the RAG pipeline to ask questions about movies and get AI-generated answers:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Example question\nquestion = &quot;Why did Manni call Lolla?&quot;\n\n# Run the RAG pipeline\nresult = rag_pipeline.run(\n    {\n        &quot;query_embedder&quot;: {&quot;text&quot;: question},\n        &quot;retriever&quot;: {&quot;top_k&quot;: 5},\n        &quot;prompt_builder&quot;: {&quot;question&quot;: question},\n        &quot;answer_builder&quot;: {&quot;query&quot;: question},\n    },\n    include_outputs_from={&quot;retriever&quot;, &quot;query_embedder&quot;}\n)\n\n# Get the generated answer\nanswer: GeneratedAnswer = result[&quot;answer_builder&quot;][&quot;answers&quot;][0]\n\n# Print retrieved documents\nprint(&quot;=== Retrieved Documents ===&quot;)\nretrieved_docs = result[&quot;retriever&quot;][&quot;documents&quot;]\nfor idx, doc in enumerate(retrieved_docs, start=1):\n    print(f&quot;Id: {doc.id} Title: {doc.meta[&#039;title&#039;]}&quot;)\n\n# Print final results\nprint(&quot;n=== Final Answer ===&quot;)\nprint(f&quot;Question: {answer.query}&quot;)\nprint(f&quot;Answer: {answer.data}&quot;)\nprint(&quot;nSources:&quot;)\nfor doc in answer.documents:\n    print(f&quot;-&gt; {doc.meta[&#039;title&#039;]}&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>=== Retrieved Documents ===\nId: 006b97c08110cb1b9b58e03943c91fa9412cfe7a2a22830ba5b9e3eb0c342344 Title: Run Lola Run\nId: 33543dab4c048c9467d632f319e02bca94da6f178250c14d26eabfb30911a823 Title: Mambo Italiano\nId: 94c55246e02c290767531f6359b5f44145191e3f2d62a3a64ed4718a666be9f2 Title: Good bye, Lenin!\nId: 00b4d1f455e45fbffa39f72be6de635bdcdb6b8a04289ba4aea41061700b9096 Title: Mean Streets\nId: 9241f819303fe61a25e05469856c01a8843d53a6ce7cec340bf0def848ddb470 Title: Magnolia\n\n=== Final Answer ===\nQuestion: Why did Manni call Lolla?\nAnswer: Manni called Lola because he lost 100,000 DM in a subway train that belongs to a very bad guy, and he needs her help to raise the money within 20 minutes to prevent him from having to rob a store to get the money.\n\nSources:\n-&gt; Run Lola Run\n-&gt; Mambo Italiano\n-&gt; Good bye, Lenin!\n-&gt; Mean Streets\n-&gt; Magnolia\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we built a Retrieval-Augmented Generation (RAG) system using Couchbase Capella, OpenAI, and Haystack with the BBC News dataset. This demonstrates how to combine Couchbase Search Vector Index with large language models to answer questions about current events using real-time information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key components include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Couchbase Capella Search Vector Index<\/strong> for vector storage and retrieval<\/li>\n\n\n<li><strong>Haystack<\/strong> for pipeline orchestration and component management<\/li>\n\n\n<li><strong>OpenAI<\/strong> for embeddings (<code>text-embedding-3-large<\/code>) and text generation (<code>gpt-4o<\/code>)<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This approach enables AI applications to access and reason over current information that extends beyond the LLM&#8217;s training data, making responses more accurate and relevant for real-world use cases.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>View Source This notebook demonstrates how to build a Retrieval Augmented Generation (RAG) system using: The system allows users to ask questions about current events and get AI-generated answers based on the latest news articles. To build our RAG system, we need a set of libraries. The libraries we install handle everything from connecting to [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"menu_order":0,"template":"","meta":{"_acf_changed":false,"inline_featured_image":false,"_acf":"","footnotes":""},"tutorial-languages":[606],"tutorial-tags":[607,620,609,615],"tutorial-technologies":[613],"tutorial-types":[555],"class_list":["post-10302","tutorials","type-tutorials","status-publish","hentry","tutorial-languages-python","tutorial-tags-artificial-intelligence","tutorial-tags-haystack","tutorial-tags-openai","tutorial-tags-search-vector-index","tutorial-technologies-vector-search","tutorial-types-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v28.8 (Yoast SEO v28.9) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>RAG with OpenAI, Haystack, and Couchbase Search Vector Index - Couchbase<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/\" \/>\n<meta property=\"og:locale\" content=\"de_DE\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"RAG with OpenAI, Haystack, and Couchbase Search Vector Index\" \/>\n<meta property=\"og:description\" content=\"View Source This notebook demonstrates how to build a Retrieval Augmented Generation (RAG) system using: The system allows users to ask questions about current events and get AI-generated answers based on the latest news articles. To build our RAG system, we need a set of libraries. The libraries we install handle everything from connecting to [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/\" \/>\n<meta property=\"og:site_name\" content=\"Couchbase\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Couchbase\/\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2548\" \/>\n\t<meta property=\"og:image:height\" content=\"1171\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@couchbase\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"13\u00a0Minuten\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/openai-haystack-rag-with-search-vector-index\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/openai-haystack-rag-with-search-vector-index\\\/\",\"name\":\"RAG with OpenAI, Haystack, and Couchbase Search Vector Index - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\"},\"datePublished\":\"2025-12-09T10:13:28+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/openai-haystack-rag-with-search-vector-index\\\/#breadcrumb\"},\"inLanguage\":\"de\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/openai-haystack-rag-with-search-vector-index\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/openai-haystack-rag-with-search-vector-index\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/ko\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"RAG with OpenAI, Haystack, and Couchbase Search Vector Index\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"name\":\"Couchbase\",\"description\":\"The Operational Data Platform for AI\u2122\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\"},\"alternateName\":\"Couchbase, Inc.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"de\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#organization\",\"name\":\"Couchbase\",\"alternateName\":\"Couchbase, Inc.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"de\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"width\":1129,\"height\":1129,\"caption\":\"Couchbase\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/Couchbase\\\/\",\"https:\\\/\\\/x.com\\\/couchbase\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/CouchbaseServer\",\"https:\\\/\\\/www.linkedin.com\\\/company\\\/couchbase\\\/\",\"https:\\\/\\\/github.com\\\/couchbase\\\/\",\"https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Couchbase,_Inc.\"],\"description\":\"Couchbase is a database software company headquartered in San Jose, California, providing an operational data platform for AI used by hundreds of global enterprises.\",\"legalName\":\"Couchbase, Inc.\",\"foundingDate\":\"2011-01-01\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"RAG with OpenAI, Haystack, and Couchbase Search Vector Index - Couchbase","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/","og_locale":"de_DE","og_type":"article","og_title":"RAG with OpenAI, Haystack, and Couchbase Search Vector Index","og_description":"View Source This notebook demonstrates how to build a Retrieval Augmented Generation (RAG) system using: The system allows users to ask questions about current events and get AI-generated answers based on the latest news articles. To build our RAG system, we need a set of libraries. The libraries we install handle everything from connecting to [&hellip;]","og_url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/","og_site_name":"Couchbase","article_publisher":"https:\/\/www.facebook.com\/Couchbase\/","og_image":[{"width":2548,"height":1171,"url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_site":"@couchbase","twitter_misc":{"Est. reading time":"13\u00a0Minuten"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/","url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/","name":"RAG with OpenAI, Haystack, and Couchbase Search Vector Index - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/de\/#website"},"datePublished":"2025-12-09T10:13:28+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/#breadcrumb"},"inLanguage":"de","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/openai-haystack-rag-with-search-vector-index\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/ko\/"},{"@type":"ListItem","position":2,"name":"RAG with OpenAI, Haystack, and Couchbase Search Vector Index"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/de\/#website","url":"https:\/\/www.couchbase.com\/de\/","name":"Couchbase","description":"The Operational Data Platform for AI\u2122","publisher":{"@id":"https:\/\/www.couchbase.com\/de\/#organization"},"alternateName":"Couchbase, Inc.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/de\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"de"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/de\/#organization","name":"Couchbase","alternateName":"Couchbase, Inc.","url":"https:\/\/www.couchbase.com\/de\/","logo":{"@type":"ImageObject","inLanguage":"de","@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","contentUrl":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","width":1129,"height":1129,"caption":"Couchbase"},"image":{"@id":"https:\/\/www.couchbase.com\/de\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Couchbase\/","https:\/\/x.com\/couchbase","https:\/\/www.youtube.com\/c\/CouchbaseServer","https:\/\/www.linkedin.com\/company\/couchbase\/","https:\/\/github.com\/couchbase\/","https:\/\/en.wikipedia.org\/wiki\/Couchbase,_Inc."],"description":"Couchbase ist ein in San Jose, Kalifornien, ans\u00e4ssiges Unternehmen f\u00fcr Datenbanksoftware, das eine operative Datenplattform f\u00fcr KI bereitstellt, die von Hunderten von globalen Unternehmen eingesetzt wird.","legalName":"Couchbase, Inc.","foundingDate":"2011-01-01"}]}},"acf":[],"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10302","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials"}],"about":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/types\/tutorials"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10302\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/media?parent=10302"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-languages?post=10302"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-tags?post=10302"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-technologies?post=10302"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-types?post=10302"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}