seed-kernel 1.0.11__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.
Files changed (60) hide show
  1. seed/__init__.py +125 -0
  2. seed/cli.py +102 -0
  3. seed/core/__init__.py +8 -0
  4. seed/core/_session_cache.py +41 -0
  5. seed/core/agent_context.py +163 -0
  6. seed/core/agent_registry.py +180 -0
  7. seed/core/agent_runtime.py +2384 -0
  8. seed/core/chat_events.py +70 -0
  9. seed/core/commands.py +149 -0
  10. seed/core/config_plane.py +537 -0
  11. seed/core/engine.py +150 -0
  12. seed/core/env_access.py +168 -0
  13. seed/core/execution.py +148 -0
  14. seed/core/llm_exec.py +1652 -0
  15. seed/core/llm_presets.py +305 -0
  16. seed/core/llm_sess.py +1094 -0
  17. seed/core/media_store.py +84 -0
  18. seed/core/mem_bridge.py +294 -0
  19. seed/core/mem_sys.py +409 -0
  20. seed/core/model_providers.py +88 -0
  21. seed/core/models.py +211 -0
  22. seed/core/paths.py +109 -0
  23. seed/core/persistence.py +133 -0
  24. seed/core/proj_reg.py +609 -0
  25. seed/core/proj_todos.py +141 -0
  26. seed/core/projection_audit.py +317 -0
  27. seed/core/routing.py +192 -0
  28. seed/core/sess_store.py +44 -0
  29. seed/core/tool_output_cap.py +122 -0
  30. seed/core/tool_runtime.py +330 -0
  31. seed/core/trace_audit.py +123 -0
  32. seed/core/turn_loop.py +750 -0
  33. seed/core/usage_accumulator.py +72 -0
  34. seed/integrations/__init__.py +33 -0
  35. seed/integrations/agent_tools.py +160 -0
  36. seed/integrations/cron_sched.py +773 -0
  37. seed/integrations/env_config.py +77 -0
  38. seed/integrations/exec_backend.py +432 -0
  39. seed/integrations/hooks.py +61 -0
  40. seed/integrations/hooks_config.py +109 -0
  41. seed/integrations/instruction_release.py +256 -0
  42. seed/integrations/lsp_client.py +219 -0
  43. seed/integrations/lsp_config.py +99 -0
  44. seed/integrations/mcp_client.py +1283 -0
  45. seed/integrations/mcp_config.py +208 -0
  46. seed/integrations/mcp_registry.py +154 -0
  47. seed/integrations/message_api.py +16 -0
  48. seed/integrations/prompt_task.py +39 -0
  49. seed/integrations/safety.py +331 -0
  50. seed/integrations/session_title.py +211 -0
  51. seed/integrations/symbol_index.py +311 -0
  52. seed/integrations/task_runner.py +275 -0
  53. seed/integrations/webhook_auth.py +33 -0
  54. seed/integrations/webhook_dedup.py +132 -0
  55. seed/models.py +31 -0
  56. seed_kernel-1.0.11.dist-info/METADATA +17 -0
  57. seed_kernel-1.0.11.dist-info/RECORD +60 -0
  58. seed_kernel-1.0.11.dist-info/WHEEL +5 -0
  59. seed_kernel-1.0.11.dist-info/entry_points.txt +2 -0
  60. seed_kernel-1.0.11.dist-info/top_level.txt +1 -0
