Langroid
是一個直觀,輕巧,可擴展和原則性的Python框架,可輕鬆從CMU和UW-Madison研究人員中構建LLM驅動的應用程序。您設置代理,為它們配備可選的組件(LLM,矢量商店和工具/功能),分配任務,並通過交換消息來協作解決問題。這個多代理範式的靈感來自Actor Framework(但是您不需要了解此事!)。
Langroid
是對LLM應用程序開發的一種新鮮感,在此簡化了開發人員的體驗方面。它不使用Langchain
或任何其他LLM框架。
閱讀Langroid體系結構的(WIP)概述
?公司正在生產/適應langroid。這是一個報價:
無效使用AI代理進行安全軟件開發。它找到,確定並修復漏洞。在評估了Crewai,Autogen,Langchain,Langflow等之後,我們已經內部適應了Langroid在生產中的多代理編排框架。我們發現Langroid在易於設置和靈活性方面比這些框架要優於這些框架。 Langroid的代理和任務抽像是直觀的,經過深思熟慮的,並提供了出色的開發人員體驗。我們想要最快的方法來獲得生產中的東西。有了其他框架,這將花費我們數週的時間,但是有了Langroid,我們在幾分鐘之內就取得了良好的成績。強烈推薦!
- 傑基·王(Jacky Wong),無效的AI負責人。
請參閱LanganceB團隊的Langroid博客文章的此簡介
剛剛在醫療保健ML上出版(2024年):基於langroid的多代理抹布系統的藥物宣傳系統,請參閱博客文章
我們歡迎貢獻:有關貢獻的想法,請參見貢獻文件。
您是在構建LLM應用程序,還是為公司的Langroid提供幫助,還是想為您的公司用例使用Langroid功能進行優先級級? Prasad Chalasani可用於諮詢(諮詢/開發):Gmail Dot com的Pchalasani。
贊助也通過GitHub贊助商接受
問題,反饋,想法?加入我們的不和諧!
這只是一個預告片;還有更多,例如函數打電話/工具,多代理協作,結構化信息提取,docChatagent(rag),sqlchatagent,non-openai local/remote llms等。向下滾動或查看文檔以獲取更多信息。請參閱使用OpenAI ChatCompletion API構建的langroid快速啟動COLAB,該Colab最多可構建2個代理信息萃取示例。另請參閱此版本,該版本使用OpenAi Assistants API。
剛發布!示例腳本顯示瞭如何僅使用本地LLM (Mistral-7B-Instruct-V0.2)從文檔中提取結構化信息來提取結構化信息。
import langroid as lr
import langroid . language_models as lm
# set up LLM
llm_cfg = lm . OpenAIGPTConfig ( # or OpenAIAssistant to use Assistant API
# any model served via an OpenAI-compatible API
chat_model = lm . OpenAIChatModel . GPT4o , # or, e.g., "ollama/mistral"
)
# use LLM directly
mdl = lm . OpenAIGPT ( llm_cfg )
response = mdl . chat ( "What is the capital of Ontario?" , max_tokens = 10 )
# use LLM in an Agent
agent_cfg = lr . ChatAgentConfig ( llm = llm_cfg )
agent = lr . ChatAgent ( agent_cfg )
agent . llm_response ( "What is the capital of China?" )
response = agent . llm_response ( "And India?" ) # maintains conversation state
# wrap Agent in a Task to run interactive loop with user (or other agents)
task = lr . Task ( agent , name = "Bot" , system_message = "You are a helpful assistant" )
task . run ( "Hello" ) # kick off with user saying "Hello"
# 2-Agent chat loop: Teacher Agent asks questions to Student Agent
teacher_agent = lr . ChatAgent ( agent_cfg )
teacher_task = lr . Task (
teacher_agent , name = "Teacher" ,
system_message = """
Ask your student concise numbers questions, and give feedback.
Start with a question.
"""
)
student_agent = lr . ChatAgent ( agent_cfg )
student_task = lr . Task (
student_agent , name = "Student" ,
system_message = "Concisely answer the teacher's questions." ,
single_round = True ,
)
teacher_task . add_sub_task ( student_task )
teacher_task . run ()
2024年11月:
Agent
S的支持和OpenAI工具API的嚴格模式。Qwen2.5-Coder-32b-Instruct
)託管在glhf.chat上2024年10月:
2024年9月:
o1-mini
和o1-preview
模型。DocChatAgent
使用倒數融合(RRF)來通過不同方法檢索的塊。run_batch_task
新選項 - stop_on_first_result
允許在任何任務返回結果後立即終止批處理。2024年8月:
Task.run(), Task.run_async
。2024年7月:
2024年6月:
RewindTool
,它使代理可以“倒帶和重做”過去的消息(並且由於譜系跟踪,清除了所有相關消息)。在這裡閱讀筆記。2024年5月:
doc-chat
, db
(用於與數據庫相關的依賴關係)。請參閱下面和文檔中更新的安裝說明。examples
的classMethod,並且該列表中的隨機示例將用於為LLM生成1次示例。這已經得到改進,因此您現在可以提供一個示例列表,每個示例是工具實例,或(描述,工具實例)的元組,其中描述是一種“思想”,導致LLM使用該工具(請參見文檔中的示例)。在某些情況下,這可以提高LLM工俱生成的準確性。另外,現在,所有示例都用於生成幾個示例,而不是隨機示例。TaskConfig
中可配置。僅檢測精確的循環,而不是在實體所說的基本相似(但不是完全相同)的內容的情況下近似循環。RecipientTool
工具機制的簡單替代方法,而權衡的折衷是,由於它不是工具,因此無法執行/提醒LLM明確指定收件人(在這很重要的情況下)。DocChatAgent
時,大量改進的引文生成和顯示。gpt-4o
現在是整個默認LLM;更新測試和示例以與此LLM一起使用;使用與LLM相對應的Tokenizer。gemini 1.5 pro
支持通過litellm
QdrantDB:
更新以支持學習的稀疏嵌入。2024年4月:
chat_model="groq/llama3-8b-8192"
。參見教程。Task.run(), Task.run_async(), run_batch_tasks
具有max_cost
和max_tokens
params在代幣或成本超過限制時退出。結果ChatDocument.metadata
現在包括一個status
字段,該字段是指示任務完成原因代碼的代碼。另外, task.run()
etc可以使用顯式session_id
字段調用,該字段用作redis緩存中各種設置的鍵。當前僅用於查找“殺死狀態” - 這允許通過task.kill()
或classMethod Task.kill_session(session_id)
殺死運行任務。例如用法,請參閱test_task_kill
in tests/main/test_task.py2024年3月:
DocChatAgent
並發運行,請參閱test_doc_chat_agent.py
,特別是test_doc_chat_batch()
;新任務運行實用程序: run_batch_task_gen
可以指定任務生成器,以每一個輸入生成一個任務。DocChatAgent
現在將與Image-PDF一起使用)。DocChatAgent
上下文窗口修復URLLoader
:在URL不會以.pdf
, .docx
等識別後綴結尾時,從標題中檢測文件時間。sentence_transformer
模塊是否可用。unstructured
, haystack
, chromadb
, mkdocs
, huggingface-hub
, sentence-transformers
。import langroid as lr
更容易的頂級導入2024年2月:
chat_model="ollama/mistral"
。請參閱發行說明。2024年1月:
SQLChatAgent
工作方式)。請參閱使用此代理的示例腳本回答有關Python PKG依賴性的問題。.doc
文件解析(除了.docx
之外)OpenAIGPTConfig
中指定可選的formatter
param param,以確保本地LLM的準確聊天格式。DocChatAgentConfig
有一個新的參數: add_fields_to_content
,指定其他文檔字段以插入主要content
字段,以幫助改善檢索。2023年12月:
DocChatAgent
:攝取pandas的數據框架和過濾。LanceDocChatAgent
利用LanceDB
vector-DB進行有效的向量搜索和全文搜索和過濾。LanceRAGTaskCreator
創建由LanceFilterAgent
組成的2代理系統,該系統決定過濾器和重新顯示查詢以發送到抹布代理。Task
初始化,默認ChatAgent
。2023年11月:
0.1.126: OpenAiassistant代理:緩存支持。
0.1.117:支持OpenAI Assistant API工具:函數呼叫,代碼窒息器和ReTRiever(RAG),文件上傳。這些與Langroid的任務 - 策劃無縫地工作。在文檔準備好之前,最好看到這些用法示例:
測試:
示例腳本:
0.1.112: OpenAIAssistant
是ChatAgent
的一個子類,它利用了新的OpenAi Assistant API。它可以用作ChatAgent
的倒入替代品,並依靠助手API來維持對話狀態,並利用持續的線程和助手在需要時重新連接。示例: test_openai_assistant.py
, test_openai_assistant_async.py
0.1.111:支持最新的OpenAI型號: GPT4_TURBO
(請參閱test_llm.py,例如用法)
0.1.110:從OpenAI v0.x升級到v1.1.1(為助手API做準備); (由於OpenAI版本衝突而導致litellm
暫時禁用)。
2023年10月:
DocChatAgent
重新排名: rank_with_diversity
, rank_to_periphery
(中間丟失)。DocChatAgentConfig.n_neighbor_chunks > 0
允許在比賽周圍返回上下文塊。DocChatAgent
使用RelevanceExtractorAgent
,以使用句子數字來使LLM提取物相關部分,從而與llmchainextractor in llmchain extractor in LangChain
在其LLMChainExtractor
使用中使用llmchain使用,從而導致較大的速度和降低成本降低和成本降低。import langroid as lr
。請參閱使用文檔以獲取使用。2023年9月:
docx
文件(初步)。SQLChatAgent
,在將自然語言轉換為SQL時可以有效檢索相關的架構信息。2023年8月:
GoogleSearchTool
啟用代理商(其LLM)通過功能稱呼/工具進行Google搜索。請參閱此聊天示例,以獲取將此工具添加到代理商的容易性。SQLChatAgent
感謝我們最新的貢獻者Rithwik Babu!2023年7月:
TableChatAgent
以與表格數據集(數據范圍,文件,URL)聊天:LLM生成PANDAS代碼,並且使用Langroid的工具/函數呼叫機制執行代碼。DocChatAgent
現在接受PDF文件或URL。假設您想提取有關商業租賃文檔的關鍵條款的結構化信息。如我們在langroid-examples repo中所示,您可以使用langroid輕鬆地使用langroid進行此操作。 (有關使用本地Mistral-7b模型具有相同功能的版本,請參見此腳本。
LeaseExtractor
負責該任務,其LLM(GPT4)生成了由DocAgent
回答的問題。DocAgent
LLM(GPT4)使用矢量商店的檢索來回答LeaseExtractor
的問題,引用了支持答案的特定摘錄。LeaseExtractor
llm使用函數呼叫以結構化格式呈現信息。這是動作中的外觀(可停止的MP4視頻在這裡)。
(有關更多最新列表,請參見上面的“更新/發布”部分)
Task.run()
方法具有與代理人的響應者的方法相同的類型簽名,這是代理如何將代理任務委派給其他子任務的關鍵:從任務的角度來看,子任務僅是其他響應者,僅在代理商自己的響應者之後以圓形robin時尚的方式使用。Agent
和Task
抽象使用戶可以設計具有特定技能的代理,將其包裹在任務中,並以靈活的方式組合任務。ToolMessage
機制,而不僅僅是OpenAI。功能調用和工具具有使用Pydantic實現的相同面向開發人員的接口,這使得定義工具/功能變得非常容易,並使代理能夠使用它們。使用pydantic的好處是,您永遠不必為函數調用編寫複雜的JSON規格,而LLM幻覺畸形的JSON時,Pydantic錯誤消息會發送回LLM,以便它可以修復它。langroid
Langroid需要Python 3.11+。我們建議使用虛擬環境。使用pip
安裝langroid
(從PYPI)到您的虛擬環境的裸露版本。
pip install langroid
核心喇叭軟件包使您可以通過其API使用OpenAI嵌入式型號。如果您想使用huggingface中嵌入模型的sentence-transformers
,請像這樣安裝langroid:
pip install " langroid[hf-embeddings] "
對於許多實際情況,您可能需要其他可選依賴性:
doc-chat
: pip install " langroid[doc-chat] "
db
Extra: pip install " langroid[db] "
` `
pip install " langroid[doc-chat,db] "
all
額外的額外(但請注意,這將導致更長的負載/啟動時間和更大的安裝尺寸): pip install " langroid[all] "
如果使用SQLChatAgent
(例如腳本examples/data-qa/sql-chat/sql_chat.py
),則使用postgres db,您將需要:
sudo apt-get install libpq-dev
,brew install postgresql
,等等。pip install langroid[postgres]
或poetry add langroid[postgres]
或poetry install -E postgres
。如果這給您一個錯誤,請嘗試在Virtualenv中pip install psycopg2-binary
。如果您遇到涉及mysqlclient
奇怪錯誤,請嘗試使用pip uninstall mysqlclient
然後進行pip install mysqlclient
。
首先,您需要的只是一個OpenAI API密鑰。如果您沒有一個,請參閱此OpenAI頁面。 (請注意,儘管這是最簡單的入門方式,但Langroid幾乎可以與任何LLM一起使用,而不僅僅是來自OpenAI的LLM。請參閱指南使用Open/Local LLM,以及其他非Openai專有專有LLMS。)
在存儲庫的根部,將.env-template
文件複製到新文件.env
:
cp .env-template .env
然後插入您的OpenAI API鍵。您的.env
文件應該看起來像這樣(組織是可選的,但在某些情況下可能需要)。
OPENAI_API_KEY=your-key-here-without-quotes
OPENAI_ORGANIZATION=optionally-your-organization-id
另外,您可以將其設置為外殼中的環境變量(每次打開新外殼時,都需要執行此操作):
export OPENAI_API_KEY=your-key-here-without-quotes
以下所有環境變量設置都是可選的,只需要使用特定功能(如下所述)。
.env
文件中輸入您的Momento令牌,作為MOMENTO_AUTH_TOKEN
的值(請參閱下面的示例文件),.env
文件集合中CACHE_TYPE=momento
(而不是CACHE_TYPE=redis
,nefault)。GoogleSearchTool
。要將Google Search用作LLM工具/插件/功能通話,您需要設置Google API密鑰,然後設置Google自定義搜索引擎(CSE)並獲取CSE ID。 (這些文檔可能具有挑戰性,我們建議詢問GPT4逐步指南。)在獲得這些憑據之後,將它們存儲為GOOGLE_API_KEY
的值和GOOGLE_CSE_ID
的值,並將其存儲在.env
文件中。關於使用此聊天的完整文檔(以及其他此類“無狀態”工具)即將推出,但是與此同時,請瀏覽此聊天示例,該聊天示例顯示瞭如何輕鬆地為代理配備GoogleSearchtool
。如果添加所有這些可選變量,則.env
文件應該看起來像這樣:
OPENAI_API_KEY=your-key-here-without-quotes
GITHUB_ACCESS_TOKEN=your-personal-access-token-no-quotes
CACHE_TYPE=redis # or momento
REDIS_PASSWORD=your-redis-password-no-quotes
REDIS_HOST=your-redis-hostname-no-quotes
REDIS_PORT=your-redis-port-no-quotes
MOMENTO_AUTH_TOKEN=your-momento-token-no-quotes # instead of REDIS* variables
QDRANT_API_KEY=your-key
QDRANT_API_URL=https://your.url.here:6333 # note port number must be included
GOOGLE_API_KEY=your-key
GOOGLE_CSE_ID=your-cse-id
使用Azure OpenAI時, .env
文件中需要其他環境變量。此頁面Microsoft Azure OpenAi提供了更多信息,您可以按以下方式設置每個環境變量:
AZURE_OPENAI_API_KEY
,來自API_KEY
的值AZURE_OPENAI_API_BASE
從ENDPOINT
的值中,通常看起來像https://your.domain.azure.com
。AZURE_OPENAI_API_VERSION
,您可以在.env-template
中使用默認值,並且可以在此處找到最新版本AZURE_OPENAI_DEPLOYMENT_NAME
是已部署模型的名稱,該模型在模型設置過程中由用戶定義AZURE_OPENAI_MODEL_NAME
azure openai允許特定的型號名稱。您需要精確列出所選擇的確切型號名稱。例如,GPT-4(應為gpt-4-32k
或gpt-4
)。AZURE_OPENAI_MODEL_VERSION
,如果AZURE_OPENAI_MODEL_NAME = gpt=4
,則需要我們通過此Docker映像提供了langroid-examples
存儲庫的容器化版本。您需要做的就是在.env
文件中設置環境變量。請按照以下步驟設置容器:
# get the .env file template from `langroid` repo
wget -O .env https://raw.githubusercontent.com/langroid/langroid/main/.env-template
# Edit the .env file with your favorite editor (here nano), and remove any un-used settings. E.g. there are "dummy" values like "your-redis-port" etc -- if you are not using them, you MUST remove them.
nano .env
# launch the container
docker run -it --rm -v ./.env:/langroid/.env langroid/langroid
# Use this command to run any of the scripts in the `examples` directory
python examples/ < Path/To/Example.py >
這些是快速的預告片,可以瞥見您可以使用langroid以及您的代碼外觀。
langroid-examples
存儲庫。
LANGROID中的各種LLM提示和說明已經過測試,可與GPT-4(以及在某種程度上GPT-4O)配合使用。切換到其他LLM(本地/開放和專有)很容易(請參見上面提到的指南),並且對於某些應用程序可能就足夠了,但是通常,除非調整提示和/或多代理設置,否則您可能會看到劣等的結果。
另請參閱Getting Started Guide
以獲取詳細的教程。
單擊以擴展下面的任何代碼示例。所有這些都可以在COLAB筆記本中運行:
import langroid . language_models as lm
mdl = lm . OpenAIGPT ()
messages = [
lm . LLMMessage ( content = "You are a helpful assistant" , role = lm . Role . SYSTEM ),
lm . LLMMessage ( content = "What is the capital of Ontario?" , role = lm . Role . USER ),
]
response = mdl . chat ( messages , max_tokens = 200 )
print ( response . message )
cfg = lm . OpenAIGPTConfig (
chat_model = "local/localhost:8000" ,
chat_context_length = 4096
)
mdl = lm . OpenAIGPT ( cfg )
# now interact with it as above, or create an Agent + Task as shown below.
如果該模型由liteLLM
支持,則無需啟動代理服務器。只需將chat_model
param上的param設置為litellm/[provider]/[model]
,例如litellm/anthropic/claude-instant-1
,然後使用上述配置對象。請注意,要使用litellm
,您需要安裝langroid fut the litellm
Extra: poetry install -E litellm
或pip install langroid[litellm]
。對於遠程模型,通常需要將API鍵等設置為環境變量。您可以根據litellm文檔設置這些設置。如果缺少任何必需的環境變量,Langroid會提供有用的錯誤消息,指示需要哪些消息。請注意,要將langroid
與litellm
一起使用,您需要在虛擬env中安裝litellm
pip install langroid[litellm]
,或者如果您在langroid
repo內開發poetry install -E litellm
。
pip install langroid[litellm]
import langroid as lr
agent = lr . ChatAgent ()
# get response from agent's LLM, and put this in an interactive loop...
# answer = agent.llm_response("What is the capital of Ontario?")
# ... OR instead, set up a task (which has a built-in loop) and run it
task = lr . Task ( agent , name = "Bot" )
task . run () # ... a loop seeking response from LLM or User at each turn
玩具號碼遊戲,當給出一個數字n
時:
repeater_task
的LLM簡單地返回n
,n
是偶數,則even_task
llm返回n/2
odd_task
的llm返回3*n+1
如果n
是奇數,否則說“不知道”這些Task
中的每一個都會自動配置默認的ChatAgent
。
import langroid as lr
from langroid . utils . constants import NO_ANSWER
repeater_task = lr . Task (
name = "Repeater" ,
system_message = """
Your job is to repeat whatever number you receive.
""" ,
llm_delegate = True , # LLM takes charge of task
single_round = False ,
)
even_task = lr . Task (
name = "EvenHandler" ,
system_message = f"""
You will be given a number.
If it is even, divide by 2 and say the result, nothing else.
If it is odd, say { NO_ANSWER }
""" ,
single_round = True , # task done after 1 step() with valid response
)
odd_task = lr . Task (
name = "OddHandler" ,
system_message = f"""
You will be given a number n.
If it is odd, return (n*3+1), say nothing else.
If it is even, say { NO_ANSWER }
""" ,
single_round = True , # task done after 1 step() with valid response
)
然後將even_task
和odd_task
添加為repeater_task
的子任務,然後運行repeater_task
,以輸入為數字:
repeater_task . add_sub_task ([ even_task , odd_task ])
repeater_task . run ( "3" )
Langroid利用Pydantic支持OpenAI的功能稱呼API以及其自己的本機工具。好處是您不必寫任何JSON來指定模式,而且LLM幻覺是畸形的工具語法,Langroid會將Pydantic驗證錯誤(適當消毒)發送到LLM,以便它可以解決!
簡單示例:說代理有一個秘密列表,我們希望LLM在列表中找到最小的數字。我們希望為LLM提供一個probe
工具/功能,該工具將單個數字n
作為參數。代理中的工具處理程序方法返回其列表中的數字最多為n
。
首先使用langroid的ToolMessage
類別定義工具:
import langroid as lr
class ProbeTool ( lr . agent . ToolMessage ):
request : str = "probe" # specifies which agent method handles this tool
purpose : str = """
To find how many numbers in my list are less than or equal to
the <number> you specify.
""" # description used to instruct the LLM on when/how to use the tool
number : int # required argument to the tool
然後將SpyGameAgent
定義為ChatAgent
的子類,並使用處理此工具的方法probe
:
class SpyGameAgent ( lr . ChatAgent ):
def __init__ ( self , config : lr . ChatAgentConfig ):
super (). __init__ ( config )
self . numbers = [ 3 , 4 , 8 , 11 , 15 , 25 , 40 , 80 , 90 ]
def probe ( self , msg : ProbeTool ) -> str :
# return how many numbers in self.numbers are less or equal to msg.number
return str ( len ([ n for n in self . numbers if n <= msg . number ]))
然後,我們實例化代理,並使其能夠使用並響應該工具:
spy_game_agent = SpyGameAgent (
lr . ChatAgentConfig (
name = "Spy" ,
vecdb = None ,
use_tools = False , # don't use Langroid native tool
use_functions_api = True , # use OpenAI function-call API
)
)
spy_game_agent . enable_message ( ProbeTool )
有關完整的工作示例,請參見langroid-examples
repo中的Chat-Agent-tool.py腳本。
假設您希望代理從租賃文檔和嵌套的JSON結構中提取租賃的關鍵條款。首先通過Pydantic模型來定義所需的結構:
from pydantic import BaseModel
class LeasePeriod ( BaseModel ):
start_date : str
end_date : str
class LeaseFinancials ( BaseModel ):
monthly_rent : str
deposit : str
class Lease ( BaseModel ):
period : LeasePeriod
financials : LeaseFinancials
address : str
然後將LeaseMessage
工具定義為Langroid ToolMessage
的子類。注意該工具具有類型Lease
的必需參數terms
:
import langroid as lr
class LeaseMessage ( lr . agent . ToolMessage ):
request : str = "lease_info"
purpose : str = """
Collect information about a Commercial Lease.
"""
terms : Lease
然後使用處理此工具的方法lease_info
定義LeaseExtractorAgent
,實例化代理,並使其能夠使用並響應此工具:
class LeaseExtractorAgent ( lr . ChatAgent ):
def lease_info ( self , message : LeaseMessage ) -> str :
print (
f"""
DONE! Successfully extracted Lease Info:
{ message . terms }
"""
)
return json . dumps ( message . terms . dict ())
lease_extractor_agent = LeaseExtractorAgent ()
lease_extractor_agent . enable_message ( LeaseMessage )
有關完整的工作示例,請參見langroid-examples
repo中的chat_multi_extract.py
腳本。
為此目的,langroid為此提供了專門的代理類DocChatAgent
。它結合了文檔碎片,嵌入,存儲在矢量db中,並結合了檢索調查的查詢 - 回答生成。使用此類與文檔集合聊天很容易。首先創建一個DocChatAgentConfig
實例,並使用doc_paths
字段指定要聊天的文檔。
import langroid as lr
from langroid . agent . special import DocChatAgentConfig , DocChatAgent
config = DocChatAgentConfig (
doc_paths = [
"https://en.wikipedia.org/wiki/Language_model" ,
"https://en.wikipedia.org/wiki/N-gram_language_model" ,
"/path/to/my/notes-on-language-models.txt" ,
],
vecdb = lr . vector_store . QdrantDBConfig (),
)
然後實例化DocChatAgent
(這將文檔攝取到矢量商店中):
agent = DocChatAgent ( config )
然後,我們可以問代理人一次性問題,
agent . llm_response ( "What is a language model?" )
或將其包裝在Task
中,並與用戶運行交互式循環:
task = lr . Task ( agent )
task . run ()
請參閱langroid-examples
Repo的docqa
文件夾中的完整工作腳本。
使用langroid,您可以使用數據集(文件路徑,URL或DataFrame)設置TableChatAgent
,並查詢它。代理的LLM生成熊貓代碼以通過函數調用(或工具/插件)回答查詢,而代理的功能處理方法執行代碼並返回答案。
這是您可以做到的:
import langroid as lr
from langroid . agent . special import TableChatAgent , TableChatAgentConfig
為數據文件,URL或DataFrame設置一個TableChatAgent
(確保數據表具有標頭行;自動刪除的分界符/分隔器):
dataset = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
# or dataset = "/path/to/my/data.csv"
# or dataset = pd.read_csv("/path/to/my/data.csv")
agent = TableChatAgent (
config = TableChatAgentConfig (
data = dataset ,
)
)
設置一個任務,並提出這樣的問題:
task = lr . Task (
agent ,
name = "DataAssistant" ,
default_human_response = "" , # to avoid waiting for user input
)
result = task . run (
"What is the average alcohol content of wines with a quality rating above 7?" ,
turns = 2 # return after user question, LLM fun-call/tool response, Agent code-exec result
)
print ( result . content )
或者,設置任務並與用戶進行交互式循環運行:
task = lr . Task ( agent , name = "DataAssistant" )
task . run ()
有關完整的工作示例,請參見langroid-examples
repo中的table_chat.py
腳本。
如果您喜歡這個項目,請給它一個明星嗎?在您的網絡或社交媒體中傳播這個詞:
您的支持將有助於建立Langroid的勢頭和社區。