sycommon-python-lib 0.2.6a3__py3-none-any.whl → 0.2.6a4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -982,7 +982,7 @@ class DeepAgent:
982
982
  不在此处重试整个 graph。
983
983
  """
984
984
  import httpx
985
- from openai import APIConnectionError, APIError, APITimeoutError
985
+ from openai import APIConnectionError, APIError, APITimeoutError, BadRequestError
986
986
 
987
987
  last_error = None
988
988
  sandbox_retries = 0
@@ -1010,6 +1010,18 @@ class DeepAgent:
1010
1010
  print(
1011
1011
  f"[DeepAgent] _astream_with_retry: stream ended normally, total_chunks={chunk_count}", flush=True)
1012
1012
  return
1013
+ except BadRequestError as e:
1014
+ # BadRequestError(含 ContextOverflowError)不重试:
1015
+ # 上下文溢出由 SummarizationMiddleware 在模型调用层处理,
1016
+ # 重试只会浪费时间且无法恢复。
1017
+ from langchain_core.exceptions import ContextOverflowError as _COE
1018
+ if isinstance(e, _COE):
1019
+ SYLogger.warning(
1020
+ f"[DeepAgent] ContextOverflowError: {e}, 不重试,交由 SummarizationMiddleware 处理")
1021
+ else:
1022
+ SYLogger.warning(
1023
+ f"[DeepAgent] BadRequestError: {e}, 不重试")
1024
+ raise
1013
1025
  except (APIConnectionError, APIError, APITimeoutError, ConnectionError, httpx.RemoteProtocolError) as e:
1014
1026
  last_error = e
1015
1027
  print(
@@ -25,6 +25,68 @@ if TYPE_CHECKING:
25
25
 
26
26
  logger = logging.getLogger(__name__)
27
27
 
28
+
29
+ # ==================== ContextOverflowError 识别补丁 ====================
30
+ # MiniMax2.5 等兼容 OpenAI API 的模型返回上下文溢出错误时,
31
+ # 错误格式为 "This model's maximum context length is N tokens...",
32
+ # 而 langchain_openai 的 _handle_openai_bad_request 只识别 OpenAI 原生格式:
33
+ # - "context_length_exceeded"
34
+ # - "Input tokens exceed the configured limit"
35
+ # - "prompt is too long"
36
+ # 导致 MiniMax 的 BadRequestError 不被转换为 ContextOverflowError,
37
+ # SummarizationMiddleware 无法捕获并触发压缩。
38
+ # 此补丁扩展错误模式匹配,使 MiniMax/vLLM 等兼容 API 的溢出错误也被正确识别。
39
+ try:
40
+ import langchain_openai.chat_models.base as _lc_oai_base
41
+ import openai
42
+ from langchain_core.exceptions import ContextOverflowError
43
+
44
+ _orig_handle_bad_request = _lc_oai_base._handle_openai_bad_request
45
+
46
+ def _patched_handle_openai_bad_request(e: openai.BadRequestError) -> None:
47
+ """扩展版 _handle_openai_bad_request,识别更多上下文溢出错误格式。"""
48
+ error_str = str(e)
49
+ error_msg = getattr(e, 'message', '') or ''
50
+
51
+ # 新增模式:覆盖 MiniMax/vLLM/其他兼容 API 的错误格式
52
+ if (
53
+ "maximum context length is" in error_str
54
+ or "Please reduce the length of the input prompt" in error_msg
55
+ or "maximum context length" in error_msg
56
+ ):
57
+ raise _lc_oai_base.OpenAIContextOverflowError(
58
+ message=e.message, response=e.response, body=e.body
59
+ ) from e
60
+
61
+ # 回退到原始处理逻辑
62
+ _orig_handle_bad_request(e)
63
+
64
+ _lc_oai_base._handle_openai_bad_request = _patched_handle_openai_bad_request
65
+
66
+ # 同步 patch _handle_openai_api_error
67
+ _orig_handle_api_error = _lc_oai_base._handle_openai_api_error
68
+
69
+ def _patched_handle_openai_api_error(e: openai.APIError) -> None:
70
+ """扩展版 _handle_openai_api_error,识别更多上下文溢出错误格式。"""
71
+ error_str = str(e)
72
+ if "maximum context length is" in error_str:
73
+ raise _lc_oai_base.OpenAIAPIContextOverflowError(
74
+ message=e.message, request=e.request, body=e.body
75
+ ) from e
76
+ _orig_handle_api_error(e)
77
+
78
+ _lc_oai_base._handle_openai_api_error = _patched_handle_openai_api_error
79
+
80
+ logger.info(
81
+ "[ContextOverflowPatch] 已扩展 _handle_openai_bad_request/_handle_openai_api_error "
82
+ "以识别 MiniMax/vLLM 上下文溢出错误格式"
83
+ )
84
+ except ImportError:
85
+ logger.debug("[ContextOverflowPatch] langchain_openai 不可用,跳过补丁")
86
+ except Exception as _patch_err:
87
+ logger.warning(f"[ContextOverflowPatch] 补丁应用失败: {_patch_err}")
88
+
89
+
28
90
  # 中文摘要提示词,替代 langchain DEFAULT_SUMMARY_PROMPT
29
91
  # 使用纯自然段落格式(无标题/小标题/列表标记),避免结构化标题被模型回显到用户输出
30
92
  CUSTOM_SUMMARY_PROMPT = """<role>
@@ -78,6 +78,11 @@ def clamp_max_tokens(
78
78
  将 model.max_tokens = min(max_output_tokens, context_window - input - buffer),
79
79
  最低保底 min_output。
80
80
 
81
+ 安全措施:
82
+ - context_window 乘以 0.95 作为有效上限,防止模型实际上下文窗口小于配置值
83
+ (如 MiniMax2.5 配置 200000 但实际为 196608)
84
+ - tiktoken 计数可能与模型内部 tokenizer 存在偏差,额外余量可以覆盖
85
+
81
86
  Args:
82
87
  model: 拥有 ``max_tokens`` 属性的 ChatModel 实例。
83
88
  messages: 即将发送给模型的消息列表。
@@ -89,8 +94,10 @@ def clamp_max_tokens(
89
94
  Returns:
90
95
  调整后的 max_tokens 值。
91
96
  """
97
+ # 有效上下文窗口 = 配置值 * 0.95,防止配置值大于模型实际上下文
98
+ effective_context = int(context_window * 0.95)
92
99
  input_est = count_messages_tokens(messages)
93
- available = context_window - input_est - buffer
100
+ available = effective_context - input_est - buffer
94
101
  dynamic_max = min(max_output_tokens, max(available, min_output))
95
102
  model.max_tokens = dynamic_max
96
103
  return dynamic_max
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sycommon-python-lib
3
- Version: 0.2.6a3
3
+ Version: 0.2.6a4
4
4
  Summary: Add your description here
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -129,9 +129,9 @@ sycommon/services.py,sha256=pUcV0xFrn1hrArD9YwE8m6CMrrWPwNBAqUIWhgsVkzY,24943
129
129
  sycommon/agent/__init__.py,sha256=mxceAeUifQ-DKvWp7ZEJIFlmOCb5wpYHPGQw3rwEN8I,4378
130
130
  sycommon/agent/agent_manager.py,sha256=UhhaekEumT7g4v_Z1UB4jTp13X0n8M8erYaQdkGGWkA,13620
131
131
  sycommon/agent/chat_events.py,sha256=t7qWa6OrIWLfqtd1AnqaVP67QWkn1JxpCBTZYQpoLuM,14226
132
- sycommon/agent/deep_agent.py,sha256=TY2C4AnF609ZFjjz2OrpcAqjRZ2v2fPFtG7LzpWVpgQ,66892
132
+ sycommon/agent/deep_agent.py,sha256=qzRms1paE0bTtMBe1ae7SgQMK_EZEtvqyV8fsUFyxSM,67704
133
133
  sycommon/agent/multi_agent_team.py,sha256=mskS-FJbAB_n5kghjHhiWxpA3L9cD1lObeW_wjrLI6s,27079
134
- sycommon/agent/summarization_utils.py,sha256=fiwvKYE_eQc1EtBiPT4UyOZoqQdd4JwEsLRDsJNioLQ,14928
134
+ sycommon/agent/summarization_utils.py,sha256=AjdJmUWIY0kgf1qYvhMMGyB2_v70CEC-SxqSUOU3ZfA,17673
135
135
  sycommon/agent/mcp/__init__.py,sha256=iKrdDhIrFsNIkqG_kgcwNe-nOiM6uVfolKv44LfQ-FQ,636
136
136
  sycommon/agent/mcp/models.py,sha256=zda4ho-UTYOJ5oPAZPZ-vxhfDRLghUCsMroHnA2A2QQ,1490
137
137
  sycommon/agent/mcp/tool_loader.py,sha256=OQa-lE7RL2s3Lqh-kNOKaUrb130hvorB_HjyFBqZBZs,10960
@@ -190,7 +190,7 @@ sycommon/llm/struct_token.py,sha256=WYNa7o2cC_3X6dJw3ZN1Zgn83HmhdD8GCUlSiEV7qus,
190
190
  sycommon/llm/sy_langfuse.py,sha256=27RyPUkScqJYHrupOEyUs23fDszoaA66FFgv5Qc7-B4,4443
191
191
  sycommon/llm/token_usage_es_service.py,sha256=-RBCwZ8jS436n8DBUBm3Lf5O6TsQMaQgIj5oYBLO4Ss,19909
192
192
  sycommon/llm/token_usage_mysql_service.py,sha256=1WhdpZ8M4v4UNP5W0ui3A-Cx5yfZiX73l77FTJvL_d8,32644
193
- sycommon/llm/token_utils.py,sha256=AT9Rl-uHeXbBK-psQ_X0EIi6ZrSmZMO_aNHFuIAq344,3428
193
+ sycommon/llm/token_utils.py,sha256=-7cONuu--9yHJQ5kNhLisMFFz8OgFfBfh2pCENpfSUc,3852
194
194
  sycommon/llm/usage_token.py,sha256=uFskOhl6IMeJtysJ6tMAmBb2taVLm5lRWjqcrbnkx54,8736
195
195
  sycommon/llm/tiktoken_cache/9b5ad71b2ce5302211f9c61530b329a4922fc6a4,sha256=Ijkht27pm96ZW3_3OFE-7xAPtR0YyTWXoRO8_-hlsqc,1681126
196
196
  sycommon/llm/tiktoken_cache/fb374d419588a4632f3f557e76b4b70aebbca790,sha256=RGqVOMtsNI41FhINfAiwn1fDZJXirP_-WaW_iwz7Gi0,3613922
@@ -284,8 +284,8 @@ sycommon/tools/syemail.py,sha256=BDFhgf7WDOQeTcjxJEQdu0dQhnHFPO_p3eI0-Ni3LhQ,561
284
284
  sycommon/tools/timing.py,sha256=OiiE7P07lRoMzX9kzb8sZU9cDb0zNnqIlY5pWqHcnkY,2064
285
285
  sycommon/xxljob/__init__.py,sha256=7eoBlQxv-B39IfRSCY2bkqdGYs1QRe1umAWd88VMEEM,86
286
286
  sycommon/xxljob/xxljob_service.py,sha256=JIEJaGXhqrTLcyxlyynSrsHg9bBnDNzX-D4qIWLRPUE,6815
287
- sycommon_python_lib-0.2.6a3.dist-info/METADATA,sha256=gKIykJEMsoqXkDXIHU1w3Kq5YK99dJcUCE8WUTfG3-g,7913
288
- sycommon_python_lib-0.2.6a3.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
289
- sycommon_python_lib-0.2.6a3.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
290
- sycommon_python_lib-0.2.6a3.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
291
- sycommon_python_lib-0.2.6a3.dist-info/RECORD,,
287
+ sycommon_python_lib-0.2.6a4.dist-info/METADATA,sha256=og-e-U_j2lvFePetXDCzD_KIp4M0yYWh5WoieUyPXbY,7913
288
+ sycommon_python_lib-0.2.6a4.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
289
+ sycommon_python_lib-0.2.6a4.dist-info/entry_points.txt,sha256=gsR4SssKxDWjRU8ggidzNcdMXDPRSKRS7UaGyNP84Qg,92
290
+ sycommon_python_lib-0.2.6a4.dist-info/top_level.txt,sha256=RgphKrg7nJyZ7irJqbxFr-5H2LUYTvI7ivoWZH2hcD0,29
291
+ sycommon_python_lib-0.2.6a4.dist-info/RECORD,,