Build PDF Chat App With Haystack, OpenAI and Couchbase Hyperscale Vector Index

  • Construct a PDF Chat App with Haystack, Couchbase Hyperscale Vector Index, and Streamlit.
  • Learn to upload PDFs into Couchbase Vector Store with Haystack.
  • Discover how to use RAG’s for context-based Q&A’s from PDFs with LLMs.

はじめに

Welcome to this comprehensive guide on constructing an AI-enhanced Chat Application using Couchbase’s Hyperscale Vector Index. We will create a dynamic chat interface capable of delving into PDF documents to extract and provide summaries, key facts, and answers to your queries. By the end of this tutorial, you’ll have a powerful tool at your disposal, transforming the way you interact with and utilize the information contained within PDFs.

Choosing Between Hyperscale and Composite Vector Indexes

Couchbase supports multiple types of vector indexes for different use cases. This tutorial uses ハイパースケール・ベクトル・インデックス, but you should be aware of the alternatives:

ハイパースケール・ベクトル・インデックス (used in this tutorial):

  • ベストなもの pure vector similarity search at massive scale
  • Optimized for RAG and chatbot applications
  • Handles billions of documents with sub-second query latency
  • Ideal when you need fast semantic search without metadata filtering

複合ベクトルインデックス:

  • ベストなもの vector search with metadata filtering
  • Combines vector fields with scalar fields (e.g., date, category, user_id)
  • Enables pre-filtering before vector search for more efficient queries
  • Ideal when you need to filter documents by attributes before semantic search
  • Example use case: “Find similar documents from last month” or “Search within user’s documents”

検索ベクトルインデックス:

  • ベストなもの ハイブリッド検索 combining keywords, geospatial, and semantic search
  • Flexible full-text search combined with vector similarity
  • Complex filtering using FTS queries
  • Compatible with Couchbase 7.6+

For this PDF chat demo, we use Hyperscale Vector Index for optimal performance in pure RAG applications. If your use case requires filtering by metadata (e.g., searching only in specific user’s documents, or documents from a certain date range), consider using Composite Vector Index instead.

To learn more about choosing the right vector index, refer to the official Couchbase vector index documentation.

このチュートリアルでは、以下の手順を説明します:

  • Create a Couchbase Hyperscale Vector Index for high-performance Vector Search.
  • Chunk PDFをベクトルに変換する Haystack そして、使用する Couchbase Vector Store ベクターをCouchbaseに格納します。.
  • Use large language models via the RAGフレームワーク コンテクストに基づく洞察を得るために、 OpenAI for generating Embeddings and querying the LLM.
  • Automatically create Hyperscale vector index after document upload.
  • Use a Streamlit interface to see it working in action. All these components come together to create a seamless, AI-powered chat experience.

前提条件

  • パイソン 3.10以上がインストールされています。.
  • Python のバージョンが 互換性あり Couchbase SDK を使用して。.
  • Couchbase Cluster (Self Managed or Capella) version 8.0+. Hyperscale Vector Index is recommended for Couchbase 8.0+.
  • Streamlit installed via pip install streamlit.

Note that this tutorial is designed to work with the latest Couchbase-haystack SDK version (2.1.0+). It will not work with the older versions.

Important: This tutorial uses Hyperscale vector index, which are optimized for high-performance vector search at scale. For Couchbase 7.6+, consider using the Search Vector Index based approach instead.

クイックスタートガイド:

Clone Repo

git clone https://github.com/couchbase-examples/haystack-demo.git

依存関係のインストール

依存関係はすべて pip, Pythonのデフォルトのパッケージマネージャです。 仮想環境 私も。.

python -m pip install -r requirements.txt

データベース設定のセットアップ

キャペラ設定

Capella クラスターへの接続について詳しくは、こちらをご覧ください。 説明書.

具体的には、以下の手順を実行する必要があります:

自己管理型セットアップ

