记住聊天机器人之前的对话

3
我使用以下代码基于OpenAI创建了一个基本的聊天机器人:
import openai
openai.api_key = "sk-xxx"
while True:
    prompt = input("User:")
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        max_tokens=50,
        temperature=0,
    )
    print(response.choices[0].text)

这是输入和输出:

enter image description here

并以文本形式:

User:What is python
Python is a high-level, interpreted, general-purpose programming language. It is a powerful and versatile language that is used for a wide range of applications, from web development and software development to data science and machine learning.`
User:What is the Latest Version of it? 
The latest version of Microsoft Office is Microsoft Office 2019. 

正如您所看到的,我正在提出与Python相关的问题,并且询问其版本时,答案却与Microsoft Office有关。然而,当我向ChatGpt提出同样的问题时,它会记住先前的对话并根据其行事。

是否有任何解决方案来记住对话?

1个回答

3

一种可能的方法是将输入和输出存储在某个地方,然后将它们包含在随后的输入中。这非常基础,但您可以执行以下操作:

inputs, outputs = [], []

while True:
    prompt = input("Enter input (or 'quit' to exit):")
    if prompt == 'quit':
        break

    if len(inputs) > 0:
        inputs.append(prompt)
        last_input, last_output = inputs[-1], outputs[-1]
        prompt = f"{prompt} (based on my previous question: {last_input}, and your previous answer {last_output}"
    else:
        inputs.append(prompt)

    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        max_tokens=200,
        temperature=0,
    )
    
    output = response.choices[0].text
    outputs.append(output)
    
    print(output)

这个程序可以回忆起上一次的输入和输出,并在当前提示信息中提供该信息。您可以根据需要增加更多的输入和输出行数,以便程序具有更多的“记忆”,同时还有一个文本限制(max_tokens),因此您可能需要调整措辞以使整个提示信息有意义。

为了避免无限循环,我们可以设置退出 while 循环的条件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接