【理解工具调用的流程,本质体现了大模型智能性】

1、工具调用

调用完结果看里面tool_calls 是否为空,不为空就调用工具函数处理,
如果为空就中断循环。大模型返回的message结果智能判断是否继续调用
在这里插入图片描述
输入输出如下:

请输入:深圳西安天气 
------------------------------------------------------------1轮大模型输出信息:{'choices': [{'message': {'content': '', 'tool_calls': [{'id': 'call_edbdb1743a724c9c9662a5', 'type': 'function', 'function': 
{'name': 'get_current_weather', 'arguments': '{"location": "深圳"}'}}]}}]}
需要调用工具,工具调用信息:[{'id': 'call_edbdb1743a724c9c9662a5', 'type': 'function', 'function': {'name': 'get_current_weather', 'arguments': '{"location": "深圳"}'}}]
工具输出信息:深圳今天是雨天。------------------------------------------------------------
深圳今天的天气是雨天。第2轮大模型输出信息:{'content': '深圳今天的天气是雨天。', 'tool_calls': [{'id': 'call_79341955209940628a5a98', 'type': 'function', 'function': {'name': 'get_current_weather', 'arguments': '{"location": "西安"}'}}]}工具输出信息:西安今天是雨天。------------------------------------------------------------
西安今天的天气也是雨天。请注意携带雨具。第3轮大模型输出信息:{'content': '西安今天的天气也是雨天。请注意携带雨具。', 'tool_calls': None}最终答案:西安今天的天气也是雨天。请注意携带雨具。
PS D:\swarm> & d:/swarm/.conda/python.exe d:/swarm/test_auzrapi/test_qwen.py请输入:深圳西安天气
------------------------------------------------------------1轮大模型输出信息:{'choices': [{'message': {'content': '', 'tool_calls': [{'id': 'call_71fa625dc1a543319dfe9d', 'type': 'function', 'function': 
{'name': 'get_current_weather', 'arguments': '{"location": "深圳"}'}}]}}]}location": "深圳"}'}}]
工具输出信息:深圳今天是雨天。------------------------------------------------------------2轮大模型输出信息:{'content': '', 'tool_calls': [{'id': 'call_188d490f167e4b109c681f', 'type': 'function', 'function': {'name': 'get_current_weather', 'arguments': '{"location": "西安"}'}}]}工具输出信息:西安今天是雨天。------------------------------------------------------------
深圳今天的天气是雨天,西安今天的天气也是雨天。请记得带伞哦!第3轮大模型输出信息:{'content': '深圳今天的天气是雨天,西安今天的天气也是雨天。请记得 
带伞哦!', 'tool_calls': None}最终答案:深圳今天的天气是雨天,西安今天的天气也是雨天。请记得带伞哦!
import os
from openai import OpenAIfrom openai import OpenAI
from datetime import datetime
import json
import osclient = OpenAI(# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx",# api_key=os.getenv("DASHSCOPE_API_KEY"),api_key="sk-112222", # 修改成你的阿里的qwen的api keybase_url="https://dashscope.aliyuncs.com/compatible-mode/v1",  # 填写DashScope SDK的base_url
)# 定义工具列表,模型在选择使用哪个工具时会参考工具的name和description
tools = [# 工具1 获取当前时刻的时间{"type": "function","function": {"name": "get_current_time","description": "当你想知道现在的时间时非常有用。",# 因为获取当前时间无需输入参数,因此parameters为空字典"parameters": {}}},  # 工具2 获取指定城市的天气{"type": "function","function": {"name": "get_current_weather","description": "当你想查询指定城市的天气时非常有用。","parameters": {  "type": "object","properties": {# 查询天气时需要提供位置,因此参数设置为location"location": {"type": "string","description": "城市或县区,比如北京市、杭州市、余杭区等。"}}},"required": ["location"]}}
]# 模拟天气查询工具。返回结果示例:"北京今天是雨天。"
def get_current_weather(location):return f"{location}今天是雨天。 "# 查询当前时间的工具。返回结果示例:"当前时间:2024-04-15 17:15:18。"
def get_current_time():# 获取当前日期和时间current_datetime = datetime.now()# 格式化当前日期和时间formatted_time = current_datetime.strftime('%Y-%m-%d %H:%M:%S')# 返回格式化后的当前时间return f"当前时间:{formatted_time}。"# 封装模型响应函数
def get_response(messages):# 添加系统消息if not any(msg.get('role') == 'system' for msg in messages):messages.insert(0, {"role": "system","content": "你是一个有用的助手,可以帮助用户查询天气和时间。"})# 确保所有消息都有正确的 rolefor msg in messages:if 'role' not in msg or msg['role'] not in ['system', 'assistant', 'user', 'tool', 'function']:if 'name' in msg and msg['name'] in ['get_current_weather', 'get_current_time']:msg['role'] = 'function'else:msg['role'] = 'user'completion = client.chat.completions.create(model="qwen-plus",messages=messages,stream=True,tools=tools)# 处理流式响应content_buffer = []tool_call_buffer = Nonefor chunk in completion:try:# 处理内容if chunk.choices[0].delta.content:content_buffer.append(chunk.choices[0].delta.content)print(chunk.choices[0].delta.content, end='', flush=True)# 处理工具调用if hasattr(chunk.choices[0].delta, 'tool_calls') and chunk.choices[0].delta.tool_calls:tool_call = chunk.choices[0].delta.tool_calls[0]if not tool_call_buffer:tool_call_buffer = {'id': tool_call.id,'type': tool_call.type,'function': {'name': tool_call.function.name,'arguments': ''}}if hasattr(tool_call.function, 'arguments') and tool_call.function.arguments:tool_call_buffer['function']['arguments'] += tool_call.function.arguments# 检查参数是否完整try:if tool_call_buffer['function']['arguments']:json.loads(tool_call_buffer['function']['arguments'])return {'choices': [{'message': {'content': ''.join(content_buffer),'tool_calls': [tool_call_buffer]}}]}except json.JSONDecodeError:continueexcept Exception as e:print(f"Error processing chunk: {e}")continue# 如果没有工具调用,返回普通消息return {'choices': [{'message': {'content': ''.join(content_buffer),'tool_calls': None}}]}def call_with_messages():print('\n')messages = [{"role": "system","content": "你是一个有用的助手,可以帮助用户查询天气和时间。"},{"role": "user","content": input('请输入:'),  # 提问示例:"现在几点了?" "一个小时后几点" "北京天气如何?"}]print("-"*60)# 模型的第一轮调用i = 1first_response = get_response(messages)assistant_output = first_response['choices'][0]['message']print(f"\n第{i}轮大模型输出信息:{first_response}\n")if assistant_output['content'] is None:assistant_output['content'] = ""messages.append({"role": "assistant","content": assistant_output['content'],"tool_calls": assistant_output.get('tool_calls')})# 如果不需要调用工具,则直接返回最终答案if not assistant_output['tool_calls']:print(f"无需调用工具,我可以直接回复:{assistant_output['content']}")returnelse:print(f"\n需要调用工具,工具调用信息:{assistant_output['tool_calls']}")while assistant_output['tool_calls']:tool_call = assistant_output['tool_calls'][0]func_name = tool_call['function']['name']# 根据工具名称调用相应的函数if func_name == 'get_current_weather':tool_result = get_current_weather(json.loads(tool_call['function']['arguments'])['location'])messages.append({"role": "tool",  # 使用 tool 而不是 function"tool_call_id": tool_call['id'],  # 添加 tool_call_id"name": "get_current_weather","content": tool_result})elif func_name == 'get_current_time':tool_result = get_current_time()messages.append({"role": "tool",  # 使用 tool 而不是 function"tool_call_id": tool_call['id'],  # 添加 tool_call_id"name": "get_current_time","content": tool_result})print(f"工具输出信息:{tool_result}\n")print("-"*60)# 获取助手的响应response = get_response(messages)assistant_output = response['choices'][0]['message']if assistant_output['content'] is None:assistant_output['content'] = ""messages.append({"role": "assistant","content": assistant_output['content'],"tool_calls": assistant_output.get('tool_calls')})i += 1print(f"第{i}轮大模型输出信息:{assistant_output}\n")# 如果助手的回复中没有工具调用,就结束循环if not assistant_output.get('tool_calls'):breakprint(f"最终答案:{assistant_output['content']}")if __name__ == '__main__':call_with_messages()

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/893385.shtml

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

相关文章

Excel 实现文本拼接方法

1. 使用 & 运算符 这是最常见和简单的拼接方法。你只需使用 & 来连接多个文本单元格或文本字符串。 示例公式: A1 & B1这个公式会将 A1 和 B1 单元格中的文本合并为一个字符串。 如果你希望在文本之间加入分隔符(如空格、逗号等&#xf…

C# ASP.NET MVC项目内使用ApiController

1.在App_Start文件夹新建WebApiConfig.cs文件,建立webApi路由的注册方法。 using System.Web.Http;namespace PrivilegeManager {public class WebApiConfig{public static void Register(HttpConfiguration config){config.MapHttpAttributeRoutes();config.Route…

【Springboot相关知识】Springboot结合SpringSecurity实现身份认证以及接口鉴权

Springboot结合SpringSecurity实现身份认证以及接口鉴权 身份认证1. 添加依赖2. 配置JWT工具类3. 配置Spring Security4. 创建JWT请求过滤器5. 创建认证控制器6. 创建请求和响应对象7. 配置UserDetailsService8. 运行应用程序9. 测试总结 接口鉴权1. 启用方法级安全注解2. 定义…

Mac开启任何来源安装配置环境变量

目录 开启任何来源配置环境变量退出保存时如果没有权限修改文件权限拓展——.bash_profile和.zshrc 开启任何来源 sudo spctl --master-disable#打开软件时提示文件损坏 sudo xattr -r -d com.apple.quarantine 进入访达应用程序拖拽应用到终端配置环境变量 cd ~ vi ~/.bash…

使用 Logback 的最佳实践:`logback.xml` 与 `logback-spring.xml` 的区别与用法

在开发 Spring Boot 项目时,日志是调试和监控的重要工具。Spring Boot 默认支持 Logback 作为日志系统,并提供了 logback.xml 和 logback-spring.xml 两种配置方式。这篇文章将详细介绍这两者的区别、各自的优缺点以及最佳实践。 目录 一、什么是 Logbac…

excel实用工具

持续更新… 文章目录 1. 快捷键1.1 求和 2. 命令2.1 查找 vloopup 1. 快捷键 1.1 求和 windows: alt mac : command shift T 2. 命令 2.1 查找 vloopup vlookup 四个入参数 要查找的内容 (A2 6xx1)查找的备选集 (C2:C19)…

QModbusTCPClient占用内存持续增长

最近使用QModbusTCPClient通信,需要频繁发送读写请求,发现软件占用内存一直在增减,经过不断咨询和尝试,终于解决了。 1.方案一(失败) 最开始以为是访问太频繁,导致创建reply的对象比delete re…

adb 命令使用大全

1.adb针对设备 adb devices //查看链接设备 adb -s "设备序号" shell 命令 //选择设备执行 adb connect "ip地址" adb disconnect "ip地址" adb shell screencap -p /sdcard/screenshot.png //截图 adb pull /sdcard/filename …

Linux(Centos 7.6)命令详解:iconv

1.命令作用 将给定文件的编码从一种编码转换为另一种编码(Convert encoding of given files from one encoding to another) 2.命令语法 Usage: iconv [OPTION...] [FILE...] 3.参数详解 OPTION: 输入/输出格式规范: -f, --from-codeNAME,原始文本编码-t, --t…

读《SQL经典实例》学数据库(系列一)

目录 友情提醒第一章、数据库简述1.1)数据库简述1.2)常见的数据库软件1.3)MySQL数据库安装 第二章、SQL语句分类2.1)操作数据仓库/数据表:DDL2.1.1)创建数据仓库/数据表2.1.2)删除数据仓库/数据表2.1.3&…

