React Agent 自定義實現(xiàn)代碼
背景
之前使用過 langchian 中的 agent 去實現(xiàn)過一些案例,angchian 的 React Agent 是有問題的,且內部代碼有點難看懂,所以自己來根據(jù) React 思想,靈活來實現(xiàn)試一下。
可以先看看我自定義實現(xiàn)的邏輯圖,后面詳細說明:

langchin 中的 agent
langchian 中的幾種 agent 怎么用,我都看過了,也整理了一下了,那些能用,那些有問題的可以看注釋,代碼鏈接:https://github.com/5zjk5/prompt-engineering

langchin 中 agent 的問題
先來說說我用過的發(fā)現(xiàn)的問題,就是它的 React agent 有點問題,只調用一個工具就結束了,詳細實驗的文章:langchain 的 agent + tool 使用_langchain agent tool-CSDN博客
想去看看代碼到底怎么運行的,發(fā)現(xiàn)太難看懂了。
后面在我自己實現(xiàn) React agent 的時候,突然發(fā)現(xiàn),跟 prompt 關系挺大的,langchian 那個 prompt 應該是根據(jù) openai 的去寫的,這是我目前想到只能調用一個工具的原因。
langchain 的 agent 案例
GitHub - 5zjk5/prompt-engineering: prompt 工程項目案例

自定義 React Agent
大模型
用的智譜 glm-4-air,如果換了模型,效果還不太穩(wěn)定,需要調 prompt。
工具定義
定義兩個工具,一個是 tavily 的搜索,去官網(wǎng)開通賬號就可以獲得一個 api,免費調用 1000 次;
一個工具是根據(jù)名字查詢身高的自定義函數(shù)
from tavily import TavilyClient
from llm.llm_api_key import TAVILY_API_KEY
import time
def tavily_search(query):
try:
# Step 1. Instantiating your TavilyClient
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
# Step 2. Executing a Q&A search query
answer = tavily_client.qna_search(query=query)
# Step 3. That's it! Your question has been answered!
return answer
except:
time.sleep(1)
# Step 1. Instantiating your TavilyClient
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
# Step 2. Executing a Q&A search query
answer = tavily_client.qna_search(query=query)
# Step 3. That's it! Your question has been answered!
return answer
def height_search(name):
height_dic = {
"張三": 180,
"李四": 175,
"王五": 170,
"趙六": 165,
"錢七": 160,
"孫八": 175,
"周九": 170,
"吳十": 165,
"鄭十一": 180,
"王十二": 175,
"李十三": 170,
"趙十四": 165,
"錢十五": 180,
"孫十六": 175,
}
return height_dic.get(name)工具描述,要讓大模型理解工具,需要定義描述,這里參考的智譜官方的工具的描述寫法:
tavily_search_tool = {
"type": "function",
"function": {
"name": 'tavily_search',
"description": "根據(jù)用戶查詢,去搜索引擎,返回搜索結果",
"parameters": {
"type": "object",
"properties": {
"query": {
"description": "用戶搜索內容 query",
"type": "string"
},
},
"required": ["query"]
}
}
}
height_search_tool = {
"type": "function",
"function": {
"name": 'height_search',
"description": "只要是有姓名,身高關鍵字,都需要使用此工具根據(jù)姓名,查詢對應身高,每次只能查詢一個人的身高",
"parameters": {
"type": "object",
"properties": {
"name": {
"description": "指具體的姓名或名字",
"type": "string"
},
},
"required": ["name"]
}
}
}問題設定
設定一個問題:

這個問題潛在意圖是查詢錢七,李四身高,并且搜索大模型定義,是想調用身高查詢工具 2 次,搜索工具 1 次。
問題改寫,挖掘潛在意圖
為什么加這一步呢?因為把問題傳給大模型后發(fā)現(xiàn)一個問題,它可能發(fā)現(xiàn)不了潛在意圖,例如這里潛在意圖要查詢身高,問題中沒有明顯提出,大模型思考結果:

這樣的話就只使用搜索工具就結束了,所以加了一步問題改寫,去發(fā)現(xiàn)潛在意圖,是利用大模型能力去做的,用 prompt,改寫結果成功識別出潛在意圖,并思考出要調用哪個工具:

