当前位置: 首页 > news >正文

使用Python调用OpenAI的function calling源码

一、第三方库

pip install openai

二、示例代码

# -*- coding: utf-8 -*-  
# @Author :Kan 
# @Date :2025/8/1 9:12  
# @File :1_function_calling.py  
import json  
import random  
from openai import OpenAI  
from datetime import datetime  # ================================================================  
# 1. Function Calling(函数调用)  
# ================================================================  class ToolsUsage:  tools = [  # 工具2 获取指定城市的天气  {  "type": "function",  "function": {  "name": "get_current_weather",  "description": "获取指定地点的天气信息",  "parameters": {  "type": "object",  "properties": {  "location": {"type": "string", "description": "地点名称"}  },  "required": ["location"]  }  }  },  # 工具1 获取当前时刻的时间  {  "type": "function",  "function": {  "name": "get_current_time",  "description": "当你想知道现在的时间时非常有用。",  # 因为获取当前时间无需输入参数,因此parameters为空字典  "parameters": {},  },  },  ]  @staticmethod  # 天气查询工具。返回结果示例:“北京今天是雨天。”  def get_current_weather(location):  weather_conditions = ["晴天", "多云", "雨天"]  # 随机选择一个天气条件  random_weather = random.choice(weather_conditions)  # 返回格式化信息  return f"{location}今天是{random_weather}。"  @staticmethod  # 查询当前时间的工具。返回结果示例:“当前时间: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}。"  @staticmethod  def execute_tools(func_name, func_args):  func_dic = {  "get_current_weather": ToolsUsage.get_current_weather,  "get_current_time": ToolsUsage.get_current_time,  }  return func_dic[func_name](**func_args)  class ChatAgent:  def __init__(self, api_key: str, url: str, model_name: str):  self.client = OpenAI(api_key=api_key, base_url=url)  self.model_name = model_name  def request_chat(self, messages: list):  response = self.client.chat.completions.create(  model=self.model_name,  messages=messages,  tools=ToolsUsage.tools,  extra_body={"enable_thinking": False},  tool_choice="auto",  )  return response  def execute_chat(self):  print("\n")  messages = [  {  # 提问示例:"现在几点了?" "一个小时后几点" "北京天气如何?"  "content": input(  "请输入问题:"  ),  "role": "user",  }  ]  print("-*" * 60)  # 模型调用次数  i = 1  first_response = self.request_chat(messages)  assistant_output = first_response.choices[0].message  print(f"\n第{i}轮大模型输出信息:{assistant_output}\n")  # 不需要调用工具,则直接返回答案  if not assistant_output.tool_calls:  print(f"无需调用工具,直接回复:{assistant_output.content}")  return  tool_calls_result = assistant_output.tool_calls  # 如果需要调用工具,则进行模型的多轮调用,直到模型判断无需调用工具  while tool_calls_result:  # 执行工具调用  for tool_call in assistant_output.tool_calls:  tool_info = {  "content": "",  "role": "tool",  "tool_call_id": assistant_output.tool_calls[0].id,  }  func_name = tool_call.function.name  func_args = json.loads(tool_call.function.arguments)  tools_result = ToolsUsage.execute_tools(func_name, func_args)  print(f"当前调用工具:{func_name},参数:{func_args},输出信息:{tools_result}\n")  tool_info["content"] = tools_result  messages.append(tool_info)  print("-*" * 60)  second_response = self.request_chat(messages)  assistant_output = second_response.choices[0].message  i += 1  print(f"第{i}轮大模型输出信息:{assistant_output}\n")  # 指导调用工具为空时终止  if not assistant_output.tool_calls:  tool_calls_result = None  print(f"最终答案:\n {assistant_output.content}")  if __name__ == "__main__":  api_key = 'xxxxxx'  base_url = "http://xxxxxxxx/v1"  model = "qwen3"  chat_service = ChatAgent(api_key, base_url, model)  chat_service.execute_chat()
http://www.dtcms.com/a/324508.html

相关文章:

  • Pytorch深度学习框架实战教程-番外篇02-Pytorch池化层概念定义、工作原理和作用
  • ROS2 QT 多线程功能包设计
  • PHP项目运行
  • (LeetCode 每日一题) 869. 重新排序得到 2 的幂 (哈希表+枚举)
  • Framework开发之Zygote进程2(基于开源的AOSP15)--init.rc在start zygote之后的事情(详细完整版逐行代码走读)
  • springboot骚操作
  • 【论文阅读】Deep Adversarial Multi-view Clustering Network
  • 视觉障碍物后处理
  • Java开发异步编程中常用的接口和类
  • 人工智能之数学基础:如何理解n个事件的独立?
  • [C/C++线程安全]_[中级]_[避免使用的C线程不安全函数]
  • Android APK 使用OpenGl 绘制三角形源码
  • Word XML 批注范围克隆处理器
  • 绕过文件上传漏洞并利用文件包含漏洞获取系统信息的技术分析
  • 使用MongoDB存储和计算距离
  • Spring Boot 2 升级 Spring Boot 3 的全方位深度指南
  • Leetcode 3644. Maximum K to Sort a Permutation
  • 9_基于深度学习的车型检测识别系统(yolo11、yolov8、yolov5+UI界面+Python项目源码+模型+标注好的数据集)
  • Error: error:0308010C:digital envelope routines::unsupported at new Hash
  • 【Python 小脚本·大用途 · 第 3 篇】
  • 编译xformers
  • 【深度学习新浪潮】遥感图像风格化迁移研究工作介绍
  • 学习记录(十九)-Overleaf如何插入图片(单,多)
  • 学习模板元编程(3)enable_if
  • CART算法:Gini指数
  • 25.机器学习入门:让机器变聪明的魔法课
  • 串口通信初始化过程是怎样的???
  • IDEA 快捷编辑指南
  • Java开源代码源码研究:我的成长之路与实战心得分享
  • IDEA 安装插件的两种方式