[datawhale202405]从零手搓大模型实战:TinyAgent

news2024/10/4 23:18:53

结论速递

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:
        pass

    def build_system_input(self):
        # 构造上文中所说的系统提示词
        pass
    
    def parse_latest_plugin_call(self, text):
        # 解析第一次大模型返回选择的工具和工具参数
        pass
    
    def call_plugin(self, plugin_name, plugin_args):
        # 调用选择的工具
        pass

    def 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 question

Begin!

修改了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:" + text
        for i in range(5):
            response, history = self.model.chat(response, history, self.system_prompt)
            if response.rfind('\nFinal Answer:') > 0:
                break
            plugin_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.coloradmin.cn/o/1690949.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

VBA语言専攻每周通知20240524

通知20240524 各位学员∶本周MF系列VBA技术资料增加611-615讲,T3学员看到通知后请免费领取,领取时间5月24日晚上18:00-5月26日晚上18:00。本次增加内容: MF611:用InputBox录入日期 MF612:信息提示10秒后关自动关闭 MF613:只是信息提示10秒 MF614:显…

Zynq-Linux移植学习笔记之68- 国产ZYNQ添加用户自定义版本信息

1、背景介绍 在使用复旦微zynq时,有时候虽然针对uboot源码进行了改动,但由于uboot基线版本只有一个(2018-07-fmsh),导致无法区分版本信息,虽然可以通过编译时间来区分,但没有版本号直观。内核也…

【Numpy】深入解析numpy中的ravel方法

NumPy中的ravel方法:一维化数组的艺术 🌈 欢迎莅临我的个人主页👈这里是我深耕Python编程、机器学习和自然语言处理(NLP)领域,并乐于分享知识与经验的小天地!🎇 🎓 博主简…

香港服务器负载过高的原因和应对办法

保持网站正常运行看似简单,但事实上,有许多问题会影响网站和应用程序的性能,并可能导致停机。其中一个问题就是服务器过载。而香港服务器作为一种常见的服务器类型,有时会出现负载过高的情况。为了帮助您确保在香港服务器过载不会…

AI应用案例:电能量异常分析智能诊断系统

窃电和计量装置故障造成漏收、少收电费使电力系统利益受损。一般情况主要通过定期巡检、定期校验电表、用户举报窃电等手段来发现窃电或计量装置故障。对人的依赖性太强,抓窃查漏的目标不明确。利用电力系统中逐步积累下来的海量真实数据,采用数据挖掘技…

C++多生产者,多消费者模型

C11实现多生产者,多消费者模型 在C标准库中实现多生产者多消费者模型,可以使用std::thread、std::queue、互斥锁(std::mutex)、条件变量(std::condition_variable)等组件。下面是一个简单的示例,展示如何创建多生产者和多消费者模型&#xf…

构建智能化的语言培训教育技术架构:挑战与机遇

随着全球化的发展和人们对语言学习需求的增长,语言培训教育行业正面临着越来越多的挑战和机遇。在这个背景下,构建智能化的语言培训教育技术架构成为提升服务质量和效率的重要手段。本文将探讨语言培训教育行业的技术架构设计与实践。 一、智能化教学平台…

Jupyter Notebook的三个使用场景:网页端、PyCharm专业版和VScode

说明,以下都是我个人的摸索感悟和总结,自己理解和猜测的是这样,欢迎指正。 Jupyter Notebook的三个常用使用地方(网页端、PyCharm专业版、VScode): 总结一句话:网页端、PyCharm中和VScode中三…

Python使用multiprocessing实现多进程

大家好,当我们工作中涉及到处理大量数据、并行计算或并发任务时,Python的multiprocessing模块是一个强大而实用的工具。通过它,我们可以轻松地利用多核处理器的优势,将任务分配给多个进程并同时执行,从而提高程序的性能…

ROCm上情感分析:使用循环神经网络

15.2. 情感分析:使用循环神经网络 — 动手学深度学习 2.0.0 documentation (d2l.ai) 代码 import torch from torch import nn from d2l import torch as d2lbatch_size 64 train_iter, test_iter, vocab d2l.load_data_imdb(batch_size)class BiRNN(nn.Module):…

躺赚零撸项目,看广告赚红包,零门槛提现,秒到账,单机每日100+

这个项目是跟广告商直接对接的,跟以前小游戏看广告差不多,看完广告得金币5000个兑换5毛钱。 不过这个是可以直接提现,而是无门槛就可以提,有设备就可以操作,有空边看连续剧边刷也是挺香的,单机可以达到100…

组网智能是啥?

组网智能是一种基于穿透技术的远程连接解决方案,它为用户提供了操作简单、跨平台应用、无网络要求和独创的安全加速方案等优势。由于这些特点,组网智能已经被几十万用户广泛应用,解决了各行业客户的远程连接需求。 跨平台应用 组网智能具备跨…

《我的阿勒泰》观后感(二、返璞归真也是一种美)

看了李娟的小说《我的阿勒泰》逐渐悟到一个道理,返璞归真也是一种美,没必要每个人的人生三十年的年华,都去追求房子,车子等逐渐贬值的东西。人究竟应该追求怎样的一种活法? 什么是城市化?这是我听到的最好…

ffmpeg-webrtc(metartc)给ffmpeg添加webrtc协议

这个是使用metrtc的库为ffmpeg添加webrtc传输协议,目前国内还有一个这样的开源项目,是杨成立大佬,大师兄他们在做,不过wili页面维护的不好,新手不知道如何使用,我专门对它做过介绍,另一篇博文&a…

Ansible01-Ansible的概述、实验环境初始化、Inventory

目录 写在前面1. Ansible是什么1.1 简介与来历1.2 Ansible的特点1.3Ansible的架构与工作流程1.3.1 ansible 任务执行模式1.3.2 ansible 执行流程1.4 Ansible的模块 2. Ansible实验初始化2.1 实验环境2.2Ansible的安装2.2.1 Ansible的程序结构 2.3 修改Ansible配置文件2.3.1 配置…

[杂项]优化AMD显卡对DX9游戏(天谕)的支持

目录 关键词平台说明背景RDNA 1、2、3 架构的显卡支持游戏一、 优化方法1.1 下载 二、 举个栗子(以《天谕》为例)2.1 下载微星 afterburner 软件 查看游戏内信息(可跳过)2.2 查看D3D9 帧数2.3 关闭游戏,替换 dll 文件2…

【C语言】8.C语言操作符详解(3)

文章目录 10.操作符的属性:优先级、结合性10.1 优先级10.2 结合性 11.表达式求值11.1 整型提升11.2 算术转换11.3 问题表达式解析11.3.1 表达式111.3.2 表达式211.3.3 表达式311.3.4 表达式411.3.5 表达式5: 11.4 总结 10.操作符的属性:优先级、结合性 …

【教学类-综合练习-05】20240524 中4班实物点数-纽扣(0-5加法、0-10加法)

背景需求: 百日咳班级只有5人,把库存的python纸类学具都用掉。其中就有大量的加减法题。 0-5以内题目早就没有了,中班幼儿做5以内。所以只能硬着头皮发0-10以内的加法题练习,并让孩子们去材料去拿10颗纽扣,进行两列摆…

webpack5 splitChunks分割代码

首先明确webpack 自身的打包行为 当splitChunks为false时,此时不启用任何打包设置 可以看到,静态引入全都打到一个chunk里,动态引入会拆分出来一个chunk,这是纯webpack无配置的打包, webpack会给每个模块打上标记 ,如下 { m…

Android Activity 设计详解

文章目录 Android Activity 设计说明1. Activity 的生命周期2. Activity 的启动模式3. Activity 的通信4. Activity 的布局和视图管理5. Activity 的配置变化处理6. Activity 的保存和恢复状态7. Activity 的任务和返回栈 总结 Android Activity 设计说明 在 Android 中&#…