【C++】模板(进阶)

本篇我们来介绍更多关于C模板的知识。模板初阶移步至:【C】模板(初阶) 1.非类型模板参数 1.1 非类型模板参数介绍 模板参数可以是类型形参,也可以是非类型形参。类型形参就是我们目前接触到的一些模板参数。 //类型模板参数 …

算法项目实时推流

1、搭建流媒体服务器 下载mediamtx 2、视频流直推 ffmpeg -stream_loop -1 -i DJI_20250109112715_0002_W.MP4 -r 30 -c:v libx264 -preset ultrafast -f flv rtmp://192.168.100.20:1935/live/test_chengdu1 3、硬件加速 如果硬件支持,可以使用硬件加速编码器&am…

99.12 金融难点通俗解释:毛利率

目录 0. 承前1. 简述2. 比喻:冰淇淋店赚钱2.1 第一步:准备材料2.2 第二步:卖冰淇淋2.3 第三步:计算毛利率 3. 生活中的例子3.1 好的毛利率3.2 一般的毛利率3.3 差的毛利率 4. 小朋友要注意4.1 毛利率高不一定好4.2 毛利率低不一定…

一文学会YOLO系列算法(从V3到11)实现遥感图像目标检测

目录 前言 数据集介绍 数据集转换 YOLO代码的下载 YOLO的配置 1.数据集的配置 2.模型的配置 YOLO11模型的训练 其它版本YOLO的训练 前言 遥感技术的快速发展,特别是在高分辨率遥感图像的获取能力上的显著提升,已经大大拓宽了遥感数据在环境监测…

