在这篇文章中,我将解释如何使用 llama2 模型构建一个聊天机器人来智能查询 excel 数据。
![使用 LlamaChat 和 Excel 构建一个简单的聊天机器人]](https://img.php.cn/upload/article/001/246/273/173277859699340.jpg)
python (≥ 3.8)
库:langchain、pandas、非结构化、chroma
%pip install -q unstructured langchain %pip install -q "unstructured[all-docs]"
import pandas as pd
excel_path = "book2.xlsx"
if excel_path:
df = pd.read_excel(excel_path)
data = df.to_string(index=false)
else:
print("upload an excel file")
大型文本数据被分割成更小的、重叠的块,以进行有效的嵌入和查询。这些块存储在 chroma 矢量数据库中。
from langchain_text_splitters import recursivecharactertextsplitter
from langchain_community.embeddings import ollamaembeddings
from langchain_community.vectorstores import chroma
text_splitter = recursivecharactertextsplitter(chunk_size=7500, chunk_overlap=100)
chunks = text_splitter.split_text(data)
embedding_model = ollamaembeddings(model="nomic-embed-text", show_progress=false)
vector_db = chroma.from_texts(
texts=chunks,
embedding=embedding_model,
collection_name="local-rag"
)
我们使用 chatollama 在本地加载 llama2 模型。
from langchain_community.chat_models import chatollama local_model = "llama2" llm = chatollama(model=local_model)
聊天机器人将根据 excel 文件中的特定列名称进行响应。我们创建一个提示模板来指导模型
from langchain.prompts import prompttemplate
query_prompt = prompttemplate(
input_variables=["question"],
template="""you are an ai assistant. answer the user's questions based on the column names:
id, order_id, name, sales, refund, and status. original question: {question}"""
)
我们配置一个检索器从向量数据库中获取相关块,llama2 模型将使用它来回答问题。
from langchain.retrievers.multi_query import multiqueryretriever
retriever = multiqueryretriever.from_llm(
vector_db.as_retriever(),
llm,
prompt=query_prompt
)
响应链集成:
from langchain.prompts import chatprompttemplate
from langchain_core.runnables import runnablepassthrough
from langchain_core.output_parsers import stroutputparser
template = """answer the question based only on the following context:
{context}
question: {question}
"""
prompt = chatprompttemplate.from_template(template)
chain = (
{"context": retriever, "question": runnablepassthrough()}
| prompt
| llm
| stroutputparser()
)
现在我们准备好提问了!以下是我们如何调用链来获取响应:
raw_result = chain.invoke("how many rows are there?")
final_result = f"{raw_result}\n\nif you have more questions, feel free to ask!"
print(final_result)
当我在示例 excel 文件上运行上述代码时,我得到的结果如下:
Based on the provided context, there are 10 rows in the table. If you have more questions, feel free to ask!
这种方法利用嵌入和 llama2 模型的强大功能,为 excel 数据创建智能、交互式聊天机器人。通过一些调整,您可以扩展它以处理其他类型的文档或将其集成到成熟的应用程序中!
隆重推出 bchat excel:用于 excel 文件交互的人工智能对话式工具
以上就是使用 LlamaChat 和 Excel 构建一个简单的聊天机器人]的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号