在這篇文章中,我將解釋如何使用 Llama2 模型建立一個聊天機器人來智慧查詢 Excel 資料。
我們正在建造什麼
- 載入 Excel 檔案。
- 將資料分割成可管理的區塊。
- 將資料儲存在向量資料庫中以便快速檢索。
- 使用本地 Llama2 模型來回答基於 Excel 檔案的內容。
先決條件:
Python (≥ 3.8)
圖庫:langchain、pandas、非結構化、Chroma
第 1 步:安裝依賴項
%pip install -q unstructured langchain %pip install -q "unstructured[all-docs]"
第 2 步:載入 Excel 文件
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")
第 3 步:將資料分塊並儲存在向量資料庫中
大型文字資料被分割成更小的、重疊的區塊,以進行有效的嵌入和查詢。這些區塊儲存在 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" )
步驟 4:初始化 Llama2 模型
我們使用 ChatOllama 在本地載入 Llama2 模型。
from langchain_community.chat_models import ChatOllama local_model = "llama2" llm = ChatOllama(model=local_model)
第 5 步:建立查詢提示
聊天機器人將根據 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}""" )
第 6 步:設定檢索器
我們配置一個檢索器從向量資料庫中取得相關區塊,Llama2 模型將使用該資料區塊來回答問題。
from langchain.retrievers.multi_query import MultiQueryRetriever retriever = MultiQueryRetriever.from_llm( vector_db.as_retriever(), llm, prompt=QUERY_PROMPT )
第 7 步:建立響應鏈
響應鏈整合:
- 用於取得上下文的檢索器。
- 格式化問題和上下文的提示。
- 用於產生答案的 Llama2 模型。
- 用於格式化回應的輸出解析器。
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() )
第 8 步:提出問題
現在我們準備好提問了!以下是我們如何調用鏈來獲取回應:
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 資料創建智慧、互動式聊天機器人。透過一些調整,您可以擴展它以處理其他類型的文件或將其整合到成熟的應用程式中!
在我的 LinkedIn 上檢查 UI 的工作範例:
介紹 BChat Excel:用於 Excel 檔案互動的對話式 AI 驅動工具
以上是使用 LlamaChat 和 Excel 建立一個簡單的聊天機器人]的詳細內容。更多資訊請關注PHP中文網其他相關文章!

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

numpyallowsforvariousoperationsonArrays:1)basicarithmeticlikeaddition,減法,乘法和division; 2)evationAperationssuchasmatrixmultiplication; 3)element-wiseOperations wiseOperationswithOutexpliitloops; 4)

Arresinpython,尤其是Throughnumpyandpandas,weessentialFordataAnalysis,offeringSpeedAndeffied.1)NumpyArseNable efflaysenable efficefliceHandlingAtaSetSetSetSetSetSetSetSetSetSetSetsetSetSetSetSetsopplexoperationslikemovingaverages.2)

列表sandnumpyArraysInpythonHavedIfferentMemoryfootprints:listSaremoreFlexibleButlessMemory-效率,而alenumpyArraySareSareOptimizedFornumericalData.1)listsStorReereReereReereReereFerenceStoObjects,with withOverHeadeBheadaroundAroundaround64byty64-bitsysysysysysysysysyssyssyssyssysssyssys2)

toensurepythonscriptsbehavecorrectlyacrycrosdevelvermations,分期和生產,USETHESTERTATE:1)Environment varriablesForsimplesettings,2)configurationfilesfilesForcomPlexSetups,3)dynamiCofforComplexSetups,dynamiqualloadingForaptaptibality.eachmethodoffersuniquebeneiquebeneqeniquebenefitsandrefitsandrequiresandrequiresandrequiresca

Python列表切片的基本語法是list[start:stop:step]。 1.start是包含的第一個元素索引,2.stop是排除的第一個元素索引,3.step決定元素之間的步長。切片不僅用於提取數據,還可以修改和反轉列表。

ListSoutPerformarRaysin:1)DynamicsizicsizingandFrequentInsertions/刪除,2)儲存的二聚體和3)MemoryFeliceFiceForceforseforsparsedata,butmayhaveslightperformancecostsinclentoperations。

toConvertapythonarraytoalist,usEthelist()constructororageneratorexpression.1)intimpthearraymoduleandcreateanArray.2)USELIST(ARR)或[XFORXINARR] to ConconverTittoalist,請考慮performorefformanceandmemoryfformanceandmemoryfformienceforlargedAtasetset。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

記事本++7.3.1
好用且免費的程式碼編輯器

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Dreamweaver CS6
視覺化網頁開發工具