Docs Menu
Docs Home
/
Atlas
/ /

Haystack 統合を使い始める

MongoDB ベクトル検索 Haystack と統合すると、 LM でカスタム アプリケーションを構築し、検索拡張生成 (RAG)(RAG)を実装できます。このチュートリアルでは、Haystack とMongoDB ベクトル検索 の使用を開始して、データに対してセマンティック検索を実行し、RAG実装を構築する方法を説明します。具体的には、次のアクションを実行します。

  1. 環境を設定します。

  2. MongoDB ベクトル検索インデックスを作成します。

  3. カスタム データをMongoDBに保存します。

  4. MongoDB ベクトル検索を使用してデータの質問に答え、RAG を実装します。

このチュートリアルの実行可能なバージョンをPythonノートとして操作します。

Haystack は、LDM、埋め込みモデル、ベクトル検索を使用してカスタム アプリケーションを構築するためのフレームワークです。MongoDB ベクトル検索 をHaystack と統合することで、 MongoDB をベクトルデータベースとして使用し、 MongoDB ベクトル検索を使用してセマンティックで類似したドキュメントを検索して RG を実装できます。RG の詳細については、MongoDBを使用した 検索拡張生成(RAG) を参照してください。

Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。

このチュートリアルの環境を設定します。 .ipynb 拡張子を持つファイルを保存して、インタラクティブPythonノートを作成します。 このノートはPythonコード スニペットを個別に実行でき、このチュートリアルのコードを実行するために使用します。

ノートク環境を設定するには、次の手順に従います。

1
  1. 次のコマンドを実行します:

    pip install --quiet --upgrade mongodb-atlas-haystack voyage-embedders-haystack pymongo
  2. 必要なパッケージをインポートするには、次のコードを実行します。

    import os
    from haystack import Pipeline, Document
    from haystack.document_stores.types import DuplicatePolicy
    from haystack.components.writers import DocumentWriter
    from haystack.components.generators import OpenAIGenerator
    from haystack.components.builders.prompt_builder import PromptBuilder
    from haystack_integrations.components.embedders.voyage_embedders import VoyageDocumentEmbedder, VoyageTextEmbedder
    from haystack_integrations.document_stores.mongodb_atlas import MongoDBAtlasDocumentStore
    from haystack_integrations.components.retrievers.mongodb_atlas import MongoDBAtlasEmbeddingRetriever
    from pymongo import MongoClient
    from pymongo.operations import SearchIndexModel
2

次のコードを実行し、プレースホルダーを次の値に置き換えます。

  • あなたの 投票AI APIキー

  • OpenAI API キー。

  • MongoDBクラスターの接続文字列。

os.environ["VOYAGE_API_KEY"] = "<voyage-api-key>"
os.environ["OPENAI_API_KEY"] = "<openai-api-key>"
os.environ["MONGO_CONNECTION_STRING"]= "<connection-string>"

注意

<connection-string> を Atlas クラスターまたはローカル Atlas 配置の接続文字列に置き換えます。

接続stringには、次の形式を使用する必要があります。

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

接続stringには、次の形式を使用する必要があります。

mongodb://localhost:<port-number>/?directConnection=true

詳細については、「接続文字列 」を参照してください。

このセクションでは、カスタム データを保存するための haystack_dbデータベースと testコレクションを作成します。次に、データに対してベクトル検索クエリを有効にするには、 MongoDB ベクトル検索インデックスを作成します。

1
client = MongoClient(os.environ.get("MONGO_CONNECTION_STRING"))
2

次のコードを実行して、 haystack_dbデータベースとtestコレクションを作成します。

# Create your database and collection
db_name = "haystack_db"
collection_name = "test"
database = client[db_name]
database.create_collection(collection_name)
# Define collection
collection = client[db_name][collection_name]
3

次のコードを実行して、vectorSearch タイプのインデックスを作成します。embeddingフィールドには、Voyage AI の voyage-3-large 埋め込みモデルを使用して作成する埋め込みが含まれます。インデックス定義では、1024ベクトル次元を指定し、cosine を使用して類似性を測定します。

