###### tags: `F3164` # ch13 更改儲存對話上限教學 因為原始程式碼中每次只會記錄前兩組的對話,使得 ChatGPT 的記憶力有限, 為了讓它擁有更多的聊天記憶, 需要更改程式中的對話紀錄串列, 以下是更改儲存對話上限的教學。 :::danger 注意 !!! 若提高對話記錄上限, 則會使用大量的 tokens, 請謹慎使用。 ::: 以下程式是原程式的加強版, 只需更改數值即可決定要儲存多少組對話。 更改步驟: 1. 第 18 行的 history_num 為儲存對話的上限, history_num = 6 代表 6 組對話。 2. 第 20 行為 max_tokens , 數字越大則容許傳遞更多的 tokens。 ```python= from flask import (Flask, request, abort) from linebot import (LineBotApi, WebhookHandler) from linebot.exceptions import (InvalidSignatureError) from linebot.models import (MessageEvent, TextMessage, TextSendMessage) app = Flask(__name__) line_bot_api = LineBotApi('輸入權杖') handler = WebhookHandler('輸入密鑰') import openai openai.api_key = '輸入 api_key' messages = [] history_num = 6 # 請更改此處數值 max_tokens = 600 # 請更改此處數值 history_ans = ["", ""]*history_num @app.route("/", methods=['POST']) def callback(): signature = request.headers['X-Line-Signature'] body = request.get_data(as_text=True) try: handler.handle(body, signature) except InvalidSignatureError: print("Please check your channel access token/channel secret.") abort(400) return 'OK' @handler.add(MessageEvent, message=TextMessage) def handle_message(event): global history_ans,messages msg_new = event.message.text for i in range(0,history_num*2,2): messages += [{"role": "user", "content": history_ans[i]}] messages += [{"role": "assistant", "content": history_ans[i+1]}] messages += [{"role": "user", "content": msg_new}] response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages = messages, temperature=0.7, max_tokens=max_tokens, ) reply_msg = response['choices'][0]['message']['content'] line_bot_api.reply_message( event.reply_token, TextSendMessage(text=reply_msg.strip().replace('\n', ''))) history_ans += [msg_new] history_ans += [reply_msg.strip().replace('\n', '')] if len(history_ans) > history_num*2: history_ans.pop(0) history_ans.pop(0) print('user:', msg_new) print('history: ',end='') for i in history_ans: print([i],end='') print() if __name__ == "__main__": app.run(host='0.0.0.0', port=5000) ```