「LangChain 學習筆記」LangChain大模型應用開發:代理 (Agent)

「LangChain大模型應用開發」 系列文章目錄:

  1. LangChain大模型應用開發:模型,提示和輸出解釋器

  2. LangChain大模型應用開發:儲存(Memory)

  3. LangChain大模型應用開發:模型鏈(Chains)

  4. LangChain大模型應用開發:基于文檔的問答

  5. LangChain大模型應用開發:評估

  6. 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。'}

上面的過程可以總結為下:

  1. 模型對于接下來需要做什么,給出思考。

    思考:我可以使用計算工具來計算300的25%

  2. 模型基于思考采取行動。

    行動: 使用計算器(calculator),輸入(action_input)300*0.25

  3. 模型得到觀察。

    觀察:答案: 75.0

  4. 基于觀察,模型對于接下來需要做什么,給出思考。

    思考: 計算工具返回了300的25%,答案為75

  5. 給出最終答案(Final Answer)。

    最終答案: 300的25%等于75。

  6. 以字典的形式給出最終答案。

另一個例子(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...

上面的過程可以總結為下:

  1. 模型對于接下來需要做什么,給出思考(Thought)

    思考:我應該使用維基百科去搜索。

  2. 模型基于思考采取行動(Action)

    行動: 使用維基百科,輸入Tom M. Mitchell

  3. 模型得到觀察(Observation)

    觀測: 頁面: Tom M. Mitchell,頁面: Tom Mitchell (澳大利亞足球運動員)

  4. 基于觀察,模型對于接下來需要做什么,給出思考(Thought)

    思考: Tom M. Mitchell寫的書是Machine Learning

  5. 給出最終答案(Final Answer)

    最終答案: Machine Learning

  6. 以字典的形式給出最終答案。

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元/克。請注意,金價可能因市場波動而有所變化,這里提供的信息僅供參考。'}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/95179.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/95179.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/95179.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python pyqt5開發DoIP上位機【介紹】

目錄文章合集一、核心功能概述二、主要模塊解析1. 導入的庫2. 輔助函數3. DOIP協議處理(DOIPProtocol類)4. 網絡工具(NetworkUtils類)5. 通信線程(DOIPCommunicationThread類)6. UDS命令輸入組件&#xff0…

從零實現一個可擴展的規則解析引擎 —— 支持 AND/OR 優先級、短路求值與多類型運算符

在日常業務開發中,我們經常需要基于一些“規則”來決定程序的走向。比如: 客服機器人 根據用戶問題領域和復雜度選擇不同的模型;營銷系統 根據用戶畫像匹配不同優惠券;風控引擎 根據請求參數、時間、分值判定是否放行。 這些規則往…

Preprocessing Model in MPC 3 - 基于同態加密的協議 - Over Rings 環

參考論文:SoK: Multiparty Computation in the Preprocessing Model MPC (Secure Multi-Party Computation) 博士生入門資料。抄襲必究。 本系列教程將逐字解讀參考論文(以下簡稱MPCiPPM),在此過程中,將論文中涵蓋的40篇參考文獻進行梳理與講…

uni-app 跨平臺項目的 iOS 上架流程:多工具組合的高效協作方案

跨平臺框架的興起,讓許多團隊選擇 uni-app 來開發移動應用。 一套代碼多端運行,確實大大降低了研發成本,但當項目進入 iOS 上架階段 時,很多團隊依舊面臨挑戰:證書復雜、環境不統一、上傳繁瑣。 本文結合實戰經驗&…

掌握 Linux 文件權限:chown 命令深度解析與實踐

在 Linux 系統的日常運維與開發工作里,文件權限管理是保障系統安全、規范文件訪問的關鍵環節。其中,chown 命令作為修改文件所有者及關聯組的核心工具,對精準把控文件權限起著重要作用。接下來,我們將全面拆解 chown 命令&#xf…

計算機算術7-浮點基礎知識

1. 浮點表示其中b表示基底,e表示指數,s表示尾數,注意在s的表示過程中,有個隱藏1.同時還有個符號位從下面這個圖可以看出,向上溢出和向下溢出的概念,overflow表示的是數的絕對值超過了最大的表示范圍&#x…

設計模式8-命令模式

定義 Command Partern: 將一個請求封裝成一個對象,從而讓你使用不同的請求把客戶端參數化,對請求排隊或者記錄請求日志,可以提供命令的撤銷和恢復功能。(核心思想是將“動作”與“執行者”解耦) 場景 GUI:…

數據結構(順序表力扣刷題)

1.移除元素 給你一個數組 nums 和一個值 val,你需要 原地 移除所有數值等于 val 的元素。元素的順序可能發生改變。然后返回 nums 中與 val 不同的元素的數量。 假設 nums 中不等于 val 的元素數量為 k,要通過此題,您需要執行以下操作&…

機器學習 - Kaggle項目實踐(6)Dogs vs. Cats Redux: Kernels Edition 貓狗二分類

Dogs vs. Cats Redux: Kernels Edition | Kaggle 任務:給定貓狗圖像數據集 進行二分類。 Cats or Dogs - using CNN with Transfer Learning | Kaggle(參考) Cats or Dogs | Kaggle (我的kaggle) 本文介紹了使用Re…

基礎的匯編指令

目錄 1、接上一個csdn特殊功能寄存器 1.1CPSR寄存器 1.2SPSR寄存器 1.3CPSR寄存器的高四位和第四位 ?編輯 2、匯編指令的分類 3、匯編指令的基本格式 4、數據搬移指令(賦值指令) 4.1指令碼 4.2指令格式 4.3測試代碼 4.5立即數 4.6ldr偽指令 …

Docker實戰避坑指南:從入門到精通

摘要:文人結合自身微服務實踐,系統梳理從安裝適配、鏡像拉取,到運行配置、構建優化、多容器編排、數據持久化、監控運維等 Docker 全流程高頻踩坑點,給出可落地的解決方案,幫助讀者快速規避同類問題并提升容器化效率。…

《Bishop PRML》10.1. Variational Inference(2)理解VAE

通過VAE與AE理解變分分布的變量 如何理解變分推斷公式中,Z和X的含義是什么? 知乎 變分自編碼器VAE的數學原理。 csdn 變分自編碼器(VAE)的數學原理以及實現 Loss functions in Variational Autoencoders (VAEs) 一文解釋 VAE+ELBO AE的編碼和解碼是確定性的。VAE的解碼過程…

函數調用中的初始化與賦值——深入理解C++對象的生命周期

技術博客:函數調用中的初始化與賦值——深入理解C對象的生命周期引言在C編程中,理解函數調用過程中參數傳遞、對象創建和返回值處理的細節對于編寫高效且無誤的代碼至關重要。本文將通過一個具體的例子來探討函數調用時實參到形參的轉換過程,…

矩陣微積分的鏈式法則(chain rule)

矩陣微積分的鏈式法則(chain rule)與標量情況一樣,用于求復合函數的導數,但由于涉及矩陣和向量的求導,維度匹配和布局約定(numerator-layout vs. denominator-layout)必須格外小心。下面給出常見…

網絡編程4-并發服務器、阻塞與非阻塞IO、信號驅動模型、IO多路復用..

一、并發服務器1、單循環服務器(順序處理) 一次只能處理一個客戶端連接,只有當前客戶端斷開連接后,才能接受新的客戶端連接2、多進程/多線程并發服務器while(1) {connfd accept(listenfd);pid fork(); // 或 pthread_cr…

在 WSL2-NVIDIA-Workbench 中安裝Anaconda、CUDA 13.0、cuDNN 9.12 及 PyTorch(含完整環境驗證)

在 WSL-NVIDIA-Workbench(NVIDIA AI Workbench & Ubuntu 22.04)中 安裝 Anaconda、CUDA 13.0、cuDNN 9.12 及 PyTorch 步驟也可參閱: 在WSL2-Ubuntu中安裝Anaconda、CUDA13.0、cuDNN9.12及PyTorch(含完整環境驗證&#xf…

Shell編程核心入門:參數傳遞、運算符與流程控制全解析

Shell編程核心入門:參數傳遞、運算符與流程控制全解析 在Linux/Unix系統中,Shell作為命令解釋器和腳本語言,是自動化運維、批量處理任務的核心工具。掌握Shell腳本的參數傳遞、運算符使用和流程控制,能讓你從“手動執行命令”升級…

如何用 Kotlin 在 Android 手機開發一個應用程序獲取網絡時間

使用 NTP 協議獲取網絡時間在 build.gradle 文件中添加以下依賴:implementation commons-net:commons-net:3.6創建 NTP 時間獲取工具類:import org.apache.commons.net.ntp.NTPUDPClient import org.apache.commons.net.ntp.TimeInfo import java.net.In…

python智慧交通數據分析可視化系統 車流實時檢測分析 深度學習 車流量實時檢測跟蹤 軌跡跟蹤 畢業設計?

博主介紹:?全網粉絲50W,前互聯網大廠軟件研發、集結碩博英豪成立軟件開發工作室,專注于計算機相關專業項目實戰6年之久,累計開發項目作品上萬套。憑借豐富的經驗與專業實力,已幫助成千上萬的學生順利畢業,…

計算機視覺第一課opencv(四)保姆級教學

目錄 簡介 一、輪廓檢測 1.查找輪廓的API 2.代碼分析 2.1.圖像二值化處理 2.2輪廓檢測 2.3輪廓繪制 2.4輪廓面積計算 2.5輪廓周長計算 2.6篩選特定面積的輪廓 2.7查找最大面積的輪廓 2.8繪制輪廓的外接圓 2.9繪制輪廓的外接矩形 二、輪廓的近似 三、模板匹配 簡…