ChatGPT API调用概述

ChatGPT API支持多种编程语言调用,本页面提供了最常用编程语言的示例代码,帮助开发者快速集成ChatGPT的强大功能到自己的应用中。

多语言API调用示例

在开始之前,请确保您已经:

  • 注册了OpenAI账户
  • 获取了API密钥
  • 了解基本的API概念和参数

如果您还没有完成上述步骤,请先查看ChatGPT API入门指南

Python示例代码

Python是调用ChatGPT API最流行的语言之一,OpenAI提供了官方Python库。

安装依赖

pip install openai

基础聊天完成示例

import openai

# 设置API密钥
openai.api_key = "sk-your-api-key"

# 创建聊天完成
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "你是一个有用的助手。"},
        {"role": "user", "content": "请介绍一下ChatGPT。"}
    ]
)

# 打印响应
print(response.choices[0].message.content)

流式响应示例

流式响应允许您在生成完整响应之前开始接收部分响应,类似于ChatGPT网页版的打字效果:

import openai

# 设置API密钥
openai.api_key = "sk-your-api-key"

# 创建流式聊天完成
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "你是一个有用的助手。"},
        {"role": "user", "content": "请介绍一下ChatGPT。"}
    ],
    stream=True  # 启用流式响应
)

# 处理流式响应
for chunk in response:
    if chunk.choices and len(chunk.choices) > 0:
        content = chunk.choices[0].delta.get("content", "")
        print(content, end="", flush=True)

带函数调用的示例

函数调用允许ChatGPT调用您定义的函数,适用于需要外部数据或执行特定操作的场景:

import openai
import json

# 设置API密钥
openai.api_key = "sk-your-api-key"

# 定义函数
functions = [
    {
        "name": "get_weather",
        "description": "获取指定城市的天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称,如北京、上海"
                }
            },
            "required": ["city"]
        }
    }
]

# 模拟天气数据获取函数
def get_weather(city):
    # 在实际应用中,这里应该调用天气API
    weather_data = {
        "北京": {"temperature": "25°C", "condition": "晴朗"},
        "上海": {"temperature": "28°C", "condition": "多云"},
        "广州": {"temperature": "30°C", "condition": "小雨"}
    }
    return weather_data.get(city, {"temperature": "未知", "condition": "未知"})

# 创建聊天完成
response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "你是一个有用的助手。"},
        {"role": "user", "content": "北京今天天气怎么样?"}
    ],
    functions=functions,
    function_call="auto"
)

# 处理响应
message = response.choices[0].message

# 检查是否有函数调用
if message.get("function_call"):
    function_name = message["function_call"]["name"]
    function_args = json.loads(message["function_call"]["arguments"])
    
    if function_name == "get_weather":
        city = function_args.get("city")
        weather_info = get_weather(city)
        
        # 将函数结果发送回模型
        second_response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "你是一个有用的助手。"},
                {"role": "user", "content": "北京今天天气怎么样?"},
                message,
                {
                    "role": "function",
                    "name": "get_weather",
                    "content": json.dumps(weather_info)
                }
            ]
        )
        
        print(second_response.choices[0].message.content)
else:
    print(message.content)

JavaScript示例代码

JavaScript可以在浏览器端或Node.js环境中调用ChatGPT API。

浏览器端示例

<!DOCTYPE html>
<html>
<head>
    <title>ChatGPT API 浏览器示例</title>
    <script src="https://cdn.jsdelivr.net/npm/openai@4.0.0/dist/openai.min.js"></script>
