开始使用
查看本页面,了解如何快速上手 Haystack。其中包含安装、运行第一个 RAG 管道、添加数据以及其他资源的说明。
构建您的第一个 RAG 应用
让我们构建您的第一个检索增强生成 (RAG) 管道,看看 Haystack 如何回答问题。
首先,安装 Haystack 的最小版本
pip install haystack-ai
您之前已经在使用 Haystack 1.x 了吗?
警告
安装
farm-haystack和haystack-ai在同一个 Python 环境(虚拟环境、Colab 或系统)中会导致问题。在同一个环境中同时安装这两个包可能会以奇怪的方式成功或失败。我们建议每个 Python 环境只安装其中一个包。请确保如果您在同一个环境中安装了这两个包,请先将它们都删除,然后再只安装其中一个。
pip uninstall -y farm-haystack haystack-ai pip install haystack-ai
在下面的示例中,我们展示了如何使用 Haystack 的 Secrets 设置 API 密钥。但是,为了更方便地使用,您也可以将 OpenAI 密钥设置为OPENAI_API_KEY 环境变量。
from haystack import Pipeline, Document
from haystack.utils import Secret
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.builders.chat_prompt_builder import ChatPromptBuilder
from haystack.dataclasses import ChatMessage
# Write documents to InMemoryDocumentStore
document_store = InMemoryDocumentStore()
document_store.write_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.")
])
# Build a RAG pipeline
prompt_template = [
ChatMessage.from_system("You are a helpful assistant."),
ChatMessage.from_user(
"Given these documents, answer the question.\n"
"Documents:\n{% for doc in documents %}{{ doc.content }}{% endfor %}\n"
"Question: {{question}}\n"
"Answer:"
)
]
# Define required variables explicitly
prompt_builder = ChatPromptBuilder(template=prompt_template, required_variables={"question", "documents"})
retriever = InMemoryBM25Retriever(document_store=document_store)
llm = OpenAIChatGenerator(api_key=Secret.from_env_var("OPENAI_API_KEY"))
rag_pipeline = Pipeline()
rag_pipeline.add_component("retriever", retriever)
rag_pipeline.add_component("prompt_builder", prompt_builder)
rag_pipeline.add_component("llm", llm)
rag_pipeline.connect("retriever", "prompt_builder.documents")
rag_pipeline.connect("prompt_builder", "llm.messages")
# Ask a question
question = "Who lives in Paris?"
results = rag_pipeline.run(
{
"retriever": {"query": question},
"prompt_builder": {"question": question},
}
)
print(results["llm"]["replies"])
想知道此代码示例中的每个步骤是做什么的吗?请查看下面的食谱了解详情
🤝
2.0 RAG 管道
打开食谱
添加您的数据
与其在示例数据上运行 RAG 管道,不如学习如何使用 Document Stores 添加您自己的自定义数据。
更新于 6 个月前
