上面代码改成while语句
时间: 2023-11-12 07:12:17 浏览: 82
当然可以,请看下面的代码:
```python
import openai
import time
openai.api_key = "YOUR_API_KEY"
# set up the model name and prompt
model_engine = "text-davinci-002"
prompt_text = "Hello, I am an AI language model. Ask me anything!"
# create the completion object
completions = openai.Completion.create(
engine=model_engine,
prompt=prompt_text,
max_tokens=1024,
n=1,
stop=None,
temperature=0.7,
)
# output the AI's response
message = completions.choices[0].text.strip()
print("AI: " + message)
# start a loop to keep the conversation going
while True:
# get input from the user
user_input = input("You: ")
# add the user's input to the prompt
prompt_text += "\nUser: " + user_input.strip()
# create the completion object with the updated prompt
completions = openai.Completion.create(
engine=model_engine,
prompt=prompt_text,
max_tokens=1024,
n=1,
stop=None,
temperature=0.7,
)
# output the AI's response
message = completions.choices[0].text.strip()
print("AI: " + message)
# wait for a second to avoid hitting the API rate limit
time.sleep(1)
```
这个代码使用了一个 `while` 循环,它会一直运行直到用户输入 `exit` 停止程序。在每次循环中,我们会向 AI 提供更新后的提示,然后获取 AI 的响应并输出。注意我们在每次操作之间加了一个延时,这是为了避免 API 调用频率过高导致 API 被限制。
阅读全文