import requests
def test_chatgpt_api(prompt):
url = "https://api.openai.com/v1/chat/completions" # ChatGPT API 的 URL
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY" # 将 YOUR_API_KEY 替换为你的 API 密钥
}
data = {
"prompt": prompt,
"max_tokens": 50 # 设置生成的最大标记数量
}
try:
response = requests.post(url, headers=headers, json=data) # 发送 POST 请求
if response.status_code == 200: # 检查响应状态码
result = response.json()
print("API 请求成功!")
print("生成的回复:", result["choices"][0]["text"].strip()) # 输出生成的回复
else:
print("API 请求失败,状态码:", response.status_code)
print("错误信息:", response.json())
except requests.exceptions.RequestException as e:
print("API 请求发生异常:", e)
# 在这里调用 test_chatgpt_api() 函数,传入你的提示(prompt)
prompt = "Tell me a joke."
test_chatgpt_api(prompt)
在上面的代码中,如果api请求失败(响应状态码不是200),它将输出相应状态码和错误信息。
response.json()
返回的是一个包含错误信息的json对象
运行前需将YOUR_API_KEY
替换成你的API密钥