はじめに
Welcome to this comprehensive guide on constructing an AI-enhanced Chat Application using Couchbase Vector Search. 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.
This tutorial uses Query Based Vector Search with Couchbase’s Query Service and Hyperscale/Composite Vector Indexes. If you are looking for Vector Search using the Search service (formerly known as Full Text Search), refer to this tutorial むしろ。.
このチュートリアルでは、以下の手順を説明します。
- Utilize Couchbase Vector Search with Query Service and Hyperscale/Composite Vector Indexes for doing Vector Search.
- Chunk PDFをベクトルに変換する ラングチェーン そして、使用する Couchbase Query Vector Store ベクターをCouchbaseに格納します。.
- 大規模な言語モデルを RAGフレームワーク コンテクストに基づく洞察を得るために、 OpenAI 埋め込みモデルとLLMの生成のため。.
- StreamlitでエレガントなUIを作成しましょう。これらのコンポーネントすべてを組み合わせることで、シームレスでAIを活用したチャット体験が実現します。.
前提条件
- パイソン 3.10以上がインストールされています。.
- Python のバージョンが 互換性あり Couchbase SDK を使用して。.
- Couchbase Cluster (Self Managed or Capella) version 8.0+ with クエリーサービス
このチュートリアルは、Couchbase 用の最新の Python SDK バージョン (4.2.0+) で動作するように設計されています。古い Python SDK バージョンでは動作しません。.
Couchbase Vector Search with Query Service is only supported at Couchbase Version 8.0+.
クイックスタートガイド:
Clone Repo
git clone https://github.com/couchbase-examples/rag-demo.git
依存関係のインストール
依存関係はすべて pip, Pythonのデフォルトのパッケージマネージャです。 仮想環境 私も。.
python -m pip install -r requirements.txt
データベース設定のセットアップ
キャペラ設定
Capella クラスターへの接続について詳しくは、こちらをご覧ください。 説明書.
具体的には、以下の手順を実行する必要があります:
- Create the データベース認証情報 SDK を介してクラスタにアクセスするには
- アクセス許可を許可する アプリケーションが実行されている IP からのクラスタへの接続です。.
自己管理型セットアップ
- フォロー Couchbaseのインストールオプション for installing the latest Couchbase Database Server Instance.
バケットを作成する
- このチュートリアルの目的で、特定のバケット、スコープ、コレクションを使用します。ただし、任意の名前を使用できますが、すべての手順で名前を更新するようにしてください。.
- 「bucket」という名前のバケットを作成する
pdf-chat. 私たちはそれを利用します_default範囲と_defaultこのバケツのコレクション。.
Create Vector Index (Optional)
While the application works without creating indexes manually, you can optionally create a vector index for better performance after uploading PDFs.
Understanding Vector Index Types
Couchbase offers different types of vector indexes for Vector Search:
ハイパースケール・ベクトル・インデックス
- Best for pure vector searches – content discovery, recommendations, semantic search
- High performance with low memory footprint – designed to scale to billions of vectors
- Optimized for concurrent operations – supports simultaneous searches and inserts
- Use when: You primarily perform vector-only queries without complex scalar filtering
- Ideal for: Large-scale semantic search, recommendation systems, content discovery
複合ベクトルインデックス
- Best for filtered vector searches – combines vector search with scalar value filtering
- Efficient pre-filtering – scalar attributes reduce the vector comparison scope
- Use when: Your queries combine vector similarity with scalar filters that eliminate large portions of data
- Ideal for: Compliance-based filtering, user-specific searches, time-bounded queries
Choosing the Right Index Type
- Start with Hyperscale Vector Index for pure vector searches and large datasets
- Use Composite Vector Index when scalar filters significantly reduce your search space
- Consider your dataset size: Hyperscale scales to billions, Composite works well for tens of millions to billions
詳細については、こちらをご覧ください。 Couchbase Vector Index documentation.
Creating Vector Index Programmatically
You can create the index programmatically after uploading your PDFs:
from langchain_couchbase.vectorstores import IndexType
# Create a vector index on the collection
vector_store.create_index(
index_name="idx_vector",
dimension=1536,
similarity="cosine",
index_type=IndexType.BHIVE, # or IndexType.COMPOSITE
index_description="IVF,SQ8"
)
For more details on the create_index() method, see the LangChain Couchbase API documentation.
Understanding Index Configuration Parameters:
について index_description parameter controls how Couchbase optimizes vector storage and search performance:
フォーマット IVF[],{PQ|SQ}
Centroids (IVF – Inverted File):
- より高速な検索のためにデータセットをどのように分割するかを制御します。
- より多くの中心点 = より高速な検索、より遅い学習
- Fewer centroids = slower search, faster training
- 省略された場合(例えば
IVF、SQ8( ), Couchbaseはデータセットのサイズに基づいて自動的に選択します
Quantization Options:
- SQ (Scalar Quantization):
SQ4,SQ6,SQ8(次元ごとに4ビット、6ビット、または8ビット) - PQ (Product Quantization):
PQx(例:,PQ32x8) - 値が高いほど精度が高く、インデックスサイズも大きくなります。
Common Examples:
IVF、SQ8– 自動中心点、8ビットのスカララル量子化(デフォルトは良好)IVF1000、SQ6– 1000 個の中心点、6 ビットのスカララル量子化IVF,PQ32x8– 自動中心点、8ビットの32サブ量子化器
詳細な設定オプションについては、 量子化と中心点の設定.
注: In Couchbase Vector Search, the distance represents the vector distance between the query and document embeddings. Lower distance indicates higher similarity, while higher distance indicates lower similarity. This demo uses cosine similarity for measuring document similarity.
セットアップ環境設定
コピーする secrets.example.toml ファイルイン .strimlath フォルダーを作成し、secrets.toml に名前を変更し、プレースホルダーを環境の実際の値に置き換えます。データベースとの通信用のすべての設定は環境変数から読み取られます。.
OPENAI_API_KEY = "<open_ai_api_key>"
DB_CONN_STR = "<connection_string_for_couchbase_cluster>"
DB_USERNAME = "<username_for_couchbase_cluster>"
DB_PASSWORD = "<password_for_couchbase_cluster>"
DB_BUCKET = "<name_of_bucket_to_store_documents>"
DB_SCOPE = "<name_of_scope_to_store_documents>"
DB_COLLECTION = "<name_of_collection_to_store_documents>"
CACHE_COLLECTION = "<name_of_collection_to_cache_llm_responses>"
AUTH_ENABLED = "False"
LOGIN_PASSWORD = "<password to access the streamlit app>"
OpenAI 埋め込み生成やLLMのクエリに使用するには、APIキーが必要です。.
について 接続文字列 期待しています
couchbases://またはcouchbase://パート。.
このチュートリアルのために、,
DB_BUCKET = pdf-chat,DB_SCOPE = _default,DB_COLLECTION = _default.
Note: Unlike the Search service based approach, this method does NOT require
INDEX_NAMEas vector indexes are optional and automatically used when available.
Login_Passwordof Streamlit app is a basic password to access the app. You can set the password here and while using the app, password will be required to access the app.
アプリケーションの実行
After starting Couchbase server and installing dependencies. Our Application is ready to run.
プロジェクトのルートディレクトリで、以下のコマンドを実行してください。
streamlit run chat_with_pdf_query.py
このアプリケーションはローカルマシン上で実行されます。 http://localhost:8501.
PDFチャットアプリの使い方
このページはログインパスワードを入力するためのテキストボックスから始まります。これは、先に定義したパスワードと同じものです。 セットアップ環境設定 セクション。パスワードの入力後、メインのアプリケーションページが開きます。.
左側のサイドバーには、このPDFチャットアプリで使用するPDFドキュメントをアップロードするオプションがあります。PDFのサイズによっては、アップロードプロセスに時間がかかる場合があります。.

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

コンセプト
The PDF Chat application leverages three powerful concepts: 検索拡張生成(RAG), Couchbase Vector Searchそして LLM Response Caching. これらの技術を組み合わせることで、PDFドキュメントとの効率的かつコンテキスト認識型の相互作用が可能になります。.
検索拡張生成(RAG)
RAGは2人のヘルパーがいるようなものです:
- レトリバーこのヘルパーは、質問やプロンプトに基づいて最も関連性の高い情報を検索するために、すべてのPDFドキュメントを調べます。.
- ジェネレーターこのヘルパーは、自然言語を理解し、人間のような応答を生成できる大規模な言語モデル(例:GPT-4、Gemini)のようなものです。.
RAGの仕組みは以下の通りです:
- アプリに質問をしたり、指示を出したりします。.
- Retriever ヘルパーは PDF ドキュメントを調べ、Vector Search を使用して質問に関連する最も関連性の高い箇所やセクションを見つけます。.
- Generator ヘルパーは、関連する部分とお客様の元の質問を組み合わせて、明確で文脈的な回答を生成します。.
これにより、PDFの文脈が強化され、LLMは一般的な結果を提供するのではなく、PDFから関連する結果を提供できるようになります。.
Vector Search with Couchbase Query Service
Couchbase is a NoSQL database that provides a powerful Vector Search capability using the Query Service. It allows you to store and search through high-dimensional vector representations (embeddings) of textual data, such as PDF content, using SQL++ queries.
PDF Chat アプリは LangChain を使用して、PDF ドキュメントのテキストをエンベディングに変換します。これらのエンベディングは、対応するテキストとともに Couchbase のバケットに保存されます。.
ユーザーが質問をしたり、プロンプトを入力すると:
- The app converts the user’s query into an embedding using LangChain’s embedding models (e.g., OpenAI’s embeddings).
- Couchbaseのベクトル検索 capability is utilized, which supports Hyperscale and Composite Vector Indexes built on the Global Secondary Index (GSI) infrastructure.
- The app performs a vector search using SQL++ queries with cosine similarity distance metric. This is done through the
CouchbaseQueryVectorStorewhich leverages Couchbase’s native query capabilities. - The vector search calculates the 類似性 (cosine distance) between the query embedding and the indexed PDF embeddings, enabling fast retrieval of the nearest neighbor embeddings.
- 最も近い隣接エンベディングは、ユーザーのクエリと比較して、PDFドキュメントの最も意味的な類似する文章またはセクションを表します。.
- このアプリは、これらの近隣の類似物エンベディングに関連するテキストコンテンツを取得し、関連する応答の生成に必要なコンテキストを提供します。.
- Couchbase’s Vector Search with Query Service offers several advantages:
- Hyperscale Vector Indexes (BHIVE): Optimized for pure vector searches with high performance and low memory footprint, designed to scale to billions of vectors
- 複合ベクトルインデックス: Efficient for filtered vector searches combining vector similarity with scalar value filtering
- SQL++ Integration: Seamlessly integrates vector search with traditional database queries
- Auto-scaling: Automatically scales to handle large datasets without manual intervention
- The Query Service facilitates fast and accurate retrieval, 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のVector SearchはLangChainとシームレスに統合されています。 CouchbaseQueryVectorStore ベクトル類似計算の複雑さを抽象化することで、クラスを作成します。.
LLM Response Caching with Couchbase
To optimize performance and reduce costs, the application implements LLM response caching using CouchbaseCache:
- Automatic Caching: All LLM responses are automatically cached in a designated Couchbase collection
- Cost Savings: Repeated identical queries retrieve results from the cache instead of making expensive API calls to the LLM provider
- Time Efficiency: Cached responses are returned instantly, significantly reducing response time for repeated queries
- Seamless Integration: LangChain’s caching layer works transparently with the RAG chain
When a user asks a question:
- The system first checks if an identical query has been asked before
- If found in cache, the stored response is returned immediately
- If not found, the LLM is queried, and the response is cached for future use
- The cache persists across application restarts, providing long-term benefits
This caching mechanism is particularly valuable in production environments where:
- Users frequently ask similar questions
- Cost optimization is critical due to high API usage
- Low latency responses improve user experience
ラングチェーン
LangChain は、アプリケーションの構築プロセスを簡素化する強力なライブラリです。 大規模言語モデル (LLMs)やCouchbaseのようなベクトルストア。.
PDF Chat アプリでは、LangChain を複数のタスクに使用しています:
- PDFドキュメントの読み込みと処理: LangChain の PDFLoader PDFファイルを読み込んで、テキスト文書に変換します。.
- テキストの分割: LangChain の RecursiveCharacterTextSplitter PDFドキュメントのテキストをより小さい部分や段に分割するために使用されます。これらは埋め込みや検索に最適です。.
- ジェネレーションの組み込みLangChainは以下の連携に対応しています。 様々な埋め込みモデル, such as OpenAI’s embeddings, to convert the text chunks into embeddings.
- ベクトルストアの統合LangChainは以下の機能を提供します。 CouchbaseQueryVectorStore class that seamlessly integrates with Couchbase’s Vector Search using Query Service, allowing the app to store and search through the embeddings and their corresponding text.
- チェーンLangChainは様々な機能を提供します。 チェーン 異なる要件に合わせて使用します。RAGコンセプトを使用するには、以下の要件が必要です。 リターチ・チェーン 検索および 質問応答チェーン Generationパートのために追加します。 プロンプト これらはすべて組み合わされて、言語モデルの動作と出力の方向性を決める。これらすべてを組み合わせることで、ユーザーの質問から得られる出力が生成される。.
- ストリーミング出力LangChainはサポートしています ストリーミング, これにより、アプリは生成された回答をクライアントにリアルタイムでストリーミングできます。.
- キャッシング: LangChain の caching layer integrates with Couchbase to cache LLM responses, reducing costs and improving response times.
By combining Vector Search with Couchbase Query Service, RAG, LLM Caching, and LangChain, 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, cache LLM responses for repeated queries, and generate context-aware and informative responses using large language models. This approach provides users with a powerful and intuitive way to explore and interact with large PDF files.
流れを理解しよう
このチュートリアルの開始にあたり、リポジトリをクローンし、お好きなIDEで開いてください。これでPDFチャットアプリの作成方法を学習できます。全体のコードは以下の通りです。 chat_with_pdf_query.py ファイル。.
アプリフロー
このアプリケーションの基本的なワークフローは以下のとおりです。ユーザーはメインページのサイドバーから、PDFファイルをアップロードすることでプロセスを開始します。このアクションにより、 save_to_vector_store この関数は、その後PDFをCouchbaseのベクトルストアにアップロードします。その後、ユーザーはLLMとチャットできるようになります。.
チャットエリアでは、ユーザーは質問を投稿できます。これらの質問はChat APIによって処理され、LLMがRAGが提供するコンテキストを参考に回答を検索します。アシスタントは回答を送信し、ユーザーは追加の質問をすることができます。.

Couchbaseへの接続
最初のステップはCouchbaseへの接続です。Couchbase Vector SearchはPDFのアップロードにもチャット中の検索にも必要です。(検索には)。Couchbase Python SDKを使用してCouchbaseクラスタに接続します。接続は以下の手順で確立されます。 connect_to_couchbase 関数です。.
接続文字列と認証情報は環境変数から読み取られます。環境変数が設定されていない場合に、いくつかの基本的な必要なチェックを実行します。 secrets.toml, 、そしてCouchbaseクラスタに接続していきます。クラスタへの接続は 接続する メソッド。.
def connect_to_couchbase(connection_string, db_username, db_password):
"""Connect to Couchbase"""
from couchbase.cluster import Cluster
from couchbase.auth import PasswordAuthenticator
from couchbase.options import ClusterOptions
from datetime import timedelta
auth = PasswordAuthenticator(db_username, db_password)
options = ClusterOptions(auth)
cluster = Cluster(connection_string, options)
# Wait until the cluster is ready for use.
cluster.wait_until_ready(timedelta(seconds=5))
return cluster
Initialize OpenAI and Couchbase Vector Store
今、初期化を行います OpenAI embeddings which will be used by CouchbaseQueryVectorStore for converting the split docs defined above to vectors (embeddings).
また、Couchbase ベクターストアをCouchbase バケット情報で初期化します。まず、Couchbase クラスターに接続します。 connect_to_couchbase メソッド。.
We will define the bucket, scope, and collection names from 環境変数.
from langchain_couchbase.vectorstores import DistanceStrategy
# Use OpenAI Embeddings
embedding = OpenAIEmbeddings()
# Connect to Couchbase Vector Store
cluster = connect_to_couchbase(DB_CONN_STR, DB_USERNAME, DB_PASSWORD)
vector_store = get_vector_store(
cluster,
DB_BUCKET,
DB_SCOPE,
DB_COLLECTION,
embedding,
distance_strategy=DistanceStrategy.COSINE,
)
私たちは以下を使用しています get_vector_store LangChain の初期化方法 CouchbaseQueryVectorStore
def get_vector_store(
_cluster,
db_bucket,
db_scope,
db_collection,
_embedding,
distance_strategy: DistanceStrategy,
):
"""Return the Couchbase vector store"""
vector_store = CouchbaseQueryVectorStore(
cluster=_cluster,
bucket_name=db_bucket,
scope_name=db_scope,
collection_name=db_collection,
embedding=_embedding,
distance_metric=distance_strategy,
)
return vector_store
注: について
DistanceStrategyenum fromlangchain_couchbase.vectorstoresprovides different distance metrics for vector similarity:COSINE,EUCLIDEAN_DISTANCEそしてDOT_PRODUCT. In this tutorial, we useCOSINEsimilarity which measures the cosine of the angle between two vectors.
PDFのアップロードとインジェスト
save_to_vector_store function takes care of uploading the PDF file in vector format to Couchbase Database using CouchbaseQueryVectorStore in LangChain. It splits text into small chunks, generate embeddings for those chunks, and ingest the chunks and their embeddings into a Couchbase vector store. Let’s go step by step on how it does.
PDFのアップロード
このコードのこの部分では、Streamlit ライブラリを使用してサイドバーにファイルアップローダーを作成します。PDF がアップロードされたら、, save_to_vector_store この関数は PDF の処理をさらに進めるために呼び出されます。.
「St.Form(「upload pdf」)」で
uploaded_file = st.file_uploader(
「PDF を選択してください。」
help="無活動状態(TTL)が1時間経過すると、このドキュメントは削除されます。"
type="pdf",
)
送信 = st.form_submit_button("Upload")
提出された場合:
# chunking を実行した後に PDF をベクトルストアに保存する
save_to_vector_store(アップロードされたファイル、ベクトルストア)
読み取りとアップロードされたPDFの読み込み
この関数は、アップロードされた PDF ファイルが適切に処理され、ベクターストアでの保存または処理のためにロードおよび準備されることを保証します。まず、ファイルが実際にアップロードされたかどうかを確認します。その後、アップロードされたファイルが一時ファイルに保存されます。 バイナリ フォーマット。.
一時ファイルから PDF が読み込まれます。 PyPDFLoader PDFを読み込むための LangChain ライブラリから LangChain ドキュメント フォーマット
def save_to_vector_store(uploaded_file, vector_store):
"""Chunk 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())
loader = PyPDFLoader(temp_file_path)
docs = loader.load()
Split Documents
This LangChain document array will contain huge individual files which defeats the purpose while retrieval as we want to send more relevant context to LLM. So we will split it into smaller chunks or passages using LangChain’s RecursiveCharacterTextSplitter:
- chunk_size: 1500: This parameter specifies that each chunk should contain approximately 1500 characters.
- chunk_overlap: 150: This parameter ensures that there is an overlap of 150 characters between consecutive chunks. This overlap helps maintain context and prevent important information from being split across chunk boundaries.
At the end split_documents method splits the large document into smaller LangChain documents based on above defined parameters.
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1500, chunk_overlap=150
)
doc_pages = text_splitter.split_documents(docs)
ドキュメントをベクターストアに追加する
作成したベクトルストアを利用します。 Initialize OpenAI and Couchbase Vector Store. In this we will add the documents using add_documents method of Couchbase vector store. This method will utilize the OpenAI embeddings to create embeddings(vectors) from text and add it to Couchbase documents in the specified collection.
vector_store.add_documents(doc_pages)
The documents are stored in Couchbase with the following structure:
テキスト: The text content of the chunk埋め込み: The vector embedding of the text (1536 dimensions for OpenAI embeddings)メタデータ: Additional metadata from the PDF (page numbers, source file, etc.)
PDFでチャット
After uploading the PDF into Couchbase, we are now ready to utilize the power of Couchbase Vector Search with Query Service, RAG and LLM to get context based answers to our questions. When the user asks a question. The assistant (LLM) is called here with RAG context, the response from the assistant is sent back to the user.
ランカイン式言語(LCEL)
We will now utilize the power of LangChain Chains using the LangChain Expression Language (LCEL). LCEL makes it easy to build complex chains from basic components, and supports out of the box functionality such as streaming, parallelism, and logging.
LCELは、LangChainでの作業にいくつかの重要な利点をもたらすドメイン固有の言語です。
- 可組込み性:これにより、リトリバー、言語モデル、出力パーサーなどのさまざまなLangChainコンポーネントを簡単に組み合わせて、複雑なワークフローを作成できます。.
- 読みやすさ:構文は簡潔かつ表現力豊かであるため、チェーンやシーケンス内の操作の流れを理解しやすくします。.
- 再利用性:より大きなチェーンに組み込むことができる再利用可能なサブチェーンやコンポーネントを定義することで、コードの再利用とモジュール性を促進できます。.
要約すると、LCELは、LangChainコンポーネントを複雑なワークフローに組み込むための、構成可能で読みやすい、再利用可能、拡張可能、型安全で抽象化された方法を提供することで、高度な自然言語処理アプリケーションの構築プロセスを合理化します。.
今後数セクションでLCELチェーンを使用していきます。それによってLCELが私たちのワークフロー全体を最適化してくれるのか見ていきます。.
リトリーブチェーンを作成する
私たちはまた、 レトリバー couchbase ベクターストアの機能です。このリトリガーは、現在のクエリと類似する以前に追加されたドキュメントを取得するために使用されます。.
retriever = vector_store.as_retriever()
The retriever uses Couchbase’s Vector Search with Query Service to perform similarity searches using SQL++ queries. It calculates the cosine distance between the query embedding and document embeddings to find the most relevant chunks.
プロンプトチェーン
A prompt for a language model is a set of instructions or input provided by a user to guide the model’s response, helping it understand the context and generate relevant and coherent language-based output, such as answering questions, completing sentences, or engaging in a conversation. We will use a template and create a prompt chain using ChatPromptTemplate LangChainのクラス
template = """あなたは役に立つボットです。提供された文脈に基づいて回答できない場合は、一般的な回答で対応してください。以下の文脈を用いて、質問にできるだけ真実で回答してください:
{context}
質問:『 {question}』
prompt = ChatPromptTemplate.from_template(template)
LLM Chain
大規模言語モデル(LLM)は LangChain の基盤です。LangChain は独自の LLM を提供するのではなく、多くの LLM との相互作用のための標準的なインターフェースを提供します。具体的には、このインターフェースは文字列を入力として受け取り、文字列を返します。我々はこれを利用します。 ChatOpenAI LLM Model. We can also set other parameters like model, API_KEY, temperature to be used for this model.
# Use OpenAI GPT 4 as the LLM for the RAG
llm = ChatOpenAI(temperature=0, model="gpt-4-1106-preview", streaming=True)
単一のチェーンに結合する
これらの異なるモジュールを単一のチェーンに結合することで、同期的に動作させることができます。これらのコンポーネントを接続するためにパイプオペレータ(|)が使用され、操作の連鎖が形成されます。.
The input dictionary with the “context” and “question” keys is passed through each component. The retriever component retrieves relevant information from the vector store using Couchbase Vector Search, which is then combined with the 質問 プロンプトを生成します。このプロンプトは言語モデル(LLM)に渡され、質問と取得されたコンテキストの両方に基づいて応答が生成されます。最後に、出力は以下の形式で解析されます。 StrOutputParser().
# RAGチェーン
チェーン = (
{"context": retriever, "question": RunnablePassthrough()}
|プロンプト
LLM
| StrOutputParser()
)
RAGなしのチェーン
上記のプロセスを繰り返しますが、この場合、ベクトルストアからのコンテキストは含まれません。基本的に、ユーザーの質問から直接LLMを呼び出します。基本的に、すべてのステップは同じですが、リトリーブを使用しないだけです。.
template_without_rag = """You are a helpful bot. Answer the question as truthfully as possible.
Question: {question}"""
prompt_without_rag = ChatPromptTemplate.from_template(template_without_rag)
llm_without_rag = ChatOpenAI(model="gpt-4-1106-preview", streaming=True)
chain_without_rag = (
{"question": RunnablePassthrough()}
| prompt_without_rag
| llm_without_rag
| StrOutputParser()
)
ユーザーが質問をします
このセクションでは、ユーザーがアップロードされたPDFに基づいて質問をすることが可能なインタラクティブなチャットインターフェースを作成します。主な手順は以下のとおりです。
- Display a chat input box with the prompt “Ask a question based on the PDF”. When the user submits a question:
- チャット画面にユーザーの質問を表示する
- ユーザーの質問をチャット履歴に追加します。.
- アシスタントの応答をストリーミングするためのプレースホルダーを作成します。.
- Use the chain.invoke(question) method to generate the response from the RAG chain.
- The response is automatically cached by the CouchbaseCache layer.
- ストリーム the response in real-time using the custom
stream_string関数です。. - 最終的なアシスタントの応答をチャット履歴に追加します。.
この設定により、ユーザーはアップロードされたPDFに関連する質問をRAGチェーンによって生成された回答とともにチャット画面上で会話形式でやり取りできます。ユーザーの質問とアシスタントの回答は、それぞれ役割とアバターとともにチャット画面に表示されます。.
# React to user input
if question := st.chat_input("Ask a question based on the PDF"):
# Display user message in chat message container
st.chat_message("user").markdown(question)
# Add user message to chat history
st.session_state.messages.append(
{"role": "user", "content": question, "avatar": "👤"}
)
# Add placeholder for streaming the response
with st.chat_message("assistant", avatar=couchbase_logo):
# Get the response from the RAG & stream it
# In order to cache the response, we need to invoke the chain and cache the response locally
# as OpenAI does not support streaming from cache yet
# Ref: https://github.com/langchain-ai/langchain/issues/9762
rag_response = chain.invoke(question)
st.write_stream(stream_string(rag_response))
st.session_state.messages.append(
{
"role": "assistant",
"content": rag_response,
"avatar": couchbase_logo,
}
)
Note that we use chain.invoke() instead of chain.stream() to enable caching. The custom stream_string function simulates streaming for a better user experience, even when the response is retrieved from the cache.
文脈のないストリーム回答
先ほどのセクションと同様に、ユーザーの質問に対する回答もLLMから得られます。ここからの回答はUIにも表示され、RAGを使用することでより良いコンテキストを活用した結果が得られるという違いを明確にします。.
# Get the response from the pure LLM & stream it
pure_llm_response = chain_without_rag.invoke(question)
# Add placeholder for streaming the response
with st.chat_message("ai", avatar="🤖"):
st.write_stream(stream_string(pure_llm_response))
st.session_state.messages.append(
{
"role": "assistant",
"content": pure_llm_response,
"avatar": "🤖",
}
)