OpenAI工具呼叫示例

梦敏吖_6387

梦敏吖_6387

2025-02-11

384人浏览

转载

GitHub & Developer Data
GitHub & Developer Data

面向AI代理的GitHub及开发者数据——仓库元数据(星标、语言、许可证)、仓库审计与风险评分、用户资料、最新发布和gist内容...

下载
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!

相关文章

PHP速学视频免费教程(入门到精通)
PHP速学视频免费教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

相关标签:

git switch chatgpt ai工具

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

相关专题

更多
Vite 项目如何打包和部署
Vite 项目如何打包和部署

Vite项目打包部署专题汇集生产构建、产物预览、输出目录、资源路径、Nginx与GitHub Pages部署及常见白屏和路由404问题的已审核文章,帮助读者完成上线流程。

2026.10.28

40

16

Vite 如何搭配 Vue.js
Vite 如何搭配 Vue.js

Vite搭配Vue.js专题汇集创建Vue 3项目、配置开发环境、路径别名、Vue插件、代理、多环境构建与调试的已审核文章,帮助读者完成从初始化到日常开发的配置。

2026.10.28

20

15

Vite 项目目录怎么看
Vite 项目目录怎么看

Vite项目目录专题汇集入口文件、src源码、public静态资源、路径别名、项目根目录和构建输出目录相关的已审核文章,帮助读者理解各文件夹的用途与引用方式。

2026.10.28

0

10

Gradle插件开发入门教程
Gradle插件开发入门教程

本专题介绍Gradle插件开发的基本流程,涵盖插件类编写、自定义任务注册、扩展参数设计和插件应用方法,帮助你理解插件如何组织构建逻辑,减少多个项目之间的重复配置。

2026.10.22

120

11

Gradle Wrapper配置教程
Gradle Wrapper配置教程

本专题介绍Gradle Wrapper的基本作用,涵盖文件组成、生成方法、版本配置和任务调用,帮助你理解项目如何使用指定的Gradle版本,减少不同开发环境带来的构建差异。

2026.10.22

80

10

Golangci-lint检查器使用教程
Golangci-lint检查器使用教程

本专题整理Golangci-lint常用Linters的用途与配置方法,覆盖错误处理、无效代码、安全、复杂度、命名和依赖检查,帮助项目合理选规则。

2026.10.22

60

15

Gradle怎么构建Java项目
Gradle怎么构建Java项目

本专题介绍Gradle Java项目构建方法,涵盖Java插件配置、依赖声明、源码编译、测试执行和打包检查,帮助你理解各阶段的任务关系,逐步完成项目构建。

2026.10.22

40

10

PHP时间戳漏洞修复教程
PHP时间戳漏洞修复教程

本专题汇总PHP常见时间戳漏洞,包括2038年溢出、时区漂移、时间戳伪造、重放攻击、时间盲注与日志审计失效等,并给出升级64位环境、使用 DateTimeImmutable、统一UTC、严格超时校验、预处理绑定、hash_equals 比对等修复方案,帮助开发者快速排查和加固时间相关代码。

2026.10.22

60

25

Golangci-lint配置文件与规则设置
Golangci-lint配置文件与规则设置

本专题聚焦Golangci-lint YAML配置文件,讲清运行参数、规则启停、目录排除、问题过滤及严重级别设置,便于团队统一检查标准。

2026.10.22

40

15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
vscode手册
vscode手册

共0课时 | 0人学习

Git 教程
Git 教程

共21课时 | 8.1万人学习

Git版本控制工具
Git版本控制工具

共8课时 | 1.9万人学习