バケットを作成する

  • For this tutorial, we will use a specific bucket, scope, and collection. However, you may use any name of your choice but make sure to update names in all the steps.
  • 「bucket」という名前のバケットを作成する sample-bucket. 私たちはそれを利用します pdf_data 範囲と pdf_chunks このバケツのコレクション。.

Automatic Hyperscale Vector Index Creation

Good news! The application automatically creates the Hyperscale vector index after you upload your first PDF. This is because Hyperscale indexes require training data (documents with embeddings) to be created successfully.

The application will:

  1. Upload and process your PDF documents
  2. Generate embeddings for document chunks
  3. Store the documents with embeddings in Couchbase
  4. Automatically create the Hyperscale vector index using SQL++

No manual index creation required! The index is created with the following configuration:

CREATE VECTOR INDEX idx_<collection_name>_vector
ON <bucket_name>.<scope_name>.<collection_name>(embedding VECTOR) 
WITH {
  "dimension": 1536,
  "similarity": "DOT"
}
Index Parameters
  • Vector field: 埋め込み with 1536 dimensions (matching OpenAI’s text-embedding-ada-002/003 models)
  • Similarity metric: DOT for dot product similarity (optimized for OpenAI embeddings)

The application uses CouchbaseQueryDocumentStore which leverages SQL++ queries with the APPROX_VECTOR_DISTANCE() function for fast approximate nearest neighbor (ANN) search.

注記: If automatic creation fails, the application will attempt to create the index on first query as a fallback. If you prefer manual control, you can create the index yourself using the SQL++ query above after uploading documents.

Alternative: Using Composite Vector Index

If your application needs to filter documents by metadata before performing vector search, you can use a 複合ベクトルインデックス instead. The same code works with minimal changes!

Creating a Composite Vector Index:

CREATE INDEX idx_<collection_name>_composite 
ON <bucket_name>.<scope_name>.<collection_name>(embedding VECTOR) 
WITH {
  "dimension": 1536,
  "similarity": "DOT"
}

Key Difference: Notice the keyword is INDEX (not VECTOR INDEX). Composite indexes combine vector fields with other scalar fields.

When to Use Composite Vector Index:

  • You need to filter by metadata (e.g., user_id, date, category) before vector search
  • Example: “Find similar documents uploaded by user X in the last 30 days”
  • Enables efficient pre-filtering to reduce the search space

Code Compatibility: The same CouchbaseQueryDocumentStore and application code works with both Hyperscale and Composite indexes! The only difference is:

  1. The SQL++ statement used to create the index
  2. How you query it (Composite allows WHERE clauses for filtering)

To learn more about Composite Vector Indexes, refer to the official documentation.

セットアップ環境設定

コピーする secrets.example.toml ファイルイン .strimlath folder and rename it to secrets.toml and replace the placeholders with the actual values for your environment. All configuration for communication with the database is read from the environment variables.

DB_CONN_STR = "<couchbase_cluster_connection_string>"
DB_USERNAME = "<couchbase_username>"
DB_PASSWORD = "<couchbase_password>"
DB_BUCKET = "<bucket_name>"
DB_SCOPE = "<scope_name>"
DB_COLLECTION = "<collection_name>"
OPENAI_API_KEY = "<openai_api_key>"

OpenAI 埋め込み生成やLLMのクエリに使用するには、APIキーが必要です。.

について 接続文字列 期待しています couchbases:// または couchbase:// パート。.

このチュートリアルのために、, DB_BUCKET = sample-bucket, DB_SCOPE = pdf_data, DB_COLLECTION = pdf_chunks.

アプリケーションの実行

After starting Couchbase server and installing dependencies, our application is ready to run. The application will automatically create the scope and collection on startup.

プロジェクトのルートディレクトリで、以下のコマンドを実行してください。

streamlit run chat_with_pdf_with_query_vector_index.py

このアプリケーションはローカルマシン上で実行されます。 http://localhost:8501.

Important: Upload a PDF first! The Hyperscale vector index will be automatically created after you upload and process your first PDF document. The index creation requires training data (documents with embeddings) to work properly.

