[datawhale202405]從零手搓大模型實戰:TinyAgent

結論速遞

TinyAgent項目實現了一個簡單的Agent智能體,主要是實現了ReAct策略(推理+調用工具的能力),及封裝了一個Tool。

項目實現有一定的疏漏。為了正確運行代碼,本次對代碼Agent部分進行了簡單修改(完善ReAct prompt及LLM的多次循環調用)。

前情回顧

  1. TinyRAG

目錄

    • 結論速遞
    • 前情回顧
  • 1 緒論
    • 1.1 LLM Agent
    • 1.2 ReAct
    • 1.3 如何手搓Agent
  • 2 TinyAgent
    • 2.1 項目結構
    • 2.2 代碼閱讀
      • 2.2.1 Agent
      • 2.2.2 Tool
      • 2.2.3 LLM
    • 2.3 運行案例
      • 2.3.1 代碼修改
      • 2.3.2 運行結果
    • 參考閱讀

1 緒論

1.1 LLM Agent

Agent是人工智能中一個廣為人知的概念,指代理人類完成部分工作的AI程序。

LLM Agent是利用LLM構建Agent,比較受到廣泛認可的方式是使用LLM作為Agent的大腦,讓其自主規劃、利用工具來完成人類指定的任務。如下圖所示,圖片出自The Rise and Potential of Large Language Model Based Agents: A Survey。

Conceptual framework of LLM-based agent with three components: brain, perception, and
action

關于Agent有很多有名的項目,除了單Agent之外,Multi-agent也是目前一個比較流行的研究方向(simulated agent society)。
請添加圖片描述

  • AI小鎮
  • ChatDev
  • MetaGPT

1.2 ReAct

ReAct是一種prompt策略,它將CoT(思維鏈策略)和action(操作工具)結合,使LLM能夠實時規劃和調整操作工具的策略,從而完成較復雜的任務。下圖出自ReAct project。

1.3 如何手搓Agent

之前簡單玩過Langchain和CrewAI的agent,都是ReAct策略的agent,簡單理解agent是prompt-based的role+tool use,其中tool use借助ReAct實現

所以,手搓Agent需要完成

  • 定義Agent的prompt構建:
    • 角色
    • 任務
    • ReAct策略
  • tool:
    • input處理:把agent的動作處理為API的輸入
    • 調用API

2 TinyAgent

2.1 項目結構

項目由三大部分構成

  • Agent:集成了prompt模板,其中agent的動作的截取也在此實現
  • Tool:實現了tool的封裝
  • LLM:實現LLM的調用

2.2 代碼閱讀

2.2.1 Agent

代碼詳見tinyAgent/Agent.py,下為筆記

有兩大部分組成

  • prompt:分為兩塊,一塊是tool描述的模板,一塊是ReAct的模板
    在這里插入圖片描述
    • tool描述:由三個部分組成,tool唯一名name_for_model,tool描述(name_for_human工具人類名,description_for_model工具功能),調用tool所需要生成的格式及參數(JSON格式,指定parameters)。
      其中tool唯一名 和 調用tool所需要生成的格式及參數 是decode LLM的回復時需要的,tool描述是方便LLM理解這個工具是干什么的(這個在多工具時很重要)
    {name_for_model}: Call this tool to interact with the {name_for_human} API. What is the {name_for_human} API useful for? {description_for_model} Parameters: {parameters} Format the arguments as a JSON object.
    
    • ReAct策略:規定了由Question,Thought,Action,Action Input, Observation構成,并且從思考動作到觀測這個步驟可以重復多次。這個是ReAct的核心。
  • Agent:
    • LLM調用:build_system_input構建調用LLM所需的prompt,text_completion調用LLM生成回復。只執行了兩次調用
    • 工具調用:parse_latest_plugin_call解析/解碼LLM回復中關于調用工具的部分,確定調用的tool唯一名 和 調用tool的參數;call_plugin調用工具得到結果。
      疑問:parse_latest_plugin_call沒有用正則,而使用的字符串遍歷,是出于什么考慮呢?
