OpenAI工具呼叫示例

花韻仙語
发布: 2025-02-11 14:58:01
转载
377人浏览过

from json import loads
from signal import signal, sigint

from requests import get  # pip install requests
from openai import openai  # pip install openai

# suppressing "keyboardinterrupt" message
signal(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) message
client = 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 now

ChatGPT: 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工具呼叫示例的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号