PDFチャットアプリの使い方

左側のサイドバーには、このPDFチャットアプリで使用するPDFドキュメントをアップロードするオプションがあります。PDFのサイズによっては、アップロードプロセスに時間がかかる場合があります。.

Main Screen Default View

メインエリアにはチャット画面があり、アップロードされたPDFに関する質問をすることができます。2つの回答を受け取ります:一つはPDFの文脈に基づいた回答(Couchbaseロゴ – couchbase ) 、また PDF コンテキストのないもの(Bot Logo – 🤖)。これにより、Retrieval Augmented Generation(RAG)モデルが、PDF コンテンツを利用して言語モデルが提供する回答をどのように強化しているかが示されます。.

Main Screen With Message View

コンセプト

PDF Chat アプリケーションは、2 つの強力なコンセプトを活用しています。 検索拡張生成(RAG) そして ベクトル検索. これらの技術を組み合わせることで、PDFドキュメントとの効率的かつコンテキスト認識型の相互作用が可能になります。.

検索拡張生成(RAG)

RAGは2人のヘルパーがいるようなものです:

  • レトリバーこのヘルパーは、質問やプロンプトに基づいて最も関連性の高い情報を検索するために、すべてのPDFドキュメントを調べます。.
  • ジェネレーターこのヘルパーは、自然言語を理解し、人間のような応答を生成できる大規模な言語モデル(例:GPT-4、Gemini)のようなものです。.

RAGの仕組みは以下の通りです:

  • アプリに質問をしたり、指示を出したりします。.
  • Retriever ヘルパーは PDF ドキュメントを調べ、Vector Search を使用して質問に関連する最も関連性の高い箇所やセクションを見つけます。.
  • Generator ヘルパーは、関連する部分とお客様の元の質問を組み合わせて、明確で文脈的な回答を生成します。.

これにより、PDFの文脈が強化され、LLMは一般的な結果を提供するのではなく、PDFから関連する結果を提供できるようになります。.

Vector Search with Couchbase Hyperscale

Couchbase is a NoSQL database that provides a powerful Hyperscale Vector Search capability. It allows you to store and search through high-dimensional vector representations (embeddings) of textual data at massive scale.

The PDF Chat app uses Haystack to convert the text from the PDF documents into embeddings. These embeddings are then stored in a Couchbase bucket, along with the corresponding text.

ユーザーが質問をしたり、プロンプトを入力すると:

  • The app converts the user’s query into an embedding using Haystack’s embedding models (e.g., OpenAI’s embeddings).
  • Couchbase’s Hyperscale Vector Index is utilized for high-performance vector search. The Hyperscale index is automatically created for the PDF embeddings and their corresponding text content.
  • The app queries this index using SQL++ with the APPROX_VECTOR_DISTANCE() function and the user’s query embedding. Couchbase’s Hyperscale Vector Search calculates the 類似性 (e.g., dot product) between the query embedding and the indexed PDF embeddings using approximate nearest neighbor (ANN) search, enabling ultra-fast retrieval.
  • 最も近い隣接エンベディングは、ユーザーのクエリと比較して、PDFドキュメントの最も意味的な類似する文章またはセクションを表します。.
  • このアプリは、これらの近隣の類似物エンベディングに関連するテキストコンテンツを取得し、関連する応答の生成に必要なコンテキストを提供します。.
  • Couchbase’s Hyperscale Vector Index is optimized for:
    • Massive scale: Billions of documents with sub-second query latency
    • Pure vector search: Optimized specifically for RAG and semantic search applications
    • SQL++ integration: Leverage familiar SQL++ syntax for vector queries
  • The Hyperscale index facilitates fast and accurate retrieval at scale, enabling the app to provide context-aware and relevant responses to the user’s queries, even when the phrasing or terminology differs from the PDF content.
  • Couchbase’s Hyperscale Vector Search integrates seamlessly with Haystack’s CouchbaseQueryDocumentStore ベクトル類似計算の複雑さを抽象化することで、クラスを作成します。.