盡你所能改寫以下問題,可以有多個答案,可以參照以下工具進行改寫,識別用戶潛在意圖:
```{tools}```
Question:`{query}`
Answer 按照以下格式,每一點代表一個意圖,如果需要用到工具的需要列出工具名字,不需要具體參數(shù):
```
1.
2.
...
```
React Prompt
React agent 核心的 prompt 怎么讓模型自動規(guī)劃,先來看 langchain 中的寫法:
Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought:{agent_scratchpad}傳入變量 tool 為所有工具,tool_names 為所有工具名稱列表,input 問題輸入,agent_scratchpad 思考要做什么,怎么做。
參照進行改編:
盡你所能回答以下問題。您可以使用以下工具:
```{tools}```
嚴格使用以下 JSON 格式:
```
{{
Question: 根據(jù) thought 當前需要回答的問題,此字段必須存在
Thought: 對于 Question 要做什么,此字段必須存在
Action: {{'tool': 要采取的動作,應該是[{tool_names}]之一,如果不需要工具可以空著}}
Action Input: 動作的輸入,是一個 JSON 格式,此字段必須存在,如果不需要輸入可以空著
Observation: 行動的結果,此字段必須存在,默認為空
}}
```
(Question/Thought/Action/Action Input/Observation 五個字段必須存在,以上步驟只能重復 1 次)
開始吧!
Question:`{query}`
thought:`{agent_scratchpad}`根據(jù) agent_scratchpad 每次運行得到 json 的 action,接著提取工具名及參數(shù),去進行工具調用,這里因為是 json,格式控制好了提取就方便了。
使用完工具后,把結果賦值給 Observation。
下一步規(guī)劃
agent_scratchpad 就是下一步規(guī)劃的思考,用 prompt 去進行規(guī)劃,傳給已經(jīng)執(zhí)行的 action,問題及思考,讓自動規(guī)劃下一步應該做什么:
# 背景
有一個問題 Question,已經(jīng)有了對這個問題的思考 Thought,已執(zhí)行的思考 Action,需要根據(jù)這些信息去規(guī)劃出下一步應該做什么。
# 輸入
## Question:`{query}`
## Thought:`{thought}`
## Action:`{all_action_res}`
# 思考推理:
- 1、參考 Question 仔細理解 Thought,思考 Action 還有哪些沒有行動。
- 2、判斷你下一步做什么行動,不能過于發(fā)散過多的行動,必須根據(jù)步驟 1 的思考。
- 3、確保你的回答在語義上與 Action 中的內容不重復是一個全新的步驟。
- 4、若 Thought 已經(jīng)全部執(zhí)行了,直接回答`no`。
# 輸出要求(嚴格按照以下要求輸出)
- 回答需要用一句話清晰的總結下一步需要做什么,不需要其他任何信息。
- 如果沒有需要做的了,直接輸出`no`,不需要其他任何信息,不需要解釋任何理由。這里遇到一個問題,就是可能會一直重復規(guī)劃,導致死循環(huán),在代碼中加了判斷,理論上開始重復規(guī)劃了,說明已經(jīng)沒有可以給出新的規(guī)劃了,那就結束吧。
問題總結
所有 action 的結果,用了一個列表保存的,最后用大模型自己去總結去回答問題就可以了。