3.1 Go函数调用过程

在 Go 语言中,函数调用的核心机制依赖于内存的栈区分配和指针操作,理解这一原理有助于掌握函数的执行过程。 1. 内存结构概述 在 Go 程序编译成可执行文件并启动后,操作系统会为其分配进程内存,进程内存主要分为以下区域&#x…

图解Git——分布式Git《Pro Git》

分布式工作流程 Centralized Workflow(集中式工作流) 所有开发者都与同一个中央仓库同步代码,每个人通过拉取、提交来合作。如果两个开发者同时修改了相同的文件,后一个开发者必须在推送之前合并其他人的更改。 Integration-Mana…

案例分析一

张某(10多年IT工作经验)应聘一家国企单位,面试官(技术副主管)面试时问了些无关痛痒的问题,谈到薪资时强调我权限范围内的数额就那么多,再多就需要走申请流程进行操作了。 没几天入职后&#xf…

【高阶数据结构】布隆过滤器(BloomFilter)

1. 概念 1.1 背景引入 背景:在计算机软件中,一个常见的需求就是 在一个集合中查找一个元素是否存在 ,比如:1. Word 等打字软件需要判断用户键入的单词是否在字典中存在 2. 浏览器等网络爬虫程序需要保存一个列表来记录已经遍历过…

【json_object】mysql中json_object函数过长,显示不全

问题:json只显示部分 解决: SET GLOBAL group_concat_max_len 1000000; -- 设置为1MB,根据需要调整如果当前在navicat上修改,只有效本次连接和后续会话,重新连接还是会恢复默认值1024 在my.ini配置文件中新增或者修…

计算机网络 (52)秘钥分配

一、重要性 在计算机网络中,密钥分配是密钥管理中的一个核心问题。由于密码算法通常是公开的,因此网络的安全性主要依赖于密钥的安全保护。密钥分配的目的是确保密钥在传输过程中不被窃取或篡改,同时确保只有合法的用户才能获得密钥。 二、方…