「LangChain大模型應用開發」 系列文章目錄:
LangChain大模型應用開發:模型,提示和輸出解釋器
LangChain大模型應用開發:儲存(Memory)
LangChain大模型應用開發:模型鏈(Chains)
LangChain大模型應用開發:基于文檔的問答
LangChain大模型應用開發:評估
LangChain大模型應用開發:代理 (Agent)
目錄
1. 使用LangChain內置工具llm-math和wikipedia
2.?定義自己的工具并在代理中使用
將自定義工具和內置工具結合
大型語言模型(LLMs)非常強大,但它們缺乏“最笨”的計算機程序可以輕松處理的特定能力。LLM 對邏輯推理、計算和檢索外部信息的能力較弱,這與最簡單的計算機程序形成對比。例如,語言模型無法準確回答簡單的計算問題,還有當詢問最近發生的事件時,其回答也可能過時或錯誤,因為無法主動獲取最新信息。這是由于當前語言模型僅依賴預訓練數據,與外界“斷開”。要克服這一缺陷,LangChain框架提出了“代理”(Agent)的解決方案。
代理作為語言模型的外部模塊,可提供計算、邏輯、檢索等功能的支持,使語言模型獲得異常強大的推理和獲取信息的超能力。
在本章中,我們將詳細介紹代理的工作機制、種類、以及如何在LangChain中將其與語言模型配合,構建功能更全面、智能程度更高的應用程序。代理機制極大擴展了語言模型的邊界,是當前提升其智能的重要途徑之一。讓我們開始學習如何通過代理釋放語言模型的最大潛力。
1. 使用LangChain內置工具llm-math和wikipedia
要使用代理 (Agents) ,我們需要三樣東西:
- 一個基本的 LLM。
- 我們將要進行交互的工具 Tools。
- 一個控制交互的代理 (Agents) 。
from langchain_openai import ChatOpenAIllm = ChatOpenAI(api_key="你的API key",base_url="https://qianfan.baidubce.com/v2",model="ernie-3.5-8k",temperature=0
)
接下來,初始化工具 Tool ,我們可以創建自定義工具 Tool 或加載預構建工具 Tool。無論哪種情況,工具 Tool 都是一個給定工具 名稱 name 和 描述 description 的 實用鏈。
- llm-math 工具結合語言模型和計算器用以進行數學計算。
- wikipedia工具通過API連接到wikipedia進行搜索查詢。
from langchain.agents import load_tools, initialize_agenttools = load_tools(["llm-math","wikipedia"], llm=llm #第一步初始化的模型
)
現在我們有了 LLM 和工具,最后讓我們初始化一個簡單的代理 (Agents) :
from langchain.agents import AgentType
# 初始化代理
agent= initialize_agent(tools, #第二步加載的工具llm, #第一步初始化的模型agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, #代理類型handle_parsing_errors=True, #處理解析錯誤verbose = True #輸出中間步驟
)
- agent: 代理類型。這里使用的是AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION。其中CHAT代表代理模型為針對對話優化的模型;Zero-shot 意味著代理 (Agents) 僅在當前操作上起作用,即它沒有記憶;REACT代表針對REACT設計的提示模版。DESCRIPTION根據工具的描述 description 來決定使用哪個工具。(我們不會在本章中討論 * REACT 框架 ,但您可以將其視為 LLM 可以循環進行 Reasoning 和 Action 步驟的過程。它啟用了一個多步驟的過程來識別答案。)
- handle_parsing_errors: 是否處理解析錯誤。當發生解析錯誤時,將錯誤信息返回給大模型,讓其進行糾正。
- verbose: 是否輸出中間步驟結果。
下面使用代理(llm-math 工具結合語言模型和計算器用以進行數學計算)回答數學問題。
agent("計算300的25%")
> Entering new AgentExecutor chain...
Question: 計算300的25%
Thought: 要計算300的25%,我可以將300乘以0.25(因為25%等于0.25)。
Action:
```json
{"action": "Calculator","action_input": "300 * 0.25"
}
```
Observation: Answer: 75.0
Thought:I now know the final answer
Final Answer: 300的25%是75。> Finished chain.{'input': '計算300的25%', 'output': '300的25%是75。'}
上面的過程可以總結為下:
模型對于接下來需要做什么,給出思考。
思考:我可以使用計算工具來計算300的25%
模型基于思考采取行動。
行動: 使用計算器(calculator),輸入(action_input)300*0.25
模型得到觀察。
觀察:答案: 75.0
基于觀察,模型對于接下來需要做什么,給出思考。
思考: 計算工具返回了300的25%,答案為75
給出最終答案(Final Answer)。
最終答案: 300的25%等于75。
以字典的形式給出最終答案。
另一個例子(wikipedia工具通過API連接到wikipedia進行搜索查詢)。
question = "Tom M. Mitchell是一位美國計算機科學家,\
也是卡內基梅隆大學(CMU)的創始人大學教授。\
他寫了哪本書呢?"agent(question)
> Entering new AgentExecutor chain...
Question: Tom M. Mitchell是哪本書的作者?
Thought: I need to find out which book was written by Tom M. Mitchell. I can use Wikipedia to search for this information.
Action:
```json
{"action": "wikipedia","action_input": "Tom M. Mitchell"
}
```Observation: Page: Tom M. Mitchell
Summary: Tom Michael Mitchell (born August 9, 1951) is an American computer scientist and the Founders University Professor at Carnegie Mellon University (CMU). He is a founder and former chair of the Machine Learning Department at CMU. Mitchell is known for his contributions to the advancement of machine learning, artificial intelligence, and cognitive neuroscience and is the author of the textbook Machine Learning. He is a member of the United States National Academy of Engineering since 2010. He is also a Fellow of the American Academy of Arts and Sciences, the American Association for the Advancement of Science and a Fellow and past president of the Association for the Advancement of Artificial Intelligence. In October 2018, Mitchell was appointed as the Interim Dean of the School of Computer Science at Carnegie Mellon.Page: Tom Mitchell (Australian footballer)
Summary: Thomas Mitchell (born 31 May 1993) is a professional Australian rules footballer playing for the Collingwood Football Club in the Australian Football League (AFL). He previously played for the Sydney Swans from 2012 to 2016, and the Hawthorn Football Club between 2017 and 2022.
Mitchell won the Brownlow Medal as the league's best and fairest player in 2018 and set the record for the most disposals in a VFL/AFL match, accruing 54 in a game against Collingwood during that season. He would later join them in 2023, en route to winning the 2023 AFL Grand Final and his first AFL premiership.
Thought:Thought: The Wikipedia page for Tom M. Mitchell mentions that he is the author of the textbook Machine Learning.
Action:
```json
{"action": "wikipedia","action_input": "Machine Learning by Tom M. Mitchell"
}
```
Observation: Page: Tom M. Mitchell
Summary: Tom Michael Mitchell (born August 9, 1951) is an American computer scientist and the Founders University Professor at Carnegie Mellon University (CMU). He is a founder and former chair of the Machine Learning Department at CMU. Mitchell is known for his contributions to the advancement of machine learning, artificial intelligence, and cognitive neuroscience and is the author of the textbook Machine Learning. He is a member of the United States National Academy of Engineering since 2010. He is also a Fellow of the American Academy of Arts and Sciences, the American Association for the Advancement of Science and a Fellow and past president of the Association for the Advancement of Artificial Intelligence. In October 2018, Mitchell was appointed as the Interim Dean of the School of Computer Science at Carnegie Mellon.Page: Machine learning
Summary: Machine learning (ML) is a field of study in artificial intelligence concerned with the development and study of statistical algorithms that can learn from data and generalise to unseen data, and thus perform tasks without explicit instructions. Within a subdiscipline in machine learning, advances in the field of deep learning have allowed neural networks, a class of statistical algorithms, to surpass many previous machine learning approaches in performance.
ML finds application in many fields, including natural language processing, computer vision, speech recognition, email filtering, agriculture, and medicine. The application of ML to business problems is known as predictive analytics.
Statistics and mathematical optimisation (mathematical programming) methods comprise the foundations of machine learning. Data mining is a related field of study, focusing on exploratory data analysis (EDA) via unsupervised learning.
From a theoretical viewpoint, probably approximately correct learning provides a framework for describing machine learning.Page: Margaret Mitchell (scientist)
...
Thought:Thought: The Wikipedia page for Tom M. Mitchell confirms that he is the author of the textbook "Machine Learning". No further action is needed.
Final Answer: Tom M. Mitchell wrote the textbook "Machine Learning".> Finished chain.
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
上面的過程可以總結為下:
模型對于接下來需要做什么,給出思考(Thought)
思考:我應該使用維基百科去搜索。
模型基于思考采取行動(Action)
行動: 使用維基百科,輸入Tom M. Mitchell
模型得到觀察(Observation)
觀測: 頁面: Tom M. Mitchell,頁面: Tom Mitchell (澳大利亞足球運動員)
基于觀察,模型對于接下來需要做什么,給出思考(Thought)
思考: Tom M. Mitchell寫的書是Machine Learning
給出最終答案(Final Answer)
最終答案: Machine Learning
以字典的形式給出最終答案。
2.?定義自己的工具并在代理中使用
在本節,我們將創建和使用自定義時間工具。LangChian tool 函數裝飾器可以應用用于任何函數,將函數轉化為LangChain 工具,使其成為代理可調用的工具。我們需要給函數加上非常詳細的文檔字符串, 使得代理知道在什么情況下、如何使用該函數/工具。比如下面的函數time
,我們加上了詳細的文檔字符串。
# 導入tool函數裝飾器
from langchain.agents import tool
from datetime import date@tool
def time(text: str) -> str:"""返回今天的日期,用于任何需要知道今天日期的問題。\輸入應該總是一個空字符串,\這個函數將總是返回今天的日期,任何日期計算應該在這個函數之外進行。"""return str(date.today())# 初始化代理
agent= initialize_agent(tools=[time], #將剛剛創建的時間工具加入代理llm=llm, #初始化的模型agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, #代理類型handle_parsing_errors=True, #處理解析錯誤verbose = True #輸出中間步驟
)# 使用代理詢問今天的日期.
# 注: 代理有時候可能會出錯(該功能正在開發中)。如果出現錯誤,請嘗試再次運行它。
agent("今天的日期是什么?")
> Entering new AgentExecutor chain...
Question: 今天的日期是什么?
Thought: I need to use the tool 'time' to get the current date.
Action:
```json
{"action": "time","action_input": ""
}
```
Observation: 2025-08-29
Thought:I now know the final answer
Final Answer: 今天的日期是2025年8月29日。> Finished chain.{'input': '今天的日期是什么?', 'output': '今天的日期是2025年8月29日。'}
將自定義工具和內置工具結合
# 導入tool函數裝飾器
from langchain.agents import tool
from datetime import date@tool
def time(text: str) -> str:"""返回今天的日期,用于任何需要知道今天日期的問題。\輸入應該總是一個空字符串,\這個函數將總是返回今天的日期,任何日期計算應該在這個函數之外進行。"""return str(date.today())tools = load_tools(["ddg-search"]) #這里使用DuckDuckGo 搜索
tools.append(time)# 初始化代理
agent= initialize_agent(tools=tools, #將剛剛創建的時間工具加入代理llm=llm, #初始化的模型agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, #代理類型handle_parsing_errors=True, #處理解析錯誤verbose = True #輸出中間步驟
)# 使用代理詢問今天的日期.
# 注: 代理有時候可能會出錯(該功能正在開發中)。如果出現錯誤,請嘗試再次運行它。today = agent("今天的日期是什么?,以年月日格式輸出")
print(today)
print(agent(f"{today}的金價是多少?用中文輸出結果。"))
{'input': "{'input': '今天的日期是什么?,以年月日格式輸出', 'output': '2025年08月29日'}的金價是多少?用中文輸出結果。", 'output': '根據搜索到的信息,2025年08月29日的金價,上海黃金交易所的現貨黃金價格為1克黃金等于779.86元人民幣。同時,也有信息顯示當日的18k金價格為596元/克。請注意,金價可能因市場波動而有所變化,這里提供的信息僅供參考。'}