写一份 与https://api.openai.com/v1/chat/completions 通讯的代码
时间: 2023-10-08 12:07:28 浏览: 479
下面是一个使用 Python 和 requests 库的示例代码,用于与 OpenAI 的 GPT-3 模型进行对话:
```python
import requests
# 在 OpenAI API 中创建一个新的引擎,获取 API 密钥
# 在这里使用 YOUR_API_KEY 替换为你自己的 API 密钥
url = "https://api.openai.com/v1/engines/davinci-codex/completions"
headers = {"Content-Type": "application/json",
"Authorization": f"Bearer {YOUR_API_KEY}"}
# 定义一个函数,用于向 OpenAI 发送请求并返回响应
def generate_text(prompt):
# 设置请求数据,prompt 是对话的起点
data = {
"prompt": prompt,
"max_tokens": 2048,
"temperature": 0.5,
"n": 1,
"stop": "\n"
}
# 发送 POST 请求
response = requests.post(url, headers=headers, json=data)
# 处理响应数据
if response.status_code == 200:
return response.json()['choices'][0]['text']
else:
raise ValueError("Failed to generate text from AI model.")
# 使用 generate_text 函数进行对话
while True:
prompt = input("You: ")
response = generate_text(prompt)
print("AI: " + response)
```
在这个示例代码中,我们使用了 OpenAI API 中的 `davinci-codex` 引擎,这是一个基于 GPT-3 的模型。我们定义了 `generate_text` 函数,该函数接受一个对话起点 prompt,然后向 OpenAI API 发送一个 POST 请求,请求的数据包括对话起点、生成的最大 token 数、温度等参数。在响应中,我们提取了模型生成的文本并返回给调用者。最后,我们使用 `while` 循环来不断与模型进行对话。
阅读全文
相关推荐

















