OpenAI ChatGPT-4开发笔记2024-03:Chat之Function Calling/Function/Tool/Tool_Choice

2024-01-05 07:28

本文主要是介绍OpenAI ChatGPT-4开发笔记2024-03:Chat之Function Calling/Function/Tool/Tool_Choice,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Updates on Function Calling were a major highlight at OpenAI DevDay.

In another world,原来的function call都不再正常工作了,必须全部重写。

function和function call全部由tool和tool_choice取代。2023年11月之前关于function call的代码都准备翘翘。

干嘛要整个tool出来取代function呢?原因有很多,不再赘述。作为程序员,我们真正关心的是:怎么改?

简单来说,就是整合chatgpt的能力和你个人的能力通过这个tools。怎么做呢?

第一步,定义你的function,最高指示是啥?

import json
from openai import OpenAI
client = OpenAI()# Example dummy function hard coded to return the same weather
# In production, this could be your backend API or an external API
def get_current_weather(location, unit="fahrenheit"):"""Get the current weather in a given location"""if "beijing" in location.lower():return json.dumps({"location": location, "temperature": "10", "unit": "celsius"})elif "tokyo" in location.lower():return json.dumps({"location": location, "temperature": "22", "unit": "celsius"})elif "shanghai" in location.lower():return json.dumps({"location": location, "temperature": "21", "unit": "celsius"})elif "san francisco" in location.lower():return json.dumps({"location": location, "temperature": "72", "unit": "fahrenheit"})else:return json.dumps({"location": location, "temperature": "22.22", "unit": "celsius"})

第二步,调用chatgpt模型

让chatgpt干活儿。问问chatgpt啥情况

def run_conversation():# Step 1: send the conversation and available functions to the modelmessages = [{"role": "user", "content": "What's the weather like in San Francisco, Tokyo, Beijing and Paris?"}]tools = [{"type": "function","function": {"name": "get_current_weather","description": "Get the current weather in a given location","parameters": {"type": "object","properties": {"location": {"type": "string","description": "The city and state, e.g. San Francisco, CA",},"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},},"required": ["location"],},},}]response = client.chat.completions.create(model="gpt-3.5-turbo-1106",messages=messages,tools = tools,tool_choice="auto",  # auto is default, but we'll be explicit)response_message = response.choices[0].messagetool_calls = response_message.tool_calls

tool_choice参数让chatgpt模型自行决断是否需要function介入。
response是返回的object,message里包含一个tool_calls array.

tool_calls array The tool calls generated by the model, such as function calls.
id string The ID of the tool call.
type string The type of the tool. Currently, only function is supported.
function object:  The function that the model called.name: string The name of the function to call.arguments: string The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function.

第三步,chatgpt判断如果需要function介入,传回一个json对象。

    # Step 2: check if the model wanted to call a functionif tool_calls:# Step 3: call the function# Note: the JSON response may not always be valid; be sure to handle errorsavailable_functions = {"get_current_weather": get_current_weather,}  # only one function in this example, but you can have multiplemessages.append(response_message)  # extend conversation with assistant's reply# Step 4: send the info for each function call and function response to the modelfor tool_call in tool_calls:function_name = tool_call.function.namefunction_to_call = available_functions[function_name]function_args = json.loads(tool_call.function.arguments)function_response = function_to_call(location=function_args.get("location"),unit=function_args.get("unit"),)messages.append({"tool_call_id": tool_call.id,"role": "tool","name": function_name,"content": function_response,})  # extend conversation with function responsesecond_response = openai.chat.completions.create(model="gpt-3.5-turbo-1106",messages=messages,)  # get a new response from the model where it can see the function responsereturn second_response
print(run_conversation())    

我们把这个传回的json,叠加在message里面,再调用chatgpt模型。得出结果:

ChatCompletion(id='chatcmpl-8ciuEU38jFKJcjEbQH66ejGNnp0kO', 
choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(
content="Currently, the weather in San Francisco, California is 72°F (22°C) with a slight breeze. In Tokyo, Japan, the temperature is 22°C with partly cloudy skies. In Beijing, China, it's 10°C with overcast conditions. And in Paris, France, the temperature is 22.22°C with clear skies.", 
role='assistant', function_call=None, tool_calls=None))], 
created=1704239774, model='gpt-3.5-turbo-1106', object='chat.completion', system_fingerprint='fp_772e8125bb', usage=CompletionUsage(completion_tokens=71, prompt_tokens=229, total_tokens=300))

tool和tool_choice,取代了过去的function和function calling。
在这里插入图片描述

这篇关于OpenAI ChatGPT-4开发笔记2024-03:Chat之Function Calling/Function/Tool/Tool_Choice的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/572103

相关文章

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

利用Python快速搭建Markdown笔记发布系统

《利用Python快速搭建Markdown笔记发布系统》这篇文章主要为大家详细介绍了使用Python生态的成熟工具,在30分钟内搭建一个支持Markdown渲染、分类标签、全文搜索的私有化知识发布系统... 目录引言:为什么要自建知识博客一、技术选型:极简主义开发栈二、系统架构设计三、核心代码实现(分步解析

Python通过模块化开发优化代码的技巧分享

《Python通过模块化开发优化代码的技巧分享》模块化开发就是把代码拆成一个个“零件”,该封装封装,该拆分拆分,下面小编就来和大家简单聊聊python如何用模块化开发进行代码优化吧... 目录什么是模块化开发如何拆分代码改进版:拆分成模块让模块更强大:使用 __init__.py你一定会遇到的问题模www.

Spring Security基于数据库的ABAC属性权限模型实战开发教程

《SpringSecurity基于数据库的ABAC属性权限模型实战开发教程》:本文主要介绍SpringSecurity基于数据库的ABAC属性权限模型实战开发教程,本文给大家介绍的非常详细,对大... 目录1. 前言2. 权限决策依据RBACABAC综合对比3. 数据库表结构说明4. 实战开始5. MyBA

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

Python基于wxPython和FFmpeg开发一个视频标签工具

《Python基于wxPython和FFmpeg开发一个视频标签工具》在当今数字媒体时代,视频内容的管理和标记变得越来越重要,无论是研究人员需要对实验视频进行时间点标记,还是个人用户希望对家庭视频进行... 目录引言1. 应用概述2. 技术栈分析2.1 核心库和模块2.2 wxpython作为GUI选择的优

基于Flask框架添加多个AI模型的API并进行交互

《基于Flask框架添加多个AI模型的API并进行交互》:本文主要介绍如何基于Flask框架开发AI模型API管理系统,允许用户添加、删除不同AI模型的API密钥,感兴趣的可以了解下... 目录1. 概述2. 后端代码说明2.1 依赖库导入2.2 应用初始化2.3 API 存储字典2.4 路由函数2.5 应