# Create your index model, then create the search index
search_index_model = SearchIndexModel(
definition={
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 1024,
"similarity": "cosine"
}
]
},
name="vector_index",
type="vectorSearch"
)
collection.create_search_index(model=search_index_model)

インデックスの構築には約 1 分かかります。 構築中、インデックスは最初の同期状態になります。 構築が完了したら、コレクション内のデータのクエリを開始できます。

このセクションでは、 MongoDB をドキュメントストア とも呼ばれるベクトルデータベースとしてインスタンス化します。次に、カスタム データからベクトル埋め込みを作成し、これらのドキュメントをMongoDBのコレクションに保存します。次のコード スニペットをノートに貼り付けて実行します。

1

次のコードを実行して、Atlas をドキュメント ストアとしてインスタンス化します。 このコードは、Atlas クラスターへの接続を確立し、次の項目を指定します。

  • haystack_db ドキュメントの保存に使用される Atlas データベースとコレクションであるtestと :

  • vector_index セマンティック検索クエリを実行するために使用されるインデックス。

document_store = MongoDBAtlasDocumentStore(
database_name="haystack_db",
collection_name="test",
vector_search_index="vector_index",
full_text_search_index="search_index" # Declared but not used in this example
)
2

このコードは、いくつかのサンプルドキュメントを定義し、次のコンポーネントでパイプラインを実行します。

# Create some example documents
documents = [
Document(content="My name is Jean and I live in Paris."),
Document(content="My name is Mark and I live in Berlin."),
Document(content="My name is Giorgio and I live in Rome."),
]
# Initializing a document embedder to convert text content into vectorized form.
doc_embedder = VoyageDocumentEmbedder()
# Setting up a document writer to handle the insertion of documents into the MongoDB collection.
doc_writer = DocumentWriter(document_store=document_store, policy=DuplicatePolicy.SKIP)
# Creating a pipeline for indexing documents. The pipeline includes embedding and writing documents.
indexing_pipe = Pipeline()
indexing_pipe.add_component(instance=doc_embedder, name="doc_embedder")
indexing_pipe.add_component(instance=doc_writer, name="doc_writer")
# Connecting the components of the pipeline for document flow.
indexing_pipe.connect("doc_embedder.documents", "doc_writer.documents")
# Running the pipeline with the list of documents to index them in MongoDB.
indexing_pipe.run({"doc_embedder": {"documents": documents}})
Calculating embeddings: 100%|██████████| 1/1 [00:00<00:00, 4.42it/s]
{'doc_embedder': {'meta': {'total_tokens': 32}},
'doc_writer': {'documents_written': 3}}

Tip

このセクションでは、 MongoDB ベクトル検索と Haystack を使用してアプリケーションに RG を実装する方法を説明します。

次のコードは、次のコンポーネントを含むパイプラインを定義して実行します。

この例では、サンプルクエリ Where does Mark live? を使用して LM をプロンプト表示します。 LM は、Atlas に保存したカスタム データから正確でコンテキストを認識する応答を生成します。