Haystack

Haystack is a powerful library that simplifies the process of building applications with 大規模言語モデル (LLMs)やCouchbaseのようなベクトルストア。.

In the PDF Chat app, Haystack is used for several tasks:

  • PDFドキュメントの読み込みと処理: Haystack’s PyPDFToDocument component can convert PDF files into Haystack Document objects, which can hold various types of content, including text, metadata, and embeddings.
  • Text preprocessing: Haystack’s DocumentCleaner removes unwanted characters and formatting from the extracted text, while DocumentSplitter splits the text from the PDF documents into smaller chunks or passages, which are more suitable for embedding and retrieval.
  • ジェネレーションの組み込み: Haystack’s OpenAIDocumentEmbedder そして OpenAITextEmbedder components convert text into vector embeddings using OpenAI’s embedding models, enabling semantic search capabilities.
  • Text generation: Haystack’s OpenAIGenerator component interfaces with OpenAI’s language models to generate human-like responses based on the retrieved context and user queries.
  • Document storage: Haystack’s DocumentWriter component handles the storage of processed documents and their embeddings into the vector store.
  • ベクトルストアの統合: Haystack provides a CouchbaseDocumentStore CouchbaseのVector Searchとシームレスに統合され、アプリがエンベディングとその対応するテキストを保存して検索できるクラスです。.
  • Pipelines: Haystack uses Pipelines to combine different components for various tasks. In this app, we have an indexing pipeline for processing and storing documents, and a RAG pipeline for retrieval and generation.
  • Prompt Building: Haystack’s PromptBuilder component allows you to create custom prompts that guide the language model’s behavior and output.
  • Answer Building: Haystack’s AnswerBuilder component structures the final response by combining the generated text with metadata and source information.

By combining Vector Search with Couchbase, RAG, and Haystack, the PDF Chat app can efficiently ingest PDF documents, convert their content into searchable embeddings, retrieve relevant information based on user queries and conversation context, and generate context-aware and informative responses using large language models.

流れを理解しよう

このチュートリアルの開始にあたり、リポジトリをクローンし、お好きなIDEで開いてください。これでPDFチャットアプリの作成方法を学習できます。全体のコードは以下の通りです。 chat_with_pdf_with_query_vector_index.py ファイル。.

アプリフロー

このアプリケーションの基本的なワークフローは以下のとおりです。ユーザーはメインページのサイドバーから、PDFファイルをアップロードすることでプロセスを開始します。このアクションにより、 save_to_vector_store この関数は、その後PDFをCouchbaseのベクトルストアにアップロードします。その後、ユーザーはLLMとチャットできるようになります。.

チャットエリアでは、ユーザーは質問を投稿できます。これらの質問はChat APIによって処理され、LLMがRAGが提供するコンテキストを参考に回答を検索します。アシスタントは回答を送信し、ユーザーは追加の質問をすることができます。.

App Flow

Couchbaseへの接続

The first step is connecting to Couchbase. Couchbase Hyperscale Vector Search is required for PDF Upload as well as during chat (For Retrieval). We will use the Haystack CouchbaseQueryDocumentStore to connect to the Couchbase cluster with Hyperscale vector search support. The connection is established in the get_document_store 関数です。.

注記: The same CouchbaseQueryDocumentStore configuration works with both ハイパースケール そして 複合材料 vector indexes! You only need to change the SQL++ statement when creating the index.

接続文字列と認証情報は環境変数から読み取られます。環境変数が設定されていない場合に、いくつかの基本的な必要なチェックを実行します。 secrets.toml, 、そしてCouchbaseクラスタに接続していきます。クラスタへの接続は 接続する メソッド。.

from couchbase_haystack import (
    CouchbaseQueryDocumentStore,
    CouchbasePasswordAuthenticator,
    CouchbaseClusterOptions,
    QueryVectorSearchType,
    QueryVectorSearchSimilarity,
    CouchbaseQueryOptions
)
from couchbase.n1ql import QueryScanConsistency
from datetime import timedelta

@st.cache_resource(show_spinner="Connecting to Vector Store")
def get_document_store():
    """Return the Couchbase document store using CouchbaseQueryDocumentStore."""
    return CouchbaseQueryDocumentStore(
        cluster_connection_string=Secret.from_env_var("DB_CONN_STR"),
        authenticator=CouchbasePasswordAuthenticator(
            username=Secret.from_env_var("DB_USERNAME"),
            password=Secret.from_env_var("DB_PASSWORD")
        ),
        cluster_options=CouchbaseClusterOptions(profile='wan_development'),
        bucket=os.getenv("DB_BUCKET"),
        scope=os.getenv("DB_SCOPE"),
        collection=os.getenv("DB_COLLECTION"),
        search_type=QueryVectorSearchType.ANN,
        similarity=QueryVectorSearchSimilarity.DOT,
        nprobes=10,
        query_options=CouchbaseQueryOptions(
            timeout=timedelta(seconds=60),
            scan_consistency=QueryScanConsistency.NOT_BOUNDED
        )
    )

We will define the bucket, scope, and collection names from 環境変数.

Configuration Parameters:

  • search_type=QueryVectorSearchType.ANN: Uses approximate nearest neighbor search for fast retrieval
  • similarity=QueryVectorSearchSimilarity.DOT: Uses dot product similarity (optimized for OpenAI embeddings)
  • nprobes=10: Controls the search accuracy/speed tradeoff (higher = more accurate but slower)
  • query_options: Configures query timeout and consistency settings

Initialize Couchbase Vector Store

We will now initialize the CouchbaseQueryDocumentStore which will be used for storing and retrieving document embeddings.

# Initialize document store
document_store = get_document_store()

PDFのアップロードとインジェスト

について save_to_vector_store function takes care of uploading the PDF file in vector format to the Couchbase Database using the Haystack indexing pipeline. It converts the PDF to documents, cleans them, splits text into small chunks, generates embeddings for those chunks, and ingests the chunks and their embeddings into the Couchbase vector store.

PDFのアップロード

このコードのこの部分では、Streamlit ライブラリを使用してサイドバーにファイルアップローダーを作成します。PDF がアップロードされたら、, save_to_vector_store この関数は PDF の処理をさらに進めるために呼び出されます。.

with st.form("upload pdf"):
    uploaded_file = st.file_uploader("Choose a PDF.", help="The document will be deleted after one hour of inactivity (TTL).", type="pdf")
    submitted = st.form_submit_button("Upload")
    if submitted:
        save_to_vector_store(uploaded_file, indexing_pipeline)

Read, Load, and Process Uploaded PDF

について save_to_vector_store function ensures that the uploaded PDF file is properly handled, loaded, and prepared for storage in the vector store. It first checks if a file was actually uploaded. Then the uploaded file is saved to a temporary file.

The indexing pipeline takes care of converting the PDF to documents, cleaning them, splitting them into chunks, generating embeddings, and storing them in the Couchbase vector store.

def save_to_vector_store(uploaded_file, indexing_pipeline):
    """Process the PDF & store it in Couchbase Vector Store"""
    if uploaded_file is not None:
        temp_dir = tempfile.TemporaryDirectory()
        temp_file_path = os.path.join(temp_dir.name, uploaded_file.name)
        
        with open(temp_file_path, "wb") as f:
            f.write(uploaded_file.getvalue())
        result = indexing_pipeline.run({"converter": {"sources": [temp_file_path]}})
        
        st.info(f"PDF loaded into vector store: {result['writer']['documents_written']} documents indexed")

Indexing Pipeline

The indexing pipeline is created to handle the entire process of ingesting PDFs into the vector store. It includes the following components:

  1. PyPDFToDocument: Converts PDF files to Haystack Document objects.
  2. DocumentCleaner: Cleans the extracted text from the PDF.
  3. DocumentSplitter: Splits the cleaned text into smaller chunks.
  4. OpenAIDocumentEmbedder: Generates embeddings for the document chunks.
  5. DocumentWriter: Writes the processed documents and their embeddings to the Couchbase vector store.
from haystack import Pipeline
from haystack.components.converters import PyPDFToDocument
from haystack.components.preprocessors import DocumentCleaner, DocumentSplitter
from haystack.components.embedders import OpenAIDocumentEmbedder, OpenAITextEmbedder
from haystack.components.generators import OpenAIGenerator
from haystack.components.builders import PromptBuilder, AnswerBuilder
from haystack.components.writers import DocumentWriter

indexing_pipeline = Pipeline()
indexing_pipeline.add_component("converter", PyPDFToDocument())
indexing_pipeline.add_component("cleaner", DocumentCleaner())
indexing_pipeline.add_component("splitter", DocumentSplitter(split_by="word", split_length=250, split_overlap=50))
indexing_pipeline.add_component("embedder", OpenAIDocumentEmbedder())
indexing_pipeline.add_component("writer", DocumentWriter(document_store=document_store))

indexing_pipeline.connect("converter.documents", "cleaner.documents")
indexing_pipeline.connect("cleaner.documents", "splitter.documents")
indexing_pipeline.connect("splitter.documents", "embedder.documents")
indexing_pipeline.connect("embedder.documents", "writer.documents")

After the documents are written to Couchbase, the application automatically creates the Hyperscale vector index using SQL++.

PDFでチャット

PDFファイルをCouchbaseにアップロードした後、CouchbaseのVector Search、RAG、LLMの力を活用して、質問に対するコンテキストに基づいた回答を得ることができます。ユーザーが質問をすると、アシスタント(LLM)はRAGコンテキストを使ってアシスタントに呼び出され、アシスタントからの回答がユーザーに送り返されます。.

RAG Pipeline

We create a RAG (Retrieval-Augmented Generation) pipeline using Haystack components. This pipeline handles the entire process of retrieving relevant context from the vector store and generating responses using the LLM.

The OpenAIGenerator is a crucial component in our RAG pipeline, responsible for generating human-like responses based on the retrieved context and user questions. Here’s a more detailed explanation of its configuration and role:

  • API Key: The OpenAIGenerator uses the OPENAI_API_KEY from the environment variables to authenticate with the OpenAI API.
  • Model: It’s configured to use the “gpt-5” model, which is a powerful language model capable of understanding context and generating coherent, relevant responses.
  • Role in the Pipeline: The OpenAIGenerator receives a prompt constructed by the PromptBuilder, which includes the user’s question and relevant context retrieved from the vector store. It then generates a response based on this input.
  • Integration: The generator’s output is connected to the AnswerBuilder component, which formats the final response for display to the user.

By using the OpenAIGenerator, we leverage state-of-the-art natural language processing capabilities to provide accurate, context-aware answers to user queries about the uploaded PDF content.

from haystack.components.embedders import OpenAITextEmbedder
from couchbase_haystack import CouchbaseQueryEmbeddingRetriever
from haystack.components.builders import PromptBuilder, AnswerBuilder

rag_pipeline = Pipeline()
rag_pipeline.add_component("query_embedder", OpenAITextEmbedder())
rag_pipeline.add_component("retriever", CouchbaseQueryEmbeddingRetriever(document_store=document_store))
rag_pipeline.add_component("prompt_builder", PromptBuilder(template="""
You are a helpful bot. If you cannot answer based on the context provided, respond with a generic answer. Answer the question as truthfully as possible using the context below:
{% for doc in documents %}
    {{ doc.content }}
{% endfor %}

Question: {{question}}
"""))
rag_pipeline.add_component(
    "llm",
    OpenAIGenerator(
        api_key=OPENAI_API_KEY,
        model="gpt-5",
    ),
)
rag_pipeline.add_component("answer_builder", AnswerBuilder())

rag_pipeline.connect("query_embedder", "retriever.query_embedding")
rag_pipeline.connect("retriever.documents", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder.prompt", "llm.prompt")
rag_pipeline.connect("llm.replies", "answer_builder.replies")
rag_pipeline.connect("llm.meta", "answer_builder.meta")
rag_pipeline.connect("retriever", "answer_builder.documents")

Key Point: We use CouchbaseQueryEmbeddingRetriever which queries the Hyperscale vector index using SQL++ with the APPROX_VECTOR_DISTANCE() 関数です。.

ユーザーが質問をします

このセクションでは、ユーザーがアップロードされたPDFに基づいて質問をすることが可能なインタラクティブなチャットインターフェースを作成します。主な手順は以下のとおりです。

  1. 「PDFに基づいて質問する」というメッセージとともにチャット入力ボックスを表示します。.
  2. ユーザーが質問を投稿するとき:
    • Display the user’s question in the chat interface.
    • ユーザーの質問をチャット履歴に追加します。.
    • Run the RAG pipeline to generate a response.
    • Display the response in the chat interface.
    • Add the assistant’s response to the chat history.
if question := st.chat_input("Ask a question based on the PDF"):
    st.chat_message("user").markdown(question)
    st.session_state.messages.append({"role": "user", "content": question, "avatar": "👤"})

    # RAG response
    with st.chat_message("assistant", avatar=couchbase_logo):
        message_placeholder = st.empty()
        rag_result = rag_pipeline.run(
            {
                "query_embedder": {"text": question},
                "retriever": {"top_k": 3},
                "prompt_builder": {"question": question},
                "answer_builder": {"query": question},
            }
        )
        rag_response = rag_result["answer_builder"]["answers"][0].data
        message_placeholder.markdown(rag_response)
    st.session_state.messages.append({"role": "assistant", "content": rag_response, "avatar": couchbase_logo})

This setup allows users to have a conversational experience, asking questions related to the uploaded PDF, with responses generated by the RAG pipeline. Both the user’s questions and the assistant’s responses are displayed in the chat interface, along with their respective roles and avatars.

文脈のないストリーム回答

先ほどのセクションと同様に、ユーザーの質問に対する回答もLLMから得られます。ここからの回答はUIにも表示され、RAGを使用することでより良いコンテキストを活用した結果が得られるという違いを明確にします。.

# stream the response from the pure LLM

# Add placeholder for streaming the response
    with st.chat_message("ai", avatar="🤖"):
        message_placeholder_pure_llm = st.empty()
        pure_llm_result = rag_pipeline.run(
            {
                "prompt_builder": {"question": question},
                "llm": {},
                "answer_builder": {"query": question},
                "query_embedder": {"text": question}
            }
        )
        pure_llm_response = pure_llm_result["answer_builder"]["answers"][0].data
        message_placeholder_pure_llm.markdown(pure_llm_response)
    st.session_state.messages.append({"role": "assistant", "content": pure_llm_response, "avatar": "🤖"})

結論

Congratulations! You’ve successfully built a PDF Chat application using Couchbase Hyperscale Vector Index, Haystack, and OpenAI. This application demonstrates the power of combining high-performance vector search with large language models to create an intelligent, context-aware chat interface for PDF documents.

Through this tutorial, you’ve learned how to:

  1. Set up a Couchbase cluster with Hyperscale vector search capabilities.
  2. Use Haystack to process and index PDF documents.
  3. Implement a Retrieval-Augmented Generation (RAG) pipeline.
  4. Create an interactive chat interface using Streamlit.
  5. Compare responses from RAG and pure LLM approaches.

We hope this tutorial has given you a solid foundation for building AI-powered document interaction systems with Couchbase Hyperscale Vector Index and Haystack. Happy coding!

データベースの膨大なサイズを過去のものとしておく

スタックの追加ごとに新たな請求書が発生し、管理するものがさらに増えます。2分でどれだけの節約ができるかを試算してください。.