ホームページ >テクノロジー周辺機器 >AI >ヘイスタックフレームワークを使用してエージェントQAラグシステムを構築する方法
製品に関する質問に答える必要があるカスタマーサポートAIを構築していると想像してください。ドキュメントから情報を取得する必要がある場合もあれば、最新の更新をWebで検索する必要がある場合もあります。エージェントRAGシステムは、このようなタイプの複雑なAIアプリケーションで役立ちます。それらは、あなたの内部ドキュメントを知っているだけでなく、Webを検索する時期を決定するスマートな研究助手と考えてください。このガイドでは、Haystackフレームワークを使用してエージェントQAラグシステムを構築するプロセスを進めます。
学習目標データサイエンスブログの一部として公開されました。 目次 エージェントLLMとは何ですか?ブロックコンポーネント
従来のRAGシステムは線形プロセスに従います。 クエリが受信されると、システムは最初にリクエスト内の重要な要素を識別します。次に、知識ベースを検索し、正確な応答を設計するのに役立つ関連情報をスキャンします。関連する情報またはデータが取得されると、システムはそれを処理して意味のあるコンテキストに関連する応答を生成します。
以下の図でプロセスを簡単に理解できます。さて、エージェントRAGシステムは次のようにこのプロセスを強化します
クエリ要件の評価
複数の知識ソース間を決定
HayStackを使用して何を構築できますか?
堅牢な取得と生成のテクニックを使用して、データをぼろぼろに進めるのは簡単です。
GPT-4、llama3.2、deepseek-r1。などの最新のGenaiモデルを使用するチャットボットとエージェント混合型(画像、テキスト、オーディオ、テーブル)の生成マルチモーダルの質問回答システム)知識ベース。
ドキュメントからの情報抽出または知識グラフの構築。
コンポーネントは、Haystackのコアビルディングブロックです。ドキュメントの保存、ドキュメントの検索、テキスト生成、埋め込みなどのタスクを実行できます。 Haystackには、インストール後に直接使用できるコンポーネントがたくさんあります。また、Pythonクラスを作成して独自のコンポーネントを作成するためのAPIも提供します。
パートナー企業とコミュニティからの統合のコレクションがあります。
ライブラリをインストールし、ollama を設定します
$ pip install haystack-ai ollama-haystack # On you system download Ollama and install LLM ollama pull llama3.2:3b ollama pull nomic-embed-text # And then start ollama server ollama serve
いくつかのコンポーネントをインポート
from haystack import Document, Pipeline from haystack.components.builders.prompt_builder import PromptBuilder from haystack.components.retrievers.in_memory import InMemoryBM25Retriever from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.generators.ollama import OllamaGeneratorドキュメントとドキュメントストアを作成します
document_store = InMemoryDocumentStore() documents = [ Document( content="Naruto Uzumaki is a ninja from the Hidden Leaf Village and aspires to become Hokage." ), Document( content="Luffy is the captain of the Straw Hat Pirates and dreams of finding the One Piece." ), Document( content="Goku, a Saiyan warrior, has defended Earth from numerous powerful enemies like Frieza and Cell." ), Document( content="Light Yagami finds a mysterious Death Note, which allows him to eliminate people by writing their names." ), Document( content="Levi Ackerman is humanity’s strongest soldier, fighting against the Titans to protect mankind." ), ]pipeline
パイプラインを
で定義できますパイプラインを視覚化できます
pipe = Pipeline() pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") ) pipe.connect("retriever", "prompt_builder.documents") pipe.connect("prompt_builder", "llm")
パイプラインが提供しています:
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)
モジュラーワークフロー管理
接続グラフ
connectiongraphは、コンポーネントがどのように相互作用するかを定義します 上記のパイプラインから、接続グラフを視覚化できます。
pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") )
このグラフ構造:
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)
コンポーネント間のデータフローを定義します
入力/出力関係を管理
並列処理を有効にします
柔軟な処理経路を作成します
応答:
template = """ Given only the following information, answer the question. Ignore your own knowledge. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }}? """
このぼろはシンプルでありながら、新人にとって概念的に価値があります。 Haystack Frameworksの概念のほとんどを理解したので、メインプロジェクトに深く飛び込むことができます。新しいことが出現した場合、私は途中で説明します。
高等二次物理学のための質問回答ragプロジェクト
使用します。
conda env python 3.12
をセットアップします
$ pip install haystack-ai ollama-haystack # On you system download Ollama and install LLM ollama pull llama3.2:3b ollama pull nomic-embed-text # And then start ollama server ollama serve
from haystack import Document, Pipeline from haystack.components.builders.prompt_builder import PromptBuilder from haystack.components.retrievers.in_memory import InMemoryBM25Retriever from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.generators.ollama import OllamaGeneratorという名前のプロジェクトディレクトリを作成します
プロジェクトにはプレーンPythonファイルを使用したり、プロジェクトにJupyterノートブックを使用したりできます。プレーンPythonファイルを使用します プロジェクトルートに
main.pydocument_store = InMemoryDocumentStore() documents = [ Document( content="Naruto Uzumaki is a ninja from the Hidden Leaf Village and aspires to become Hokage." ), Document( content="Luffy is the captain of the Straw Hat Pirates and dreams of finding the One Piece." ), Document( content="Goku, a Saiyan warrior, has defended Earth from numerous powerful enemies like Frieza and Cell." ), Document( content="Light Yagami finds a mysterious Death Note, which allows him to eliminate people by writing their names." ), Document( content="Levi Ackerman is humanity’s strongest soldier, fighting against the Titans to protect mankind." ), ]ファイルを作成します。
必要なライブラリのインポート
システムパッケージ
pipe = Pipeline() pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") ) pipe.connect("retriever", "prompt_builder.documents") pipe.connect("prompt_builder", "llm")ドキュメントストアは最も重要です。ここでは、入力のために埋め込みを保存します。具体化ストアに
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)chromadb
pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") )を使用します。以前の例でわかるように、迅速な取得のためにインメモリドキュメントストアを使用します。システムを開始します。
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)
template = """ Given only the following information, answer the question. Ignore your own knowledge. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }}? """ソリューションは、松ぼっくり、織り、ポストグレスベクターDB、ChromADBなどのベクトルデータベースです。 ChromAdbを使用しています。これは、無料でオープンソース、使いやすく、堅牢であるためです。
westing_pathは、埋め込みを保存したい場所です。
pdfファイルパス
query = "How Goku eliminate people?" response = pipe.run({"prompt_builder": {"query": query}, "retriever": {"query": query}}) print(response["llm"]["replies"])
PDFファイルで構成されるデータフォルダーからファイルのリストを作成します。 ドキュメント前処理コンポーネント
クリーナー、スプリッター、ファイルコンバーターなどのHayStackの組み込みドキュメントプリプロセッサを使用し、ライターを使用してデータをストアに書き込みます。 クリーナー:
ドキュメントから余分なスペース、繰り返しの行、空の線などがきれいになります。$conda create --name agenticlm python=3.12 $conda activate agenticlmスプリッター:
PYPDFを使用して、PDFをドキュメントに変換します。
$ pip install haystack-ai ollama-haystack # On you system download Ollama and install LLM ollama pull llama3.2:3b ollama pull nomic-embed-text # And then start ollama server ollama serve
ライター:ドキュメントを保存する場所にドキュメントを保存し、ドキュメントを重複させるために、以前のドキュメントで上書きします。
from haystack import Document, Pipeline from haystack.components.builders.prompt_builder import PromptBuilder from haystack.components.retrievers.in_memory import InMemoryBM25Retriever from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.generators.ollama import OllamaGeneratorドキュメントインデックスのために埋め込みを設定します。
Embedder:NOMIC EMBED TEXT 非常に効果的で無料のinhuggingfaceとollamaです。 インデックスパイプラインを実行する前に、端末を開き、以下を入力して、ノミック埋め込みテキストとllama3.2:3bモデルをオラマモデルストア
コマンドを入力してオラマを開始します
ollama serve埋め込みコンポーネント
document_store = InMemoryDocumentStore() documents = [ Document( content="Naruto Uzumaki is a ninja from the Hidden Leaf Village and aspires to become Hokage." ), Document( content="Luffy is the captain of the Straw Hat Pirates and dreams of finding the One Piece." ), Document( content="Goku, a Saiyan warrior, has defended Earth from numerous powerful enemies like Frieza and Cell." ), Document( content="Light Yagami finds a mysterious Death Note, which allows him to eliminate people by writing their names." ), Document( content="Levi Ackerman is humanity’s strongest soldier, fighting against the Titans to protect mankind." ), ]
ollamadocumentembedder
コンポーネントを埋め込むにはドキュメントを埋め込みますが、テキスト文字列を埋めたい場合は、olamatextembedder。
インデックス作成パイプラインの作成pipe = Pipeline() pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") ) pipe.connect("retriever", "prompt_builder.documents") pipe.connect("prompt_builder", "llm")
以前のおもちゃのぼろきれの例と同様に、パイプラインクラスを開始することから始めます。 次に、コンポーネントをパイプラインに1つずつ追加します
パイプラインにコンポーネントを追加しても注文は気にしないため、任意の順序でコンポーネントを追加できます。しかし、接続することが重要です。
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)ここでは、コンポーネントを接続する方法がパイプラインにパイプラインをどのように流れるかをパイプラインに伝えるため、注文することが重要です。それは、どの順序で、または配管品を購入する場所から重要ではありませんが、それらをまとめる方法はあなたがあなたの水を得るかどうかを決定するでしょう。
コンバーターはPDFを変換し、洗浄のために掃除するように送信します。次に、クリーナーがクリーニングされたドキュメントをスプリッターに送信してチャンクします。その後、これらのチャンクはベクトル化のために埋め込まれたものに渡され、最後の埋め込まれたものはこれらの埋め込みをライターに渡してストレージのために引き渡します。
理解!わかりました、データフローを検査できるように、インデックスの視覚的なグラフを教えてください。pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") )
インデックス作成パイプラインを描画します
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)
インデックス作成パイプラインのグラフ
template = """ Given only the following information, answer the question. Ignore your own knowledge. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }}? """router
を実装します
次に、異なるパスを通してデータをルーティングするためにルーターを作成する必要があります。この場合、特定の条件でルーティングジョブを行う条件付きルーターを使用します。条件付きルーターは、コンポーネントの出力に基づいて条件を評価します。さまざまなパイプラインブランチを介してデータフローを導き、動的な意思決定を可能にします。また、堅牢なフォールバック戦略もあります
$ pip install haystack-ai ollama-haystack # On you system download Ollama and install LLM ollama pull llama3.2:3b ollama pull nomic-embed-text # And then start ollama server ollama serve
システムが埋め込みストアのコンテキストからNO_ANSWERが返信すると、インターネットから関連するデータを収集するためにWeb検索ツールに移動します。
Web検索では、DuckDuckgo APIまたはTavilyを使用します。ここではDuckDuckgoを使用しました。わかりました、重い持ち上げのほとんどが行われました。さて、迅速なエンジニアリングの時間
from haystack import Document, Pipeline from haystack.components.builders.prompt_builder import PromptBuilder from haystack.components.retrievers.in_memory import InMemoryBM25Retriever from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.generators.ollama import OllamaGenerator
プロンプトテンプレートを作成
最初に、qa
のプロンプトを作成しますドキュメントからコンテキストを取り、質問に答えようとします。ただし、ドキュメントに関連するコンテキストが見つからない場合は、no_answerに返信します。
document_store = InMemoryDocumentStore() documents = [ Document( content="Naruto Uzumaki is a ninja from the Hidden Leaf Village and aspires to become Hokage." ), Document( content="Luffy is the captain of the Straw Hat Pirates and dreams of finding the One Piece." ), Document( content="Goku, a Saiyan warrior, has defended Earth from numerous powerful enemies like Frieza and Cell." ), Document( content="Light Yagami finds a mysterious Death Note, which allows him to eliminate people by writing their names." ), Document( content="Levi Ackerman is humanity’s strongest soldier, fighting against the Titans to protect mankind." ), ]さて、LLMからNO_Answerを取得した後の2番目のプロンプトで、システムはインターネットからコンテキストを収集するためにWeb検索ツールを使用します。 duckduckgoプロンプトテンプレート
システムがWeb検索に移動し、クエリに応答しようとするようになります。
HayStackのPromptBuilderを使用してプロンプトを作成しますpipe = Pipeline() pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") ) pipe.connect("retriever", "prompt_builder.documents") pipe.connect("prompt_builder", "llm")
ヘイスタックプロンプトジョイナーを使用して、プロンプトのブランチに参加します。 クエリパイプラインを実装
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)クエリパイプラインは、埋め込みからコンテキストリソースを収集し、LLMまたはWeb検索ツールを使用してクエリに答えるクエリを埋め込みます。
インデックスパイプラインに似ています。
pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") )パイプラインの開始
クエリパイプラインにコンポーネントを追加
ここで、LLM世代には、llama3.2または1bまたは1b、またはツールの呼び出しで好きなLLMを使用して回答を生成するためにOllamageneratorコンポーネントを使用します。 クエリフローと回答生成のために、すべてのコンポーネントを一緒に接続する
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)
Text_embedderからの埋め込みは、レトリーバーのクエリの埋め込みに送信されました。
template = """ Given only the following information, answer the question. Ignore your own knowledge. Context: {% for document in documents %} {{ document.content }} {% endfor %} Question: {{ query }}? """Retriverは、prospt_builderのドキュメントにデータを送信します
プロンプトビルダーは、他のプロンプトと参加するためにプロンプトジョイナーに移動します。
プロンプトジョイナーは、生成のためにデータをLLMに渡します。llmの返信はルーターに移動して、返信が
query = "How Goku eliminate people?" response = pipe.run({"prompt_builder": {"query": query}, "retriever": {"query": query}}) print(response["llm"]["replies"])no_answer
またはnot.if
no_answer私はそれが巨大なグラフであることを知っていますが、それは獣の腹の下で何が起こっているのかを正確に示します。
今、私たちの努力の果物を楽しむ時が来ました。
簡単にクエリするための関数を作成します
$ pip install haystack-ai ollama-haystack # On you system download Ollama and install LLM ollama pull llama3.2:3b ollama pull nomic-embed-text # And then start ollama server ollama serveこれは、回答生成のための簡単な単純な機能です。
NCERT物理学の本をインデックスするためにメインスクリプトを実行してください
from haystack import Document, Pipeline from haystack.components.builders.prompt_builder import PromptBuilder from haystack.components.retrievers.in_memory import InMemoryBM25Retriever from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack_integrations.components.generators.ollama import OllamaGeneratorそれは1回限りの仕事です。インデックスをインデックスした後、この行にコメントする必要があります。そうしないと、本の再インデックスを開始します。
そして、ファイルの下部にクエリのためにドライバーコードを記述します
本の知識からの抵抗性に関する
mcqdocument_store = InMemoryDocumentStore() documents = [ Document( content="Naruto Uzumaki is a ninja from the Hidden Leaf Village and aspires to become Hokage." ), Document( content="Luffy is the captain of the Straw Hat Pirates and dreams of finding the One Piece." ), Document( content="Goku, a Saiyan warrior, has defended Earth from numerous powerful enemies like Frieza and Cell." ), Document( content="Light Yagami finds a mysterious Death Note, which allows him to eliminate people by writing their names." ), Document( content="Levi Ackerman is humanity’s strongest soldier, fighting against the Titans to protect mankind." ), ]
本にない別の質問
pipe = Pipeline() pipe.add_component("retriever", InMemoryBM25Retriever(document_store=document_store)) pipe.add_component("prompt_builder", PromptBuilder(template=template)) pipe.add_component( "llm", OllamaGenerator(model="llama3.2:1b", url="http://localhost:11434") ) pipe.connect("retriever", "prompt_builder.documents") pipe.connect("prompt_builder", "llm")output
別の質問を試してみましょう。
image_param = { "format": "img", "type": "png", "theme": "forest", "bgColor": "f2f3f4", } pipe.show(params=image_param)
それで、それは機能しています!より多くのデータ、書籍、またはPDFを埋め込みに使用することができます。また、GPT-4O、AnthropicのClaude、またはその他のクラウドLLMなどのLLMは、仕事をさらに良くします。
私たちのエージェントRAGシステムは、コンポーネントとパイプラインを組み合わせる力を持つHaystackフレームワークの柔軟性と堅牢性を示しています。このぼろきれは、Webサービスプラットフォームに展開し、Openaiやnthropicなどのより良い有料LLMを使用することにより、生産対応にすることができます。より良いユーザーエクスペリエンスを得るために、RestreylitまたはReactベースのWebスパを使用してUIを構築できます。
エージェントラグシステムは、従来のぼろきれよりもインテリジェントで柔軟な応答を提供します。
Haystackのパイプラインアーキテクチャにより、複雑でモジュラーワークフローが可能になります以上がヘイスタックフレームワークを使用してエージェントQAラグシステムを構築する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。