微信扫码
添加专属顾问
我要投稿
深入探索AI智能体如何通过ReAct实现工具调用,提升自主性和任务执行效率。 核心内容: 1. AI智能体的定义及其技术构成 2. Function Calling在智能体中的应用及其局限性 3. ReAct基础及其在工具调用中的作用和实现步骤
AI智能体是指具备一定自主性、能感知环境并通过智能决策执行特定任务的软件或硬件实体。它结合了人工智能技术(如机器学习、自然语言处理、计算机视觉等),能够独立或协作完成目标。
基于大语言模型(LLM)的Function Calling可以令智能体实现有效的工具使用和与外部API的交互。支持Function Calling的模型(如gpt-4,qwen-plus等)能够检测何时需要调用函数,并输出调用函数的函数名和所需参数的JSON格式结构化数据。
但并非所有的LLM模型都支持Function Calling(如deepseel-v3)。对于不支持Function Calling的模型,可通过ReAct的相对较为复杂的提示词工程,要求模型返回特定格式的响应,以便区分不同的阶段(思考、行动、观察)。
工具调用主要有两个用途:
获取数据:执行行动:本文包含如下内容:
ReAct源于经典论文: REACT: SYNERGIZING REASONING AND ACTING IN LANGUAGE MODELS (链接:https://arxiv.org/pdf/2210.03629)
基于ReAct的智能体为了解决问题,需要经过几个阶段
以上3个阶段可能迭代多次,直到问题得到解决或者达到迭代次数上限。
基于ReAct的工具调用依赖于复杂的提示词工程。系统提示词参考langchain的模板:
Answer the following questions as best you can. You have access to the following tools:{tool_strings}The way you use the tools is by specifying a json blob.Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).The only values that should be in the "action" field are: {tool_names}The $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:```{{{{"action": $TOOL_NAME,"action_input": $INPUT}}}}```ALWAYS use the following format:Question: the input question you must answerThought: you should always think about what to doAction:```$JSON_BLOB```Observation: the result of the action... (this Thought/Action/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input questionBegin! Reminder to always use the exact characters `Final Answer` when responding.
我们以查询北京和广州天气为例,LLM采用阿里云的DeepSeek-v3。查询天气的流程如下图:
向LLM发起查询时,messages列表有2条messages:
system,定义了系统提示词(含工具定义)user,包含如下内容:我们用curl发起POST请求,body的JSON结构可参考https://platform.openai.com/docs/api-reference/chat/create 。
请求里的
stop字段需要设置为Observation:,否则LLM会直接输出整个Thought/Action/Observation流程并给出虚构的最终答案。我们仅需要LLM输出Thought/Action即可
#!/bin/bashexport OPENAI_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"export OPENAI_API_KEY="sk-xxx" # 替换为你的keycurl ${OPENAI_BASE_URL}/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer $OPENAI_API_KEY" \-d '{"model": "deepseek-v3","messages": [{"role": "system","content": "\nAnswer the following questions as best you can. You have access to the following tools:\n{\"name\": \"get_weather\", \"description\": \"Get weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"location\": {\"type\": \"string\", \"description\": \"the name of the location\"}}, \"required\": [\"location\"]}}\n\n\nThe way you use the tools is by specifying a json blob.\nSpecifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).\n\nThe only values that should be in the \"action\" field are: get_weather\n\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\n\n```\n{{\n\"action\": $TOOL_NAME,\n\"action_input\": $INPUT\n}}\n```\n\nALWAYS use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n... (this Thought/Action/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\n\nBegin! Reminder to always use the exact characters `Final Answer` when responding. \n"},{"role": "user","content": "Question: 北京和广州天气怎么样\n\n"}],"stop": "Observation:"}'
LLM经过推理,发现需要先调用函数获取北京天气。
Thought: 我需要获取北京和广州的天气信息。首先,我将获取北京的天气。Action:```{ "action": "get_weather", "action_input": { "location": "北京" }}```完整的JSON响应如下:
{ "choices": [ { "message": { "content": "Thought: 我需要获取北京和广州的天气信息。首先,我将获取北京的天气。\n\nAction:\n```\n{\n \"action\": \"get_weather\",\n \"action_input\": {\n \"location\": \"北京\"\n }\n}\n```", "role": "assistant" }, "finish_reason": "stop", "index": 0, "logprobs": null } ], "object": "chat.completion", "usage": { "prompt_tokens": 305, "completion_tokens": 49, "total_tokens": 354 }, "created": 1745651748, "system_fingerprint": null, "model": "deepseek-v3", "id": "chatcmpl-697b0627-4fca-975b-954c-7304386ac224"}
解析处理LLM的Action获得函数名和参数列表,调用相应的API接口获得结果。
例如:通过http://weather.cma.cn/api/now/54511可获得北京的天气情况。
完整的JSON响应如下:
{ "msg": "success", "code": 0, "data": { "location": { "id": "54511", "name": "北京", "path": "中国, 北京, 北京" }, "now": { "precipitation": 0.0, "temperature": 23.4, "pressure": 1005.0, "humidity": 43.0, "windDirection": "西南风", "windDirectionDegree": 216.0, "windSpeed": 2.7, "windScale": "微风", "feelst": 23.1 }, "alarm": [], "jieQi": "", "lastUpdate": "2025/04/26 15:00" }}
发给LLM的messages列表有2条messages:
system,定义了系统提示词(含工具定义)user,包含如下内容:get_weather('北京')的结果#!/bin/bashexport OPENAI_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"export OPENAI_API_KEY="sk-xxx" # 替换为你的keycurl ${OPENAI_BASE_URL}/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer $OPENAI_API_KEY" \-d '{"model": "deepseek-v3","messages": [{"role": "system","content": "\nAnswer the following questions as best you can. You have access to the following tools:\n{\"name\": \"get_weather\", \"description\": \"Get weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"location\": {\"type\": \"string\", \"description\": \"the name of the location\"}}, \"required\": [\"location\"]}}\n\n\nThe way you use the tools is by specifying a json blob.\nSpecifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).\n\nThe only values that should be in the \"action\" field are: get_weather\n\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\n\n```\n{{\n\"action\": $TOOL_NAME,\n\"action_input\": $INPUT\n}}\n```\n\nALWAYS use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n... (this Thought/Action/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\n\nBegin! Reminder to always use the exact characters `Final Answer` when responding. \n"},{"role": "user","content": "Question: 北京和广州天气怎么样\n\nThought: 我需要获取北京和广州的天气信息。首先,我将获取北京的天气。\n\nAction:\n```\n{\n\"action\": \"get_weather\",\n\"action_input\": {\n\"location\": \"北京\"\n}\n}\n```\nObservation: {\"msg\":\"success\",\"code\":0,\"data\":{\"location\":{\"id\":\"54511\",\"name\":\"北京\",\"path\":\"中国, 北京, 北京\"},\"now\":{\"precipitation\":0.0,\"temperature\":23.4,\"pressure\":1005.0,\"humidity\":43.0,\"windDirection\":\"西南风\",\"windDirectionDegree\":216.0,\"windSpeed\":2.7,\"windScale\":\"微风\",\"feelst\":23.1},\"alarm\":[],\"jieQi\":\"\",\"lastUpdate\":\"2025/04/26 15:00\"}}\n"}],"stop": "Observation:"}'
LLM经过推理,发现还需要调用函数获取广州天气。
Thought: 我已经获取了北京的天气信息。接下来,我将获取广州的天气信息。Action:```{ "action": "get_weather", "action_input": { "location": "广州" }}```
完整的JSON响应如下:
{ "choices": [ { "message": { "content": "Thought: 我已经获取了北京的天气信息。接下来,我将获取广州的天气信息。\n\nAction:\n```\n{\n\"action\": \"get_weather\",\n\"action_input\": {\n\"location\": \"广州\"\n}\n}\n```\nObservation", "role": "assistant" }, "finish_reason": "stop", "index": 0, "logprobs": null } ], "object": "chat.completion", "usage": { "prompt_tokens": 472, "completion_tokens": 46, "total_tokens": 518 }, "created": 1745651861, "system_fingerprint": null, "model": "deepseek-v3", "id": "chatcmpl-a822b8d7-9105-9dc2-8e98-4327afb50b3a"}
解析处理LLM的Action获得函数名和参数列表,调用相应的API接口获得结果。
例如:通过http://weather.cma.cn/api/now/59287可获得广州的天气情况。
完整的JSON响应如下:
{ "msg": "success", "code": 0, "data": { "location": { "id": "59287", "name": "广州", "path": "中国, 广东, 广州" }, "now": { "precipitation": 0.0, "temperature": 24.2, "pressure": 1005.0, "humidity": 79.0, "windDirection": "东北风", "windDirectionDegree": 31.0, "windSpeed": 1.3, "windScale": "微风", "feelst": 27.1 }, "alarm": [], "jieQi": "", "lastUpdate": "2025/04/26 15:00" }}
发给LLM的messages列表有2条messages:
system,定义了系统提示词(含工具定义)user,包含如下内容:get_weather('北京')的结果get_weather('广州')的结果#!/bin/bashexport OPENAI_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1"export OPENAI_API_KEY="sk-xxx" # 替换为你的keycurl ${OPENAI_BASE_URL}/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer $OPENAI_API_KEY" \-d '{"model": "deepseek-v3","messages": [{"role": "system","content": "\nAnswer the following questions as best you can. You have access to the following tools:\n{\"name\": \"get_weather\", \"description\": \"Get weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"location\": {\"type\": \"string\", \"description\": \"the name of the location\"}}, \"required\": [\"location\"]}}\n\n\nThe way you use the tools is by specifying a json blob.\nSpecifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).\n\nThe only values that should be in the \"action\" field are: get_weather\n\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\n\n```\n{{\n\"action\": $TOOL_NAME,\n\"action_input\": $INPUT\n}}\n```\n\nALWAYS use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n... (this Thought/Action/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\n\nBegin! Reminder to always use the exact characters `Final Answer` when responding. \n"},{"role": "user","content": "Question: 北京和广州天气怎么样\n\nThought: 我需要获取北京和广州的天气信息。首先,我将获取北京的天气。\n\nAction:\n```\n{\n\"action\": \"get_weather\",\n\"action_input\": {\n\"location\": \"北京\"\n}\n}\n```\nObservation: {\"msg\":\"success\",\"code\":0,\"data\":{\"location\":{\"id\":\"54511\",\"name\":\"北京\",\"path\":\"中国, 北京, 北京\"},\"now\":{\"precipitation\":0.0,\"temperature\":23.4,\"pressure\":1005.0,\"humidity\":43.0,\"windDirection\":\"西南风\",\"windDirectionDegree\":216.0,\"windSpeed\":2.7,\"windScale\":\"微风\",\"feelst\":23.1},\"alarm\":[],\"jieQi\":\"\",\"lastUpdate\":\"2025/04/26 15:00\"}}\nThought: 现在我已经获取了北京的天气信息,接下来我将获取广州的天气信息。\n\nAction:\n```\n{\n\"action\": \"get_weather\",\n\"action_input\": {\n\"location\": \"广州\"\n}\n}\n```\nObservation\nObservation: {\"msg\":\"success\",\"code\":0,\"data\":{\"location\":{\"id\":\"59287\",\"name\":\"广州\",\"path\":\"中国, 广东, 广州\"},\"now\":{\"precipitation\":0.0,\"temperature\":24.2,\"pressure\":1005.0,\"humidity\":79.0,\"windDirection\":\"东北风\",\"windDirectionDegree\":31.0,\"windSpeed\":1.3,\"windScale\":\"微风\",\"feelst\":27.1},\"alarm\":[],\"jieQi\":\"\",\"lastUpdate\":\"2025/04/26 15:00\"}}\n"}],"stop": "Observation:"}'
LLM生成最终的回复:
Thought: 我已经获取了北京和广州的天气信息,现在可以回答用户的问题了。Final Answer: 北京的天气温度为23.4°C,湿度为43%,风向为西南风,风速为2.7米/秒。广州 的天气温度为24.2°C,湿度为79%,风向为东北风,风速为1.3米/秒。
完整的JSON响应如下:
{ "choices": [ { "message": { "content": "Thought: 我已经获取了北京和广州的天气信息,现在可以回答用户的问题了。\n\nFinal Answer: 北京的天气温度为23.4°C,湿度为43%,风向为西南风,风速为2.7米/秒。广州 的天气温度为24.2°C,湿度为79%,风向为东北风,风速为1.3米/秒。", "role": "assistant" }, "finish_reason": "stop", "index": 0, "logprobs": null } ], "object": "chat.completion", "usage": { "prompt_tokens": 641, "completion_tokens": 79, "total_tokens": 720 }, "created": 1745652025, "system_fingerprint": null, "model": "deepseek-v3", "id": "chatcmpl-d9b85f31-589e-9c6f-8694-cf813344e464"}
uv init agent
cd agent
uv venv
.venv\Scripts\activate
uv add openai requests python-dotenv
创建.env,.env内容如下(注意修改OPENAI_API_KEY为您的key)
OPENAI_API_KEY=your_api_key_here
OPENAI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1
把.env添加到.gitignore
基于openai sdk实现ReAct agent的伪代码主体逻辑如下:
maxIter = 5 # 最大迭代次数agent_scratchpad = "" # agent思考过程(Thought/Action/Observation)for iterSeq in range(1, maxIter+1): 构造chat completion请求 messages有2条 第1条为系统提示词消息(含工具定义) 第2条为用户消息:Question + agent思考过程(Thought/Action/Observation) stop参数设置为"Observation:" 获取chat completion结果 如果chat completion结果带有"Final Answer:" 返回最终答案 如果chat completion结果带有Action 解析并调用相应函数 更新agent思考过程:把本次LLM的输出(Though/Action)和工具调用结果(Observation)添加到agent_scratchpad 继续迭代
完整的main.py代码如下:
import jsonimport reimport requestsimport urllib.parsefrom typing import Iterablefrom openai import OpenAIfrom openai.types.chat.chat_completion_message_param import ChatCompletionMessageParamfrom openai.types.chat.chat_completion_user_message_param import (ChatCompletionUserMessageParam,)from openai.types.chat.chat_completion_system_message_param import (ChatCompletionSystemMessageParam,)# 加载环境变量from dotenv import load_dotenvload_dotenv()client = OpenAI()model = "deepseek-v3"# 工具定义tools = [{"type": "function","function": {"name": "get_weather","description": "Get weather","parameters": {"type": "object","properties": {"location": {"type": "string", "description": "location"}},"required": ["location"],},},}]# 系统提示词def get_system_prompt():tool_strings = "\n".join([json.dumps(tool["function"]) for tool in tools])tool_names = ", ".join([tool["function"]["name"] for tool in tools])systemPromptFormat = """Answer the following questions as best you can. You have access to the following tools:{tool_strings}The way you use the tools is by specifying a json blob.Specifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).The only values that should be in the "action" field are: {tool_names}The $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:```{{{{"action": $TOOL_NAME,"action_input": $INPUT}}}}```ALWAYS use the following format:Question: the input question you must answerThought: you should always think about what to doAction:```$JSON_BLOB```Observation: the result of the action... (this Thought/Action/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input questionBegin! Reminder to always use the exact characters `Final Answer` when responding."""return systemPromptFormat.format(tool_strings=tool_strings, tool_names=tool_names)# 实现获取天气def get_weather(location: str) -> str:url = "http://weather.cma.cn/api/autocomplete?q=" + urllib.parse.quote(location)response = requests.get(url)data = response.json()if data["code"] != 0:return "没找到该位置的信息"location_code = ""for item in data["data"]:str_array = item.split("|")if (str_array[1] == locationor str_array[1] + "市" == locationor str_array[2] == location):location_code = str_array[0]breakif location_code == "":return "没找到该位置的信息"url = f"http://weather.cma.cn/api/now/{location_code}"return requests.get(url).text# 实现工具调用def invoke_tool(toolName: str, toolParamaters) -> str:result = ""if toolName == "get_weather":result = get_weather(toolParamaters["location"])else:result = f"函数{toolName}未定义"return resultdef main():query = "北京和广州天气怎么样"systemMsg = ChatCompletionSystemMessageParam(role="system", content=get_system_prompt())maxIter = 5 # 最大迭代次数agent_scratchpad = "" # agent思考过程action_pattern = re.compile(r"\nAction:\n`{3}(?:json)?\n(.*?)`{3}.*?$", re.DOTALL)for iterSeq in range(1, maxIter + 1):messages: Iterable[ChatCompletionMessageParam] = list()messages.append(systemMsg)messages.append(ChatCompletionUserMessageParam(role="user", content=f"Question: {query}\n\n{agent_scratchpad}"))print(f">> iterSeq:{iterSeq}")print(f">>> messages: {json.dumps(messages)}")# 向LLM发起请求,注意需要设置stop参数chat_completion = client.chat.completions.create(messages=messages,model=model,stop="Observation:",)content = chat_completion.choices[0].message.contentprint(f">>> content:\n{content}")final_answer_match = re.search(r"\nFinal Answer:\s*(.*)", content)if final_answer_match:final_answer = final_answer_match.group(1)print(f">>> 最终答案: {final_answer}")returnaction_match = action_pattern.search(content)if action_match:obj = json.loads(action_match.group(1))toolName = obj["action"]toolParameters = obj["action_input"]print(f">>> tool name:{toolName}")print(f">>> tool parameters:{toolParameters}")result = invoke_tool(toolName, toolParameters)print(f">>> tool result: {result}")# 把本次LLM的输出(Though/Action)和工具调用结果(Observation)添加到agent_scratchpadagent_scratchpad += content + f"\nObservation: {result}\n"else:print(">>> ERROR: detect invalid response")returnprint(">>> 迭代次数达到上限,我无法得到最终答案")main()
运行代码:uv run .\main.py
>> iterSeq:1>>> messages: [{"role": "system", "content": "\nAnswer the following questions as best you can. You have access to the following tools:\n{\"name\": \"get_weather\", \"description\": \"Get weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"location\": {\"type\": \"string\", \"description\": \"the name of the location\"}}, \"required\": [\"location\"]}}\n\n\nThe way you use the tools is by specifying a json blob.\nSpecifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).\n\nThe only values that should be in the \"action\" field are: get_weather\n\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\n\n```\n{{\n\"action\": $TOOL_NAME,\n\"action_input\": $INPUT\n}}\n```\n\nALWAYS use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n... (this Thought/Action/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\n\nBegin! Reminder to always use the exact characters `Final Answer` when responding. \n"}, {"role": "user", "content": "Question: \u5317\u4eac\u548c\u5e7f\u5dde\u5929\u6c14\u600e\u4e48\u6837\n\n"}]>>> content:Thought: 我需要获取北京和广州的天气信息。首先,我将获取北京的天气。Action:```{"action": "get_weather","action_input": {"location": "北京"}}```>>> tool name:get_weather>>> tool parameters:{'location': '北京'}>>> tool result: {"msg":"success","code":0,"data":{"location":{"id":"54511","name":"北京","path":"中国, 北京, 北京"},"now":{"precipitation":0.0,"temperature":23.4,"pressure":1005.0,"humidity":43.0,"windDirection":"西南风","windDirectionDegree":216.0,"windSpeed":2.7,"windScale":"微风","feelst":23.1},"alarm":[],"jieQi":"","lastUpdate":"2025/04/26 15:00"}}>> iterSeq:2>>> messages: [{"role": "system", "content": "\nAnswer the following questions as best you can. You have access to the following tools:\n{\"name\": \"get_weather\", \"description\": \"Get weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"location\": {\"type\": \"string\", \"description\": \"the name of the location\"}}, \"required\": [\"location\"]}}\n\n\nThe way you use the tools is by specifying a json blob.\nSpecifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).\n\nThe only values that should be in the \"action\" field are: get_weather\n\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\n\n```\n{{\n\"action\": $TOOL_NAME,\n\"action_input\": $INPUT\n}}\n```\n\nALWAYS use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n... (this Thought/Action/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\n\nBegin! Reminder to always use the exact characters `Final Answer` when responding. \n"}, {"role": "user", "content": "Question: \u5317\u4eac\u548c\u5e7f\u5dde\u5929\u6c14\u600e\u4e48\u6837\n\nThought: \u6211\u9700\u8981\u83b7\u53d6\u5317\u4eac\u548c\u5e7f\u5dde\u7684\u5929\u6c14\u4fe1\u606f\u3002\u9996\u5148\uff0c\u6211\u5c06\u83b7\u53d6\u5317\u4eac\u7684\u5929\u6c14\u3002\n\nAction:\n```\n{\n\"action\": \"get_weather\",\n\"action_input\": {\n\"location\": \"\u5317\u4eac\"\n}\n}\n```\nObservation: {\"msg\":\"success\",\"code\":0,\"data\":{\"location\":{\"id\":\"54511\",\"name\":\"\u5317\u4eac\",\"path\":\"\u4e2d\u56fd, \u5317\u4eac, \u5317\u4eac\"},\"now\":{\"precipitation\":0.0,\"temperature\":23.4,\"pressure\":1005.0,\"humidity\":43.0,\"windDirection\":\"\u897f\u5357\u98ce\",\"windDirectionDegree\":216.0,\"windSpeed\":2.7,\"windScale\":\"\u5fae\u98ce\",\"feelst\":23.1},\"alarm\":[],\"jieQi\":\"\",\"lastUpdate\":\"2025/04/26 15:00\"}}\n"}]>>> content:Thought: 现在我已经获取了北京的天气信息,接下来我将获取广州的天气信息。Action:```{"action": "get_weather","action_input": {"location": "广州"}}```Observation>>> tool name:get_weather>>> tool parameters:{'location': '广州'}>>> tool result: {"msg":"success","code":0,"data":{"location":{"id":"59287","name":"广州","path":"中国, 广东, 广州"},"now":{"precipitation":0.0,"temperature":24.2,"pressure":1005.0,"humidity":79.0,"windDirection":"东北风","windDirectionDegree":31.0,"windSpeed":1.3,"windScale":"微风","feelst":27.1},"alarm":[],"jieQi":"","lastUpdate":"2025/04/26 15:00"}}>> iterSeq:3>>> messages: [{"role": "system", "content": "\nAnswer the following questions as best you can. You have access to the following tools:\n{\"name\": \"get_weather\", \"description\": \"Get weather\", \"parameters\": {\"type\": \"object\", \"properties\": {\"location\": {\"type\": \"string\", \"description\": \"the name of the location\"}}, \"required\": [\"location\"]}}\n\n\nThe way you use the tools is by specifying a json blob.\nSpecifically, this json should have a `action` key (with the name of the tool to use) and a `action_input` key (with the input to the tool going here).\n\nThe only values that should be in the \"action\" field are: get_weather\n\nThe $JSON_BLOB should only contain a SINGLE action, do NOT return a list of multiple actions. Here is an example of a valid $JSON_BLOB:\n\n```\n{{\n\"action\": $TOOL_NAME,\n\"action_input\": $INPUT\n}}\n```\n\nALWAYS use the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction:\n```\n$JSON_BLOB\n```\nObservation: the result of the action\n... (this Thought/Action/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\n\nBegin! Reminder to always use the exact characters `Final Answer` when responding. \n"}, {"role": "user", "content": "Question: \u5317\u4eac\u548c\u5e7f\u5dde\u5929\u6c14\u600e\u4e48\u6837\n\nThought: \u6211\u9700\u8981\u83b7\u53d6\u5317\u4eac\u548c\u5e7f\u5dde\u7684\u5929\u6c14\u4fe1\u606f\u3002\u9996\u5148\uff0c\u6211\u5c06\u83b7\u53d6\u5317\u4eac\u7684\u5929\u6c14\u3002\n\nAction:\n```\n{\n\"action\": \"get_weather\",\n\"action_input\": {\n\"location\": \"\u5317\u4eac\"\n}\n}\n```\nObservation: {\"msg\":\"success\",\"code\":0,\"data\":{\"location\":{\"id\":\"54511\",\"name\":\"\u5317\u4eac\",\"path\":\"\u4e2d\u56fd, \u5317\u4eac, \u5317\u4eac\"},\"now\":{\"precipitation\":0.0,\"temperature\":23.4,\"pressure\":1005.0,\"humidity\":43.0,\"windDirection\":\"\u897f\u5357\u98ce\",\"windDirectionDegree\":216.0,\"windSpeed\":2.7,\"windScale\":\"\u5fae\u98ce\",\"feelst\":23.1},\"alarm\":[],\"jieQi\":\"\",\"lastUpdate\":\"2025/04/26 15:00\"}}\nThought: \u73b0\u5728\u6211\u5df2\u7ecf\u83b7\u53d6\u4e86\u5317\u4eac\u7684\u5929\u6c14\u4fe1\u606f\uff0c\u63a5\u4e0b\u6765\u6211\u5c06\u83b7\u53d6\u5e7f\u5dde\u7684\u5929\u6c14\u4fe1\u606f\u3002\n\nAction:\n```\n{\n\"action\": \"get_weather\",\n\"action_input\": {\n\"location\": \"\u5e7f\u5dde\"\n}\n}\n```\nObservation\nObservation: {\"msg\":\"success\",\"code\":0,\"data\":{\"location\":{\"id\":\"59287\",\"name\":\"\u5e7f\u5dde\",\"path\":\"\u4e2d\u56fd, \u5e7f\u4e1c, \u5e7f\u5dde\"},\"now\":{\"precipitation\":0.0,\"temperature\":24.2,\"pressure\":1005.0,\"humidity\":79.0,\"windDirection\":\"\u4e1c\u5317\u98ce\",\"windDirectionDegree\":31.0,\"windSpeed\":1.3,\"windScale\":\"\u5fae\u98ce\",\"feelst\":27.1},\"alarm\":[],\"jieQi\":\"\",\"lastUpdate\":\"2025/04/26 15:00\"}}\n"}]>>> content:Thought: 我已经获取了北京和广州的天气信息,现在可以回答用户的问题了。Final Answer: 北京的天气情况为:温度23.4°C,湿度43%,西南风,风速2.7米/秒,微风。广州的天气情况为:温度24.2°C,湿度79%,东北风,风速1.3米/秒,微风。>>> 最终答案: 北京的天气情况为:温度23.4°C,湿度43%,西南风,风速2.7米/秒,微风。广州的天气情况为:温度24.2°C,湿度79%,东北风,风速1.3米/秒,微风。
基于Function Calling和基于ReAct的工具调用有各自的优缺点:
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2025-10-16
基于大模型的智能问答场景解决方案——RAG提升召回率的关键
2025-10-16
用合成数据评测 RAG 系统:一份可直接上手的 DeepEval 实操指南
2025-10-16
2025 年 RAG 最佳 Reranker 模型
2025-10-16
HiRAG问答流程深入分析
2025-10-13
LightRAG × Yuxi-Know——「知识检索 + 知识图谱」实践案例
2025-10-13
PG用户福音|一次性搞定RAG完整数据库套装
2025-10-12
任何格式RAG数据实现秒级转换!彻底解决RAG系统中最令人头疼的数据准备环节
2025-10-12
总结了 13 个 顶级 RAG 技术
2025-09-15
2025-09-02
2025-08-05
2025-08-18
2025-08-25
2025-08-25
2025-08-25
2025-09-03
2025-08-20
2025-09-08
2025-10-04
2025-09-30
2025-09-10
2025-09-10
2025-09-03
2025-08-28
2025-08-25
2025-08-20