OpenAI工具呼叫示例

from json import loadsfrom signal import signal, sigintfrom requests import get  # pip install requestsfrom openai import openai  # pip install openai# suppressing "keyboardinterrupt" messagesignal(sigint, lambda _, __: exit())def get_weather(latitude, longitude):    response = get(f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&current=temperature_2m")    data = response.json()    temperature = data['current']['temperature_2m']    return str(temperature)tools = [{    "type": "function",    "function": {        "name": "get_weather",        "description": "get current temperature for provided coordinates in celsius.",        "parameters": {            "type": "object",            "properties": {                "latitude": {"type": "number"},                "longitude": {"type": "number"}            },            "required": ["latitude", "longitude"],            "additionalproperties": false        },        "strict": true    }}]# openai client and chat history with the first (system) messageclient = openai()messages = [{"role": "system", "content": "you are a weather assistant."}]while true:    # sending message and getting a response back (chat completion)    completion = client.chat.completions.create(model="gpt-4o-mini", messages=messages, tools=tools)    # getting the first choice (is it possible to get more than one at a time?)    choice = completion.choices[0]    # appending the message to the conversation history    messages.append(choice.message)    # switch based on the finish reason    match choice.finish_reason:        # stop (weirdly) means we got a message response        case "stop":            # asking for the user for a prompt            print("\nchatgpt:", choice.message.content)            prompt = input("\nuser: ").strip()            # appending the user message to the conversation history            messages.append({"role": "user", "content": prompt})        # in case we got a tool call        case "tool_calls":            # getting the first tool call (is it possible to get more than one at a time?)            tool_call = choice.message.tool_calls[0]            # function name and arguments            function_name = tool_call.function.name            arguments = loads(tool_call.function.arguments)            match function_name:                # calling the function and appending the result to conversation history                case "get_weather":                    result = get_weather(**arguments)                    messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": result})                case unexpected_function:                    raise exception(f"unexpected function call: {unexpected_function}")        case unexpected_reason:            raise exception(f"unexpected \"finish_reason\": {unexpected_reason}")

>运行它:

ChatGPT: How can I assist you with the weather today?User: whats the weather in ny right nowChatGPT: The current temperature in New York is -2.9°C. If you need more information about the weather or forecast, just let me know!

以上就是OpenAI工具呼叫示例的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1356038.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
从零到fastapi英雄:我的hngstage dventure
上一篇 2025年12月13日 19:35:05
使用Zappa在AWS lambda + API网关上部署数字分类API
下一篇 2025年12月13日 19:35:24

相关推荐

发表回复

登录后才能评论
关注微信