对话模型 调用示例
本文中,我们将介绍如何使用 Python 调用 OpenKEY 提供的ChatGPT API接口来调用 ChatGPT 对话模型,包括使用 OpenAI 库和 HTTP requests原始JSON请求两种方式。
1. 使用 OpenAI 库调用 ChatGPT (流式输出)
系统环境:
Python 3.8.10
Name: openai Version: 0.27.8
pip install openai
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
实现效果如下:

OpenKey完全兼容OpenAI接口协议,具体调用方法参考官方文档:
https://platform.openai.com/docs/introduction
本文中的python openai包过于老旧,新版调用方式已经更新:
Python示范代码(最新)Last updated