# 对话模型 调用示例

**本文中，我们将介绍如何使用 Python 调用** [**OpenKEY**](https://openkey.cloud/) **提供的ChatGPT API接口来调用 ChatGPT 对话模型，包括使用 OpenAI 库和 HTTP requests原始JSON请求两种方式。**

#### 1. 使用 OpenAI 库调用 ChatGPT （流式输出）

**系统环境：**

> Python 3.8.10
>
> Name: openai Version: 0.27.8

**`pip install openai`**

```python
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)
```

**实现效果如下：**

<figure><img src="https://gptocean.com/assets/files/2023-07-12/1689165825-698477-openkey-0.gif" alt=""><figcaption></figcaption></figure>

#### 2. 使用 HTTP requests 请求调用 ChatGPT

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

**实现效果如下：**

<figure><img src="https://gptocean.com/assets/files/2023-07-12/1689165843-25184-openkey-1.gif" alt=""><figcaption></figcaption></figure>

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

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

本文中的python openai包过于老旧，新版调用方式已经更新：

{% content-ref url="/pages/Rh9Vvx1QizEt2a2BDKIb" %}
[Python示范代码（最新）](/api/oai146.md)
{% endcontent-ref %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.openkey.cloud/api/model-chat.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
