「LangChainやLlamaIndexとは異なるフレームワークで、ローカルLLMのパイプラインを構築する方法を調べている」
そんな悩みを抱えるLinux担当者は多いはずです。この記事では、deepset社が開発するNLPパイプラインフレームワーク「Haystack 2.x」とOllamaを連携させ、コンポーネントを組み合わせた文書Q&Aシステムをローカル環境に構築する手順を解説します。
「ドキュメントを取り込む」「埋め込みベクトルに変換する」「質問に近い文書を取得する」「回答を生成する」の4ステップをHaystackのパイプラインとして定義し、Ollamaのモデルがすべてローカルで実行できる構成をLinuxサーバーに整えます。
この記事のポイント
・pip install haystack-ai ollama-haystackでHaystackのOllama統合コンポーネントを導入できる
・OllamaDocumentEmbedderで文書をベクトル化し、InMemoryDocumentStoreに索引を構築する
・pipeline.connect("component_a.output", "component_b.input")でコンポーネントを直列に接続する
・nomic-embed-textで埋め込み、llama3.3:8b-instruct-q8_0で回答生成するRAG構成が基本形
でも安心してください。プロのエンジニアはコマンドを暗記していません。
「現場で使える型」を効率よく使いこなしているだけです。
Haystackとは何か(LangChainとの違いとローカルLLMとの組み合わせ)
Haystackはドイツの企業deepsetが開発するPython製NLPパイプラインフレームワークです。バージョン2.xから「コンポーネント」を中心に据えた設計に切り替わり、各処理ステップを部品として定義し、`Pipeline`クラスで接続・実行する構成になりました。LangChainとの主な違いは処理の接続方法にあります。LangChainがChainクラスや関数のつなぎ合わせを中心とするのに対し、Haystackは「コンポーネントAの出力XをコンポーネントBの入力Yに接続する」という宣言的な配線を`pipeline.connect("a.x", "b.y")`で記述します。処理フローを設定ファイルとして保存・再現しやすい点が特徴です。
社内ドキュメントの機密性を保ちたい場合、すべての処理をクラウドAPIに送らずローカルで完結させる必要があります。Haystackは`ollama-haystack`パッケージを通じてOllamaと統合でき、埋め込みモデルと生成モデルをOllamaサーバーで動かせます。
Ollamaのセットアップと基本的な動作確認については「Ubuntu ServerでローカルLLMを構築する方法|Ollamaで機密データを外に出さず業務AIを動かす完全ガイド」を事前に済ませておいてください。
インストールと事前準備(Python仮想環境とhaystack-aiのセットアップ手順)
1. Pythonバージョンを確認する
Haystack 2.xはPython 3.9以上が必要です。AlmaLinux 9やUbuntu 22.04以降の標準Pythonはこの要件を満たしています。$ python3 --version Python 3.11.9
2. 仮想環境を作成してパッケージをインストールする
システムPythonを汚染しないよう、仮想環境を作成してからインストールします。`haystack-ai`がHaystackのコアパッケージ、`ollama-haystack`がOllamaとの統合コンポーネントを提供します。$ python3 -m venv ~/haystack-env $ source ~/haystack-env/bin/activate (haystack-env) $ pip install haystack-ai ollama-haystack Collecting haystack-ai Downloading haystack_ai-2.9.0-py3-none-any.whl (542 kB) Collecting ollama-haystack Downloading ollama_haystack-2.1.0-py3-none-any.whl (21 kB) ... Successfully installed haystack-ai-2.9.0 ollama-haystack-2.1.0 (haystack-env) $ python3 -c "import haystack; print(haystack.__version__)" 2.9.0
3. 埋め込みモデルと生成モデルをOllamaで取得する
RAGパイプラインでは埋め込みモデル(`nomic-embed-text`)と生成モデルの2種類が必要です。事前に両方を取得しておきます。$ ollama pull nomic-embed-text $ ollama pull llama3.3:8b-instruct-q8_0 $ ollama list NAME ID SIZE MODIFIED nomic-embed-text:latest 0a109f422b47 274 MB 1 minute ago llama3.3:8b-instruct-q8_0 abc123def456 8.5 GB 2 hours ago
DocumentStoreに文書を取り込む(OllamaDocumentEmbedderで索引を構築する手順)
1. DocumentStoreを初期化してインデックスパイプラインを定義する
Haystackの`InMemoryDocumentStore`は、追加設定不要でメモリ上に文書ストアを作れる開発・検証向けのバックエンドです。本番環境ではElasticsearchやQdrantなどの外部ストアに差し替えられますが、動作確認には十分です。# indexing_pipeline.py from haystack import Document, Pipeline from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack.components.writers import DocumentWriter from haystack_integrations.components.embedders.ollama import OllamaDocumentEmbedder document_store = InMemoryDocumentStore() indexing_pipeline = Pipeline() indexing_pipeline.add_component( "doc_embedder", OllamaDocumentEmbedder( model="nomic-embed-text", url="http://localhost:11434" ) ) indexing_pipeline.add_component( "doc_writer", DocumentWriter(document_store=document_store) ) indexing_pipeline.connect("doc_embedder", "doc_writer")
2. 文書を取り込む
`Document`オブジェクトに文書の本文と任意のメタデータを設定し、インデックスパイプラインに渡します。docs = [ Document( content="Ubuntu ServerにNginxをインストールするには apt install nginx を実行します。", meta={"source": "setup_guide.txt", "page": 1} ), Document( content="Nginxの設定ファイルは /etc/nginx/nginx.conf にあります。変更後は nginx -t で文法を確認してから nginx -s reload で反映します。", meta={"source": "setup_guide.txt", "page": 3} ), Document( content="SSL証明書の取得には certbot を使います。certbot --nginx -d example.com で自動設定できます。", meta={"source": "ssl_guide.txt", "page": 2} ), ] result = indexing_pipeline.run({"doc_embedder": {"documents": docs}}) print(f"取り込み完了: {result['doc_writer']['documents_written']} 件") # 出力例 # 取り込み完了: 3 件
OllamaのLLMをGeneratorとして設定する
HaystackでOllamaの生成モデルを使うには`OllamaGenerator`コンポーネントを使います。`model`にモデル名、`url`にOllamaサーバーのエンドポイントを指定します。VRAMが16GB以上ある環境では`llama3.3:70b-instruct-q4_0`を検討してください。モデルごとの性能や必要VRAMの比較は「ローカルLLMのモデルを比較する方法|Llama3.3・Mistral・Gemma・Phi-4をUbuntuで使い分けるポイント」を参照してください。
from haystack_integrations.components.generators.ollama import OllamaGenerator generator = OllamaGenerator( model="llama3.3:8b-instruct-q8_0", url="http://localhost:11434", generation_kwargs={ "temperature": 0.3, "num_ctx": 4096 } ) # 単体テスト response = generator.run(prompt="LinuxでNginxを起動するコマンドを教えてください。") print(response["replies"][0])
RAGパイプラインを組み立てる(Retriever・PromptBuilder・Generatorの接続手順)
1. 各コンポーネントを定義する
RAGパイプラインは4つのコンポーネントで構成します。・`OllamaTextEmbedder`: 質問文を埋め込みベクトルに変換する
・`InMemoryEmbeddingRetriever`: ベクトル類似度で関連文書を取得する
・`PromptBuilder`: 取得した文書と質問をプロンプトに組み立てる
・`OllamaGenerator`: プロンプトをもとに回答を生成する
# rag_pipeline.py from haystack import Pipeline from haystack.components.builders import PromptBuilder from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever from haystack_integrations.components.embedders.ollama import OllamaTextEmbedder from haystack_integrations.components.generators.ollama import OllamaGenerator template = """ 提供された文書を参照し、以下の質問に日本語で答えてください。 文書に答えが見つからない場合は「文書には記載されていません」と回答してください。 文書: {% for doc in documents %} - {{ doc.content }} {% endfor %} 質問: {{ question }} 回答: """ rag_pipeline = Pipeline() rag_pipeline.add_component( "text_embedder", OllamaTextEmbedder(model="nomic-embed-text", url="http://localhost:11434") ) rag_pipeline.add_component( "retriever", InMemoryEmbeddingRetriever(document_store=document_store, top_k=3) ) rag_pipeline.add_component( "prompt_builder", PromptBuilder(template=template) ) rag_pipeline.add_component( "generator", OllamaGenerator(model="llama3.3:8b-instruct-q8_0", url="http://localhost:11434") )
2. コンポーネントを接続して実行する
`pipeline.connect()`で各コンポーネントの出力と入力を配線します。接続の書式は`"コンポーネント名.出力名"`→`"コンポーネント名.入力名"`です。rag_pipeline.connect("text_embedder.embedding", "retriever.query_embedding") rag_pipeline.connect("retriever.documents", "prompt_builder.documents") rag_pipeline.connect("prompt_builder.prompt", "generator.prompt") question = "NginxでSSL証明書を設定する方法を教えてください。" result = rag_pipeline.run({ "text_embedder": {"text": question}, "prompt_builder": {"question": question} }) print(result["generator"]["replies"][0]) # 出力例 # SSL証明書の設定には certbot を使います。 # certbot --nginx -d example.com を実行すると自動で設定されます。
実用例:社内マニュアルをローカルLLMで質問応答するシステムの実装
ファイルからドキュメントを読み込む場合は、テキストの分割と埋め込みを含む索引パイプラインが必要です。ここでは`.txt`ファイルを読み込んで索引を構築し、対話的に質問応答できる完全なスクリプトを示します。社内サーバー上の機密マニュアルをローカルLLMで検索・質問応答できるようにすることで、外部クラウドへのデータ送信を防ぎながらAI活用を実現できます。機密情報を扱う業務でのローカルLLM導入の背景については「社内でChatGPTが使えないときの代替手段|機密データを守るローカルLLMという選択肢」が参考になります。
# full_qa_system.py from pathlib import Path from haystack import Document, Pipeline from haystack.document_stores.in_memory import InMemoryDocumentStore from haystack.components.preprocessors import DocumentSplitter from haystack.components.writers import DocumentWriter from haystack.components.builders import PromptBuilder from haystack.components.retrievers.in_memory import InMemoryEmbeddingRetriever from haystack_integrations.components.embedders.ollama import ( OllamaTextEmbedder, OllamaDocumentEmbedder ) from haystack_integrations.components.generators.ollama import OllamaGenerator OLLAMA_URL = "http://localhost:11434" EMBED_MODEL = "nomic-embed-text" GEN_MODEL = "llama3.3:8b-instruct-q8_0" document_store = InMemoryDocumentStore() # 索引パイプライン index_pipeline = Pipeline() index_pipeline.add_component("splitter", DocumentSplitter(split_by="sentence", split_length=5)) index_pipeline.add_component("embedder", OllamaDocumentEmbedder(model=EMBED_MODEL, url=OLLAMA_URL)) index_pipeline.add_component("writer", DocumentWriter(document_store=document_store)) index_pipeline.connect("splitter", "embedder") index_pipeline.connect("embedder", "writer") # テキストファイルを読み込んで索引を構築する docs_dir = Path("/etc/mycompany/manuals") raw_docs = [] for txt_file in docs_dir.glob("*.txt"): content = txt_file.read_text(encoding="utf-8") raw_docs.append(Document(content=content, meta={"source": txt_file.name})) result = index_pipeline.run({"splitter": {"documents": raw_docs}}) print(f"索引構築完了: {result['writer']['documents_written']} チャンク") # RAGパイプライン template = """ 以下の文書を参照して質問に答えてください。 文書: {% for doc in documents %} [{{ doc.meta['source'] }}] {{ doc.content }} {% endfor %} 質問: {{ question }} 回答: """ rag_pipeline = Pipeline() rag_pipeline.add_component("embedder", OllamaTextEmbedder(model=EMBED_MODEL, url=OLLAMA_URL)) rag_pipeline.add_component("retriever", InMemoryEmbeddingRetriever(document_store=document_store, top_k=5)) rag_pipeline.add_component("prompt", PromptBuilder(template=template)) rag_pipeline.add_component("generator", OllamaGenerator(model=GEN_MODEL, url=OLLAMA_URL, generation_kwargs={"temperature": 0.2, "num_ctx": 4096})) rag_pipeline.connect("embedder.embedding", "retriever.query_embedding") rag_pipeline.connect("retriever.documents", "prompt.documents") rag_pipeline.connect("prompt.prompt", "generator.prompt") while True: question = input("質問(終了はq): ") if question == "q": break res = rag_pipeline.run({ "embedder": {"text": question}, "prompt": {"question": question} }) print(res["generator"]["replies"][0]) print()
$ source ~/haystack-env/bin/activate (haystack-env) $ python3 full_qa_system.py 索引構築完了: 42 チャンク 質問(終了はq): バックアップの設定方法を教えてください。 バックアップはcronで毎日実行するよう設定します。 backup_guide.txtによれば、tar czfでアーカイブして SFTPで転送する手順が推奨されています。 質問(終了はq): q
よくあるエラーと対処法
エラー1:ComponentError(コンポーネント名または出力/入力名のスペルミス)
`pipeline.connect()`で指定したコンポーネント名や出力/入力名が誤っている場合に発生します。コンポーネントを`add_component()`で追加した後は`pipeline.show()`で構成を確認できます。# パイプラインの構成を表示する rag_pipeline.show() # 出力例(コンポーネントと接続の一覧が表示される) # Component 'embedder': OllamaTextEmbedder # Component 'retriever': InMemoryEmbeddingRetriever # Connections: embedder.embedding -> retriever.query_embedding, ...
エラー2:OllamaへのConnection refused(接続拒否)
Ollamaサービスが起動していないか、URLが誤っている場合に発生します。`systemctl status ollama`でサービスの状態を確認し、停止していれば`systemctl start ollama`で起動します。リモートサーバーのOllamaに接続する場合はURLを`http://サーバーIP:11434`に変更します。ファイアウォールでポート11434が開いているかもあわせて確認してください。
エラー3:OllamaDocumentEmbedderのタイムアウト
大量のドキュメントを一度に索引化しようとするとタイムアウトが発生することがあります。`batch_size`パラメータを設定して処理を分割します。OllamaDocumentEmbedder( model="nomic-embed-text", url="http://localhost:11434", batch_size=10 # 一度に処理するドキュメント数を制限する )
エラー4:回答の品質が低い(文書内容と関係ない回答が返る)
`InMemoryEmbeddingRetriever`の`top_k`を増やして取得する文書数を増やすか、`DocumentSplitter`の`split_length`を短くしてチャンクを細かくすることで改善できます。また`PromptBuilder`のテンプレートで「文書に答えがない場合は記載なしと答える」と明示するのも効果的です。まとめ
HaystackとOllamaを組み合わせることで、コンポーネントを宣言的に接続したRAGパイプラインをローカル完結で動かせます。LangChainやLlamaIndexとは異なる「配線モデル」の設計思想を持ち、パイプラインの見通しの良さと再現性が特徴です。| 手順 | コマンド・設定 |
|---|---|
| パッケージのインストール | pip install haystack-ai ollama-haystack |
| 埋め込みモデルの取得 | ollama pull nomic-embed-text |
| 生成モデルの取得 | ollama pull llama3.3:8b-instruct-q8_0 |
| 索引パイプラインの実行 | indexing_pipeline.run({"doc_embedder": {"documents": docs}}) |
| RAGパイプラインのコンポーネント接続 | pipeline.connect("text_embedder.embedding", "retriever.query_embedding") |
| コンポーネント構成の確認 | pipeline.show() |
ローカルLLMのRAGシステム構築を2日間のハンズオンで体験する
HaystackとOllamaによるコンポーネント型パイプラインの構築から、社内文書Q&Aシステムの本番展開まで、実機GPU環境で手を動かしながら習得したい方向けに、「ローカルAIマスターセミナー」を開催しています。
少人数(最大8名)ZOOMハンズオン形式で実施しています。
・Ubuntu ServerでローカルLLMを構築する方法|Ollamaで機密データを外に出さず業務AIを動かす完全ガイド
・社内でChatGPTが使えないときの代替手段|機密データを守るローカルLLMという選択肢
・ローカルLLMのモデルを比較する方法|Llama3.3・Mistral・Gemma・Phi-4をUbuntuで使い分けるポイント
3,100名以上が実践した「型」を無料で公開中
プロのエンジニアはコマンドを暗記していません。
「現場で使える型」を効率よく使いこなしているだけです。
その「型」を図解60Pにまとめた入門マニュアルを、完全無料でプレゼントしています。
姓・名・メールの3つだけ/30秒/解除は3秒 / 詳細はこちら
- 前のページへ:OllamaをSELinux有効なAlmaLinux 9で動かす方法|AVC denied解消とカスタムポリシー追加の手順
- この記事の属するカテゴリ:ローカルLLMへ戻る

無料メルマガで学習を続ける
Linuxの実践スキルをメールで毎週お届け。
登録は30秒、解除もいつでも可。
登録無料・いつでも解除できます