D:\programming\dev_env\anaconda\anaconda3\python.exe "D:\Python_project\NLP\大模型學習\prompt-engineering\自定義 React Agant\run_agent.py"
D:\programming\dev_env\anaconda\anaconda3\Lib\site-packages\langchain\callbacks\__init__.py:37: LangChainDeprecationWarning: Importing this callback from langchain is deprecated. Importing it from langchain will no longer be supported as of langchain==0.2.0. Please import from langchain-community instead:
`from langchain_community.callbacks import get_openai_callback`.
To install langchain-community run `pip install -U langchain-community`.
warnings.warn(
輸入 token:103/輸出 token:268/總共 token:371/
問題改寫,識別潛在意圖:
1. 識別用戶提到的“身高比較高的小伙子”和“長得像錢七”,可能需要查詢錢七的身高信息(使用工具:height_search)。
2. 識別用戶提到的“還有他跟他身高差不多的兄弟李四”,可能需要查詢李四的身高信息(使用工具:height_search)。
3. 用戶對“大模型”表示不清楚,需要解釋或搜索“大模型”的定義和相關信息(使用工具:tavily_search)。
=====================================
輸入 token:53/輸出 token:376/總共 token:429/
解決此問題的思考 Thought:
根據(jù)用戶的問題,我們需要查詢錢七和李四的身高信息,并獲取關于“大模型”的解釋和相關信息。因此,我們需要使用height_search工具來查詢身高信息,以及使用tavily_search工具來搜索大模型的相關內容。
=====================================
輸入 token:89/輸出 token:426/總共 token:515/
{'Action': {'tool': 'height_search'},
'Action Input': {'name': '錢七'},
'Observation': 160,
'Question': '1. 識別用戶提到的“身高比較高的小伙子”和“長得像錢七”,可能需要查詢錢七的身高信息(使用工具:height_search)。',
'Thought': '需要使用工具查詢錢七的身高信息。'}
=====================================
輸入 token:12/輸出 token:289/總共 token:301/
下一步需要做什么:
需要使用工具查詢李四的身高信息。
=====================================
輸入 token:60/輸出 token:435/總共 token:495/
{'Action': {'tool': 'height_search'},
'Action Input': {'name': '李四'},
'Observation': 175,
'Question': '查詢李四的身高信息。',
'Thought': '使用height_search工具查詢李四的身高。'}
=====================================
輸入 token:14/輸出 token:301/總共 token:315/
下一步需要做什么:
使用tavily_search工具搜索大模型的相關內容。
=====================================
輸入 token:61/輸出 token:437/總共 token:498/
{'Action': {'tool': 'tavily_search'},
'Action Input': {'query': '大模型是什么意思'},
'Observation': 'Based on the data provided, the term "大模型" (Big Model) refers '
'to a method or technology used in the fields of machine '
'learning and artificial intelligence to handle large-scale '
'data and complex models. These models are typically '
'constructed using deep neural networks with a large number of '
'parameters, ranging from billions to even trillions. The '
'purpose of big models is to improve model expressive power '
'and predictive performance, enabling them to handle more '
'complex tasks and datasets effectively. Big models play a '
'crucial role in addressing challenges posed by increasing '
'data volumes and model complexities in the field of AI and '
'machine learning.',
'Question': '大模型是什么意思?',
'Thought': '使用搜索引擎查詢大模型的相關信息。'}
=====================================
輸入 token:10/輸出 token:311/總共 token:321/
開始生成重復步驟,或已執(zhí)行 action 過多,判斷結束了!重復步驟:使用搜索引擎查詢大模型的相關信息。
下一步需要做什么:
no
=====================================
輸入 token:109/輸出 token:332/總共 token:441/
最終答案:
根據(jù)您的描述,錢七的身高是160厘米,而李四的身高是175厘米。至于您提到的“大模型”,這是一種在機器學習和人工智能領域中使用的方法或技術。大模型通常指的是具有大量參數(shù)(從數(shù)十億到數(shù)萬億不等)的深度神經(jīng)網(wǎng)絡模型。這些模型的目的是提高表達能力和預測性能,使它們能夠更有效地處理大規(guī)模數(shù)據(jù)和復雜任務。
簡而言之,大模型是為了應對人工智能和機器學習領域中數(shù)據(jù)量增加和模型復雜性提升的挑戰(zhàn)而發(fā)展起來的技術。
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Process finished with exit code 0代碼
prompt-engineering/自定義 React Agant at master · 5zjk5/prompt-engineering · GitHub
到此這篇關于React Agent 自定義實現(xiàn)的文章就介紹到這了,更多相關React Agent 自定義內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
解決React報錯React.Children.only expected to rece
這篇文章主要為大家介紹了React報錯React.Children.only expected to receive single React element child分析解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01
react-navigation 如何判斷用戶是否登錄跳轉到登錄頁的方法
本篇文章主要介紹了react-navigation 如何判斷用戶是否登錄跳轉到登錄頁的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12
React系列useSyncExternalStore學習詳解
這篇文章主要為大家介紹了React系列useSyncExternalStore的學習及示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
React動畫實現(xiàn)方案Framer Motion讓頁面自己動起來
這篇文章主要為大家介紹了React動畫實現(xiàn)方案Framer Motion讓頁面自己動起來,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
React使用fullpage.js實現(xiàn)整屏翻頁功能
最近筆者在完成一個移動端小項目的過程中需要實現(xiàn)整屏翻頁的效果;調研完畢之后,最終決定使用pullPage.js實現(xiàn)此功能,fullPage.js使用起來比較方便,并且官網(wǎng)上也給了在react項目中使用的demo,本文記錄了這個第三方庫的使用過程,感興趣的朋友可以參考下2023-11-11
React如何使用Portal實現(xiàn)跨層級DOM渲染
Portal 就像是一個“傳送門”,能讓你把組件里的元素“傳送到”其他 DOM 節(jié)點下面去渲染,下面小編就來和大家簡單介紹一下具體的使用方法吧2025-04-04
React自定義實現(xiàn)useWatch的方式和特點
這篇文章主要介紹了React自定義實現(xiàn)useWatch的方式和特點,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2025-05-05

