把上面代码的功能整合为一个
时间: 2023-07-16 08:16:48 浏览: 43
完整的代码:
```python
import openai
import time
# 配置 OpenAI API 密钥
openai.api_key = "YOUR_API_KEY_HERE"
# 设置对话起始点
start_sequence = "\nAI: "
restart_sequence = "\n\nHuman: "
# 设置模型、引擎、温度和最大回复长度
model_engine = "text-davinci-002"
temperature = 0.7
max_tokens = 150
# 初始化对话历史记录
chat_history = start_sequence
print("AI: Hello! How can I help you today?")
while True:
# 获取用户输入
user_input = input("You: ")
# 拼接用户输入到对话历史记录中
chat_history += restart_sequence + user_input
# 发送对话历史记录给 OpenAI API 进行回复
response = openai.Completion.create(
engine=model_engine,
prompt=chat_history,
temperature=temperature,
max_tokens=max_tokens,
n=1,
stop=None,
timeout=15,
)
# 提取回复并拼接到对话历史记录中
ai_response = response.choices[0].text
chat_history += start_sequence + ai_response.strip()
# 输出回复
print("AI:", ai_response.strip())
# 等待一段时间以避免 API 过载
time.sleep(0.5)
```