From 691de01b79837c92aafe3a142a1ded75dcb6bc18 Mon Sep 17 00:00:00 2001 From: Soulter <905617992@qq.com> Date: Wed, 26 Mar 2025 00:46:15 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20=E6=94=AF=E6=8C=81=E8=AE=BE?= =?UTF-8?q?=E7=BD=AE=E6=9C=80=E5=A4=9A=E6=90=BA=E5=B8=A6=E5=AF=B9=E8=AF=9D?= =?UTF-8?q?=E6=95=B0=E9=87=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- astrbot/core/config/default.py | 6 ++++++ .../core/pipeline/process_stage/method/llm_request.py | 11 +++++++++++ 2 files changed, 17 insertions(+) diff --git a/astrbot/core/config/default.py b/astrbot/core/config/default.py index 9bcacce9c..793227f3f 100644 --- a/astrbot/core/config/default.py +++ b/astrbot/core/config/default.py @@ -49,6 +49,7 @@ DEFAULT_CONFIG = { "datetime_system_prompt": True, "default_personality": "default", "prompt_prefix": "", + "max_context_length": -1, }, "provider_stt_settings": { "enable": False, @@ -909,6 +910,11 @@ CONFIG_METADATA_2 = { "type": "string", "hint": "添加之后,会在每次对话的 Prompt 前加上此文本。", }, + "max_context_length": { + "description": "最多携带对话数量(条)", + "type": "int", + "hint": "超出这个数量时将丢弃最旧的部分,用户和AI的一轮聊天记为 1 条。-1 表示不限制,默认为不限制。", + }, }, }, "persona": { diff --git a/astrbot/core/pipeline/process_stage/method/llm_request.py b/astrbot/core/pipeline/process_stage/method/llm_request.py index b49cd6581..872875e8f 100644 --- a/astrbot/core/pipeline/process_stage/method/llm_request.py +++ b/astrbot/core/pipeline/process_stage/method/llm_request.py @@ -34,6 +34,9 @@ class LLMRequestSubStage(Stage): self.provider_wake_prefix = ctx.astrbot_config["provider_settings"][ "wake_prefix" ] # str + self.max_context_length = ctx.astrbot_config["provider_settings"][ + "max_context_length" + ] # int for bwp in self.bot_wake_prefixs: if self.provider_wake_prefix.startswith(bwp): @@ -123,6 +126,14 @@ class LLMRequestSubStage(Stage): if isinstance(req.contexts, str): req.contexts = json.loads(req.contexts) + # max context length + if ( + self.max_context_length != -1 # -1 为不限制 + and len(req.contexts) // 2 > self.max_context_length + ): + logger.debug("上下文长度超过限制,将截断。") + req.contexts = req.contexts[-self.max_context_length * 2 :] + try: need_loop = True while need_loop: