1. 使用 OpenAI 库调用 ChatGPT (流式输出)
Python 3.8.10
Name: openai Version: 0.27.8
import openai
# openai.api_base = "https://api.openai.com/v1" # 换成代理,一定要加v1
openai.api_base = "https://openkey.cloud/v1" # 换成代理,一定要加v1
# openai.api_key = "API_KEY"
openai.api_key = "sk-JdKYK4xHHVF6b40A6e724a8e497c442cB1A2B44a1c4768B7"
for resp in openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "证明费马大定理"}
],
# 流式输出
stream = True):
if 'content' in resp.choices[0].delta:
print(resp.choices[0].delta.content, end="", flush=True)
2. 使用 HTTP requests 请求调用 ChatGPT
import requests
# url = "https://api.openai.com/v1/chat/completions"
url = "https://openkey.cloud/v1/chat/completions"
headers = {
'Content-Type': 'application/json',
# 填写OpenKEY生成的令牌/KEY,注意前面的 Bearer 要保留,并且和 KEY 中间有一个空格。
'Authorization': 'Bearer sk-JdKYK4xHHVF6b40A6e724a8e497c442cB1A2B44a1c4768B7'
}
data = {
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "你好呀"}]
}
response = requests.post(url, headers=headers, json=data)
print("Status Code", response.status_code)
print("JSON Response ", response.json())