编辑代码

import http.client
import json

# 设置主机地址和端口
conn = http.client.HTTPSConnection("api.openai.com")

# 设置你的 OpenAI API 密钥
api_key = "你的API密钥"

# 请求头
headers = {
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {api_key}'
}

# 请求体(请求使用 GPT-4 生成回答)
data = {
    "model": "gpt-4",
    "messages": [
        {"role": "user", "content": "写一首关于胡萝卜的诗,用中文"}
    ]
}

# 发送 POST 请求
conn.request("POST", "/v1/chat/completions", body=json.dumps(data), headers=headers)

# 读取响应
response = conn.getresponse()
response_data = response.read().decode()

# 转换为 JSON 并打印结果
result = json.loads(response_data)
print(result["choices"][0]["message"]["content"])

# 关闭连接
conn.close()