class Agent:def __init__(self, path: str = '') -> None:passdef build_system_input(self):# 構造上文中所說的系統提示詞passdef parse_latest_plugin_call(self, text):# 解析第一次大模型返回選擇的工具和工具參數passdef call_plugin(self, plugin_name, plugin_args):# 調用選擇的工具passdef text_completion(self, text, history=[]):# 整合兩次調用pass

Agent的一次回答(解決問題)是LLM多次回復的結果,這是和先前的ChatLLM顯著不同的地方。

疑問:是不是應該有action回合數控制?以實現多次調用

2.2.2 Tool

代碼詳見tinyAgent/tool.py,下為筆記

實現了Tools類,其實應該是寫成abstract類及繼承子類的形式會比較合理,但是因為這里只有一個tool,所以就混在了一起。

  • 內部方法_tools,包含了構建tool描述prompt的四大基本信息:name_for_modelname_for_humandescription_for_modelparameters
  • 調用API的功能方法:這里是Google search所以是 google_search的調用google搜索的http POST。

2.2.3 LLM

代碼詳見tinyAgent/LLM.py,下為筆記

abstract類+繼承子類的形式,就是LLM的調用封裝(因為這里是開源模型調用),兩個核心功能

  • 加載模型
  • 推理

如果改調用API的話,可以參考TinyRAG的實現。

2.3 運行案例

2.3.1 代碼修改

用Colab跑的,開源模型調用的是internlm/internlm2-chat-1_8b,把所有中文描述都改成了英文。

internlm/internlm2-chat-1_8b會編造工具,所以修改了system_prompt,要求它不能使用其他工具。

完整的prompt:

Answer the following questions as best you can. You have access to the following tools:google_search: Call this tool to interact with the Google Search API. What is the Google Search API useful for? Google Search is a general search engine that can be used to access the internet, consult encyclopedias, learn about current news, and more. Parameters: [{'name': 'search_query', 'description': 'Search for a keyword or phrase', 'required': True, 'schema': {'type': 'string'}}] Format the arguments as a JSON object.Do not use other 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 [google_search]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
Thought: I now know the final answer
Final Answer: the final answer to the original input questionBegin!

修改了Agent類的兩個函數,使其:

  • 在調用其他工具時返回Wrong input的提示、
  • 多次調用LLM,直到獲得Final Answer或者達到調用上限(設為5)
class Agent:...def call_plugin(self, plugin_name, plugin_args):plugin_args = json5.loads(plugin_args)if plugin_name == 'google_search':return '\nObservation:' + self.tool.google_search(**plugin_args)else:return '\nWrong input!'def text_completion(self, text, history=[]):response = "\nQuestion:" + textfor i in range(5):response, history = self.model.chat(response, history, self.system_prompt)if response.rfind('\nFinal Answer:') > 0:breakplugin_name, plugin_args, response = self.parse_latest_plugin_call(response)if plugin_name:response += self.call_plugin(plugin_name, plugin_args)print(response)return response, history

2.3.2 運行結果

運行示例如下,可以正確解決問題

  • 周杰倫哪年生
response, _ = agent.text_completion(text='Which year was Jay Chou born?', history=_)
print(response)
Thought: To answer this question, I need to search for information about Jay Chou's birth year. I will use the Google Search API to find relevant search results.
Action: google_search
Action Input: {"search_query": "Jay Chou birth year"}
Observation:Overview · Born. January 18, 1979 · New Taipei, Taiwan · Birth name. Chieh-Lun Chou · Nicknames. President Chou; Director Chou · Height. 5′ 8″ (1.73 m) ...
Thought: Jay Chou was born on January 18, 1979. He is a Taiwanese singer, songwriter, and actor. He is known for his contributions to the Taiwanese music industry and has released numerous hit songs throughout his career. Chou has also acted in Taiwanese television dramas and films. He is considered one of the most successful and influential Taiwanese artists of all time.
Final Answer: Jay Chou was born on January 18, 1979. He is a Taiwanese singer, songwriter, and actor. He is known for his contributions to the Taiwanese music industry and has released numerous hit songs throughout his career. Chou has also acted in Taiwanese television dramas and films. He is considered one of the most successful and influential Taiwanese artists of all time.
  • 第一張專輯什么時候發的
