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

【python openai function2json小工具】

两种方法 一种openai-swarm中提供的、一种langchain实现的

一、openai工具函数调用

import inspectdef merge_chunk(final_response: dict, delta: dict) -> None:delta.pop("role", None)merge_fields(final_response, delta)tool_calls = delta.get("tool_calls")if tool_calls and len(tool_calls) > 0:index = tool_calls[0].pop("index")merge_fields(final_response["tool_calls"][index], tool_calls[0])def function_to_json(func) -> dict:"""Converts a Python function into a JSON-serializable dictionarythat describes the function's signature, including its name,description, and parameters.Args:func: The function to be converted.Returns:A dictionary representing the function's signature in JSON format."""type_map = {str: "string",int: "integer",float: "number",bool: "boolean",list: "array",dict: "object",type(None): "null",}try:signature = inspect.signature(func)except ValueError as e:raise ValueError(f"Failed to get signature for function {func.__name__}: {str(e)}")parameters = {}for param in signature.parameters.values():try:param_type = type_map.get(param.annotation, "string")except KeyError as e:raise KeyError(f"Unknown type annotation {param.annotation} for parameter {param.name}: {str(e)}")parameters[param.name] = {"type": param_type}required = [param.namefor param in signature.parameters.values()if param.default == inspect._empty]return {"type": "function","function": {"name": func.__name__,"description": func.__doc__ or "","parameters": {"type": "object","properties": parameters,"required": required,},},}if __name__=='__main__':print(function_to_json(merge_chunk))

二、使用langchain

from langchain_core.utils.function_calling import (convert_to_openai_function,convert_to_openai_tool,
)
from langchain_core.tools.convert import tool
from typing import Annotated@tool
def slide_ops(idx: Annotated[int, "元素index"],left: Annotated[int, "元素的左上横坐标"] = None,top: Annotated[int, "元素的左上纵坐标"] = None,width: Annotated[int, "元素的宽度"] = None,height: Annotated[int, "元素的高度"] = None,fontcolor: Annotated[str, "元素的前景颜色"] = None,backcolor: Annotated[int, "元素的背景颜色"] = None,delete: Annotated[bool, "删除此元素"] = None,
):"""修改幻灯片中元素的信息"""...convert_to_openai_function(slide_ops)
convert_to_openai_tool(slide_ops)

http://www.lryc.cn/news/465937.html

相关文章:

  • super()和super().__init__()的解释
  • 【C++】—— 多态(下)
  • idea 2023 配置 web service
  • MYSQL数据库SQL+DQL
  • Java中的异常Throwable
  • Day4顺序表c++代码实现
  • 将图片转换成base64格式
  • 征服ES(ElasticSearch)的慢查询实战
  • 如何才能从普通程序员转行AI大模型?
  • 【番外】软件设计师中级笔记关于数据库技术更新笔记问题
  • 【代码】约瑟夫问题——故事背景
  • 什么是事件冒泡和事件捕获
  • 高端优质建站公司具备哪些优势?2024高端建站公司哪家好
  • word删除空白页 | 亲测有效
  • YashanDB学习-服务启停
  • 在未排序的整数数组找到最小的缺失正整数
  • TCP连接管理机制:三次握手四次挥手
  • 1022. 宠物小精灵之收服
  • 人工智能生成内容(AI-Generated Content)
  • 深度学习:强化学习(Reinforcement Learning, RL)详解
  • C语言笔记20
  • 基于SSM+微信小程序的房屋租赁管理系统(房屋2)
  • selenium案例——爬取哔哩哔哩排行榜
  • HTML5教程(三)- 常用标签
  • 【HCIE-Datacom考试战报】2024-08-21 深圳 SRv6
  • 【京准电钟】“安全卫士”:卫星时空安全隔离防护装置
  • 优先级队列(2)_数据流中第k大元素
  • 【CSS】纯CSS Loading动画组件
  • rootless模式下istio ambient鉴权策略
  • 超详细的总结!最新大模型算法岗面试题(含答案)来了!