seed/core/llm_exec.py ADDED
@@ -0,0 +1,1652 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from typing import Optional
5
+
6
+ from seed.core import env_access as _ea
7
+
8
+
9
+ class LLMAPIExecutor:
10
+ """
11
+ Executes LLM calls via OpenAI-compatible API.
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ baseURL: str,
17
+ model: str,
18
+ maxOutputTokens: int = 8192,
19
+ temperature: float = 0.7,
20
+ topP: float = 0.95,
21
+ topK: int = 40,
22
+ api_key: Optional[str] = None,
23
+ auth_scheme: Optional[str] = None,
24
+ provider: Optional[str] = None,
25
+ ):
26
+ """
27
+ Initialize LLM API executor.
28
+
29
+ Args:
30
+ baseURL: API base URL (OpenAI-compatible, e.g., https://api.openai.com/v1)
31
+ model: Model name to use
32
+ maxOutputTokens: Maximum output tokens
33
+ temperature: Temperature for sampling
34
+ topP: Top-p sampling parameter
35
+ topK: Top-k sampling parameter
36
+ """
37
+ self.baseURL = baseURL
38
+ self.model = model
39
+ self.temperature = temperature
40
+ self.topP = topP
41
+ self.topK = topK
42
+ self.api_key = (
43
+ api_key if api_key is not None else _ea.pick_nonempty(*_ea.LLM_API_KEY)
44
+ )
45
+ self.auth_scheme = (
46
+ auth_scheme
47
+ if auth_scheme is not None
48
+ else (_ea.pick_nonempty(*_ea.LLM_AUTH_SCHEME) or "Bearer")
49
+ )
50
+ self.maxOutputTokens = int(
51
+ _ea.pick_default(str(maxOutputTokens), *_ea.LLM_MAX_TOKENS)
52
+ )
53
+ from seed.core.model_providers import resolve_chat_protocol, apply_provider_chat_headers
54
+
55
+ self.provider = (provider or "").strip()
56
+ self.chat_protocol = resolve_chat_protocol(
57
+ provider=self.provider, base_url=self.baseURL
58
+ )
59
+ self.headers = {
60
+ "Content-Type": "application/json"
61
+ }
62
+ if self.api_key:
63
+ self.headers["Authorization"] = f"{self.auth_scheme} {self.api_key}"
64
+ apply_provider_chat_headers(
65
+ provider=self.provider,
66
+ base_url=self.baseURL,
67
+ headers=self.headers,
68
+ )
69
+
70
+ def _ensure_base_url(self) -> None:
71
+
72
+ if not (self.baseURL or "").strip():
73
+ raise LLMError(
74
+ "未配置 LLM API 地址:请在 config/env 中设置 SEED_LLM_BASEURL(Code Agent 可在 config 中使用 CODEAGENT_LLM_BASEURL,由产品层 bridge 同步),"
75
+ "或在 config/seed.models.json(旧文件名 codeagent.models.json)中至少保存一条含 Base URL 与模型的预设"
76
+ "(未点「设为默认」时将自动使用列表中的第一条)。"
77
+ )
78
+
79
+ def _get_completion_url(self) -> str:
80
+ """Get the completion endpoint URL"""
81
+ if self.chat_protocol == "minimax_anthropic":
82
+ base = (self.baseURL or "").rstrip("/")
83
+ if base.endswith("/v1"):
84
+ base = base[:-3]
85
+ return f"{base}/v1/messages"
86
+ return f"{self.baseURL}/chat/completions"
87
+
88
+
89
+
90
+
91
+ import copy
92
+ import json
93
+ import logging
94
+ import os
95
+ import re
96
+ from typing import Any, Dict, List, Optional, Tuple
97
+
98
+ import requests
99
+
100
+
101
+ logger = logging.getLogger(__name__)
102
+
103
+
104
+ def _requests_proxies_for(url: str):
105
+ """Disable proxying for local LLM endpoints (Ollama / SGLang / etc.).
106
+
107
+ A system/env proxy cannot reach loopback addresses, so requests to a local
108
+ base URL must bypass it. Remote endpoints keep the default proxy behaviour.
109
+ """
110
+ try:
111
+ from seed_model_providers import requests_proxies_for
112
+
113
+ return requests_proxies_for(url)
114
+ except Exception:
115
+ return None
116
+
117
+
118
+ def generate(
119
+ self,
120
+ messages: List[Dict[str, Any]],
121
+ tools: Optional[List[Dict[str, Any]]] = None,
122
+ max_turns: int = 1,
123
+ temperature: Optional[float] = None,
124
+ temperature_reset: bool = False,
125
+ max_tokens: Optional[int] = None,
126
+ enable_thinking: Optional[bool] = None,
127
+ reasoning_effort: Optional[str] = None,
128
+ ) -> Tuple[str, Dict[str, Any]]:
129
+ """
130
+ Generate response from LLM.
131
+
132
+ Args:
133
+ messages: List of messages in OpenAI format
134
+ tools: Optional list of tool definitions
135
+ max_turns: Number of completion turns
136
+ temperature: Override temperature for this call
137
+ temperature_reset: Whether to reset temperature after first turn
138
+ max_tokens: If set, cap completion tokens for this call only
139
+
140
+ Returns:
141
+ Tuple of (content, metadata including tool_calls)
142
+ """
143
+ self._ensure_base_url()
144
+ eff_max = self.maxOutputTokens if max_tokens is None else int(max_tokens)
145
+ api_messages = _openai_chat_messages(
146
+ messages, base_url=self.baseURL, chat_protocol=self.chat_protocol
147
+ )
148
+ params: Dict[str, Any] = {
149
+ "model": self.model,
150
+ "messages": copy.deepcopy(api_messages),
151
+ "max_tokens": eff_max,
152
+ "temperature": self.temperature if temperature is None else temperature,
153
+ }
154
+ if not _ea.any_nonempty(*_ea.LLM_NO_TOP_P):
155
+ params["top_p"] = self.topP
156
+ if not _ea.any_nonempty(*_ea.LLM_NO_TOPK):
157
+ params["top_k"] = self.topK
158
+
159
+ if tools:
160
+ params["tools"] = tools
161
+ params["tool_choice"] = "auto"
162
+
163
+ # --- Reasoning separation (provider-specific) -----
164
+ extra_body: Dict[str, Any] = {}
165
+ # Resolve enable_thinking from caller arg or env.
166
+ if enable_thinking is None:
167
+ env_val = _ea.pick_default("1", *_ea.LLM_ENABLE_THINKING)
168
+ resolved_thinking = env_val.lower() not in ("0", "false", "no", "")
169
+ else:
170
+ resolved_thinking = bool(enable_thinking)
171
+
172
+ from seed.core.model_providers import apply_chat_thinking_extra_body, apply_chat_stream_options
173
+
174
+ apply_chat_thinking_extra_body(
175
+ chat_protocol=self.chat_protocol,
176
+ base_url=self.baseURL,
177
+ params=params,
178
+ extra_body=extra_body,
179
+ resolved_thinking=resolved_thinking,
180
+ reasoning_effort=reasoning_effort,
181
+ model=self.model,
182
+ )
183
+ user_extra = _ea.pick_nonempty(*_ea.LLM_EXTRA_BODY)
184
+ if user_extra:
185
+ try:
186
+ parsed = json.loads(user_extra)
187
+ if isinstance(parsed, dict):
188
+ # Deep-merge chat_template_kwargs so user can add/override keys.
189
+ ctk = parsed.pop("chat_template_kwargs", None)
190
+ extra_body.update(parsed)
191
+ if isinstance(ctk, dict):
192
+ extra_body.setdefault("chat_template_kwargs", {}).update(ctk)
193
+ except (json.JSONDecodeError, TypeError) as e:
194
+ logger.warning("SEED_LLM_EXTRA_BODY invalid JSON, ignored: %s", e)
195
+ # Merge into top-level params (sglang accepts them at the request root).
196
+ for k, v in extra_body.items():
197
+ params.setdefault(k, v)
198
+
199
+ max_body = max_llm_request_body_bytes(self.baseURL, chat_protocol=self.chat_protocol)
200
+ if max_body > 0:
201
+ maybe_shrink_llm_request_params(params, max_bytes=max_body, base_url=self.baseURL)
202
+
203
+ # Clamp completion max_tokens using an estimated input budget. Prefer setting
204
+ # SEED_LLM_CONTEXT_SIZE to the inference server's *effective* KV token pool
205
+ # (e.g. SGLang ``max_total_num_tokens`` minus headroom), not always the model's
206
+ # configured ``context_len`` when VRAM limits the cache.
207
+ ctx = int(_ea.pick_default("262144", *_ea.LLM_CONTEXT_SIZE) or "262144")
208
+ if ctx > 0:
209
+ body = json.dumps(
210
+ {"messages": params["messages"], "tools": tools or []},
211
+ ensure_ascii=False,
212
+ )
213
+ div = int(_ea.pick_default("3", *_ea.LLM_INPUT_TOKEN_EST_DIVISOR))
214
+ est_in = max(1, len(body.encode("utf-8")) // max(div, 1))
215
+ margin = int(_ea.pick_default("8192", *_ea.LLM_CONTEXT_MARGIN))
216
+ cap = ctx - est_in - margin
217
+ req = int(params.get("max_tokens") or 0)
218
+ if req > 0:
219
+ allowance = max(1, cap) if cap > 0 else 1
220
+ safe = max(1, min(req, allowance))
221
+ if safe < req:
222
+ logger.warning(
223
+ "Lowering max_tokens %s -> %s (est_input≈%s, ctx=%s, margin=%s)",
224
+ req,
225
+ safe,
226
+ est_in,
227
+ ctx,
228
+ margin,
229
+ )
230
+ params["max_tokens"] = safe
231
+
232
+ # MiniMax-only precheck: ask the API for an exact input-token estimate
233
+ # before paying for a request that may exceed the model's context window.
234
+ if self.chat_protocol == "minimax":
235
+ try:
236
+ est = estimate_minimax_tokens(
237
+ base_url=self.baseURL,
238
+ api_key=self.api_key,
239
+ auth_scheme=self.auth_scheme,
240
+ model=self.model,
241
+ messages=api_messages,
242
+ tools=tools,
243
+ reasoning_effort=reasoning_effort,
244
+ )
245
+ est_n = int(est.get("input_tokens") or 0)
246
+ ctx_override = int(_ea.pick_default("0", *_ea.LLM_CONTEXT_SIZE) or "0") or None
247
+ err = precheck_minimax_context(
248
+ model=self.model,
249
+ estimated_input_tokens=est_n,
250
+ context_override=ctx_override,
251
+ )
252
+ if err:
253
+ raise LLMError(err)
254
+ if est_n >= MINIMAX_LONG_CONTEXT_THRESHOLD:
255
+ logger.info(
256
+ "MiniMax '%s' long-context request: %d tokens (>= %d, "
257
+ "long-context pricing applies).",
258
+ self.model,
259
+ est_n,
260
+ MINIMAX_LONG_CONTEXT_THRESHOLD,
261
+ )
262
+ except LLMError:
263
+ raise
264
+ except Exception as e: # noqa: BLE001
265
+ # Precheck is best-effort; never block a real request on it.
266
+ logger.debug("MiniMax input_tokens precheck skipped: %s", e)
267
+
268
+ # Anthropic 主动缓存分支:把 OpenAI 风格 messages 转换为 Anthropic Messages
269
+ # 协议 payload,自动给 system / tools / 最后一条历史消息打 cache_control。
270
+ if self.chat_protocol == "minimax_anthropic":
271
+ params = _to_minimax_anthropic_request(
272
+ api_messages,
273
+ model=self.model,
274
+ max_tokens=int(params.get("max_tokens") or self.maxOutputTokens),
275
+ tools=tools,
276
+ enable_caching=True,
277
+ extra_body=extra_body,
278
+ )
279
+
280
+ try:
281
+ _url = self._get_completion_url()
282
+ response = requests.post(
283
+ _url,
284
+ headers=self.headers,
285
+ json=params,
286
+ timeout=120,
287
+ proxies=_requests_proxies_for(_url),
288
+ )
289
+ if not response.ok:
290
+ snippet = (response.text or "")[:2000]
291
+ raise LLMError(
292
+ f"LLM HTTP {response.status_code} for {self._get_completion_url()}: {snippet}"
293
+ )
294
+ if self.chat_protocol == "minimax_anthropic":
295
+ raw = response.json()
296
+ data = _parse_minimax_anthropic_response(raw)
297
+ else:
298
+ data = response.json()
299
+
300
+ choices = data.get("choices") or []
301
+ if not choices:
302
+ raise LLMError(f"LLM returned no choices: {json.dumps(data)[:1200]}")
303
+
304
+ msg = choices[0].get("message")
305
+ if not isinstance(msg, dict):
306
+ raise LLMError(f"LLM message missing or invalid: {choices[0]!r}")
307
+
308
+ content = _msg_text_to_str(msg.get("content"))
309
+ # sglang separate_reasoning populates `reasoning_content` (DeepSeek
310
+ # API contract); some older/alt backends use `reasoning` or
311
+ # `thinking`. Read all three and keep them OUT of `content`.
312
+ reasoning_content = _msg_text_to_str(msg.get("reasoning_content") or "")
313
+ reasoning_alt = _msg_text_to_str(msg.get("reasoning") or "")
314
+ thinking = _msg_text_to_str(msg.get("thinking") or "")
315
+ # MiniMax-M3 (with reasoning_split=True) returns reasoning in a
316
+ # separate `reasoning_details` list. 旧版 MiniMax-M2.x / 未启用
317
+ # reasoning_split 时,思考会内联在 `content` 中,被 <think>...</think>
318
+ # 标签包裹;下面一并剥离。
319
+ reasoning_details_text = _extract_reasoning_details_text(msg.get("reasoning_details"))
320
+ stripped_content, inline_think_text = _strip_think_tags(content)
321
+ if stripped_content != content:
322
+ content = stripped_content
323
+ if inline_think_text and not reasoning_details_text:
324
+ reasoning_details_text = inline_think_text
325
+ reasoning_parts = [
326
+ s
327
+ for s in (
328
+ reasoning_content,
329
+ reasoning_alt,
330
+ thinking,
331
+ reasoning_details_text,
332
+ )
333
+ if s.strip()
334
+ ]
335
+ reasoning = "\n\n".join(reasoning_parts)
336
+ # IMPORTANT: do NOT fall back to copying `reasoning` into `content`.
337
+ # That fallback historically caused raw CoT to leak into visible
338
+ # chat output and pollute session history. If the server emits
339
+ # reasoning-only (empty content), that's a server/model config
340
+ # issue; we prefer an empty assistant turn + upstream rescue over
341
+ # silent CoT leakage.
342
+ reasoning_for_meta = reasoning
343
+ if not content.strip() and reasoning.strip():
344
+ # Keep content empty; surface the anomaly in logs so operators
345
+ # notice missing `enable_thinking` / parser config.
346
+ logger.warning(
347
+ "LLM returned reasoning (%d chars) but empty content; "
348
+ "check --reasoning-parser and chat_template enable_thinking.",
349
+ len(reasoning),
350
+ )
351
+
352
+ tool_calls = _extract_tool_calls(msg)
353
+ if tool_calls and not (content or "").strip():
354
+ ph = assistant_toolcall_content_placeholder()
355
+ if ph is not None:
356
+ content = ph
357
+
358
+ if temperature_reset:
359
+ self.temperature = self.temperature
360
+
361
+ # `reasoning_content` metadata: prefer API `reasoning_content`, else any
362
+ # CoT-bearing field so persist/echo never drops DeepSeek's chain.
363
+ reasoning_echo = (reasoning_content.strip() or reasoning.strip())
364
+ raw_usage = data.get("usage", {})
365
+ from seed.core.model_providers import normalize_chat_usage
366
+
367
+ raw_usage = normalize_chat_usage(
368
+ raw_usage if isinstance(raw_usage, dict) else {},
369
+ chat_protocol=self.chat_protocol,
370
+ provider=self.provider,
371
+ )
372
+ metadata = {
373
+ "model": self.model,
374
+ "usage": raw_usage,
375
+ "tool_calls": tool_calls,
376
+ "reasoning": reasoning_for_meta,
377
+ "reasoning_content": reasoning_echo,
378
+ }
379
+
380
+ return content, metadata
381
+
382
+ except LLMError:
383
+ raise
384
+ except requests.exceptions.RequestException as e:
385
+ raise LLMError(f"Failed to call LLM API: {e}", original_error=e)
386
+ except (KeyError, IndexError, TypeError) as e:
387
+ raise LLMError(f"Unexpected API response format: {e}", original_error=e)
388
+
389
+
390
+
391
+
392
+ import copy
393
+ import json
394
+ import logging
395
+ import os
396
+ from typing import Any, Dict, Generator, List, Optional
397
+
398
+ import requests
399
+
400
+
401
+ logger = logging.getLogger(__name__)
402
+
403
+
404
+ def generate_stream(
405
+ self,
406
+ messages: List[Dict[str, Any]],
407
+ tools: Optional[List[Dict[str, Any]]] = None,
408
+ temperature: Optional[float] = None,
409
+ max_tokens: Optional[int] = None,
410
+ enable_thinking: Optional[bool] = None,
411
+ reasoning_effort: Optional[str] = None,
412
+ ) -> Generator[Dict[str, Any], None, None]:
413
+ """Stream response from LLM, yielding SSE chunks as they arrive.
414
+
415
+ Each yielded dict has ``type``:
416
+ - ``"delta"``: ``{"type": "delta", "text": "..."}``
417
+ - ``"reasoning_delta"``: ``{"type": "reasoning_delta", "text": "..."}``
418
+ - ``"tool_calls"``: ``{"type": "tool_calls", "tool_calls": [...]}``
419
+ - ``"done"``: ``{"type": "done", "content": "...", "metadata": {...}}``
420
+ """
421
+ self._ensure_base_url()
422
+ eff_max = self.maxOutputTokens if max_tokens is None else int(max_tokens)
423
+ api_messages = _openai_chat_messages(
424
+ messages, base_url=self.baseURL, chat_protocol=self.chat_protocol
425
+ )
426
+ params: Dict[str, Any] = {
427
+ "model": self.model,
428
+ "messages": copy.deepcopy(api_messages),
429
+ "max_tokens": eff_max,
430
+ "temperature": self.temperature if temperature is None else temperature,
431
+ }
432
+ if not _ea.any_nonempty(*_ea.LLM_NO_TOP_P):
433
+ params["top_p"] = self.topP
434
+ if not _ea.any_nonempty(*_ea.LLM_NO_TOPK):
435
+ params["top_k"] = self.topK
436
+ params["stream"] = True
437
+
438
+ if tools:
439
+ params["tools"] = tools
440
+ params["tool_choice"] = "auto"
441
+
442
+ # Reasoning / thinking params (same logic as generate())
443
+ extra_body: Dict[str, Any] = {}
444
+ if enable_thinking is None:
445
+ env_val = _ea.pick_default("1", *_ea.LLM_ENABLE_THINKING)
446
+ resolved_thinking = env_val.lower() not in ("0", "false", "no", "")
447
+ else:
448
+ resolved_thinking = bool(enable_thinking)
449
+
450
+ from seed.core.model_providers import apply_chat_thinking_extra_body, apply_chat_stream_options
451
+
452
+ apply_chat_thinking_extra_body(
453
+ chat_protocol=self.chat_protocol,
454
+ base_url=self.baseURL,
455
+ params=params,
456
+ extra_body=extra_body,
457
+ resolved_thinking=resolved_thinking,
458
+ reasoning_effort=reasoning_effort,
459
+ model=self.model,
460
+ )
461
+ user_extra = _ea.pick_nonempty(*_ea.LLM_EXTRA_BODY)
462
+ if user_extra:
463
+ try:
464
+ parsed = json.loads(user_extra)
465
+ if isinstance(parsed, dict):
466
+ ctk = parsed.pop("chat_template_kwargs", None)
467
+ extra_body.update(parsed)
468
+ if isinstance(ctk, dict):
469
+ extra_body.setdefault("chat_template_kwargs", {}).update(ctk)
470
+ except (json.JSONDecodeError, TypeError):
471
+ pass
472
+ for k, v in extra_body.items():
473
+ params.setdefault(k, v)
474
+
475
+ apply_chat_stream_options(chat_protocol=self.chat_protocol, params=params)
476
+
477
+ max_body = max_llm_request_body_bytes(self.baseURL, chat_protocol=self.chat_protocol)
478
+ if max_body > 0:
479
+ maybe_shrink_llm_request_params(params, max_bytes=max_body, base_url=self.baseURL)
480
+
481
+ resp = None
482
+ try:
483
+ _url = self._get_completion_url()
484
+ resp = requests.post(
485
+ _url,
486
+ headers=self.headers,
487
+ json=params,
488
+ stream=True,
489
+ timeout=120,
490
+ proxies=_requests_proxies_for(_url),
491
+ )
492
+ if not resp.ok:
493
+ snippet = (resp.text or "")[:2000]
494
+ raise LLMError(
495
+ f"LLM HTTP {resp.status_code} for {self._get_completion_url()}: {snippet}"
496
+ )
497
+
498
+ content_parts: List[str] = []
499
+ reasoning_parts: List[str] = []
500
+ tool_calls_accum: List[Dict[str, Any]] = []
501
+ finish_reason: Optional[str] = None
502
+ usage: Dict[str, Any] = {}
503
+
504
+ # 强制 UTF-8 解码,兼容部分 SSE 服务端未返回 charset=utf-8 的情况
505
+ resp.encoding = "utf-8"
506
+
507
+ try:
508
+ from seed.core.chat_events import is_chat_cancelled
509
+ except Exception:
510
+ is_chat_cancelled = lambda: False # type: ignore[assignment, misc]
511
+
512
+ for line in resp.iter_lines(decode_unicode=True):
513
+ if is_chat_cancelled():
514
+ break
515
+ if not line or not line.startswith("data: "):
516
+ continue
517
+ payload = line[len("data: "):].strip()
518
+ if payload in ("[DONE]", ""):
519
+ break
520
+ try:
521
+ chunk = json.loads(payload)
522
+ except json.JSONDecodeError:
523
+ continue
524
+
525
+ # usage may appear in final chunk (sglang-style) or separate key —
526
+ # must extract BEFORE `if not choices: continue` so we don't lose it.
527
+ raw_usage = chunk.get("usage")
528
+ if raw_usage:
529
+ usage = raw_usage
530
+
531
+ choices = chunk.get("choices") or []
532
+ if not choices:
533
+ continue
534
+ delta = choices[0].get("delta") or {}
535
+ # finish_reason at the choice level
536
+ fr = choices[0].get("finish_reason")
537
+ if fr:
538
+ finish_reason = fr
539
+
540
+ # Content delta
541
+ text = _msg_text_to_str(delta.get("content"))
542
+ if text:
543
+ content_parts.append(text)
544
+ yield {"type": "delta", "text": text}
545
+
546
+ # Reasoning content (sglang separate_reasoning / DeepSeek)
547
+ rc = _msg_text_to_str(delta.get("reasoning_content"))
548
+ if rc:
549
+ reasoning_parts.append(rc)
550
+ yield {"type": "reasoning_delta", "text": rc}
551
+
552
+ # Tool calls (typically only in the final choice chunk)
553
+ tc_raw = delta.get("tool_calls")
554
+ if tc_raw:
555
+ for i, tc in enumerate(tc_raw):
556
+ idx = tc.get("index", i)
557
+ while len(tool_calls_accum) <= idx:
558
+ tool_calls_accum.append({"id": "", "type": "function", "function": {"name": "", "arguments": ""}})
559
+ slot = tool_calls_accum[idx]
560
+ if tc.get("id"):
561
+ slot["id"] = tc["id"]
562
+ if tc.get("type"):
563
+ slot["type"] = tc["type"]
564
+ fn = tc.get("function") or {}
565
+ if fn.get("name"):
566
+ slot["function"]["name"] = fn["name"]
567
+ if fn.get("arguments"):
568
+ slot["function"]["arguments"] += fn["arguments"]
569
+
570
+ full_content = "".join(content_parts)
571
+ reasoning = "".join(reasoning_parts)
572
+ built_tool_calls = _extract_tool_calls({"tool_calls": tool_calls_accum}) if tool_calls_accum else []
573
+
574
+ if built_tool_calls and not full_content.strip():
575
+ ph = assistant_toolcall_content_placeholder()
576
+ if ph is not None:
577
+ full_content = ph
578
+
579
+ reasoning_echo = reasoning.strip()
580
+ stream_usage = usage
581
+ from seed.core.model_providers import normalize_chat_usage
582
+
583
+ stream_usage = normalize_chat_usage(
584
+ stream_usage if isinstance(stream_usage, dict) else {},
585
+ chat_protocol=self.chat_protocol,
586
+ provider=self.provider,
587
+ )
588
+ metadata = {
589
+ "model": self.model,
590
+ "usage": stream_usage,
591
+ "tool_calls": built_tool_calls,
592
+ "reasoning": reasoning,
593
+ "reasoning_content": reasoning_echo,
594
+ }
595
+
596
+ yield {
597
+ "type": "done",
598
+ "content": full_content,
599
+ "reasoning": reasoning,
600
+ "tool_calls": built_tool_calls,
601
+ "metadata": metadata,
602
+ }
603
+
604
+ except LLMError:
605
+ raise
606
+ except requests.exceptions.RequestException as e:
607
+ raise LLMError(f"Failed to call LLM API (stream): {e}", original_error=e)
608
+ except (KeyError, IndexError, TypeError) as e:
609
+ raise LLMError(f"Unexpected API stream response: {e}", original_error=e)
610
+ finally:
611
+ if resp is not None:
612
+ try:
613
+ resp.close()
614
+ except Exception:
615
+ pass
616
+
617
+ def count_tokens(self, text: str) -> int:
618
+ """
619
+ Estimate token count (simple approximation).
620
+
621
+ Args:
622
+ text: Text to estimate tokens for
623
+
624
+ Returns:
625
+ Approximate token count
626
+ """
627
+ return len(text.encode('utf-8')) // 4
628
+
629
+
630
+ # Implemented as module-level functions (``self`` first arg) for historical file layout;
631
+ # expose them on the class so instances match ``llm.generate(...)`` / ``llm.generate_stream(...)``.
632
+ def ensure_llm_executor_methods() -> None:
633
+ """Attach module-level implementations to :class:`LLMAPIExecutor` if missing."""
634
+ if callable(getattr(LLMAPIExecutor, "generate_stream", None)):
635
+ return
636
+ LLMAPIExecutor.generate = generate # type: ignore[assignment]
637
+ LLMAPIExecutor.generate_stream = generate_stream # type: ignore[assignment]
638
+ LLMAPIExecutor.count_tokens = count_tokens # type: ignore[assignment]
639
+
640
+
641
+ ensure_llm_executor_methods()
642
+
643
+
644
+ """LLM API executor for CodeAgent - Connect to external LLM API"""
645
+ import json
646
+ import logging
647
+ import os
648
+ from typing import Any, Dict, List, Optional
649
+
650
+ from seed.core import env_access as _ea
651
+
652
+ logger = logging.getLogger(__name__)
653
+
654
+
655
+ def _is_deepseek_url(base_url: Optional[str] = None) -> bool:
656
+ """
657
+ Legacy URL heuristic; prefer explicit ``provider`` / ``chat_protocol`` on executor.
658
+ """
659
+ from seed.core.model_providers import uses_deepseek_chat_protocol
660
+
661
+ return uses_deepseek_chat_protocol(provider="", base_url=base_url or "")
662
+
663
+
664
+ def _openai_chat_messages(
665
+ messages: List[Dict[str, Any]],
666
+ *,
667
+ base_url: Optional[str] = None,
668
+ chat_protocol: Optional[str] = None,
669
+ ) -> List[Dict[str, Any]]:
670
+ """
671
+ Strip non-API keys (e.g. ``ts``) before POSTing to OpenAI-compatible endpoints.
672
+ """
673
+ def _should_send_reasoning_content() -> bool:
674
+ """
675
+ DeepSeek thinking-mode contract: assistant `reasoning_content` must be
676
+ echoed on every subsequent request (often including non-tool replies),
677
+ otherwise the API returns HTTP 400. Tool-call chains remain the strictest
678
+ case; plain multi-turn chat in thinking mode also requires the field.
679
+
680
+ Some strict OpenAI-compatible gateways reject unknown keys, so this is
681
+ gated behind an env flag, with a safe auto-enable for DeepSeek's
682
+ official endpoint.
683
+ """
684
+ from seed.core.model_providers import resolve_chat_protocol, should_send_reasoning_content
685
+
686
+ proto = chat_protocol or resolve_chat_protocol(provider="", base_url=base_url or "")
687
+ return should_send_reasoning_content(chat_protocol=proto, base_url=base_url or "")
688
+
689
+ def _normalize_minimax_multimodal(content: Any) -> Any:
690
+ """Normalize MiniMax Responses-style multimodal blocks → OpenAI style.
691
+
692
+ MiniMax-M3 has two API surfaces:
693
+ - ``/v1/responses`` uses ``input_text`` / ``input_image`` / ``input_video``
694
+ - ``/v1/chat/completions`` uses ``text`` / ``image_url`` / ``video_url``
695
+
696
+ When a caller mixes schemas (e.g. agent code wrote Responses-style blocks
697
+ but the preset routes through chat/completions), we rewrite the
698
+ ``type`` so the OpenAI-compatible endpoint accepts the payload.
699
+ """
700
+ if not isinstance(content, list):
701
+ return content
702
+ out_parts: List[Dict[str, Any]] = []
703
+ changed = False
704
+ for p in content:
705
+ if not isinstance(p, dict):
706
+ out_parts.append(p)
707
+ continue
708
+ ptype = p.get("type")
709
+ if ptype == "input_text" and isinstance(p.get("text"), str):
710
+ out_parts.append({"type": "text", "text": p["text"]})
711
+ changed = True
712
+ elif ptype == "output_text" and isinstance(p.get("text"), str):
713
+ out_parts.append({"type": "text", "text": p["text"]})
714
+ changed = True
715
+ elif ptype == "input_image":
716
+ src = p.get("image_url") or p.get("image")
717
+ url = src.get("url") if isinstance(src, dict) else (src if isinstance(src, str) else None)
718
+ detail = src.get("detail") if isinstance(src, dict) else None
719
+ block: Dict[str, Any] = {"type": "image_url", "image_url": {"url": url or ""}}
720
+ if detail:
721
+ block["image_url"]["detail"] = detail
722
+ out_parts.append(block)
723
+ changed = True
724
+ elif ptype == "input_video":
725
+ src = p.get("video_url") or p.get("video")
726
+ url = src.get("url") if isinstance(src, dict) else (src if isinstance(src, str) else None)
727
+ fps = src.get("fps") if isinstance(src, dict) else None
728
+ vblock: Dict[str, Any] = {"type": "video_url", "video_url": {"url": url or ""}}
729
+ if fps is not None:
730
+ vblock["video_url"]["fps"] = fps
731
+ out_parts.append(vblock)
732
+ changed = True
733
+ else:
734
+ out_parts.append(p)
735
+ return out_parts if changed else content
736
+
737
+ include_rc = _should_send_reasoning_content()
738
+ from seed.core.model_providers import resolve_chat_protocol, uses_full_reasoning_content_echo
739
+
740
+ _full_rc_echo = uses_full_reasoning_content_echo(
741
+ chat_protocol=chat_protocol
742
+ or resolve_chat_protocol(provider="", base_url=base_url or ""),
743
+ base_url=base_url or "",
744
+ )
745
+ out: List[Dict[str, Any]] = []
746
+ for m in messages:
747
+ if not isinstance(m, dict):
748
+ continue
749
+ role = m.get("role")
750
+ if role == "tool":
751
+ row: Dict[str, Any] = {"role": "tool"}
752
+ if "content" in m:
753
+ row["content"] = m["content"]
754
+ if m.get("tool_call_id") is not None:
755
+ row["tool_call_id"] = m["tool_call_id"]
756
+ if m.get("name"):
757
+ row["name"] = m["name"]
758
+ out.append(row)
759
+ continue
760
+ if role not in ("system", "user", "assistant"):
761
+ continue
762
+ row = {"role": role}
763
+ if "content" in m:
764
+ content = m["content"]
765
+ if chat_protocol in ("minimax", "minimax_anthropic") or (
766
+ not chat_protocol and base_url and "minimaxi.com" in base_url.lower()
767
+ ):
768
+ content = _normalize_minimax_multimodal(content)
769
+ row["content"] = content
770
+ if m.get("name"):
771
+ row["name"] = m["name"]
772
+ if m.get("tool_calls"):
773
+ row["tool_calls"] = m["tool_calls"]
774
+ if "content" not in row:
775
+ row["content"] = None
776
+ # DeepSeek: echo reasoning_content for every assistant turn when enabled
777
+ # (not only tool chains); missing key → invalid_request_error.
778
+ # Other backends: only send when we have tool_calls or a stored key, so
779
+ # strict OpenAI-compatible proxies are not spammed with unknown fields.
780
+ if include_rc and role == "assistant":
781
+ if _full_rc_echo:
782
+ rc = m.get("reasoning_content")
783
+ row["reasoning_content"] = "" if rc is None else _msg_text_to_str(rc)
784
+ elif m.get("tool_calls") or ("reasoning_content" in m):
785
+ row["reasoning_content"] = (
786
+ m["reasoning_content"] if m.get("reasoning_content") is not None else ""
787
+ )
788
+ out.append(row)
789
+
790
+ # After the last `user` in this request, if the tail contains any `tool`
791
+ # message, DeepSeek requires every `assistant` in that tail to carry
792
+ # `reasoning_content` (possibly ""). Fill missing keys so the request validates.
793
+ if include_rc and out:
794
+ last_user_i = -1
795
+ for i, x in enumerate(out):
796
+ if isinstance(x, dict) and x.get("role") == "user":
797
+ last_user_i = i
798
+ if last_user_i >= 0:
799
+ tail = out[last_user_i + 1 :]
800
+ if any(isinstance(x, dict) and x.get("role") == "tool" for x in tail):
801
+ for row in tail:
802
+ if not isinstance(row, dict) or row.get("role") != "assistant":
803
+ continue
804
+ val = row.get("reasoning_content")
805
+ if val is None:
806
+ row["reasoning_content"] = ""
807
+ elif not isinstance(val, str):
808
+ row["reasoning_content"] = _msg_text_to_str(val)
809
+ return out
810
+
811
+
812
+ def assistant_toolcall_content_placeholder() -> Optional[str]:
813
+ """
814
+ 当模型在返回 ``tool_calls`` 时把 ``content`` 置空,部分 OpenAI 兼容栈或下游
815
+ 会把「空正文 + 工具」误判为异常并中断工具链。用非空占位符可稳定多轮。
816
+
817
+ 环境变量:
818
+ - ``SEED_ASSISTANT_TOOLCALL_PLACEHOLDER_DISABLE=1``(或 ``CODEAGENT_*`` 别名):不替换
819
+ - ``SEED_ASSISTANT_TOOLCALL_PLACEHOLDER=...``:显式指定占位正文(可为空字符串)
820
+ - 未设置 PLACEHOLDER 时:默认一个 ASCII 空格(对模型干扰最小)
821
+ """
822
+ dis = _ea.pick_default("", *_ea.ASSISTANT_TOOLCALL_PLACEHOLDER_DISABLE).lower()
823
+ if dis in ("1", "true", "yes", "on"):
824
+ return None
825
+ for k in _ea.ASSISTANT_TOOLCALL_PLACEHOLDER:
826
+ if k in os.environ:
827
+ return os.environ[k]
828
+ return " "
829
+
830
+
831
+ def _msg_text_to_str(raw: Any) -> str:
832
+ """Normalize `message.content` (string, null, or multimodal list) to str."""
833
+ if raw is None:
834
+ return ""
835
+ if isinstance(raw, str):
836
+ return raw
837
+ if isinstance(raw, list):
838
+ parts: List[str] = []
839
+ for item in raw:
840
+ if isinstance(item, dict):
841
+ if item.get("type") == "text":
842
+ parts.append(str(item.get("text") or ""))
843
+ elif "text" in item:
844
+ parts.append(str(item.get("text") or ""))
845
+ elif isinstance(item, str):
846
+ parts.append(item)
847
+ return "".join(parts)
848
+ return str(raw)
849
+
850
+
851
+ msg_text_to_str = _msg_text_to_str
852
+
853
+
854
+ # ---------------------------------------------------------------------------
855
+ # MiniMax-specific helpers: ``<think>`` tag stripping + reasoning_details
856
+ # ---------------------------------------------------------------------------
857
+
858
+ _THINK_TAG_RE = re.compile(r"<think>\s*(.*?)\s*</think>", re.IGNORECASE | re.DOTALL)
859
+
860
+
861
+ def _strip_think_tags(content: str) -> tuple[str, str]:
862
+ """Strip ``<think>...</think>`` blocks from MiniMax-M2.x responses.
863
+
864
+ Returns ``(cleaned_content, extracted_thinking)``. The thinking text is
865
+ concatenated from every ``<think>`` block (in order) so we can surface it
866
+ alongside the visible reply instead of leaking raw CoT into chat history.
867
+ Empty tuples are returned when the content has no think tag.
868
+ """
869
+ if not content or "<think>" not in content.lower():
870
+ return content, ""
871
+ parts: List[str] = []
872
+ last_end = 0
873
+ for m in _THINK_TAG_RE.finditer(content):
874
+ parts.append(m.group(1))
875
+ last_end = m.end()
876
+ cleaned = _THINK_TAG_RE.sub("", content).strip()
877
+ thinking = "\n\n".join(p.strip() for p in parts if p and p.strip())
878
+ return cleaned, thinking
879
+
880
+
881
+ def _extract_reasoning_details_text(raw: Any) -> str:
882
+ """Flatten MiniMax-M3 ``reasoning_details`` list to a single text.
883
+
884
+ Schema (when ``reasoning_split=True``):
885
+ ``{"summary": [{"type": "summary_text", "text": "..."}]}``
886
+ Older variants use ``{"reasoning_text": "..."}``. Empty string on miss.
887
+ """
888
+ if raw is None:
889
+ return ""
890
+ pieces: List[str] = []
891
+ if isinstance(raw, str):
892
+ return raw
893
+ if isinstance(raw, dict):
894
+ summary = raw.get("summary")
895
+ if isinstance(summary, list):
896
+ for s in summary:
897
+ if isinstance(s, dict) and s.get("type") in ("summary_text", None):
898
+ t = s.get("text")
899
+ if isinstance(t, str) and t.strip():
900
+ pieces.append(t)
901
+ rt = raw.get("reasoning_text")
902
+ if isinstance(rt, str) and rt.strip():
903
+ pieces.append(rt)
904
+ # 兼容 list 元素直接传 dict 的形态:{"type": "summary_text", "text": "..."}
905
+ if not pieces and raw.get("type") in ("summary_text", "reasoning_text", None) and isinstance(raw.get("text"), str):
906
+ pieces.append(raw["text"])
907
+ return "\n\n".join(pieces)
908
+ if isinstance(raw, list):
909
+ for item in raw:
910
+ t = _extract_reasoning_details_text(item)
911
+ if t:
912
+ pieces.append(t)
913
+ return "\n\n".join(pieces)
914
+ return ""
915
+
916
+
917
+ def _to_minimax_anthropic_request(
918
+ messages: List[Dict[str, Any]],
919
+ *,
920
+ model: str,
921
+ max_tokens: int,
922
+ tools: Optional[List[Dict[str, Any]]] = None,
923
+ enable_caching: bool = True,
924
+ extra_body: Optional[Dict[str, Any]] = None,
925
+ ) -> Dict[str, Any]:
926
+ """Convert OpenAI-style chat messages → Anthropic Messages API payload.
927
+
928
+ Implements MiniMax Anthropic 主动缓存 by tagging the last block of
929
+ ``system`` / ``tools`` / and the last historical message with
930
+ ``cache_control: ephemeral`` (per Anthropic spec). 5 min TTL, auto-renewed
931
+ on subsequent calls.
932
+ """
933
+ sys_blocks: List[Dict[str, Any]] = []
934
+ api_messages: List[Dict[str, Any]] = []
935
+ for m in messages or []:
936
+ if not isinstance(m, dict):
937
+ continue
938
+ role = str(m.get("role") or "")
939
+ content = m.get("content")
940
+ if role == "system":
941
+ text = content if isinstance(content, str) else _msg_text_to_str(content)
942
+ sys_blocks.append({"type": "text", "text": str(text or "")})
943
+ continue
944
+ if role == "tool":
945
+ api_messages.append(
946
+ {
947
+ "role": "user",
948
+ "content": [
949
+ {
950
+ "type": "tool_result",
951
+ "tool_use_id": m.get("tool_call_id") or "",
952
+ "content": content if isinstance(content, str) else _msg_text_to_str(content),
953
+ }
954
+ ],
955
+ }
956
+ )
957
+ continue
958
+ # user / assistant
959
+ anth_role = "assistant" if role == "assistant" else "user"
960
+ if isinstance(content, list):
961
+ blocks: List[Dict[str, Any]] = []
962
+ for p in content:
963
+ if not isinstance(p, dict):
964
+ continue
965
+ ptype = p.get("type")
966
+ if ptype == "text" or isinstance(p.get("text"), str):
967
+ blocks.append({"type": "text", "text": str(p.get("text") or "")})
968
+ elif ptype == "image_url":
969
+ blocks.append(_anthropic_image_block(p.get("image_url")))
970
+ elif ptype == "video_url":
971
+ blocks.append(_anthropic_video_block(p.get("video_url")))
972
+ api_messages.append({"role": anth_role, "content": blocks or [{"type": "text", "text": ""}]})
973
+ else:
974
+ text = content if isinstance(content, str) else _msg_text_to_str(content)
975
+ api_messages.append({"role": anth_role, "content": str(text or "")})
976
+ # Assistant tool_calls → tool_use blocks (extend the just-appended
977
+ # assistant message; do NOT pop the previous one).
978
+ if role == "assistant" and m.get("tool_calls") and api_messages:
979
+ last = api_messages[-1]
980
+ if last.get("role") == "assistant":
981
+ if isinstance(last.get("content"), list):
982
+ content_blocks = list(last["content"])
983
+ elif isinstance(last.get("content"), str) and last["content"]:
984
+ content_blocks = [{"type": "text", "text": last["content"]}]
985
+ else:
986
+ content_blocks = []
987
+ for tc in m.get("tool_calls") or []:
988
+ fn = (tc.get("function") or {}) if isinstance(tc, dict) else {}
989
+ args = fn.get("arguments") or "{}"
990
+ if not isinstance(args, str):
991
+ try:
992
+ args = json.dumps(args)
993
+ except TypeError:
994
+ args = "{}"
995
+ content_blocks.append(
996
+ {
997
+ "type": "tool_use",
998
+ "id": tc.get("id") or f"toolu_{len(content_blocks)}",
999
+ "name": fn.get("name") or "",
1000
+ "input": _safe_json_loads(args),
1001
+ }
1002
+ )
1003
+ last["content"] = content_blocks or [{"type": "text", "text": ""}]
1004
+
1005
+ # Apply cache_control to the last blocks of system / tools / last message.
1006
+ if enable_caching and api_messages:
1007
+ # 1) system
1008
+ if sys_blocks:
1009
+ sys_blocks[-1]["cache_control"] = {"type": "ephemeral"}
1010
+ payload: Dict[str, Any] = {
1011
+ "model": model,
1012
+ "max_tokens": int(max_tokens),
1013
+ "messages": api_messages,
1014
+ }
1015
+ if sys_blocks:
1016
+ payload["system"] = sys_blocks
1017
+ elif enable_caching:
1018
+ # Even with no system prompt, send an empty one to anchor the cache.
1019
+ payload["system"] = [{"type": "text", "text": "", "cache_control": {"type": "ephemeral"}}]
1020
+
1021
+ if tools:
1022
+ anth_tools: List[Dict[str, Any]] = []
1023
+ for t in tools:
1024
+ if not isinstance(t, dict):
1025
+ continue
1026
+ fn = t.get("function") if isinstance(t.get("function"), dict) else t
1027
+ if not isinstance(fn, dict) or not fn.get("name"):
1028
+ continue
1029
+ anth_tools.append(
1030
+ {
1031
+ "name": str(fn.get("name") or ""),
1032
+ "description": str(fn.get("description") or ""),
1033
+ "input_schema": fn.get("parameters") or {"type": "object", "properties": {}},
1034
+ }
1035
+ )
1036
+ if anth_tools:
1037
+ if enable_caching:
1038
+ anth_tools[-1]["cache_control"] = {"type": "ephemeral"}
1039
+ payload["tools"] = anth_tools
1040
+ if enable_caching and api_messages:
1041
+ tail = api_messages[-1]
1042
+ if isinstance(tail.get("content"), list) and tail["content"]:
1043
+ tail["content"][-1].setdefault("cache_control", {"type": "ephemeral"})
1044
+ elif isinstance(tail.get("content"), str) and tail["content"]:
1045
+ # Anthropic requires a list of blocks; wrap the trailing string
1046
+ # and tag the new block for cache_control.
1047
+ tail["content"] = [
1048
+ {
1049
+ "type": "text",
1050
+ "text": tail["content"],
1051
+ "cache_control": {"type": "ephemeral"},
1052
+ }
1053
+ ]
1054
+
1055
+ if extra_body:
1056
+ # Carry through thinking / reasoning_split etc.
1057
+ for k, v in extra_body.items():
1058
+ if k in ("reasoning_split",):
1059
+ continue
1060
+ payload.setdefault(k, v)
1061
+ return payload
1062
+
1063
+
1064
+ def _safe_json_loads(s: str) -> Dict[str, Any]:
1065
+ try:
1066
+ loaded = json.loads(s)
1067
+ except (ValueError, TypeError):
1068
+ return {"_raw": s}
1069
+ return loaded if isinstance(loaded, dict) else {"_raw": loaded}
1070
+
1071
+
1072
+ def _anthropic_image_block(image_url: Any) -> Dict[str, Any]:
1073
+ """Best-effort conversion: pass through URL or data URL."""
1074
+ if isinstance(image_url, str):
1075
+ return {"type": "image", "source": {"type": "url", "url": image_url}}
1076
+ if isinstance(image_url, dict):
1077
+ url = image_url.get("url") or ""
1078
+ if url.startswith("data:"):
1079
+ media_type, _, b64 = url.partition(";base64,")
1080
+ media_type = media_type[len("data:"):] if media_type.startswith("data:") else "image/jpeg"
1081
+ return {
1082
+ "type": "image",
1083
+ "source": {"type": "base64", "media_type": media_type, "data": b64},
1084
+ }
1085
+ return {"type": "image", "source": {"type": "url", "url": url}}
1086
+ return {"type": "text", "text": "[unsupported image input]"}
1087
+
1088
+
1089
+ def _anthropic_video_block(video_url: Any) -> Dict[str, Any]:
1090
+ """MiniMax accepts video_url on /anthropic/v1/messages (MP4/AVI/MOV/MKV)."""
1091
+ if isinstance(video_url, str):
1092
+ return {"type": "video", "source": {"type": "url", "url": video_url}}
1093
+ if isinstance(video_url, dict):
1094
+ return {"type": "video", "source": {"type": "url", "url": video_url.get("url") or ""}}
1095
+ return {"type": "text", "text": "[unsupported video input]"}
1096
+
1097
+
1098
+ def _parse_minimax_anthropic_response(data: Dict[str, Any]) -> Dict[str, Any]:
1099
+ """Convert Anthropic Messages response → OpenAI-style chat completion shape
1100
+ so the rest of the LLM stack (tool_calls / reasoning extraction) keeps working.
1101
+ """
1102
+ if not isinstance(data, dict):
1103
+ raise LLMError("MiniMax Anthropic response invalid: not a dict")
1104
+ content = data.get("content") or []
1105
+ text_parts: List[str] = []
1106
+ thinking_parts: List[str] = []
1107
+ tool_calls: List[Dict[str, Any]] = []
1108
+ for block in content if isinstance(content, list) else []:
1109
+ if not isinstance(block, dict):
1110
+ continue
1111
+ btype = block.get("type")
1112
+ if btype == "text":
1113
+ text_parts.append(str(block.get("text") or ""))
1114
+ elif btype == "thinking":
1115
+ thinking_parts.append(str(block.get("thinking") or ""))
1116
+ elif btype == "tool_use":
1117
+ tool_calls.append(
1118
+ {
1119
+ "id": block.get("id") or f"toolu_{len(tool_calls)}",
1120
+ "type": "function",
1121
+ "function": {
1122
+ "name": block.get("name") or "",
1123
+ "arguments": json.dumps(block.get("input") or {}, ensure_ascii=False),
1124
+ },
1125
+ }
1126
+ )
1127
+ stop_reason = data.get("stop_reason") or "end_turn"
1128
+ return {
1129
+ "choices": [
1130
+ {
1131
+ "index": 0,
1132
+ "finish_reason": stop_reason,
1133
+ "message": {
1134
+ "role": "assistant",
1135
+ "content": "".join(text_parts),
1136
+ "tool_calls": tool_calls or None,
1137
+ "reasoning_content": "\n\n".join(thinking_parts) if thinking_parts else "",
1138
+ },
1139
+ }
1140
+ ],
1141
+ "usage": data.get("usage") or {},
1142
+ "model": data.get("model") or "",
1143
+ }
1144
+
1145
+
1146
+ def normalize_minimax_usage(usage: Dict[str, Any]) -> Dict[str, Any]:
1147
+ """Backward-compatible alias — prefer ``normalize_chat_usage``."""
1148
+ from seed.core.model_providers import normalize_chat_usage
1149
+
1150
+ return normalize_chat_usage(usage, chat_protocol="minimax", provider="minimax")
1151
+
1152
+
1153
+ MINIMAX_CONTEXT_WINDOWS: Dict[str, int] = {
1154
+ "MiniMax-M3": 1_000_000,
1155
+ "MiniMax-M2.7": 204_800,
1156
+ "MiniMax-M2.7-highspeed": 204_800,
1157
+ "MiniMax-M2.5": 204_800,
1158
+ "MiniMax-M2.5-highspeed": 204_800,
1159
+ "MiniMax-M2.1": 204_800,
1160
+ "MiniMax-M2.1-highspeed": 204_800,
1161
+ "MiniMax-M2": 204_800,
1162
+ "MiniMax-M2-Her": 64_000,
1163
+ "MiniMax-Text-01": 4_000_000,
1164
+ "MiniMax-VL-01": 4_000_000,
1165
+ }
1166
+ # 512K is the threshold where MiniMax-M3 starts charging the long-context
1167
+ # price. See https://platform.minimaxi.com/docs/api-reference/text-prompt-caching
1168
+ MINIMAX_LONG_CONTEXT_THRESHOLD = 512_000
1169
+
1170
+
1171
+ def _minimax_input_tokens_url(base_url: str) -> str:
1172
+ """Resolve MiniMax token-estimation endpoint from preset base_url."""
1173
+ base = (base_url or "").strip().rstrip("/")
1174
+ if base.endswith("/v1/responses/input_tokens"):
1175
+ return base
1176
+ if base.endswith("/v1/responses"):
1177
+ return f"{base}/input_tokens"
1178
+ if base.endswith("/v1"):
1179
+ return f"{base}/responses/input_tokens"
1180
+ return f"{base}/v1/responses/input_tokens"
1181
+
1182
+
1183
+ def _to_minimax_responses_input(
1184
+ messages: List[Dict[str, Any]],
1185
+ tools: Optional[List[Dict[str, Any]]] = None,
1186
+ ) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
1187
+ """Convert OpenAI-style chat messages to MiniMax Responses API ``input`` items.
1188
+
1189
+ Only the fields the input-tokens endpoint needs are populated; the endpoint
1190
+ does not actually invoke the model, so we keep the payload small.
1191
+ """
1192
+ out: List[Dict[str, Any]] = []
1193
+ for m in messages or []:
1194
+ if not isinstance(m, dict):
1195
+ continue
1196
+ role = str(m.get("role") or "user")
1197
+ content = m.get("content")
1198
+ if isinstance(content, list):
1199
+ parts: List[Dict[str, Any]] = []
1200
+ for p in content:
1201
+ if isinstance(p, dict):
1202
+ if p.get("type") == "text":
1203
+ parts.append({"type": "input_text", "text": str(p.get("text") or "")})
1204
+ elif p.get("type") == "image_url":
1205
+ parts.append({"type": "input_image", "image_url": p.get("image_url") or ""})
1206
+ elif p.get("type") == "video_url":
1207
+ parts.append({"type": "input_video", "video_url": p.get("video_url") or ""})
1208
+ elif isinstance(p.get("text"), str):
1209
+ parts.append({"type": "input_text", "text": str(p.get("text") or "")})
1210
+ elif isinstance(p, str):
1211
+ parts.append({"type": "input_text", "text": p})
1212
+ out.append({"type": "message", "role": role, "content": parts})
1213
+ else:
1214
+ out.append({"type": "message", "role": role, "content": str(content or "")})
1215
+ out_tools: List[Dict[str, Any]] = []
1216
+ if tools:
1217
+ for t in tools:
1218
+ if not isinstance(t, dict):
1219
+ continue
1220
+ fn = t.get("function") if isinstance(t.get("function"), dict) else t
1221
+ if not isinstance(fn, dict) or not fn.get("name"):
1222
+ continue
1223
+ out_tools.append(
1224
+ {
1225
+ "type": "function",
1226
+ "name": str(fn.get("name") or ""),
1227
+ "description": str(fn.get("description") or ""),
1228
+ "parameters": fn.get("parameters") or {"type": "object", "properties": {}},
1229
+ }
1230
+ )
1231
+ return out, out_tools
1232
+
1233
+
1234
+ def estimate_minimax_tokens(
1235
+ *,
1236
+ base_url: str,
1237
+ api_key: str,
1238
+ auth_scheme: str = "Bearer",
1239
+ model: str,
1240
+ messages: List[Dict[str, Any]],
1241
+ tools: Optional[List[Dict[str, Any]]] = None,
1242
+ reasoning_effort: Optional[str] = None,
1243
+ timeout: float = 30.0,
1244
+ ) -> Dict[str, Any]:
1245
+ """Call ``POST /v1/responses/input_tokens`` to estimate prompt size.
1246
+
1247
+ Returns ``{"input_tokens": int, "raw": dict}``. Raises ``LLMError`` on
1248
+ transport failure or invalid response.
1249
+ """
1250
+ if not api_key:
1251
+ raise LLMError("MiniMax input_tokens estimate requires an API key")
1252
+ input_items, out_tools = _to_minimax_responses_input(messages, tools)
1253
+ payload: Dict[str, Any] = {"model": model, "input": input_items}
1254
+ if out_tools:
1255
+ payload["tools"] = out_tools
1256
+ if reasoning_effort:
1257
+ payload["reasoning"] = {"effort": reasoning_effort}
1258
+ url = _minimax_input_tokens_url(base_url)
1259
+ headers = {
1260
+ "Content-Type": "application/json",
1261
+ "Authorization": f"{auth_scheme} {api_key}",
1262
+ }
1263
+ try:
1264
+ resp = requests.post(url, json=payload, headers=headers, timeout=timeout)
1265
+ except requests.exceptions.RequestException as e:
1266
+ raise LLMError(f"MiniMax input_tokens request failed: {e}", original_error=e)
1267
+ if resp.status_code >= 400:
1268
+ try:
1269
+ body = resp.json()
1270
+ detail = body.get("base_resp", {}).get("status_msg") if isinstance(body, dict) else None
1271
+ except Exception:
1272
+ detail = None
1273
+ raise LLMError(
1274
+ f"MiniMax input_tokens failed ({resp.status_code}): {detail or resp.text[:500]}"
1275
+ )
1276
+ try:
1277
+ body = resp.json()
1278
+ except ValueError as e:
1279
+ raise LLMError(f"MiniMax input_tokens returned invalid JSON: {e}", original_error=e)
1280
+ if not isinstance(body, dict):
1281
+ raise LLMError("MiniMax input_tokens returned unexpected body")
1282
+ n = body.get("input_tokens")
1283
+ if not isinstance(n, (int, float)):
1284
+ raise LLMError(f"MiniMax input_tokens missing input_tokens: {body!r}")
1285
+ return {"input_tokens": int(n), "raw": body}
1286
+
1287
+
1288
+ def precheck_minimax_context(
1289
+ *,
1290
+ model: str,
1291
+ estimated_input_tokens: int,
1292
+ context_override: Optional[int] = None,
1293
+ ) -> Optional[str]:
1294
+ """Return an error message if ``estimated_input_tokens`` exceeds the
1295
+ model's context window; ``None`` when within budget.
1296
+
1297
+ ``context_override`` lets callers inject a custom budget (e.g. via
1298
+ ``SEED_LLM_CONTEXT_SIZE``); otherwise the catalog mapping is used.
1299
+ """
1300
+ if context_override is not None and context_override > 0:
1301
+ window = int(context_override)
1302
+ else:
1303
+ window = MINIMAX_CONTEXT_WINDOWS.get(str(model) or "", 0)
1304
+ if window <= 0:
1305
+ return None
1306
+ if estimated_input_tokens > window:
1307
+ return (
1308
+ f"Estimated input tokens ({estimated_input_tokens}) exceed model "
1309
+ f"'{model}' context window ({window}). Shorten the conversation "
1310
+ "or switch to a larger-context model."
1311
+ )
1312
+ return None
1313
+
1314
+
1315
+ def _extract_tool_calls(msg: Dict[str, Any]) -> List[Dict[str, Any]]:
1316
+ """Parse tool_calls; tolerate missing ids or oddly-shaped function payloads.
1317
+
1318
+ **Argument validation**: ``function.arguments`` must be a non-empty string of
1319
+ valid JSON. This is the exact contract the LLM API (OpenAI / DeepSeek /
1320
+ MiniMax / Minimax / SGLang ...) validates on the *next* turn when it sees the
1321
+ historical ``tool_calls`` echoed back. If a streaming response was truncated
1322
+ (network blip, token limit, mid-arg server drop) the accumulated
1323
+ ``function.arguments`` can be ``""`` or partial JSON. Persisting that into
1324
+ message history poisons the conversation: the next LLM call returns HTTP 400
1325
+ ``invalid function arguments json string`` and the chat dies.
1326
+
1327
+ We drop such malformed tool_calls here so the loop can keep going (e.g. the
1328
+ model just emits plain text on the next turn) instead of carrying a time bomb
1329
+ forward.
1330
+ """
1331
+ raw = msg.get("tool_calls")
1332
+ if not raw:
1333
+ return []
1334
+ out: List[Dict[str, Any]] = []
1335
+ for i, tc in enumerate(raw):
1336
+ if not isinstance(tc, dict):
1337
+ continue
1338
+ tid = tc.get("id") or f"call_{i}"
1339
+ fn = tc.get("function")
1340
+ if isinstance(fn, str):
1341
+ try:
1342
+ fn = json.loads(fn)
1343
+ except (json.JSONDecodeError, TypeError):
1344
+ fn = {"name": "", "arguments": "{}"}
1345
+ if not isinstance(fn, dict):
1346
+ fn = {"name": "", "arguments": "{}"}
1347
+ # --- Validate arguments is non-empty valid JSON ---
1348
+ raw_args = fn.get("arguments")
1349
+ if isinstance(raw_args, str):
1350
+ if not raw_args.strip():
1351
+ logger.warning(
1352
+ "Dropping tool_call id=%r name=%r: arguments is empty "
1353
+ "(likely streaming truncation).",
1354
+ tid, fn.get("name") or "",
1355
+ )
1356
+ continue
1357
+ try:
1358
+ json.loads(raw_args)
1359
+ except (json.JSONDecodeError, TypeError, ValueError) as e:
1360
+ logger.warning(
1361
+ "Dropping tool_call id=%r name=%r: arguments is not valid JSON (%s). "
1362
+ "Preview: %s",
1363
+ tid, fn.get("name") or "", e, raw_args[:200],
1364
+ )
1365
+ continue
1366
+ else:
1367
+ # Provider gave us a dict / other non-string; normalize to a
1368
+ # canonical JSON string. json.dumps("{}") is still valid.
1369
+ try:
1370
+ raw_args = json.dumps(raw_args if raw_args is not None else {}, ensure_ascii=False)
1371
+ except (TypeError, ValueError) as e:
1372
+ logger.warning(
1373
+ "Dropping tool_call id=%r name=%r: arguments is not JSON-serializable (%s).",
1374
+ tid, fn.get("name") or "", e,
1375
+ )
1376
+ continue
1377
+ out.append(
1378
+ {
1379
+ "id": tid,
1380
+ "type": tc.get("type") or "function",
1381
+ "function": {
1382
+ "name": fn.get("name") or "",
1383
+ "arguments": raw_args,
1384
+ },
1385
+ }
1386
+ )
1387
+ return out
1388
+
1389
+
1390
+ class LLMError(Exception):
1391
+ """Exception raised for LLM API errors"""
1392
+
1393
+ def __init__(self, message: str, original_error: Optional[Exception] = None):
1394
+ self.message = message
1395
+ self.original_error = original_error
1396
+ super().__init__(message)
1397
+
1398
+
1399
+
1400
+
1401
+
1402
+ import os
1403
+ from typing import Optional, Tuple
1404
+
1405
+
1406
+ _default_executor: Optional[LLMAPIExecutor] = None
1407
+ _executor_env_key: Optional[Tuple[str, str, str, str, str, str]] = None
1408
+
1409
+
1410
+ def get_llm_executor(
1411
+ baseURL: Optional[str] = None,
1412
+ model: Optional[str] = None,
1413
+ *,
1414
+ api_key: Optional[str] = None,
1415
+ auth_scheme: Optional[str] = None,
1416
+ max_tokens: Optional[int] = None,
1417
+ provider: Optional[str] = None,
1418
+ ) -> LLMAPIExecutor:
1419
+ """
1420
+ Get or create default LLM executor.
1421
+
1422
+ Args:
1423
+ baseURL: Override baseURL from environment (``None`` = read env)
1424
+ model: Override model name from environment
1425
+ api_key: Override API key from environment (non-empty only)
1426
+ auth_scheme: Override auth scheme from environment (non-empty only)
1427
+ max_tokens: Override ``SEED_LLM_MAX_TOKENS`` when set
1428
+
1429
+ Returns:
1430
+ LLMAPIExecutor instance
1431
+ """
1432
+ global _default_executor, _executor_env_key
1433
+
1434
+ resolved_url = (
1435
+ (baseURL if baseURL is not None else _ea.pick_nonempty(*_ea.LLM_BASEURL))
1436
+ .strip()
1437
+ .rstrip("/")
1438
+ )
1439
+ if model is not None and str(model).strip():
1440
+ resolved_model = str(model).strip()
1441
+ else:
1442
+ resolved_model = _ea.pick_default(
1443
+ "Qwen/Qwen3.5-35B-A3B-GPTQ-Int4", *_ea.LLM_MODEL
1444
+ )
1445
+
1446
+ max_tok = (
1447
+ str(int(max_tokens))
1448
+ if max_tokens is not None
1449
+ else _ea.pick_default("8192", *_ea.LLM_MAX_TOKENS)
1450
+ )
1451
+
1452
+ resolved_api = _ea.pick_nonempty(*_ea.LLM_API_KEY)
1453
+ if api_key is not None and api_key.strip():
1454
+ resolved_api = api_key.strip()
1455
+
1456
+ resolved_scheme = (_ea.pick_nonempty(*_ea.LLM_AUTH_SCHEME) or "Bearer")
1457
+ if auth_scheme is not None and auth_scheme.strip():
1458
+ resolved_scheme = auth_scheme.strip()
1459
+
1460
+ resolved_provider = (provider or "").strip()
1461
+ key = (
1462
+ resolved_url,
1463
+ resolved_model,
1464
+ max_tok,
1465
+ resolved_api,
1466
+ resolved_scheme,
1467
+ resolved_provider,
1468
+ )
1469
+
1470
+ if _default_executor is None or _executor_env_key != key:
1471
+ _default_executor = LLMAPIExecutor(
1472
+ baseURL=resolved_url,
1473
+ model=resolved_model,
1474
+ api_key=resolved_api,
1475
+ auth_scheme=resolved_scheme,
1476
+ maxOutputTokens=int(max_tok),
1477
+ provider=resolved_provider or None,
1478
+ )
1479
+ _executor_env_key = key
1480
+
1481
+ return _default_executor
1482
+
1483
+
1484
+ def reset_llm_executor() -> None:
1485
+ """Reset the default executor"""
1486
+ global _default_executor, _executor_env_key
1487
+ _default_executor = None
1488
+ _executor_env_key = None
1489
+
1490
+
1491
+ """Shrink chat-completions JSON before HTTP POST to avoid gateway 413 (body too large)."""
1492
+
1493
+
1494
+ import json
1495
+ import logging
1496
+ import os
1497
+ from typing import Any, Dict, List, Optional
1498
+
1499
+
1500
+ logger = logging.getLogger(__name__)
1501
+
1502
+
1503
+ def request_json_size(params: Dict[str, Any]) -> int:
1504
+ return len(json.dumps(params, ensure_ascii=False).encode("utf-8"))
1505
+
1506
+
1507
+ def max_llm_request_body_bytes(
1508
+ base_url: Optional[str],
1509
+ *,
1510
+ chat_protocol: Optional[str] = None,
1511
+ ) -> int:
1512
+ """0 = disabled. Official DeepSeek API often sits behind a ~1MiB reverse-proxy limit."""
1513
+ from seed.core.model_providers import default_max_request_body_bytes, resolve_chat_protocol
1514
+
1515
+ raw = _ea.pick_nonempty(*_ea.LLM_MAX_REQUEST_BODY_BYTES)
1516
+ if raw:
1517
+ try:
1518
+ return max(0, int(raw))
1519
+ except ValueError:
1520
+ logger.warning("Invalid SEED_LLM_MAX_REQUEST_BODY_BYTES=%r", raw)
1521
+ proto = chat_protocol or resolve_chat_protocol(provider="", base_url=base_url or "")
1522
+ return default_max_request_body_bytes(proto, base_url or "")
1523
+
1524
+
1525
+ def maybe_shrink_llm_request_params(
1526
+ params: Dict[str, Any],
1527
+ *,
1528
+ max_bytes: int,
1529
+ base_url: Optional[str],
1530
+ ) -> None:
1531
+ """Mutates ``params`` (especially ``messages``) in place."""
1532
+ if max_bytes <= 0:
1533
+ return
1534
+ try:
1535
+ before = request_json_size(params)
1536
+ except (TypeError, ValueError):
1537
+ return
1538
+ if before <= max_bytes:
1539
+ return
1540
+
1541
+ msgs = params.get("messages")
1542
+ if not isinstance(msgs, list):
1543
+ return
1544
+
1545
+ last_ai = -1
1546
+ for i in range(len(msgs) - 1, -1, -1):
1547
+ if isinstance(msgs[i], dict) and msgs[i].get("role") == "assistant":
1548
+ last_ai = i
1549
+ break
1550
+
1551
+ base_cap = int(_ea.pick_default("48000", *_ea.TOOL_OUTPUT_MAX_CHARS))
1552
+ base_cap = max(500, min(base_cap, 200_000))
1553
+ tool_caps: List[int] = []
1554
+ x = base_cap
1555
+ while x >= 500:
1556
+ tool_caps.append(x)
1557
+ x //= 2
1558
+ if not tool_caps or tool_caps[-1] != 500:
1559
+ tool_caps.append(500)
1560
+
1561
+ def sz() -> int:
1562
+ return request_json_size(params)
1563
+
1564
+ def trunc_tools(cap: int) -> None:
1565
+ for m in msgs:
1566
+ if isinstance(m, dict) and m.get("role") == "tool":
1567
+ content = m.get("content")
1568
+ if isinstance(content, str) and len(content) > cap:
1569
+ drop = len(content) - cap
1570
+ m["content"] = (
1571
+ content[:cap]
1572
+ + f"\n...[truncated {drop} chars for HTTP request body limit]"
1573
+ )
1574
+
1575
+ def trunc_rc(cap: int) -> None:
1576
+ from seed.core.model_providers import resolve_chat_protocol
1577
+
1578
+ proto = resolve_chat_protocol(provider="", base_url=base_url or "")
1579
+ if proto != "deepseek":
1580
+ return
1581
+ for i, m in enumerate(msgs):
1582
+ if not isinstance(m, dict) or m.get("role") != "assistant":
1583
+ continue
1584
+ if i == last_ai:
1585
+ continue
1586
+ rc = m.get("reasoning_content")
1587
+ if not isinstance(rc, str) or not rc:
1588
+ continue
1589
+ if cap <= 0:
1590
+ m["reasoning_content"] = ""
1591
+ elif len(rc) > cap:
1592
+ drop = len(rc) - cap
1593
+ m["reasoning_content"] = (
1594
+ rc[:cap] + f"\n...[truncated reasoning {drop} chars for HTTP body limit]"
1595
+ )
1596
+
1597
+ def trunc_asst_content(cap: int) -> None:
1598
+ for i, m in enumerate(msgs):
1599
+ if not isinstance(m, dict) or m.get("role") != "assistant":
1600
+ continue
1601
+ if i == last_ai:
1602
+ continue
1603
+ ctn = m.get("content")
1604
+ if isinstance(ctn, str) and len(ctn) > cap:
1605
+ drop = len(ctn) - cap
1606
+ m["content"] = ctn[:cap] + f"\n...[truncated {drop} chars for HTTP body limit]"
1607
+
1608
+ def trunc_system(cap: int) -> None:
1609
+ if not msgs or not isinstance(msgs[0], dict) or msgs[0].get("role") != "system":
1610
+ return
1611
+ ctn = msgs[0].get("content")
1612
+ if isinstance(ctn, str) and len(ctn) > cap:
1613
+ drop = len(ctn) - cap
1614
+ msgs[0]["content"] = ctn[:cap] + f"\n...[truncated system prompt {drop} chars]"
1615
+
1616
+ for cap in tool_caps:
1617
+ trunc_tools(cap)
1618
+ if sz() <= max_bytes:
1619
+ break
1620
+ else:
1621
+ for cap in (16000, 8000, 4000, 2000, 800, 0):
1622
+ trunc_rc(cap)
1623
+ if sz() <= max_bytes:
1624
+ break
1625
+ else:
1626
+ for cap in (50000, 20000, 8000, 2000):
1627
+ trunc_asst_content(cap)
1628
+ if sz() <= max_bytes:
1629
+ break
1630
+ else:
1631
+ for cap in (40000, 20000, 10000, 5000):
1632
+ trunc_system(cap)
1633
+ if sz() <= max_bytes:
1634
+ break
1635
+
1636
+ after = sz()
1637
+ if after <= max_bytes:
1638
+ logger.warning(
1639
+ "Shrunk LLM JSON request body %s -> %s bytes (limit %s) to reduce HTTP 413 risk",
1640
+ before,
1641
+ after,
1642
+ max_bytes,
1643
+ )
1644
+ else:
1645
+ logger.warning(
1646
+ "LLM JSON request body still ~%s bytes (limit %s). "
1647
+ "Enable SEED_CONTEXT_COMPACT=1, lower SEED_CHAT_USER_ROUNDS / "
1648
+ "SEED_TOOL_OUTPUT_MAX_CHARS, or set SEED_LLM_MAX_REQUEST_BODY_BYTES=0 "
1649
+ "only if your gateway allows larger uploads.",
1650
+ after,
1651
+ max_bytes,
1652
+ )