# Template for generating prompts for a movie recommendation engine.
prompt_template = """
You are an assistant allowed to use the following context documents.\nDocuments:
{% for doc in documents %}
{{ doc.content }}
{% endfor %}
\nQuery: {{query}}
\nAnswer:
"""
# Setting up a retrieval-augmented generation (RAG) pipeline for generating responses.
rag_pipeline = Pipeline()
rag_pipeline.add_component("text_embedder", VoyageTextEmbedder())
# Adding a component for retrieving related documents from MongoDB based on the query embedding.
rag_pipeline.add_component(instance=MongoDBAtlasEmbeddingRetriever(document_store=document_store,top_k=15), name="retriever")
# Building prompts based on retrieved documents to be used for generating responses.
rag_pipeline.add_component("prompt_builder", PromptBuilder(template=prompt_template, required_variables=["query", "documents"]))
# Adding a language model generator to produce the final text output.
rag_pipeline.add_component("llm", OpenAIGenerator())
# Connecting the components of the RAG pipeline to ensure proper data flow.
rag_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
rag_pipeline.connect("retriever", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder", "llm")
# Run the pipeline
query = "Where does Mark live?"
result = rag_pipeline.run(
{
"text_embedder": {"text": query},
"prompt_builder": {"query": query},
});
print(result['llm']['replies'][0])
Mark lives in Berlin.

Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。

このチュートリアルの環境を設定します。 .ipynb 拡張機能のファイルを保存して、インタラクティブPythonノートを作成します。 このノートはPythonコード スニペットを個別に実行でき、このチュートリアルのコードを実行するために使用します。

ノートク環境を設定するには、次の手順に従います。

1
  1. 次のコマンドを実行します:

    pip install --quiet --upgrade mongodb-atlas-haystack pymongo
  2. 必要なパッケージをインポートするには、次のコードを実行します。

    import os
    from haystack import Pipeline, Document
    from haystack.document_stores.types import DuplicatePolicy
    from haystack.components.writers import DocumentWriter
    from haystack.components.generators import OpenAIGenerator
    from haystack.components.builders.prompt_builder import PromptBuilder
    from haystack.components.embedders import OpenAITextEmbedder, OpenAIDocumentEmbedder
    from haystack_integrations.document_stores.mongodb_atlas import MongoDBAtlasDocumentStore
    from haystack_integrations.components.retrievers.mongodb_atlas import MongoDBAtlasEmbeddingRetriever
    from pymongo import MongoClient
    from pymongo.operations import SearchIndexModel
2

次のコードを実行し、プレースホルダーを次の値に置き換えます。

  • OpenAI API キー。

  • MongoDBクラスターの接続文字列。

os.environ["OPENAI_API_KEY"] = "<api-key>"
os.environ["MONGO_CONNECTION_STRING"]= "<connection-string>"

注意

<connection-string> を Atlas クラスターまたはローカル Atlas 配置の接続文字列に置き換えます。

接続stringには、次の形式を使用する必要があります。

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

詳しくは、ドライバーを使用してクラスターに接続する を参照してください。

接続stringには、次の形式を使用する必要があります。

mongodb://localhost:<port-number>/?directConnection=true

詳細については、「接続文字列 」を参照してください。

このセクションでは、カスタム データを保存するための haystack_dbデータベースと testコレクションを作成します。次に、データに対してベクトル検索クエリを有効にするには、 MongoDB ベクトル検索インデックスを作成します。

1
client = MongoClient(os.environ.get("MONGO_CONNECTION_STRING"))
2

次のコードを実行して、 haystack_dbデータベースとtestコレクションを作成します。

# Create your database and collection
db_name = "haystack_db"
collection_name = "test"
database = client[db_name]
database.create_collection(collection_name)
# Define collection
collection = client[db_name][collection_name]
3

次のコードを実行して、 vectorSearchタイプのインデックスを作成します。 embeddingフィールドには、OpenAI のtext-embedding-ada-002埋め込みモデルを使用して作成する埋め込みが含まれます。 インデックス定義では、 1536ベクトル次元を指定し、 cosineを使用して類似性を測定します。

# Create your index model, then create the search index
search_index_model = SearchIndexModel(
definition={
"fields": [
{
"type": "vector",
"path": "embedding",
"numDimensions": 1536,
"similarity": "cosine"
}
]
},
name="vector_index",
type="vectorSearch"
)
collection.create_search_index(model=search_index_model)

インデックスの構築には約 1 分かかります。 構築中、インデックスは最初の同期状態になります。 構築が完了したら、コレクション内のデータのクエリを開始できます。

このセクションでは、 MongoDB をドキュメントストア とも呼ばれるベクトルデータベースとしてインスタンス化します。次に、カスタム データからベクトル埋め込みを作成し、これらのドキュメントをMongoDBのコレクションに保存します。次のコード スニペットをノートに貼り付けて実行します。

1

次のコードを実行して、Atlas をドキュメント ストアとしてインスタンス化します。 このコードは、Atlas クラスターへの接続を確立し、次の項目を指定します。

  • haystack_db ドキュメントの保存に使用される Atlas データベースとコレクションであるtestと :

  • vector_index セマンティック検索クエリを実行するために使用されるインデックス。

document_store = MongoDBAtlasDocumentStore(
database_name="haystack_db",
collection_name="test",
vector_search_index="vector_index",
full_text_search_index="search_index" # Declared but not used in this example
)
2

このコードは、いくつかのサンプルドキュメントを定義し、次のコンポーネントでパイプラインを実行します。

# Create some example documents
documents = [
Document(content="My name is Jean and I live in Paris."),
Document(content="My name is Mark and I live in Berlin."),
Document(content="My name is Giorgio and I live in Rome."),
]
# Initializing a document embedder to convert text content into vectorized form.
doc_embedder = OpenAIDocumentEmbedder()
# Setting up a document writer to handle the insertion of documents into the MongoDB collection.
doc_writer = DocumentWriter(document_store=document_store, policy=DuplicatePolicy.SKIP)
# Creating a pipeline for indexing documents. The pipeline includes embedding and writing documents.
indexing_pipe = Pipeline()
indexing_pipe.add_component(instance=doc_embedder, name="doc_embedder")
indexing_pipe.add_component(instance=doc_writer, name="doc_writer")
# Connecting the components of the pipeline for document flow.
indexing_pipe.connect("doc_embedder.documents", "doc_writer.documents")
# Running the pipeline with the list of documents to index them in MongoDB.
indexing_pipe.run({"doc_embedder": {"documents": documents}})
Calculating embeddings: 100%|██████████| 1/1 [00:00<00:00, 4.16it/s]
{'doc_embedder': {'meta': {'model': 'text-embedding-ada-002',
'usage': {'prompt_tokens': 32, 'total_tokens': 32}}},
'doc_writer': {'documents_written': 3}}

このセクションでは、 MongoDB ベクトル検索と Haystack を使用してアプリケーションに RG を実装する方法を説明します。

次のコードは、次のコンポーネントを含むパイプラインを定義して実行します。

この例では、サンプルクエリ Where does Mark live? を使用して LM をプロンプト表示します。 LM は、Atlas に保存したカスタム データから正確でコンテキストを認識する応答を生成します。

# Template for generating prompts for a movie recommendation engine.
prompt_template = """
You are an assistant allowed to use the following context documents.\nDocuments:
{% for doc in documents %}
{{ doc.content }}
{% endfor %}
\nQuery: {{query}}
\nAnswer:
"""
# Setting up a retrieval-augmented generation (RAG) pipeline for generating responses.
rag_pipeline = Pipeline()
rag_pipeline.add_component("text_embedder", OpenAITextEmbedder())
# Adding a component for retrieving related documents from MongoDB based on the query embedding.
rag_pipeline.add_component(instance=MongoDBAtlasEmbeddingRetriever(document_store=document_store,top_k=15), name="retriever")
# Building prompts based on retrieved documents to be used for generating responses.
rag_pipeline.add_component("prompt_builder", PromptBuilder(template=prompt_template, required_variables=["query", "documents"]))
# Adding a language model generator to produce the final text output.
rag_pipeline.add_component("llm", OpenAIGenerator())
# Connecting the components of the RAG pipeline to ensure proper data flow.
rag_pipeline.connect("text_embedder.embedding", "retriever.query_embedding")
rag_pipeline.connect("retriever", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder", "llm")
# Run the pipeline
query = "Where does Mark live?"
result = rag_pipeline.run(
{
"text_embedder": {"text": query},
"prompt_builder": {"query": query},
});
print(result['llm']['replies'][0])
Mark lives in Berlin.

MongoDBは、次の開発者リソースも提供しています。

戻る

C# 統合

項目一覧