</head>
<body>
    <h1>ChatGPT API 浏览器示例</h1>
    <div>
        <textarea id="prompt" rows="4" cols="50" placeholder="输入您的问题..."></textarea>
        <button id="submit">提交</button>
    </div>
    <div id="response" style="margin-top: 20px; white-space: pre-wrap;"></div>

    <script>
        // 注意:在浏览器中直接暴露API密钥是不安全的
        // 实际应用中应该通过后端服务中转API请求
        const apiKey = 'sk-your-api-key';
        const openai = new OpenAI({ apiKey, dangerouslyAllowBrowser: true });

        document.getElementById('submit').addEventListener('click', async () => {
            const promptText = document.getElementById('prompt').value;
            const responseDiv = document.getElementById('response');
            
            responseDiv.textContent = '正在生成回答...';
            
            try {
                const response = await openai.chat.completions.create({
                    model: 'gpt-3.5-turbo',
                    messages: [
                        { role: 'system', content: '你是一个有用的助手。' },
                        { role: 'user', content: promptText }
                    ]
                });
                
                responseDiv.textContent = response.choices[0].message.content;
            } catch (error) {
                responseDiv.textContent = `错误: ${error.message}`;
            }
        });
    </script>
</body>
</html>

Node.js示例

// 安装依赖: npm install openai
const { OpenAI } = require('openai');

// 初始化OpenAI客户端
const openai = new OpenAI({
    apiKey: 'sk-your-api-key'
});

async function generateResponse() {
    try {
        const response = await openai.chat.completions.create({
            model: 'gpt-3.5-turbo',
            messages: [
                { role: 'system', content: '你是一个有用的助手。' },
                { role: 'user', content: '请介绍一下ChatGPT。' }
            ]
        });
        
        console.log(response.choices[0].message.content);
    } catch (error) {
        console.error('Error:', error);
    }
}

generateResponse();

Java示例代码

使用Java调用ChatGPT API,可以通过官方SDK或HTTP客户端实现。

使用HTTP客户端

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class ChatGPTExample {
    public static void main(String[] args) throws IOException, InterruptedException {
        // API密钥
        String apiKey = "sk-your-api-key";
        
        // 请求体
        String requestBody = "{\n" +
                "    \"model\": \"gpt-3.5-turbo\",\n" +
                "    \"messages\": [\n" +
                "        {\"role\": \"system\", \"content\": \"你是一个有用的助手。\"},\n" +
                "        {\"role\": \"user\", \"content\": \"请介绍一下ChatGPT。\"}\n" +
                "    ]\n" +
                "}";
        
        // 创建HTTP客户端
        HttpClient client = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();
        
        // 创建HTTP请求
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.openai.com/v1/chat/completions"))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
        
        // 发送请求并获取响应
        HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
        
        // 打印响应
        System.out.println(response.body());
    }
}

PHP示例代码

使用PHP调用ChatGPT API的示例:

<?php
// API密钥
$apiKey = 'sk-your-api-key';

// 请求数据
$data = [
    'model' => 'gpt-3.5-turbo',
    'messages' => [
        ['role' => 'system', 'content' => '你是一个有用的助手。'],
        ['role' => 'user', 'content' => '请介绍一下ChatGPT。']
    ]
];

// 初始化cURL会话
$ch = curl_init('https://api.openai.com/v1/chat/completions');

// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $apiKey
]);

// 执行请求
$response = curl_exec($ch);

// 检查错误
if (curl_errno($ch)) {
    echo 'Error: ' . curl_error($ch);
} else {
    // 解析JSON响应
    $responseData = json_decode($response, true);
    
    // 打印生成的文本
    if (isset($responseData['choices'][0]['message']['content'])) {
        echo $responseData['choices'][0]['message']['content'];
    } else {
        echo 'Error: Unexpected response format';
        print_r($responseData);
    }
}

// 关闭cURL会话
curl_close($ch);
?>

最佳实践与注意事项

API密钥安全

永远不要在客户端代码中暴露API密钥。在生产环境中,应该通过后端服务中转API请求。

错误处理与重试

实现指数退避重试策略,以应对API限制和临时错误。

成本控制

设置合理的max_tokens参数,并考虑使用缓存机制减少重复请求。

超时处理

为API请求设置合理的超时时间,并实现适当的用户反馈机制。