代码如下。注意,api_key需要改成自己的密钥才能成功运行。
import openaiapi_key = "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"openai.api_key = api_keydef askChatGPT(messages):MODEL = "gpt-3.5-turbo"response = openai.ChatCompletion.create(model=MODEL,messages = messages,temperature=1)return response['choices'][0]['message']['content']def main():messages = [{"role": "user","content":""}]while 1:try:text = input('你:')if text == 'quit':breakd = {"role":"user","content":text}messages.append(d)text = askChatGPT(messages)d = {"role":"assistant","content":text}print('ChatGPT:'+text+'\n')messages.append(d)except:messages.pop()print('ChatGPT:error\n')
main()
运行效果如下: