在过去我通过chatgpt调用api时只知道进行孤立的调用,即这一次调用时,chatgpt并没有拿到上一次调用的上下文,这无疑损失很大。通过探索,我知道了如何通过修改messages这个字典类型的list来告知chatgpt我和它的聊天历史。
关键代码如下
def generate_chat_completion(question):data = {'model': 'gpt-3.5-turbo','messages': [{"role": "system", "content": "You are a helpful calendar assistant"},{"role": "user", "content": "六月的下一个月有多少天?"},{"role": "assistant", "content": "七月有31天。"},{"role": "user", "content": "八月有多少天?"},{"role": "assistant", "content": "八月也有31天。"},{"role": "user", "content": "二月有多少天?"},{"role": "assistant", "content": "这要分平年和闰年"},{"role": "user", "content": "按照先后顺序,重复一下我原先问你的所有问题和你给我的相应回答。"}]}headers = {'Authorization': f"Bearer {KEY}",'Content-Type': 'application/json'}response = requests.post(f'{PROXY_URL}/v1/chat/completions', data=json.dumps(data), headers=headers)if response.status_code == 200:response_json = response.json()choices = response_json.get('choices')if choices:result = response_json['choices'][0]['message']['content']else:print("chatgpt调用出现问题,状态码是:", response.status_code)answer = ""return answer, data["messages"]
让我们近距离观察一下传入请求中的data的message属性的值
{"role": "system", "content": "You are a helpful calendar assistant"},
{"role": "user", "content": "六月的下一个月有多少天?"},
{"role": "assistant", "content": "七月有31天。"},
{"role": "user", "content": "八月有多少天?"},
{"role": "assistant", "content": "八月也有31天。"},
{"role": "user", "content": "二月有多少天?"},
{"role": "assistant", "content": "这要分平年和闰年"},
{"role": "user", "content": "按照先后顺序,重复一下我原先问你的所有问题和你给我的相应回答。"}
该值是一个list,一共包含1+6+1个字典,如果不加上历史记录,通常就只是一头一尾两个字典,而中间出现了3组user-assistant字典,就代表着之前的三轮对话。
我调用上述方法的代码如下
def main():# 输入问题和上下文question = "按照先后顺序,重复一下我原先问你的所有问题,再进行总结。"# 调用方法进行对话生成response, message_list = generate_chat_completion(question)# 打印生成的回答current_folder = os.getcwd()write_file = os.path.join(current_folder, "codex_api", "chatgpt_answer7.txt")os.makedirs(os.path.dirname(write_file), exist_ok=True)with open(write_file, "w", encoding="utf-8") as f:for message in message_list:f.write(message["role"]+"\n"+message["content"])f.write("\n")f.write("\n"+'-'*100+"\n")f.write(response)
保存下来的文件内容如下
当然,让我来回顾一下之前的问题和回答:
1. 六月的下一个月有多少天?
回答:七月有31天。2. 八月有多少天?
回答:八月也有31天。3. 二月有多少天?
回答:二月的天数取决于是平年还是闰年。在平年中,二月有28天;而在闰年中,二月有29天。请问还有其他问题需要我回答吗