response, _ = agent.text_completion(text='What was his first album?', history=_)
print(response)
Thought: To answer this question, I need to search for information about Jay Chou's first album. I will use the Google Search API to find relevant search results.
Action: google_search
Action Input: {"search_query": "Jay Chou first album"}
Observation:Jay is the debut studio album by Taiwanese singer Jay Chou. It was released on November 7, 2000, by BMG Taiwan. It was entirely produced and composed by ...
Thought: Jay Chou's first album is titled \"Jay\" and was released on November 7, 2000. It was entirely produced and composed by Jay Chou himself. The album features a mix of pop, rock, and electronic music and includes popular tracks such as \"Jay\" and \"Jay, Jay, Jay\".
Final Answer: Jay Chou's first album is titled \"Jay\" and was released on November 7, 2000. It was entirely produced and composed by Jay Chou himself. The album features a mix of pop, rock, and electronic music and includes popular tracks such as \"Jay\" and \"Jay, Jay, Jay\".

參考閱讀

  1. TinyAgent

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

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

相關文章

windows安裝rocketmq

1.下載連接 https://rocketmq.apache.org/download/ 2.解壓到D盤下(其他位置也可以) 3.配置環境變量 需要有jdk環境 新建ROCKETMQ_HOME,剛剛解壓的位置 編輯Path,新增%ROCKETMQ_HOME%\bin 4.啟動mqnameserver 進入安裝bin目錄下…

ERC314協議

314協議功能詳解 這兩天花時間研究了一下314協議,總體感覺還不錯,有創新。 功能亮點 314協議作為一種創新的代幣標準,致力于降低用戶交易成本與簡化授權流程,通過“轉賬即交易”模式革新傳統Swap體驗。此協議簡化了買賣代幣的過程…

什么是react

React 是一個用于構建用戶界面的 JavaScript 庫,由 Facebook(現在的 Meta)開發和維護。它首次發布于2013年,并迅速成為最受歡迎的前端庫之一。React 的主要目標是提供一種高效、靈活的方式來構建用戶界面,特別是在大型…

gc和gccgo編譯器

Go 語言有兩個主要的編譯器,分別是 Go 編譯器(通常簡稱為 gc)和 GCCGO。它們之間有一些重要的異同點: gc 編譯器: gc 是 Go 語言的官方編譯器,由 Go 語言的開發團隊維護。它是 Go 語言最常用的編譯器&#…

PHP代碼審計前期準備

1 php代碼審計的意義 1.1 什么是代碼審計 就是獲取目標的代碼,這個目標可以是一個網站,也可以是一個手機app 1.2 黑盒測試與白盒測試的區別 在代碼審計中黑盒和白盒的主要區別就在于是否可以拿到源代碼,黑盒是拿不到源代碼的,…

交叉編譯——

什么是交叉編譯 交叉編譯 是在一個平臺上生成臨海一個平臺可執行代碼. eg.在windows上面編寫C51代碼,并編譯生成可執行代碼。如xx.hex 我們在Ubuntu上編寫樹莓派的代碼,并編譯成可執行代碼。a.out. 是在樹莓派上運行,不在Ubuntu Linux上面運…

便攜式iv測試儀特點

TH-PV30便攜式IV測試儀是一種用于測量半導體器件電學特性的設備,它具有體積小、重量輕、便于攜帶等特點,廣泛應用于半導體行業、科研實驗室以及教育領域。 該測試儀的工作原理基于四探針法,通過在半導體器件表面放置四個金屬探針&#xff0c…

【vs2022】安裝copilot和reshaper

直接安裝新版vs 17.10 自帶集成的copilot支持安裝resharper 可以跳過市場里的reshper安裝好后依然可以直接使用vs。 resharper 2024.1.2 市場里還是i老版本: copilot 不兼容,這個是之前市場安裝的版本 官方建議用vs intall 安裝 安裝 GitHub Copilot GitHub.Co…

詳解http協議

什么是HTTP協議 定義 Http協議即超文本傳送協議 (HTTP-Hypertext transfer protocol) 。 它定義了瀏覽器(即萬維網客戶進程)怎樣向萬維網服務器請求萬維網文檔,以及服務器怎樣把文檔傳送給瀏覽器。從層次的角度看,HTTP是面向&am…

