python实现ChatGPT连续多轮对话

代码如下。注意,api_key需要改成自己的密钥才能成功运行。

import openai

api_key = "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"

openai.api_key = api_key

def 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':
                break

            d = {"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()

运行效果如下:
python实现ChatGPT连续多轮对话_第1张图片

你可能感兴趣的:(ChatGPT,chatgpt)