建设网站查询密码,网站管理运营,wordpress 外贸 开发,做网站租空间Agent是什么#xff1f;
Agent一词起源于拉丁语中的Agere#xff0c;意思是“to do”。在LLM语境下#xff0c;Agent可以理解为在某种能自主理解、规划决策、执行复杂任务的智能体。
Agent并非ChatGPT升级版#xff0c;它不仅告诉你“如何做”#xff0c;更会帮你去做。…Agent是什么
Agent一词起源于拉丁语中的Agere意思是“to do”。在LLM语境下Agent可以理解为在某种能自主理解、规划决策、执行复杂任务的智能体。
Agent并非ChatGPT升级版它不仅告诉你“如何做”更会帮你去做。如果Copilot是副驾驶那么Agent就是主驾驶。
自主Agent是由人工智能驱动的程序当给定目标时它们能够自己创建任务、完成任务、创建新任务、重新确定任务列表的优先级、完成新的顶级任务并循环直到达到目标。
最直观的公式Agent LLMPlanningFeedbackTool use
Agent决策流程
感知Perception→ 规划Planning→ 行动Action • 感知Perception是指Agent从环境中收集信息并从中提取相关知识的能力。 • 规划Planning是指Agent为了某一目标而作出的决策过程。 • 行动Action是指基于环境和规划做出的动作。
Agent通过感知从环境中收集信息并提取相关知识。然后通过规划为了达到某个目标做出决策。最后通过行动基于环境和规划做出具体的动作。Policy是Agent做出行动的核心决策而行动又为进一步感知提供了观察的前提和基础形成了一个自主的闭环学习过程。
人是如何做事的
在工作中我们通常会用到PDCA思维模型。基于PDCA模型我们可以将完成一项任务进行拆解按照作出计划、计划实施、检查实施效果然后将成功的纳入标准不成功的留待下一循环去解决。目前这是人们高效完成一项任务非常成功的经验总结。 请添加图片描述
如何让LLM替代人去做事?
要让LLM替代人去做事我们可以基于PDCA模型进行 规划、执行、评估和反思。
规划能力Plan- 分解任务Agent大脑把大的任务拆解为更小的可管理的子任务这对有效的、可控的处理好大的复杂的任务效果很好。
执行能力Done- 使用工具Agent能学习到在模型内部知识不够时比如在pre-train时不存在且之后没法改变的模型weights去调用外部API比如获取实时的信息、执行代码的能力、访问专有的信息知识库等等。这是一个典型的平台工具的场景我们要有生态意识即我们构建平台以及一些必要的工具然后大力吸引其他厂商提供更多的组件工具形成生态。
评估能力Check- 确认执行结果Agent要能在任务正常执行后判断产出物是否符合目标在发生异常时要能对异常进行分类危害等级对异常进行定位哪个子任务产生的错误对异常进行原因分析什么导致的异常。
反思能力Adjust- 基于评估结果重新规划Agent要能在产出物符合目标时及时结束任务是整个流程最核心的部分同时进行归因分析总结导致成果的主要因素另外Agent要能在发生异常或产出物不符合目标时给出应对措施并重新进行规划开启再循环过程。
下面来看几个具体的案例
让LLM能够获取当前时间
首先我们定义一个获取当前时间的tool
from langchain.tools import Tool def get_time(input): return datetime.datetime.now() #定义获取当前时间
time_tool Tool( nameget current time, func get_time, description用来获取当前时间. input should be time
)name: 工具名称 func: 工具的实现 description: 工具的描述一定要是准确的描述该部分会加入到LLM的prompt中若描述不准确LLM可能无法准确调用
我们将langchain中内置的prompt打印出来看看 Respond to the human as helpfully and accurately as possible. You have access to the following tools: get current time: 用来获取当前时间. input should be time, args: {{tool_input: {{type: string}}}} Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input). Valid action values: Final Answer or get current time Provide only ONE action per $JSON_BLOB, as shown: {{ action: $TOOL_NAME, action_input: $INPUT }} Follow this format: Question: input question to answer Thought: consider previous and subsequent steps Action: $JSON_BLOB Observation: action result ... (repeat Thought/Action/Observation N times) Thought: I know what to respond Action: {{ action: Final Answer, action_input: Final response to human }} Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:$JSON_BLOBthen Observation:. Thought:从以上prompt可以看出我们定义好的获取当前时间的工具函数也被包裹在里面并且他还帮我们生成了一个输入参数的格式限制promptargs: {{‘tool_input’: {{‘type’: ‘string’}}}}
我们接着看 Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input). Valid action values: Final Answer or get current time Provide only ONE action per $JSON_BLOB, as shown: {{ action: $TOOL_NAME, action_input: $INPUT }} 这段prompt要求LLM生成的action需要是一个jsonb的格式并且包含两个keyaction和action_input分别对应工具名和工具的输入并且给了一个样例。
并且有效的action不仅包含了get current time还多了个Final Answer
我们来用一个实际的问题试试
question 现在几点 result agent.run(question)
print(result)输出
当前时间是2024年01月02日11点12分01秒。对比下未使用tool的输出
我无法回答这个问题因为我没有实时访问实际的时间或日期。我是根据我的训练数据提供信息的。可见当不使用tool时LLM是无法知道当前时间的
为了更容易理解Agent是如何工作的我打印出了中间过程的日志 Thought: 需要使用工具获取当前时间 Action: { action: get current time, action_input: { type: string } } Observation: 2024-01-02 11:44:16.900356 我现在知道了当前时间 Action: { action: Final Answer, action_input: 当前时间是2024年01月02日11点44分16秒。 } 首先LLM先思考应该调用哪个工具并且知道应该调用get current time且给出了输入参数的类型
接着拿到了LLM输出的结果即Observation: 2024-01-02 11:44:16.900356
最后LLM知道了答案再次调用工具Final Answer输出答案
让LLM拥有计算器的功能
langchain内置了许多工具使用load_tools函数即可加载这次我们不自己定义tool了我们使用langchain内置的工具试试。 tools load_tools(tool_names[llm-math], llmllm) tools.append(time_tool)看看llm-math的定义
def _get_llm_math(llm: BaseLanguageModel) - BaseTool: return Tool( nameCalculator, descriptionUseful for when you need to answer questions about math., funcLLMMathChain.from_llm(llmllm).run, coroutineLLMMathChain.from_llm(llmllm).arun, )
我们看看此时的prompt Respond to the human as helpfully and accurately as possible. You have access to the following tools: Calculator: Useful for when you need to answer questions about math., args: {{tool_input: {{type: string}}}} get current time: 用来获取当前时间. input should be now, args: {{tool_input: {{type: string}}}} Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input). Valid action values: Final Answer or Calculator, get current time Provide only ONE action per $JSON_BLOB, as shown: {{ action: $TOOL_NAME, action_input: $INPUT }} Follow this format: Question: input question to answer Thought: consider previous and subsequent steps Action: $JSON_BLOB Observation: action result ... (repeat Thought/Action/Observation N times) Thought: I know what to respond Action: {{ action: Final Answer, action_input: Final response to human }} Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:$JSON_BLOBthen Observation:. Thought:相比上一个例子多了一个名叫Calculator的prompt: Calculator: Useful for when you need to answer questions about math., args: {{tool_input: {{type: string}}}}
实际上就是多了个tool name 和 tool description
来试试效果
question 789*324353等于多少 result agent.run(question)
print(result)输出
255914517对比下未使用tool的输出
789 * 324353 324353 * (700 80 9) 324353 * 700 324353 * 80 324353 * 9 227047100 25948240 2921177 252995340 2921177 255916517未使用tool虽然没有获得正确答案但好在知道将数学问题分解但我这里使用的是qwen-72b-chat-int4要是小一点的模型就不一定有这样的效果了。
以下是baichuan2-13b-chat的输出
789乘以324353等于259553427。让LLM获取实时天气
定义tool:
China-City-List-latest.csv文件从(https://github.com/qwd/LocationList/blob/master/China-City-List-latest.csv下载
和风天气API key需要在https://dev.qweather.com注册获取自行google
def getLocationId(city): d collections.defaultdict(str) try: df pd.read_csv(./data/datasets/virus/China-City-List-latest.csv, encodingutf-8) except Exception as e: print(e) for i, row in df.iterrows(): d[row[Location_Name_ZH]] row[Location_ID] return d[city] if city in d else def get_weather(location): key 你的和风天气API key id getLocationId(location) if not id: return 没有这个城市 base_url https://devapi.qweather.com/v7/weather/now? params {location: id, key: key, lang: zh} response requests.get(base_url, paramsparams) data response.json() if data[code] ! 200: return 没有这个城市的天气情况 return get_weather_info(data) def get_weather_info(info): if info[code] ! 200: return 没有这个城市的天气情况 # result f现在天气{info[hourly][0][text]}温度 {info[hourly][0][temp]} 度, 未来 24 小时天气{info[hourly][-1][text]}温度 {info[hourly][-1][temp]} 度。 result f
现在天气: {info[now][text]}
温度: {info[now][temp]} 摄氏度
风向: {info[now][windDir]}
风力等级: {info[now][windScale]}
风速: {info[now][windSpeed]} 公里/小时 return result weather_tool Tool( nameget current weather, func get_weather, description用来获取当地的天气信息输入应该是城市名称
)来试试效果
question 杭州今天能穿短袖吗 result agent.run(question)
print(result)输出
不建议穿短袖今天杭州有霾温度为10摄氏度。对比下未使用tool的输出
作为一个语言模型我无法获取实时的天气信息。请您自行查询杭州当前的天气情况并根据气温和个人体质决定是否穿短袖。以上工具函数输入参数均只有一个接下来看看当输入参数有多个时应如何处理
tool有多个输入参数的场景
定义tool:
class FutureWeatherInput(BaseModel): location: str Field(description城市名称) date: str Field(description日期格式yyyy-mm-dd如2021-11-15) def get_future_weather(location, date): key 你的和风天气API key id getLocationId(location) if not id: return 没有这个城市 base_url https://devapi.qweather.com/v7/weather/7d? params {location: id, key: key, lang: zh} response requests.get(base_url, paramsparams) data response.json() if data[code] ! 200: return 没有这个城市的天气情况 result {} daily data[daily] for item in daily: fxDate item[fxDate] weather_text f
天气: {item[textDay]}
最高温度: {item[tempMax]} 摄氏度
最低温度: {item[tempMin]} 摄氏度
风向: {item[windDirDay]}
风力等级: {item[windScaleDay]}
风速: {item[windSpeedDay]} 公里/小时 result[fxDate] weather_text return result[date] future_weather_tool StructuredTool( nameget future weather, func get_future_weather, description用来获取当地今天和未来六天的天气信息。, args_schemaFutureWeatherInput
)当tool需要多个输入参数时我们不再使用Tool类而使用StructuredTool类它的定义如下从langchain源码里可以找到
class StructuredTool(BaseTool): Tool that can operate on any number of inputs. description: str args_schema: Type[BaseModel] Field(..., descriptionThe tool schema.) The input arguments schema. func: Optional[Callable[..., Any]] The function to run when the tool is called. coroutine: Optional[Callable[..., Awaitable[Any]]] None The asynchronous version of the function.且通过pydantic的BaseModel来约束输入对输入参数的description也是必要的因为该description也会传到prompt中
Calculator: Useful for when you need to answer questions about math., args: {{tool_input: {{type: string}}}}
get current time: 用来获取当前时间. input should be now。当需要获取今天、明天、后天等的日期时你应该调用此函数获取今天的日期, args: {{tool_input: {{type: string}}}}
get current weather: 用来获取当地当天的天气信息输入应该是城市名称, args: {{tool_input: {{type: string}}}}
get future weather: 用来获取当地今天和未来六天的天气信息。, args: {{location: {{title: Location, description: 城市名称, type: string}}, date: {{title: Date, description: 日期格式yyyy-mm-dd如2021-11-15, type: string}}}} Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input). Valid action values: Final Answer or Calculator, get current time, get current weather, get future weather来试试效果
question 今天是几号明天准备去杭州旅游能穿短袖吗 result agent.run(question)
print(result)输出
明天杭州的天气预报为晴最高温度为13摄氏度最低温度为2摄氏度建议携带一些保暖衣物。让LLM实现联网搜索
定义tool
def get_internet_content(query): params { engine: baidu, q: query, api_key: 你的 Serpapi key } search BaiduSearch(params) result search.get_json()[organic_results][0][snippet] return result baidu_search_tool Tool( name百度搜索, func get_internet_content, description用来从互联网上获取当前时事信息输入应该是搜索query
)Serpapi key需要你自行注册获取地址https://serpapi.com/
来试试效果
question 小米su7什么时候发布 result agent.run(question)
print(result)输出
小米su7预计将于2024年上半年量产上市。Agent之所以能回答该问题是因为我们使用百度搜索获取了小米su7 发布日期的相关信息LLM再基于该信息总结答案相当于外挂了一个知识库只不过这个知识库不再是我们本地的数据库而是百度搜索
到这里你会发现其实不同的工具就是不同的函数而已要想Agent能够适配自己的业务场景只是把这些函数换成了自己业务相关的函数或接口。
以上LLM使用的均是qwen-72b-chat-int4同时也对比过baichuan2-13b-chat、yi-34b-chatqwen-14b-chat其中baichuan2-13b-chat效果最差基本无法理解如何调用toolyi-34b-chat不如qwen-14b-chatqwen-72b-chat-int4效果最好个人猜测主要原因是因为qwen系列的模型在专门的工具调用数据集上训练过因此效果要比其他模型要好且官方开源了一个大模型工具调用数据集地址 MSAgent-Bench大模型工具调用数据集
完整代码
import collections
import random
import requests
import datetime
import pandas as pd
from langchain.tools import Tool, StructuredTool
from langchain.agents import initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.agents import load_tools
from langchain.agents import AgentType from pydantic import BaseModel, Field
from serpapi.baidu_search import BaiduSearch def getLocationId(city): d collections.defaultdict(str) try: df pd.read_csv(./data/datasets/virus/China-City-List-latest.csv, encodingutf-8) except Exception as e: print(e) for i, row in df.iterrows(): d[row[Location_Name_ZH]] row[Location_ID] return d[city] if city in d else def get_weather(location): key 你的和风天气API key id getLocationId(location) if not id: return 没有这个城市 base_url https://devapi.qweather.com/v7/weather/now? params {location: id, key: key, lang: zh} response requests.get(base_url, paramsparams) data response.json() if data[code] ! 200: return 没有这个城市的天气情况 return get_weather_info(data) class FutureWeatherInput(BaseModel): location: str Field(description城市名称) date: str Field(description日期格式yyyy-mm-dd如2021-11-15) def get_future_weather(location, date): key 你的和风天气API key id getLocationId(location) if not id: return 没有这个城市 base_url https://devapi.qweather.com/v7/weather/7d? params {location: id, key: key, lang: zh} response requests.get(base_url, paramsparams) data response.json() if data[code] ! 200: return 没有这个城市的天气情况 result {} daily data[daily] for item in daily: fxDate item[fxDate] weather_text f
天气: {item[textDay]}
最高温度: {item[tempMax]} 摄氏度
最低温度: {item[tempMin]} 摄氏度
风向: {item[windDirDay]}
风力等级: {item[windScaleDay]}
风速: {item[windSpeedDay]} 公里/小时 result[fxDate] weather_text return result[date] def get_weather_info(info): if info[code] ! 200: return 没有这个城市的天气情况 # result f现在天气{info[hourly][0][text]}温度 {info[hourly][0][temp]} 度, 未来 24 小时天气{info[hourly][-1][text]}温度 {info[hourly][-1][temp]} 度。 result f
现在天气: {info[now][text]}
温度: {info[now][temp]} 摄氏度
风向: {info[now][windDir]}
风力等级: {info[now][windScale]}
风速: {info[now][windSpeed]} 公里/小时 return result def get_internet_content(query): params { engine: baidu, q: query, api_key: 你的SerpApi key } search BaiduSearch(params) result search.get_json()[organic_results][0][snippet] return result def test_agent_example(): model Qwen-72B-Chat-Int4 api_key EMPTY base_url http://localhost:8000/v1 llm ChatOpenAI(modelmodel, temperature0, api_keyapi_key, base_urlbase_url) print(get_weather(北京)) def get_time(input): return datetime.datetime.now() #定义获取当前时间 time_tool Tool( nameget current time, func get_time, description用来获取当前时间. input should be now。当需要获取今天、明天、后天等的日期时你应该调用此函数获取今天的日期 ) weather_tool Tool( nameget current weather, func get_weather, description用来获取当地当天的天气信息输入应该是城市名称 ) future_weather_tool StructuredTool( nameget future weather, func get_future_weather, description用来获取当地今天和未来六天的天气信息。, args_schemaFutureWeatherInput ) tools load_tools(tool_names[llm-math], llmllm) tools.extend([time_tool, weather_tool, future_weather_tool]) #创建代理 agent initialize_agent( agentAgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, toolstools, llmllm, verboseTrue, max_iterations5, handle_parsing_errorsTrue ) print(agent.agent.llm_chain.prompt[0].prompt.template) question 今天是几号明天准备去杭州旅游能穿短袖吗 result agent.run(question) print(----*20) print(result)总结
1、tool description 非常重要没有写好descriptionagent无法理解在什么情况下应该调用该tool
2、输入参数的 description 非常重要想要LLM生成给定格式的输入参数可以给一些few shot样例
3、agent本质还是prompt工程极大程度上依赖于LLM的参数量。小模型无法理解prompt无法生成给定格式的输入参数导致tool函数不能被正常调用
如何学习AI大模型
作为一名热心肠的互联网老兵我决定把宝贵的AI知识分享给大家。 至于能学习到多少就看你的学习毅力和能力了 。我已将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。
这份完整版的大模型 AI 学习资料已经上传CSDN朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】 一、全套AGI大模型学习路线
AI大模型时代的学习之旅从基础到前沿掌握人工智能的核心技能 二、640套AI大模型报告合集
这套包含640份报告的合集涵盖了AI大模型的理论研究、技术实现、行业应用等多个方面。无论您是科研人员、工程师还是对AI大模型感兴趣的爱好者这套报告合集都将为您提供宝贵的信息和启示。 三、AI大模型经典PDF籍
随着人工智能技术的飞速发展AI大模型已经成为了当今科技领域的一大热点。这些大型预训练模型如GPT-3、BERT、XLNet等以其强大的语言理解和生成能力正在改变我们对人工智能的认识。 那以下这些PDF籍就是非常不错的学习资源。 四、AI大模型商业化落地方案 作为普通人入局大模型时代需要持续学习和实践不断提高自己的技能和认知水平同时也需要有责任感和伦理意识为人工智能的健康发展贡献力量。