对话模型 调用示例

本文中,我们将介绍如何使用 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

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())

实现效果如下:

OpenKey完全兼容OpenAI接口协议,具体调用方法参考官方文档:

https://platform.openai.com/docs/introduction

Last updated