Hugging Face 發佈 Transformers Agents 2.0,新增兩種可迭代的智能體
License to Call: Introducing Transformers Agents 2.0
Hugging Face 發佈 Transformers Agents 2.0,新增 ReactCodeAgent 和 ReactJsonAgent,能根據過往觀察迭代。框架以簡潔、模組化,以及工具和提示詞透明為設計目標。使用 Llama-3-70B-Instruct 的智能體在完整 GAIA 基準中排名第 4,超越多個基於 GPT-4 的智能體。
文中比較 Code 與 JSON 智能體在不同模型上的表現,並展示 Llama-3-70B-Instruct 智能體於 GAIA 的名次,可作為評估 Agent 架構與模型搭配的具體參照。
重點摘要
我們推出 Transformers Agents 2.0!
⇒ 🎁 除了原有的 agent 類型,我們新增兩種 agent,可根據過往觀察反覆操作,以解決複雜任務。
⇒ 💡 我們希望程式碼清晰、模組化,並讓最終提示和工具等常用屬性保持透明。
⇒ 🤝 我們新增分享選項,促進社羣 agent 的交流。
⇒ 💪 全新的 agent 框架效能極高,讓 Llama-3-70B-Instruct agent 在 GAIA Leaderboard 上的表現超越以 GPT-4 為基礎的 agents!
🚀 快來試試,繼續提升 GAIA leaderboard 排名!
transformers.agents現已升級為獨立函式庫 smolagents!兩者 API 非常相似,因此轉換很容易。 歡迎閲讀smolagents介紹網誌。
目錄
甚麼是 agent?
大型語言模型(LLM)能處理各式各樣的任務,但面對邏輯、計算和搜尋等特定任務時往往力有不逮。在這些表現較弱的領域給予提示,模型經常無法生成正確答案。
克服這項弱點的一種方法是建立agent,即由 LLM 驅動的程式。agent 可使用工具執行操作;解決特定問題需要某項技能時,便會從工具箱選用合適工具。
因此,agent 在解題時若需要特定技能,便可直接使用工具箱中的合適工具。
實驗結果顯示,agent 框架普遍表現出色,在多項基準測試中達到最先進水平。例如,看看 HumanEval 排名靠前的提交:它們都是 agent 系統。
Transformers Agents 的做法
建立 agent 工作流程很複雜;我們認為這些系統需要高度清晰和模組化。一年前我們推出 Transformers Agents,現在會更專注實踐核心設計目標。
我們的框架追求:
- 簡單清晰:把抽象概念減至最低。簡單的錯誤記錄和容易存取的屬性,讓你輕鬆查看運作狀況,掌握更多資訊。
- 模組化: 我們傾向提供構建積木,而非完整複雜的功能組合。你可以按專案需要,自由選擇最合適的構建積木。
- 例如,agent 系統本質上只是由 LLM engine 驅動的載體,因此我們決定在概念上把兩者分開,讓你可以配搭任何底層 LLM,建立任何類型的 agent。
此外,我們還提供分享功能,讓你站在巨人的肩膀上繼續創作!
主要元素
Tool:讓你使用工具或實作新工具的類別。它主要由可呼叫的 forwardmethod(負責執行工具操作)以及幾個必要屬性組成:name、descriptions、inputs和output_type。系統會利用這些屬性動態生成工具使用手冊,並加入 LLM 的提示。Toolbox:提供給 agent 作為解題資源的一組工具。為提升效能,工具箱內的工具都已建立實例並可隨時使用。由於部分工具需要時間初始化,通常重用現有工具箱、只替換其中一項工具,會比每次初始化 agent 時從頭建立工具組更好。CodeAgent:一種非常簡單的 agent,會把所有操作一次輸出為單一 Python 程式碼區塊,無法根據先前觀察反覆操作。ReactAgent:ReAct agents 會依循 Thought ⇒ Action ⇒ Observation 循環,直至完成任務。我們提供兩個 ReactAgent 類別:ReactCodeAgent會以 Python 程式碼區塊生成操作。ReactJsonAgent會以 JSON 區塊生成操作。
想了解如何使用各個元件,請參閲文件!
Agent 底層如何運作?
本質上,agent 的作用是「讓 LLM 使用工具」。Agent 有一個關鍵的 agent.run() 方法,會:
- 以特定提示向 LLM 説明工具的用法,讓 LLM 選取工具來完成任務。
- 從 LLM 輸出中解析工具呼叫(可使用程式碼、JSON 或其他格式)。
- 執行這些呼叫。
- 如果 agent 設計為根據先前輸出反覆操作,它會保留記憶,記錄之前的工具呼叫和觀察結果。視乎你需要的長期記憶程度,記憶內容可詳可略。
想了解 agent 的一般背景,可閲讀 Lilian Weng 的這篇精彩網誌,或參閲我們之前介紹使用 LangChain 建立 agents 的網誌。
如想深入瞭解我們的套件,請參閲agents 文件。
示例用途
如要試用此功能的搶先版,請先安裝 transformers,並使用 main branch:
pip install "git+https://github.com/huggingface/transformers.git#egg=transformers[agents]"
Agents 2.0 將於 5 月中旬推出的 v4.41.0 版本中發佈。
自我修正的檢索增強生成(RAG)
簡單來説,檢索增強生成(RAG)是「使用 LLM 回答使用者查詢,並以知識庫檢索到的資料作為依據」。相較直接使用一般或微調後的 LLM,它有不少優點:例如,答案可根據真實事實,減少虛構內容;可向 LLM 提供特定領域知識;也能精細控制知識庫資料的存取權限。
假設我們要執行 RAG,而部分參數必須動態生成。例如,視乎使用者查詢,我們可能想把搜尋限制在知識庫的特定子集,或調整檢索文件數量。難題是:如何根據使用者查詢動態調整這些參數?
我們可以讓 agent 存取這些參數來做到!
來設定這個系統。
執行以下指令,安裝所需依賴套件:
pip install langchain sentence-transformers faiss-cpu
首先載入要用於 RAG 的知識庫:這個資料集收集了多個 huggingface 套件的文件頁面,並以 Markdown 格式儲存。
import datasets
knowledge_base = datasets.load_dataset("m-ric/huggingface_doc", split="train")
接著處理資料集並將它存入向量資料庫,供檢索器使用,藉此準備知識庫。我們會使用 LangChain,因為它提供出色的向量資料庫工具:
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
source_docs = [
Document(
page_content=doc["text"], metadata={"source": doc["source"].split("/")[1]}
) for doc in knowledge_base
]
docs_processed = RecursiveCharacterTextSplitter(chunk_size=500).split_documents(source_docs)[:1000]
embedding_model = HuggingFaceEmbeddings("thenlper/gte-small")
vectordb = FAISS.from_documents(
documents=docs_processed,
embedding=embedding_model
)
資料庫準備完成後,來建立一個根據資料庫回答使用者查詢的 RAG 系統!
我們希望系統根據查詢,只從最相關的資訊來源中選取內容。
我們的文件來自以下來源:
>>> all_sources = list(set([doc.metadata["source"] for doc in docs_processed]))
>>> print(all_sources)
['blog', 'optimum', 'datasets-server', 'datasets', 'transformers', 'course',
'gradio', 'diffusers', 'evaluate', 'deep-rl-class', 'peft',
'hf-endpoints-documentation', 'pytorch-image-models', 'hub-docs']
如何根據使用者查詢選取相關來源?
👉 讓我們把 RAG 系統設計成 agent,讓它自行選擇來源!
我們建立一個檢索器工具,agent 可自行選擇參數並呼叫:
import json
from transformers.agents import Tool
from langchain_core.vectorstores import VectorStore
class RetrieverTool(Tool):
name = "retriever"
description = "Retrieves some documents from the knowledge base that have the closest embeddings to the input query."
inputs = {
"query": {
"type": "text",
"description": "The query to perform. This should be semantically close to your target documents. Use the affirmative form rather than a question.",
},
"source": {
"type": "text",
"description": ""
},
}
output_type = "text"
def __init__(self, vectordb: VectorStore, all_sources: str, **kwargs):
super().__init__(**kwargs)
self.vectordb = vectordb
self.inputs["source"]["description"] = (
f"The source of the documents to search, as a str representation of a list. Possible values in the list are: {all_sources}. If this argument is not provided, all sources will be searched."
)
def forward(self, query: str, source: str = None) -> str:
assert isinstance(query, str), "Your search query must be a string"
if source:
if isinstance(source, str) and "[" not in str(source): # if the source is not representing a list
source = [source]
source = json.loads(str(source).replace("'", '"'))
docs = self.vectordb.similarity_search(query, filter=({"source": source} if source else None), k=3)
if len(docs) == 0:
return "No documents found with this filtering. Try removing the source filter."
return "Retrieved documents:\n\n" + "\n===Document===\n".join(
[doc.page_content for doc in docs]
)
現在可以輕鬆建立使用這項工具的 agent!
初始化 agent 時需要提供以下參數:
tools:agent 可呼叫的工具清單。llm_engine:驅動 agent 的 LLM。
我們的 llm_engine 必須是可呼叫物件,輸入一組訊息並傳迴文字。它亦須接受 stop_sequences 參數,用來指定停止生成的時機。為求方便,我們直接使用套件提供的 HfEngine 類別,取得會呼叫我們Inference API 的 LLM engine。
from transformers.agents import HfEngine, ReactJsonAgent
llm_engine = HfEngine("meta-llama/Meta-Llama-3-70B-Instruct")
agent = ReactJsonAgent(
tools=[RetrieverTool(vectordb, all_sources)],
llm_engine=llm_engine
)
agent_output = agent.run("Please show me a LORA finetuning script")
print("Final output:")
print(agent_output)
由於我們把 agent 初始化為 ReactJsonAgent,系統會自動提供預設 system prompt,指示 LLM engine 逐步處理,並以 JSON 區塊生成工具呼叫(你也可以按需要改用自訂提示模板)。
啟動 agent 的 .run() 方法後,它會在迴圈中負責呼叫 LLM engine、解析工具呼叫 JSON 區塊並執行工具,直至產生最終答案才停止。
結果如下:
Calling tool: retriever with arguments: {'query': 'LORA finetuning script', 'source': "['transformers', 'datasets-server', 'datasets']"}
Calling tool: retriever with arguments: {'query': 'LORA finetuning script'}
Calling tool: retriever with arguments: {'query': 'LORA finetuning script example', 'source': "['transformers', 'datasets-server', 'datasets']"}
Calling tool: retriever with arguments: {'query': 'LORA finetuning script example'}
Calling tool: final_answer with arguments: {'answer': 'Here is an example of a LORA finetuning script: https://github.com/huggingface/diffusers/blob/dd9a5caf61f04d11c0fa9f3947b69ab0010c9a0f/examples/text_to_image/train_text_to_image_lora.py#L371'}
Final output:
Here is an example of a LORA finetuning script: https://github.com/huggingface/diffusers/blob/dd9a5caf61f04d11c0fa9f3947b69ab0010c9a0f/examples/text_to_image/train_text_to_image_lora.py#L371
可以看到 agent 正在自我修正:它最初嘗試限制來源,但由於沒有找到對應文件,最後取消了所有來源限制。
可檢查第 2 步的記錄,以確認這點:print(agent.logs[2]['llm_output'])
Thought: I'll try to retrieve some documents related to LORA finetuning scripts from the entire knowledge base, without any source filtering.
Action:
{
"action": "retriever",
"action_input": {"query": "LORA finetuning script"}
}
以簡單多 agent 配置 🤝 提升網頁瀏覽效率
在此示例中,我們要建立 agent,並以 GAIA 基準測試它(Mialon 等人,2023)。GAIA 是極具挑戰性的基準測試,大多數問題都需要使用不同工具進行多步推理。其中一項特別困難的要求,是具備強大的網頁瀏覽器,能在特定限制下瀏覽頁面:透過網站內部導覽發現頁面、按時間篩選特定文章……
網頁瀏覽需要深入子頁面,並閲讀大量對較高層次解題任務並無必要的文字 token。我們把網頁瀏覽子任務交給專用的網頁瀏覽 agent,並提供一些瀏覽工具和特定提示(實作詳情請查看 repo)。
定義這些工具不在本文討論範圍內;你可查看這個 repo瞭解具體實作。
from transformers.agents import ReactJsonAgent, HfEngine
WEB_TOOLS = [
SearchInformationTool(),
NavigationalSearchTool(),
VisitTool(),
DownloadTool(),
PageUpTool(),
PageDownTool(),
FinderTool(),
FindNextTool(),
]
websurfer_llm_engine = HfEngine(
model="CohereForAI/c4ai-command-r-plus"
) # We choose Command-R+ for its high context length
websurfer_agent = ReactJsonAgent(
tools=WEB_TOOLS,
llm_engine=websurfer_llm_engine,
)
若要讓高階任務解題 agent 呼叫這個 agent,只需把它封裝成另一個工具:
class SearchTool(Tool):
name = "ask_search_agent"
description = "A search agent that will browse the internet to answer a question. Use it to gather informations, not for problem-solving."
inputs = {
"question": {
"description": "Your question, as a natural language sentence. You are talking to an agent, so provide them with as much context as possible.",
"type": "text",
}
}
output_type = "text"
def forward(self, question: str) -> str:
return websurfer_agent.run(question)
接著使用這個搜尋工具初始化任務解題 agent:
from transformers.agents import ReactCodeAgent
llm_engine = HfEngine(model="meta-llama/Meta-Llama-3-70B-Instruct")
react_agent_hf = ReactCodeAgent(
tools=[SearchTool()],
llm_engine=llm_engine,
)
以以下任務執行 agent:
使用 LibreText《基礎化學》教材中,依據 CK-12 授權、由 Marisa Alviar-Agnew 和 Henry Agnew 編製的化學材料密度數值(整理日期:08/21/2023)。 我有一加侖蜂蜜和一加侖蛋黃醬,兩者温度均為 25C。我每次從蜂蜜中取出一杯,要取幾次,蜂蜜的重量才會低於蛋黃醬?假設兩個容器重量相同。
Thought: I will use the 'ask_search_agent' tool to find the density of honey and mayonnaise at 25C.
==== Agent is executing the code below:
density_honey = ask_search_agent(question="What is the density of honey at 25C?")
print("Density of honey:", density_honey)
density_mayo = ask_search_agent(question="What is the density of mayonnaise at 25C?")
print("Density of mayo:", density_mayo)
===
Observation:
Density of honey: The density of honey is around 1.38-1.45kg/L at 20C. Although I couldn't find information specific to 25C, minor temperature differences are unlikely to affect the density that much, so it's likely to remain within this range.
Density of mayo: The density of mayonnaise at 25°C is 0.910 g/cm³.
===== New step =====
Thought: I will convert the density of mayonnaise from g/cm³ to kg/L and then calculate the initial weights of the honey and mayonnaise in a gallon. After that, I will calculate the weight of honey after removing one cup at a time until it weighs less than the mayonnaise.
==== Agent is executing the code below:
density_honey = 1.42 # taking the average of the range
density_mayo = 0.910 # converting g/cm³ to kg/L
density_mayo = density_mayo * 1000 / 1000 # conversion
gallon_to_liters = 3.785 # conversion factor
initial_honey_weight = density_honey * gallon_to_liters
initial_mayo_weight = density_mayo * gallon_to_liters
cup_to_liters = 0.236 # conversion factor
removed_honey_weight = cup_to_liters * density_honey
===
Observation:
===== New step =====
Thought: Now that I have the initial weights of honey and mayonnaise, I'll try to calculate the number of cups to remove from the honey to make it weigh less than the mayonnaise using a simple arithmetic operation.
==== Agent is executing the code below:
cups_removed = int((initial_honey_weight - initial_mayo_weight) / removed_honey_weight) + 1
print("Cups removed:", cups_removed)
final_answer(cups_removed)
===
>>> Final answer: 6
✅ 答案正確!
測試我們的 agents
現在讓我們試用這套 agent 框架,並以不同模型進行基準測試!
以下實驗的所有程式碼都可在此處找到。
LLM engine 基準測試
agents_reasoning_benchmark 是一項規模小但能力強的推理測試,用來評估 agent 表現。我們之前的網誌已使用這項基準測試並有更詳細的説明。
核心概念是:agent 使用哪些工具,可能大幅改變它在特定任務上的表現。因此,這項基準測試把工具限制為計算機和基本搜尋工具。我們從多個資料集中挑選可單靠這兩種工具解決的問題:
- HotpotQA 的 30 條問題(HotpotQA;Yang 等人,2018),用來測試搜尋工具的使用。
- 來自 GSM8K 的 40 條問題 (Cobbe 等人,2021),用來測試計算機的使用。
- GAIA 的 20 條問題 (GAIA;Mialon 等人,2023),用來測試同時使用兩種工具解決難題。
我們測試 3 種 engine:Mixtral-8x7B、Llama-3-70B-Instruct 和 GPT-4 Turbo。
以上展示的結果是兩次完整測試的平均值,以提高準確度。我們也測試了 Command-R+ 和 Mixtral-8x22B,但為求清晰沒有顯示。
⇒ Llama-3-70B-Instruct 在開放原始碼模型中領先,表現與 GPT-4 相若;它在 ReactCodeAgent 上尤其出色,受惠於 Llama 3 強大的程式碼能力!
💡 比較 JSON 和程式碼形式的 React agents 很有意思:使用 Mixtral-8x7B 等較弱的 LLM engine 時,程式碼 agent 表現不及 JSON,因為 engine 經常無法生成良好程式碼。但搭配更強大的模型時,程式碼版本就大放異彩;以我們的經驗,它在 Llama-3-70B-Instruct 上甚至勝過 JSON 版本。因此,我們會使用程式碼版本挑戰下一項任務:測試完整 GAIA 基準測試。
以多模態 agent 攀升 GAIA Leaderboard 排名
GAIA(Mialon 等人,2023)是極具挑戰性的基準測試:如上方 agent_reasoning_benchmark 所示,即使我們只挑選可用 2 種基本工具解決的任務,模型表現仍不到 50%。
現在我們要在完整資料集取得分數,不再挑選問題。因此必須涵蓋所有模態,並使用以下特定工具:
SearchTool:上方定義的網頁瀏覽器。TextInspectorTool:以文字檔開啟文件並傳回內容。SpeechToTextTool:把音訊檔轉錄為文字。我們使用以 distil-whisper 為基礎的預設工具。VisualQATool:以視覺方式分析圖像。我們使用全新的 Idefics2-8b-chatty!
首先初始化這些工具(詳情請查看repo 中的程式碼)。
然後初始化 agent:
from transformers.agents import ReactCodeAgent, HfEngine
TASK_SOLVING_TOOLBOX = [
SearchTool(),
VisualQATool(),
SpeechToTextTool(),
TextInspectorTool(),
]
react_agent_hf = ReactCodeAgent(
tools=TASK_SOLVING_TOOLBOX,
llm_engine=HfEngine(model="meta-llama/Meta-Llama-3-70B-Instruct"),
memory_verbose=True,
)
等待完成 165 條問題後,我們把結果提交至 GAIA Leaderboard,然後……🥁🥁🥁
⇒ 我們的 agent 排名第 4:表現超越多個以 GPT-4 為基礎的 agents,並成為開放原始碼類別的現任領先者!
總結
未來幾個月,我們會繼續改進這個套件,並已在開發路線圖中確定數個令人振奮的方向:
- 更多 agent 分享選項:目前可從 Hub 推送或載入工具;接下來也會加入推送和載入 agents 的功能。
- 更好的工具,尤其是圖像處理工具。
- 長期記憶管理。
- 多 agent 協作。
👉 快來試用 transformers agents!期待收到你的意見和想法。
讓我們以更多開放原始碼模型登上排行榜前列!🚀
transformers.agents現已升級為獨立函式庫 smolagents!兩者 API 非常相似,因此轉換很容易。 歡迎閲讀smolagents介紹網誌。
來源:Hugging Face Blog · huggingface.co