視頻講解
在過去我通過chatgpt調(diào)用api時只知道進行孤立的調(diào)用,即這一次調(diào)用時,chatgpt并沒有拿到上一次調(diào)用的上下文,這無疑損失很大。通過探索,我知道了如何通過修改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調(diào)用出現(xiàn)問題,狀態(tài)碼是:", 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個字典,如果不加上歷史記錄,通常就只是一頭一尾兩個字典,而中間出現(xiàn)了3組user-assistant字典,就代表著之前的三輪對話。
我調(diào)用上述方法的代碼如下
def main():
# 輸入問題和上下文
question = "按照先后順序,重復一下我原先問你的所有問題,再進行總結(jié)。"
# 調(diào)用方法進行對話生成
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)
保存下來的文件內(nèi)容如下
當然,讓我來回顧一下之前的問題和回答:
1. 六月的下一個月有多少天?
? ?回答:七月有31天。2. 八月有多少天?
? ?回答:八月也有31天。3. 二月有多少天?
? ?回答:二月的天數(shù)取決于是平年還是閏年。在平年中,二月有28天;而在閏年中,二月有29天。文章來源:http://www.zghlxwxcb.cn/news/detail-609097.html請問還有其他問題需要我回答嗎文章來源地址http://www.zghlxwxcb.cn/news/detail-609097.html
到了這里,關于解鎖ChatGPT的潛能:API調(diào)用中運用聊天記錄的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!