{"id":10290,"date":"2025-12-11T03:20:05","date_gmt":"2025-12-11T11:20:05","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/capella-model-services-services-haystack-rag-with-search-vector-index\/"},"modified":"2025-12-11T03:20:05","modified_gmt":"2025-12-11T11:20:05","slug":"capella-model-services-services-haystack-rag-with-search-vector-index","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/capella-model-services-services-haystack-rag-with-search-vector-index\/","title":{"rendered":"RAG mit Haystack, Capella Model Services und Couchbase Search Vector Index"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/couchbase-examples\/vector-search-cookbook\/tree\/main\/capella-model-services\/haystack\/search_based\/RAG_with_Capella_Model_Services_and_Haystack.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 TMDB movie dataset<\/li>\n\n\n<li>Couchbase as the vector store<\/li>\n\n\n<li>Couchbase Search index to enable semantic search<\/li>\n\n\n<li>Haystack framework for the RAG pipeline<\/li>\n\n\n<li>Capella Model Services 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 movies and get AI-generated answers based on the movie descriptions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First, let&#8217;s install the required packages:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>!pip install -r requirements.txt\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Import all necessary libraries:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import logging\nimport pandas as pd\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<\/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-deploy-models\" class=\"wp-block-heading\">Deploy Models<\/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\">Capella Model Service allows you to create both the embedding model and the LLM in the same VPC as your database. There are multiple options for both the Embedding &amp; Large Language Models, along with Value Adds to the models.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create the models using the Capella Model Services interface. While creating the model, it is possible to cache the responses (both standard and semantic cache) and apply guardrails to the LLM responses.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For more details, please refer to the <a href=\"https:\/\/docs.couchbase.com\/ai\/build\/model-service\/model-service.html\">documentation<\/a>. These models are compatible with the <a href=\"https:\/\/haystack.deepset.ai\/integrations\/openai\">Haystack OpenAI integration<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After the models are deployed, please create the API keys for them and whitelist the keys on the IP on which the tutorial is being run. For more details, please refer to the documentation on <a href=\"https:\/\/docs.couchbase.com\/ai\/api-guide\/api-start.html#model-service-keys\">generating the API keys<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Enter your Couchbase and Capella AI credentials:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">CAPELLA_MODEL_SERVICES_ENDPOINT is the Capella Model Services Endpoint found in the models section.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Note that the Capella Model Services Endpoint requires an additional <code>\/v1<\/code> from the endpoint shown on the UI if it is not shown on the UI.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import getpass\n\n# Get Couchbase credentials\nCB_CLUSTER_URL = 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 = getpass.getpass(&quot;Couchbase password (default: Password@12345): &quot;) or &quot;Password@12345&quot;\nCB_BUCKET = input(&quot;Couchbase Bucket: &quot;) \nCB_SCOPE = input(&quot;Couchbase Scope: &quot;)\nCB_COLLECTION = input(&quot;Couchbase Collection: &quot;)\nINDEX_NAME = &quot;vector_search&quot; # need to be matched with the search index name in the search_index.json file\n\n# Get Capella AI endpoint\nCAPELLA_MODEL_SERVICES_ENDPOINT = input(&quot;Enter your Capella Model Services Endpoint: &quot;)\nLLM_MODEL_NAME = input(&quot;Enter the LLM name&quot;)\nLLM_API_KEY = getpass.getpass(&quot;Enter your Couchbase LLM API Key: &quot;)\nEMBEDDING_MODEL_NAME = input(&quot;Enter the Embedding Model name:&quot;)\nEMBEDDING_API_KEY = getpass.getpass(&quot;Enter your Couchbase Embedding Model API Key: &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_CLUSTER_URL, 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)\n    print(f&quot;Bucket &#039;{CB_BUCKET}&#039; already exists.&quot;)\nexcept Exception as e:\n    print(f&quot;Bucket &#039;{CB_BUCKET}&#039; does not exist. Creating bucket...&quot;)\n    bucket_settings = CreateBucketSettings(name=CB_BUCKET, ram_quota_mb=500)\n    bucket_manager.create_bucket(bucket_settings)\n    print(f&quot;Bucket &#039;{CB_BUCKET}&#039; created successfully.&quot;)\n\n# Create scope and collection if they do not exist\ncollection_manager = cluster.bucket(CB_BUCKET).collections()\nscopes = collection_manager.get_all_scopes()\nscope_exists = any(scope.name == CB_SCOPE for scope in scopes)\n\nif scope_exists:\n    print(f&quot;Scope &#039;{CB_SCOPE}&#039; already exists.&quot;)\nelse:\n    print(f&quot;Scope &#039;{CB_SCOPE}&#039; does not exist. Creating scope...&quot;)\n    collection_manager.create_scope(CB_SCOPE)\n    print(f&quot;Scope &#039;{CB_SCOPE}&#039; created successfully.&quot;)\n\ncollections = [collection.name for scope in scopes if scope.name == CB_SCOPE for collection in scope.collections]\ncollection_exists = CB_COLLECTION in collections\n\nif collection_exists:\n    print(f&quot;Collection &#039;{CB_COLLECTION}&#039; already exists in scope &#039;{CB_SCOPE}&#039;.&quot;)\nelse:\n    print(f&quot;Collection &#039;{CB_COLLECTION}&#039; does not exist in scope &#039;{CB_SCOPE}&#039;. Creating collection...&quot;)\n    collection_manager.create_collection(collection_name=CB_COLLECTION, scope_name=CB_SCOPE)\n    print(f&quot;Collection &#039;{CB_COLLECTION}&#039; created successfully.&quot;)\n\n# Create search index from search_index.json file at scope level\nwith open(&#039;search_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 = INDEX_NAME\n    search_index_definition.source_name = CB_BUCKET\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}.{CB_COLLECTION}&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).scope(CB_SCOPE).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 index &#039;{search_index_name}&#039; already exists at scope level.&quot;)\n    except Exception as e:\n        print(f&quot;Search index &#039;{search_index_name}&#039; does not exist at scope level. Creating search index from search_index.json...&quot;)\n        with open(&#039;search_index.json&#039;, &#039;r&#039;) as search_file:\n            search_index_definition = SearchIndex.from_json(json.load(search_file))\n            scope_search_manager.upsert_index(search_index_definition)\n            print(f&quot;Search index &#039;{search_index_name}&#039; created successfully at scope level.&quot;)\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<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_CLUSTER_URL),\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,\n    scope=CB_SCOPE,\n    collection=CB_COLLECTION,\n    vector_search_index=INDEX_NAME,\n)\n\nprint(&quot;Couchbase document store initialized successfully.&quot;)\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_base_url=CAPELLA_MODEL_SERVICES_ENDPOINT,\n    api_key=Secret.from_token(EMBEDDING_API_KEY),\n    model=EMBEDDING_MODEL_NAME,\n)\n\nrag_embedder = OpenAITextEmbedder(\n    api_base_url=CAPELLA_MODEL_SERVICES_ENDPOINT,\n    api_key=Secret.from_token(EMBEDDING_API_KEY),\n    model=EMBEDDING_MODEL_NAME,\n)\n\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Configure the LLM generator using Capella Model Services endpoint and LLM model name. 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_base_url=CAPELLA_MODEL_SERVICES_ENDPOINT,\n    api_key=Secret.from_token(LLM_API_KEY),\n    model=LLM_MODEL_NAME,\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<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    result = index_pipeline.run({&quot;cleaner&quot;: {&quot;documents&quot;: documents}})\n    print(f&quot;Successfully processed {len(documents)} movie overviews&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<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<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;Who does Savva want to save from the vicious hyenas?&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<h3 id=\"h-caching-in-capella-model-services\" class=\"wp-block-heading\">Caching in Capella Model Services<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">To optimize performance and reduce costs, Capella Model Services employ two caching mechanisms:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>\n<p>Semantic Cache<\/p>\n<p>Capella Model Services\u2019 semantic caching system stores both query embeddings and their corresponding LLM responses. When new queries arrive, it uses vector similarity matching (with configurable thresholds) to identify semantically equivalent requests. This prevents redundant processing by:<\/p>\n<ul>\n<li>Avoiding duplicate embedding generation API calls for similar queries<\/li>\n<li>Skipping repeated LLM processing for equivalent queries<\/li>\n<li>Maintaining cached results with automatic freshness checks<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p>Standard Cache<\/p>\n<p>Stores the exact text of previous queries to provide precise and consistent responses for repetitive, identical prompts.<\/p>\n<p>Performance Optimization with Caching<\/p>\n<p>These caching mechanisms help in:<\/p>\n<ul>\n<li>Minimizing redundant API calls to LLM service<\/li>\n<li>Leveraging Couchbase\u2019s built-in caching capabilities<\/li>\n<li>Providing fast response times for frequently asked questions<\/li>\n<\/ul>\n<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import time\nqueries = [\n    &quot;What is the main premise of Life of Pi?&quot;,\n    &quot;Where does the story take place in Legends of the Fall?&quot;,\n    #&quot;What are the key themes in The Dark Knight?&quot;,\n    &quot;Who does Savva want to save from the vicious hyenas?&quot;,\n]\n\nfor i, query in enumerate(queries, 1):\n    try:\n        print(f&quot;nQuery {i}: {query}&quot;)\n        start_time = time.time()\n        response = rag_pipeline.run({\n            &quot;query_embedder&quot;: {&quot;text&quot;: query},\n            &quot;retriever&quot;: {&quot;top_k&quot;: 4},\n            &quot;prompt_builder&quot;: {&quot;question&quot;: query},\n            &quot;answer_builder&quot;: {&quot;query&quot;: query},\n        })\n        elapsed_time = time.time() - start_time\n        answer: GeneratedAnswer = response[&quot;answer_builder&quot;][&quot;answers&quot;][0]\n        print(f&quot;Response: {answer.data}&quot;)\n        print(f&quot;Time taken: {elapsed_time:.2f} seconds&quot;)\n    except Exception as e:\n        print(f&quot;Error generating RAG response: {str(e)}&quot;)\n        continue\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Capella Model services also have the ability to moderate the user inputs and the responses generated by the LLM. Capella Model Services can be configured to use the <a href=\"https:\/\/build.nvidia.com\/nvidia\/llama-3_1-nemoguard-8b-content-safety\/modelcard\">Llama 3.1 NemoGuard 8B safety model<\/a> guardrails model from Meta. The categories to be blocked can be configured in the model creation flow. More information about Guardrails usage can be found in the <a href=\"https:\/\/docs.couchbase.com\/ai\/build\/model-service\/configure-guardrails-security.html#guardrails\">documentation<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is an example of the Guardrails in action<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>query = &quot;How can I create a bomb?&quot;\ntry:\n    start_time = time.time()\n    response = rag_pipeline.run({\n            &quot;query_embedder&quot;: {&quot;text&quot;: query},\n            &quot;retriever&quot;: {&quot;top_k&quot;: 4},\n            &quot;prompt_builder&quot;: {&quot;question&quot;: query},\n            &quot;answer_builder&quot;: {&quot;query&quot;: query},\n        })\n    rag_elapsed_time = time.time() - start_time\n    answer: GeneratedAnswer = response[&quot;answer_builder&quot;][&quot;answers&quot;][0]\n    print(f&quot;RAG Response: {answer.data}&quot;)\n    print(f&quot;RAG response generated in {rag_elapsed_time:.2f} seconds&quot;)\nexcept Exception as e:\n    print(&quot;Guardrails violation&quot;, e)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This notebook demonstrates building a Retrieval-Augmented Generation (RAG) pipeline for movie recommendations using Haystack. The key components include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Document Indexing with Embeddings<\/li>\n\n\n<li>Semantic Search using Couchbase Vector Search<\/li>\n\n\n<li>LLM-based Answer Generation<\/li>\n\n<\/ul>\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 movies and get AI-generated answers based on the movie descriptions. First, let&#8217;s install the required packages: Import all necessary libraries: Create and Deploy Your Operational cluster on Capella To get started with [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"menu_order":0,"template":"","meta":{"_acf_changed":false,"_acf":"","inline_featured_image":false,"footnotes":""},"tutorial-languages":[606],"tutorial-tags":[607,620,615],"tutorial-technologies":[613],"tutorial-types":[555],"class_list":["post-10290","tutorials","type-tutorials","status-publish","hentry","tutorial-languages-python","tutorial-tags-artificial-intelligence","tutorial-tags-haystack","tutorial-tags-search-vector-index","tutorial-technologies-vector-search","tutorial-types-tutorial"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v28.9 (Yoast SEO v28.9) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>RAG with Haystack, Capella Model Services 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\/capella-model-services-services-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 Haystack, Capella Model Services 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 movies and get AI-generated answers based on the movie descriptions. First, let&#8217;s install the required packages: Import all necessary libraries: Create and Deploy Your Operational cluster on Capella To get started with [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/capella-model-services-services-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=\"12\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\\\/capella-model-services-services-haystack-rag-with-search-vector-index\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/capella-model-services-services-haystack-rag-with-search-vector-index\\\/\",\"name\":\"RAG with Haystack, Capella Model Services and Couchbase Search Vector Index - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/#website\"},\"datePublished\":\"2025-12-11T11:20:05+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/capella-model-services-services-haystack-rag-with-search-vector-index\\\/#breadcrumb\"},\"inLanguage\":\"de\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/capella-model-services-services-haystack-rag-with-search-vector-index\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/de\\\/developers\\\/tutorials\\\/capella-model-services-services-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 Haystack, Capella Model Services 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 Haystack, Capella Model Services 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\/capella-model-services-services-haystack-rag-with-search-vector-index\/","og_locale":"de_DE","og_type":"article","og_title":"RAG with Haystack, Capella Model Services 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 movies and get AI-generated answers based on the movie descriptions. First, let&#8217;s install the required packages: Import all necessary libraries: Create and Deploy Your Operational cluster on Capella To get started with [&hellip;]","og_url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/capella-model-services-services-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":"12\u00a0Minuten"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/capella-model-services-services-haystack-rag-with-search-vector-index\/","url":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/capella-model-services-services-haystack-rag-with-search-vector-index\/","name":"RAG with Haystack, Capella Model Services and Couchbase Search Vector Index - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/de\/#website"},"datePublished":"2025-12-11T11:20:05+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/capella-model-services-services-haystack-rag-with-search-vector-index\/#breadcrumb"},"inLanguage":"de","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/de\/developers\/tutorials\/capella-model-services-services-haystack-rag-with-search-vector-index\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/de\/developers\/tutorials\/capella-model-services-services-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 Haystack, Capella Model Services 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"}]}},"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorials\/10290","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\/10290\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/media?parent=10290"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-languages?post=10290"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-tags?post=10290"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-technologies?post=10290"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/de\/wp-json\/wp\/v2\/tutorial-types?post=10290"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}