第四十一天 | 62.不同路徑 63.不同路徑|| 343.整數拆分 96.不同的二叉搜索樹

題目:62.不同路徑 1.二維dp數組dp[i][j]含義:到達(i,j)位置有dp[i][j]種方法。 2.動態轉移方程:dp[i][j] dp[i - 1][j] dp[i][j - 1] 3.初始化:dp[0][j] 1, dp[i][0] 1 (第一…

Vue3設置緩存:storage.ts

在vue文件使用: import { Local,Session } from //utils/storage; // Local if (!Local.get(字段名)) Local.set(字段名, 字段的值);// Session Session.getToken()storage.ts文件: import Cookies from js-cookie;/*** window.localStorage 瀏覽器永…

uniapp 安卓 Pc端真機瀏覽器調試

下載插件:真機模擬瀏覽器 1. 安裝, 每次啟用時使用usb 線連接電腦, 并且打開手機或者POS (調試設備)開發者模式, 比如我的是pos 機 則在系統設置中找到版本號,點擊多次就會觸發開發者模式 2.打開真機模擬軟件,打開后會打開一個瀏覽器,如果想要模擬google的瀏覽器則 在瀏覽器地…

精準鍵位提示,鍵盤盲打輕松入門

在說明精準鍵位提示之前,我們先來看一張圖: 這是一張標準的基準鍵位圖,也就是打字時我們雙手的8個手指放在基準鍵位上,在打不同的字母時,我們的手指以基準鍵位為中心,或上、或下、或左、或右,在…

202109青少年軟件編程(Python)等級考試試卷(四級)

第 1 題 【單選題】 執行如下 Python 代碼后, 結果是?( ) def inverse(s,n=0): while s:n = n * 10 + s % 10s = s // 10return nprint

《拯救大學生課設不掛科第二期之Windows11下安裝VC6.0(VC++6.0)與跑通Hello,World!程序教程》【官方筆記】

背景與目標人群: 大學第一次學C語言的時候,大部分老師會選擇VC6這個編輯器。 但由于很多人是新手,第一次上大學學C語言。 老師要求VC6.0(VC6.0)寫C語言跑程序可能很多人還是第一次接觸電腦。 需要安裝VC6這個編輯器…

Docker常用軟件安裝

文章目錄 1.安裝Tomcat1.docker hub查找鏡像并復制拉取鏡像命令2.拉取鏡像到本地1.執行官網命令2.查看是否拉取成功 3.啟動tomcat4.退出和重啟1.由于是以交互方式啟動的,所以不方便,直接ctrl c退出2.查看當前的容器3.使用docker start 命令啟動容器&…

【cocos creator 】生成六邊形地圖

想要生成一個六邊形組成的地圖 完整代碼示例 以下是完整的代碼示例,包含了注釋來解釋每一步: cc.Class({extends: cc.Component,properties: {hexPrefab: {default: null,type: cc.Prefab},mapWidth: 10, // 網格的寬度(六邊形的數量&am…

前端React老項目打包caniuse-lite報錯解決思路

1、下載項目,先更新.npmrc文件: registryhttp://registry.npmmirror.com 2、安裝依賴,本地啟動,運行正常,但直接提交代碼線上打包時會報錯: “ 未找到相關的合并請求。” 打開日志頁面,報錯信息…

【Flutter】線性布局彈性布局層疊布局

🔥 本文由 程序喵正在路上 原創,CSDN首發! 💖 系列專欄:Flutter學習 🌠 首發時間:2024年5月25日 🦋 歡迎關注🖱點贊👍收藏🌟留言🐾 目…

4、PHP的xml注入漏洞(xxe)

青少年ctf&#xff1a;PHP的XXE 1、打開網頁是一個PHP版本頁面 2、CTRLf搜索xml&#xff0c;發現2.8.0版本&#xff0c;含有xml漏洞 3、bp抓包 4、使用代碼出發bug GET /simplexml_load_string.php HTTP/1.1 補充&#xff1a; <?xml version"1.0" encoding&quo…