sycommon-python-lib 0.2.10b6__py3-none-any.whl → 0.2.12a1__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.
- sycommon/agent/agent_manager.py +110 -2
- sycommon/agent/dashboard/__init__.py +22 -0
- sycommon/agent/dashboard/api.py +76 -0
- sycommon/agent/dashboard/models.py +44 -0
- sycommon/agent/dashboard/stats.py +98 -0
- sycommon/agent/deep_agent.py +95 -0
- sycommon/agent/middleware/model_request_prep.py +81 -3
- sycommon/agent/sandbox/file_ops.py +20 -3
- sycommon/agent/sandbox/http_sandbox_backend.py +8 -0
- sycommon/agent/skills_retry_patch.py +10 -2
- sycommon/agent/summarization_utils.py +3 -2
- sycommon/alert/__init__.py +32 -0
- sycommon/alert/alert_sdk.py +71 -0
- sycommon/alert/ao.py +91 -0
- sycommon/alert/api.py +75 -0
- sycommon/alert/bridge.py +58 -0
- sycommon/alert/env.py +144 -0
- sycommon/alert/guard.py +73 -0
- sycommon/alert/monitor.py +223 -0
- sycommon/alert/mq_alert.py +190 -0
- sycommon/alert/queue.py +118 -0
- sycommon/alert/ratelimit.py +82 -0
- sycommon/alert/sdk.py +332 -0
- sycommon/alert/sdk_selfcheck.py +275 -0
- sycommon/config/Config.py +112 -18
- sycommon/database/distlock.py +246 -0
- sycommon/database/txnref.py +193 -0
- sycommon/health/readiness.py +481 -0
- sycommon/heartbeat_process/__init__.py +7 -51
- sycommon/heartbeat_process/heartbeat_config.py +3 -42
- sycommon/heartbeat_process/heartbeat_process_manager.py +7 -13
- sycommon/heartbeat_process/heartbeat_process_worker.py +7 -206
- sycommon/logging/async_sql_logger.py +2 -1
- sycommon/logging/kafka_log.py +597 -34
- sycommon/logging/log_masker.py +111 -21
- sycommon/logging/logger_levels.py +9 -3
- sycommon/logging/mask_engine.py +940 -0
- sycommon/logging/process_logger.py +5 -0
- sycommon/logging/sql_logger.py +2 -1
- sycommon/middleware/context.py +15 -0
- sycommon/middleware/crosstenant.py +95 -0
- sycommon/middleware/exception.py +52 -0
- sycommon/middleware/middleware.py +4 -0
- sycommon/middleware/sandbox.py +198 -16
- sycommon/middleware/traceid.py +151 -3
- sycommon/models/sandbox.py +12 -2
- sycommon/pi/agent/loop.py +1013 -0
- sycommon/pi/agent/types.py +233 -0
- sycommon/pi/coding/__init__.py +5 -0
- sycommon/pi/coding/mcpserver.py +314 -0
- sycommon/pi/core/json_parse.py +243 -0
- sycommon/pi/core/message.py +349 -0
- sycommon/pi/core/model.py +251 -0
- sycommon/pi/core/retry.py +175 -0
- sycommon/pi/core/transcript.py +404 -0
- sycommon/pi/core/transform.py +185 -0
- sycommon/pi/core/usage.py +264 -0
- sycommon/pi/core/validation.py +308 -0
- sycommon/pi/mcp/__init__.py +6 -0
- sycommon/pi/mcp/client.py +467 -0
- sycommon/pi/mcp/jsonrpc.py +191 -0
- sycommon/pi/mcp/transport.py +673 -0
- sycommon/pi/providers/__init__.py +15 -0
- sycommon/pi/providers/anthropic_client.py +829 -0
- sycommon/pi/providers/bedrock_client.py +860 -0
- sycommon/pi/providers/faux.py +446 -0
- sycommon/pi/providers/google_client.py +635 -0
- sycommon/pi/providers/kimi_client.py +152 -0
- sycommon/pi/providers/openai_client.py +1199 -0
- sycommon/rabbitmq/delay_queue.py +145 -0
- sycommon/rabbitmq/mq_store.py +271 -0
- sycommon/rabbitmq/rabbitmq_client.py +457 -39
- sycommon/rabbitmq/rabbitmq_pool.py +91 -16
- sycommon/rabbitmq/rabbitmq_service_client_manager.py +1 -0
- sycommon/rabbitmq/rabbitmq_service_connection_monitor.py +57 -10
- sycommon/rabbitmq/rabbitmq_service_core.py +87 -45
- sycommon/rabbitmq/rabbitmq_service_producer_manager.py +52 -5
- sycommon/rabbitmq/raw_mq.py +262 -0
- sycommon/rabbitmq/topic_registry.py +82 -0
- sycommon/services.py +30 -0
- sycommon/synacos/feign.py +59 -1
- sycommon/synacos/feign_client.py +41 -2
- sycommon/synacos/nacos_async_loop.py +110 -0
- sycommon/synacos/nacos_client_base.py +374 -132
- sycommon/synacos/nacos_config_manager.py +81 -60
- sycommon/synacos/nacos_connection_alert_listener.py +132 -0
- sycommon/synacos/nacos_service.py +15 -149
- sycommon/synacos/nacos_service_discovery.py +22 -140
- sycommon/synacos/nacos_service_registration.py +22 -50
- sycommon/tests/test_consumer_recovery_fix.py +3 -0
- sycommon/tests/test_mq_config_driven.py +27 -0
- sycommon/tests/test_sandbox_glob_hardening.py +89 -0
- sycommon/tests/test_upgrade_aio_pika.py +24 -11
- sycommon/tests/test_upgrade_verification.py +7 -7
- sycommon/tools/audit.py +149 -0
- sycommon/tools/excel.py +307 -0
- sycommon/tools/money.py +89 -0
- sycommon/tools/sso_token.py +127 -0
- sycommon/tools/tree.py +112 -0
- sycommon/tools/usercache.py +121 -0
- sycommon/xxljob/sharding.py +69 -0
- {sycommon_python_lib-0.2.10b6.dist-info → sycommon_python_lib-0.2.12a1.dist-info}/METADATA +27 -27
- {sycommon_python_lib-0.2.10b6.dist-info → sycommon_python_lib-0.2.12a1.dist-info}/RECORD +106 -49
- {sycommon_python_lib-0.2.10b6.dist-info → sycommon_python_lib-0.2.12a1.dist-info}/WHEEL +1 -1
- sycommon/synacos/nacos_heartbeat_manager.py +0 -245
- {sycommon_python_lib-0.2.10b6.dist-info → sycommon_python_lib-0.2.12a1.dist-info}/entry_points.txt +0 -0
- {sycommon_python_lib-0.2.10b6.dist-info → sycommon_python_lib-0.2.12a1.dist-info}/top_level.txt +0 -0
sycommon/agent/agent_manager.py
CHANGED
|
@@ -42,6 +42,7 @@ Agent 管理器
|
|
|
42
42
|
|
|
43
43
|
import asyncio
|
|
44
44
|
import threading
|
|
45
|
+
import time
|
|
45
46
|
from typing import Any, Dict, List, Optional, Union
|
|
46
47
|
from pathlib import Path
|
|
47
48
|
|
|
@@ -83,6 +84,12 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
83
84
|
self._sandbox_backends: Dict[str, HTTPSandboxBackend] = {}
|
|
84
85
|
# 使用线程锁保护字典,避免在 loop 重启后 asyncio.Lock 失效的问题
|
|
85
86
|
self._lock = threading.Lock()
|
|
87
|
+
# 空闲淘汰:记录每个 agent 最近活跃时间(monotonic 秒)。
|
|
88
|
+
# get/get_or_create/create 命中即 touch;淘汰循环只清超过
|
|
89
|
+
# idle_ttl 的条目。0/None = 禁用(默认禁用,长跑服务按需开启)。
|
|
90
|
+
self._last_used: Dict[str, float] = {}
|
|
91
|
+
self._idle_ttl: Optional[float] = None
|
|
92
|
+
self._reaper_task: Optional[asyncio.Task] = None
|
|
86
93
|
|
|
87
94
|
def _get_async_lock(self) -> asyncio.Lock:
|
|
88
95
|
"""获取当前 event loop 的 asyncio.Lock,避免跨 loop 问题"""
|
|
@@ -133,6 +140,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
133
140
|
# 保存引用
|
|
134
141
|
with self._lock:
|
|
135
142
|
self._agents[user_id] = agent
|
|
143
|
+
self._last_used[user_id] = time.monotonic()
|
|
136
144
|
self._agent_configs[user_id] = AgentInfo(
|
|
137
145
|
user_id=user_id,
|
|
138
146
|
type="agent",
|
|
@@ -188,6 +196,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
188
196
|
# 保存引用
|
|
189
197
|
with self._lock:
|
|
190
198
|
self._agents[user_id] = team
|
|
199
|
+
self._last_used[user_id] = time.monotonic()
|
|
191
200
|
self._agent_configs[user_id] = AgentInfo(
|
|
192
201
|
user_id=user_id,
|
|
193
202
|
type="team",
|
|
@@ -200,6 +209,90 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
200
209
|
SYLogger.info(f"[AgentManager] 创建数字团队: {user_id}, 成员: {[m.name for m in members]}")
|
|
201
210
|
return team
|
|
202
211
|
|
|
212
|
+
def _touch(self, user_id: str) -> None:
|
|
213
|
+
"""记录/刷新 agent 的最近活跃时间(淘汰判据)。
|
|
214
|
+
|
|
215
|
+
Deprecated: 保留兼容旧调用方;新代码用 _touch_if_present
|
|
216
|
+
(语义相同,命名与 get_agent 内部路径统一)。
|
|
217
|
+
"""
|
|
218
|
+
self._touch_if_present(user_id)
|
|
219
|
+
|
|
220
|
+
def set_idle_ttl(self, ttl_seconds: Optional[float], reaper_interval: float = 300.0) -> None:
|
|
221
|
+
"""开启/关闭空闲淘汰。
|
|
222
|
+
|
|
223
|
+
ttl_seconds=None/0 关闭淘汰并停掉后台任务;>0 时启动(或重启)
|
|
224
|
+
后台淘汰循环,每 reaper_interval 秒清理一次空闲超 TTL 的 agent。
|
|
225
|
+
|
|
226
|
+
幂等:重复调用以最新参数为准;先停旧任务再起新任务。
|
|
227
|
+
必须在 event loop 内调用(asyncio.create_task 需要运行中的 loop);
|
|
228
|
+
无运行 loop 时仅记录 TTL、不起后台任务(下次调用再起),并告警。
|
|
229
|
+
"""
|
|
230
|
+
if ttl_seconds and ttl_seconds > 0:
|
|
231
|
+
self._idle_ttl = float(ttl_seconds)
|
|
232
|
+
else:
|
|
233
|
+
self._idle_ttl = None
|
|
234
|
+
|
|
235
|
+
old = self._reaper_task
|
|
236
|
+
self._reaper_task = None
|
|
237
|
+
if old is not None and not old.done():
|
|
238
|
+
old.cancel()
|
|
239
|
+
if self._idle_ttl is not None:
|
|
240
|
+
try:
|
|
241
|
+
self._reaper_task = asyncio.create_task(self._reap_idle_loop(reaper_interval))
|
|
242
|
+
except RuntimeError:
|
|
243
|
+
# 无运行 event loop(如同步启动路径):不起后台任务。
|
|
244
|
+
# reap_idle 仍可被外部周期性调用(判据已就绪)。
|
|
245
|
+
self._reaper_task = None
|
|
246
|
+
SYLogger.warning(
|
|
247
|
+
"[AgentManager] set_idle_ttl 无运行 event loop,未起淘汰循环"
|
|
248
|
+
"(TTL 已记录,可手动周期调 reap_idle)")
|
|
249
|
+
|
|
250
|
+
async def _reap_idle_loop(self, interval: float) -> None:
|
|
251
|
+
"""后台淘汰循环:周期性销毁空闲超 TTL 的 agent。
|
|
252
|
+
|
|
253
|
+
CancelledError 正常退出(set_idle_ttl 关闭/重启时 cancel);
|
|
254
|
+
其他异常记 warning 后继续(淘汰失败不应杀死循环)。
|
|
255
|
+
"""
|
|
256
|
+
while True:
|
|
257
|
+
try:
|
|
258
|
+
await asyncio.sleep(interval)
|
|
259
|
+
await self.reap_idle()
|
|
260
|
+
except asyncio.CancelledError:
|
|
261
|
+
return
|
|
262
|
+
except Exception as e: # noqa: BLE001 - 守护循环必须吞异常续跑
|
|
263
|
+
SYLogger.warning(f"[AgentManager] 空闲淘汰循环异常(继续运行): {e}")
|
|
264
|
+
|
|
265
|
+
async def reap_idle(self) -> List[str]:
|
|
266
|
+
"""销毁所有空闲超过 TTL 的 agent,返回被销毁的 user_id 列表。
|
|
267
|
+
|
|
268
|
+
判据快照在锁内取;cleanup()(含沙箱 HTTP 调用)在锁外逐个执行;
|
|
269
|
+
destroy 前用 _touch 时间复核,避免清理期间刚被复用的 agent 误杀。
|
|
270
|
+
TTL 未设置时为 no-op。
|
|
271
|
+
"""
|
|
272
|
+
if self._idle_ttl is None:
|
|
273
|
+
return []
|
|
274
|
+
now = time.monotonic()
|
|
275
|
+
with self._lock:
|
|
276
|
+
expired = [
|
|
277
|
+
uid for uid, ts in self._last_used.items()
|
|
278
|
+
if now - ts > self._idle_ttl and uid in self._agents
|
|
279
|
+
]
|
|
280
|
+
destroyed: List[str] = []
|
|
281
|
+
for uid in expired:
|
|
282
|
+
# 复核(取当下时间而非快照 now):cleanup 可能耗时(沙箱 HTTP),
|
|
283
|
+
# 期间该 agent 可能刚被 touch(活跃中)——last 被推到当下后
|
|
284
|
+
# now2-last<=ttl 自然跳过,不会误杀在用 agent。
|
|
285
|
+
now2 = time.monotonic()
|
|
286
|
+
with self._lock:
|
|
287
|
+
last = self._last_used.get(uid)
|
|
288
|
+
if last is None or now2 - last <= self._idle_ttl:
|
|
289
|
+
continue
|
|
290
|
+
if await self.destroy_agent(uid):
|
|
291
|
+
destroyed.append(uid)
|
|
292
|
+
if destroyed:
|
|
293
|
+
SYLogger.info(f"[AgentManager] 空闲淘汰: {len(destroyed)} 个 ({destroyed})")
|
|
294
|
+
return destroyed
|
|
295
|
+
|
|
203
296
|
async def get_agent(self, user_id: str) -> Optional[Union[DeepAgent, MultiAgentTeam]]:
|
|
204
297
|
"""
|
|
205
298
|
获取已存在的 Agent
|
|
@@ -211,7 +304,17 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
211
304
|
DeepAgent | MultiAgentTeam | None: Agent 实例或 None
|
|
212
305
|
"""
|
|
213
306
|
with self._lock:
|
|
214
|
-
|
|
307
|
+
agent = self._agents.get(user_id)
|
|
308
|
+
if agent is not None:
|
|
309
|
+
# 命中即视为活跃(消费方拿到后可能直接 chat,不走
|
|
310
|
+
# get_or_create)——刷新淘汰判据,避免在用中被 reap。
|
|
311
|
+
self._last_used[user_id] = time.monotonic()
|
|
312
|
+
return agent
|
|
313
|
+
|
|
314
|
+
def _touch_if_present(self, user_id: str) -> None:
|
|
315
|
+
with self._lock:
|
|
316
|
+
if user_id in self._agents:
|
|
317
|
+
self._last_used[user_id] = time.monotonic()
|
|
215
318
|
|
|
216
319
|
async def get_or_create_agent(
|
|
217
320
|
self,
|
|
@@ -232,6 +335,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
232
335
|
"""
|
|
233
336
|
agent = await self.get_agent(user_id)
|
|
234
337
|
if agent and isinstance(agent, DeepAgent):
|
|
338
|
+
self._touch_if_present(user_id)
|
|
235
339
|
return agent
|
|
236
340
|
return await self.create_agent(user_id, config, project_root)
|
|
237
341
|
|
|
@@ -256,6 +360,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
256
360
|
"""
|
|
257
361
|
agent = await self.get_agent(user_id)
|
|
258
362
|
if agent and isinstance(agent, MultiAgentTeam):
|
|
363
|
+
self._touch_if_present(user_id)
|
|
259
364
|
return agent
|
|
260
365
|
return await self.create_team(user_id, members, config, project_root)
|
|
261
366
|
|
|
@@ -282,10 +387,12 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
282
387
|
SYLogger.warning(f"[AgentManager] Agent 清理失败 (user={user_id}): {e}")
|
|
283
388
|
|
|
284
389
|
with self._lock:
|
|
285
|
-
# 重新检查,防止并发 destroy
|
|
390
|
+
# 重新检查,防止并发 destroy(cleanup 在锁外执行期间
|
|
391
|
+
# 另一路可能已删;同时 _last_used 一并清理,避免判据字典残留)
|
|
286
392
|
if user_id not in self._agents:
|
|
287
393
|
return False
|
|
288
394
|
del self._agents[user_id]
|
|
395
|
+
self._last_used.pop(user_id, None)
|
|
289
396
|
if user_id in self._agent_configs:
|
|
290
397
|
del self._agent_configs[user_id]
|
|
291
398
|
if user_id in self._sandbox_backends:
|
|
@@ -360,6 +467,7 @@ class AgentManager(metaclass=SingletonMeta):
|
|
|
360
467
|
self._agents.clear()
|
|
361
468
|
self._agent_configs.clear()
|
|
362
469
|
self._sandbox_backends.clear()
|
|
470
|
+
self._last_used.clear()
|
|
363
471
|
|
|
364
472
|
SYLogger.info(f"[AgentManager] 清理所有 Agent: {count} 个")
|
|
365
473
|
return count
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""驾驶舱模块: 「AI 在跑数量」统计链路."""
|
|
2
|
+
from sycommon.agent.dashboard.api import (
|
|
3
|
+
dashboard_permission_required,
|
|
4
|
+
register_dashboard_routes,
|
|
5
|
+
)
|
|
6
|
+
from sycommon.agent.dashboard.models import (
|
|
7
|
+
AgentRunRecord,
|
|
8
|
+
AgentRunStatus,
|
|
9
|
+
AgentRunsStatsData,
|
|
10
|
+
AgentRunsStatsResponse,
|
|
11
|
+
)
|
|
12
|
+
from sycommon.agent.dashboard.stats import AgentRunStats
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"AgentRunRecord",
|
|
16
|
+
"AgentRunStats",
|
|
17
|
+
"AgentRunStatus",
|
|
18
|
+
"AgentRunsStatsData",
|
|
19
|
+
"AgentRunsStatsResponse",
|
|
20
|
+
"dashboard_permission_required",
|
|
21
|
+
"register_dashboard_routes",
|
|
22
|
+
]
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""驾驶舱 API: 「AI 在跑数量」统计接口.
|
|
2
|
+
|
|
3
|
+
- GET /api/dashboard/agent-runs/stats: 返回各状态计数, runningCount 为统计卡数据源.
|
|
4
|
+
- 统计源异常/缺失/非法值时降级为占位符 0, 不 500、不 NaN.
|
|
5
|
+
- 鉴权通过 FastAPI 依赖注入: dashboard_permission_required 组合宿主自定义校验.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from typing import Any, Callable, Optional
|
|
11
|
+
|
|
12
|
+
from fastapi import FastAPI, HTTPException, Request
|
|
13
|
+
|
|
14
|
+
from sycommon.agent.dashboard.models import AgentRunsStatsData, AgentRunsStatsResponse
|
|
15
|
+
from sycommon.agent.dashboard.stats import AgentRunStats
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
_STATS_ATTR = "agent_run_stats"
|
|
20
|
+
ROUTE_STATS = "/api/dashboard/agent-runs/stats"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def register_dashboard_routes(app: FastAPI) -> FastAPI:
|
|
24
|
+
"""把驾驶舱统计路由挂载到 app."""
|
|
25
|
+
|
|
26
|
+
@app.get(ROUTE_STATS, response_model=AgentRunsStatsResponse)
|
|
27
|
+
async def agent_runs_stats(request: Request) -> AgentRunsStatsResponse:
|
|
28
|
+
stats: Any = getattr(request.app.state, _STATS_ATTR, None)
|
|
29
|
+
data = AgentRunsStatsData()
|
|
30
|
+
if stats is None:
|
|
31
|
+
logger.warning("[dashboard] 统计源未初始化, runningCount 降级为 0")
|
|
32
|
+
return AgentRunsStatsResponse(data=data)
|
|
33
|
+
try:
|
|
34
|
+
raw = stats.running_count()
|
|
35
|
+
data.runningCount = _sanitize_count(raw)
|
|
36
|
+
raw_counts = stats.counts() if hasattr(stats, "counts") else None
|
|
37
|
+
if raw_counts:
|
|
38
|
+
data.succeededCount = _sanitize_count(raw_counts.get("succeeded", 0))
|
|
39
|
+
data.failedCount = _sanitize_count(raw_counts.get("failed", 0))
|
|
40
|
+
data.pendingCount = _sanitize_count(raw_counts.get("pending", 0))
|
|
41
|
+
except Exception as exc: # noqa: BLE001
|
|
42
|
+
# 接口异常降级: 占位 0 而不是 500, 页面其余部分正常渲染
|
|
43
|
+
logger.warning(f"[dashboard] 统计接口异常, 降级为占位 0: {exc}")
|
|
44
|
+
return AgentRunsStatsResponse(data=data)
|
|
45
|
+
|
|
46
|
+
return app
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _sanitize_count(raw: Any) -> int:
|
|
50
|
+
"""非法值(null/负数/字符串/科学计数)一律归一为 0."""
|
|
51
|
+
try:
|
|
52
|
+
value = int(raw)
|
|
53
|
+
except (TypeError, ValueError):
|
|
54
|
+
return 0
|
|
55
|
+
return value if value >= 0 else 0
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def dashboard_permission_required(
|
|
59
|
+
checker: Optional[Callable[..., Any]] = None,
|
|
60
|
+
):
|
|
61
|
+
"""驾驶舱权限依赖工厂.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
checker: 宿主自定义校验函数, 抛 HTTPException(401/403) 表示拒绝.
|
|
65
|
+
"""
|
|
66
|
+
if checker is None:
|
|
67
|
+
async def _default_checker() -> None:
|
|
68
|
+
raise HTTPException(status_code=401, detail="未登录")
|
|
69
|
+
checker = _default_checker
|
|
70
|
+
|
|
71
|
+
async def _dependency() -> None:
|
|
72
|
+
result = checker()
|
|
73
|
+
if result is not None and hasattr(result, "__await__"):
|
|
74
|
+
await result
|
|
75
|
+
|
|
76
|
+
return _dependency
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""驾驶舱「AI 在跑数量」数据模型."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel, Field
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class AgentRunStatus(str, Enum):
|
|
11
|
+
"""Agent 运行记录状态."""
|
|
12
|
+
|
|
13
|
+
PENDING = "pending"
|
|
14
|
+
RUNNING = "running"
|
|
15
|
+
SUCCEEDED = "succeeded"
|
|
16
|
+
FAILED = "failed"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class AgentRunRecord(BaseModel):
|
|
20
|
+
"""单条 Agent 运行记录."""
|
|
21
|
+
|
|
22
|
+
task_id: str
|
|
23
|
+
user_id: str
|
|
24
|
+
agent_name: str = "agent"
|
|
25
|
+
status: AgentRunStatus = AgentRunStatus.RUNNING
|
|
26
|
+
started_at: Optional[float] = None
|
|
27
|
+
finished_at: Optional[float] = None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class AgentRunsStatsData(BaseModel):
|
|
31
|
+
"""统计接口 data 字段."""
|
|
32
|
+
|
|
33
|
+
runningCount: int = Field(default=0, description="AI 在跑数量(仅 running 状态)")
|
|
34
|
+
succeededCount: int = 0
|
|
35
|
+
failedCount: int = 0
|
|
36
|
+
pendingCount: int = 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class AgentRunsStatsResponse(BaseModel):
|
|
40
|
+
"""统计接口统一响应."""
|
|
41
|
+
|
|
42
|
+
code: int = 0
|
|
43
|
+
message: str = "ok"
|
|
44
|
+
data: AgentRunsStatsData = AgentRunsStatsData()
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Agent 运行统计: 驾驶舱「AI 在跑数量」数据源.
|
|
2
|
+
|
|
3
|
+
线程安全的进程内统计器, 统计口径: runningCount 只计 status == running
|
|
4
|
+
的记录, succeeded/failed/pending 不计入。宿主服务可替换为 DB/Redis 实现,
|
|
5
|
+
只需保持同名方法契约。
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import threading
|
|
10
|
+
import time
|
|
11
|
+
from typing import Dict, List, Optional
|
|
12
|
+
|
|
13
|
+
from sycommon.agent.dashboard.models import AgentRunRecord, AgentRunStatus
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class AgentRunStats:
|
|
17
|
+
"""线程安全的 Agent 运行记录统计器."""
|
|
18
|
+
|
|
19
|
+
def __init__(self) -> None:
|
|
20
|
+
self._lock = threading.RLock()
|
|
21
|
+
self._runs: Dict[str, AgentRunRecord] = {}
|
|
22
|
+
|
|
23
|
+
# -- 写入 ---------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
def record_start(
|
|
26
|
+
self,
|
|
27
|
+
task_id: str,
|
|
28
|
+
user_id: str,
|
|
29
|
+
agent_name: str = "agent",
|
|
30
|
+
status: AgentRunStatus = AgentRunStatus.RUNNING,
|
|
31
|
+
) -> AgentRunRecord:
|
|
32
|
+
"""记录一次任务启动(新任务默认进入 running)."""
|
|
33
|
+
record = AgentRunRecord(
|
|
34
|
+
task_id=task_id,
|
|
35
|
+
user_id=user_id,
|
|
36
|
+
agent_name=agent_name,
|
|
37
|
+
status=status,
|
|
38
|
+
started_at=time.time(),
|
|
39
|
+
)
|
|
40
|
+
with self._lock:
|
|
41
|
+
self._runs[task_id] = record
|
|
42
|
+
return record
|
|
43
|
+
|
|
44
|
+
def record_finish(
|
|
45
|
+
self,
|
|
46
|
+
task_id: str,
|
|
47
|
+
status: AgentRunStatus = AgentRunStatus.SUCCEEDED,
|
|
48
|
+
) -> Optional[AgentRunRecord]:
|
|
49
|
+
"""记录任务结束(running → succeeded/failed)."""
|
|
50
|
+
with self._lock:
|
|
51
|
+
record = self._runs.get(task_id)
|
|
52
|
+
if record is None:
|
|
53
|
+
return None
|
|
54
|
+
record.status = status
|
|
55
|
+
record.finished_at = time.time()
|
|
56
|
+
return record
|
|
57
|
+
|
|
58
|
+
def seed_running(self, count: int) -> None:
|
|
59
|
+
"""批量造 running 记录(测试/演示用)."""
|
|
60
|
+
for i in range(count):
|
|
61
|
+
self.record_start(
|
|
62
|
+
task_id=f"seed-{i}",
|
|
63
|
+
user_id="seed-user",
|
|
64
|
+
agent_name="seed-agent",
|
|
65
|
+
status=AgentRunStatus.RUNNING,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
# -- 查询 ---------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
def running_count(self) -> int:
|
|
71
|
+
"""AI 在跑数量: 只计 running 状态."""
|
|
72
|
+
with self._lock:
|
|
73
|
+
return sum(
|
|
74
|
+
1 for r in self._runs.values()
|
|
75
|
+
if r.status == AgentRunStatus.RUNNING
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
def counts(self) -> dict:
|
|
79
|
+
"""各状态计数."""
|
|
80
|
+
with self._lock:
|
|
81
|
+
result = {
|
|
82
|
+
AgentRunStatus.RUNNING: 0,
|
|
83
|
+
AgentRunStatus.SUCCEEDED: 0,
|
|
84
|
+
AgentRunStatus.FAILED: 0,
|
|
85
|
+
AgentRunStatus.PENDING: 0,
|
|
86
|
+
}
|
|
87
|
+
for r in self._runs.values():
|
|
88
|
+
if r.status in result:
|
|
89
|
+
result[r.status] += 1
|
|
90
|
+
return result
|
|
91
|
+
|
|
92
|
+
def list_runs(self, status: Optional[AgentRunStatus] = None) -> List[AgentRunRecord]:
|
|
93
|
+
"""列出运行记录, 可按状态过滤."""
|
|
94
|
+
with self._lock:
|
|
95
|
+
records = list(self._runs.values())
|
|
96
|
+
if status is not None:
|
|
97
|
+
records = [r for r in records if r.status == status]
|
|
98
|
+
return records
|
sycommon/agent/deep_agent.py
CHANGED
|
@@ -133,6 +133,52 @@ def _match_summary_prefix_overlap(text: str, summary: str,
|
|
|
133
133
|
return 0
|
|
134
134
|
|
|
135
135
|
|
|
136
|
+
# 🔑 复读尾部熔断(9/9 田甜事故最后一环):贪心解码锁死后输出退化成
|
|
137
|
+
# 「短单元无脑重复」(实测指令句连抄 1780 次直到 max_tokens)。只查
|
|
138
|
+
# 尾部 —— 重复段在中间而结尾正常是正常文本(引用/排比),交给回显剥离。
|
|
139
|
+
def _detect_repetition_tail(text: str, *, unit_min: int = 6) -> bool:
|
|
140
|
+
"""检测文本尾部是否陷入单元级复读。
|
|
141
|
+
|
|
142
|
+
取尾部 window 字符,对长度 >= unit_min 的所有候选单元,若该单元
|
|
143
|
+
连续重复出现在尾部且重复次数 >= repeat_min 即判定锁死。
|
|
144
|
+
unit_min=6 让 markdown 表格分隔线(|---|)、常见短语相邻复现不误伤;
|
|
145
|
+
超短单元(单字/两字词)复读用更小下限单独判定。
|
|
146
|
+
"""
|
|
147
|
+
if not text or len(text) < 40:
|
|
148
|
+
return False
|
|
149
|
+
window = text[-600:]
|
|
150
|
+
repeat_min = 4
|
|
151
|
+
# 1) 常规单元:长度 unit_min..64,从长到短,命中即报
|
|
152
|
+
for size in range(64, unit_min - 1, -1):
|
|
153
|
+
unit = window[-size:]
|
|
154
|
+
if unit.count("\n") > size // 2:
|
|
155
|
+
continue # 大半是换行的"单元"不可信
|
|
156
|
+
n = 0
|
|
157
|
+
i = len(window)
|
|
158
|
+
while i >= size and window[i - size:i] == unit:
|
|
159
|
+
n += 1
|
|
160
|
+
i -= size
|
|
161
|
+
if n >= repeat_min:
|
|
162
|
+
return True
|
|
163
|
+
# 2) 超短单元(2-5 字符)复读:需要更高重复次数(10+)才报,
|
|
164
|
+
# 避免「的地得」、缩进、表格线等正常高频短串误伤。
|
|
165
|
+
# 下限取 unit_min(调用方传 unit_min=2 即启用 2 字符判定)。
|
|
166
|
+
for size in range(5, unit_min - 1, -1):
|
|
167
|
+
if size < 2:
|
|
168
|
+
break
|
|
169
|
+
unit = window[-size:]
|
|
170
|
+
if unit.strip() == "":
|
|
171
|
+
continue
|
|
172
|
+
n = 0
|
|
173
|
+
i = len(window)
|
|
174
|
+
while i >= size and window[i - size:i] == unit:
|
|
175
|
+
n += 1
|
|
176
|
+
i -= size
|
|
177
|
+
if n >= 10:
|
|
178
|
+
return True
|
|
179
|
+
return False
|
|
180
|
+
|
|
181
|
+
|
|
136
182
|
@tool
|
|
137
183
|
def get_current_date() -> str:
|
|
138
184
|
"""获取当前日期时间(北京时间)"""
|
|
@@ -364,6 +410,9 @@ class DeepAgent:
|
|
|
364
410
|
# 兜底:累积流式 chunk 中的 usage_metadata(middleware 在流式场景可能拿不到)
|
|
365
411
|
total_input_tokens = 0
|
|
366
412
|
total_output_tokens = 0
|
|
413
|
+
# 🔑 复读尾部熔断状态:上次判定时的文本长度(100 字符节流)+ 熔断标记
|
|
414
|
+
_last_repetition_check = 0
|
|
415
|
+
_repetition_detected = False
|
|
367
416
|
|
|
368
417
|
# ── 设置 chat turn 级 trace_id ──
|
|
369
418
|
# 如果上层(HTTP 中间件等)已设置 trace_id 则沿用,否则生成新的。
|
|
@@ -847,6 +896,21 @@ class DeepAgent:
|
|
|
847
896
|
await on_event(event)
|
|
848
897
|
yield event
|
|
849
898
|
|
|
899
|
+
# 🔑 复读尾部熔断:累积文本尾部陷入单元级复读即中断流,
|
|
900
|
+
# 不再继续消费(后面全是复读垃圾,还会烧满 max_tokens)。
|
|
901
|
+
# 判定按 100 字符节流,避免每 token 全量比对。
|
|
902
|
+
if len(ai_text_content) - _last_repetition_check >= 100:
|
|
903
|
+
_last_repetition_check = len(ai_text_content)
|
|
904
|
+
if _detect_repetition_tail(ai_text_content):
|
|
905
|
+
SYLogger.warning(
|
|
906
|
+
f"[DeepAgent] 复读熔断: 检测到尾部单元级复读,中断本轮流 "
|
|
907
|
+
f"(ai_text_len={len(ai_text_content)}, stream_step={stream_step})")
|
|
908
|
+
_repetition_detected = True
|
|
909
|
+
break
|
|
910
|
+
elif _detect_repetition_tail(ai_text_content) and not _repetition_detected:
|
|
911
|
+
# content 为空但此前已判定复读(如续流 chunk),同样熔断
|
|
912
|
+
pass
|
|
913
|
+
|
|
850
914
|
elif msg_type == "ToolMessage":
|
|
851
915
|
if ai_chunk_buffer:
|
|
852
916
|
SYLogger.debug(
|
|
@@ -927,6 +991,37 @@ class DeepAgent:
|
|
|
927
991
|
f"stream_step={stream_step} | ai_text_len={len(ai_text_content)} | "
|
|
928
992
|
f"tool_calls={len(current_tool_calls)}")
|
|
929
993
|
|
|
994
|
+
# 🔑 复读熔断收尾:熔断发生时尾部截掉复读垃圾(保留正常前文),
|
|
995
|
+
# 追加一个 error 事件提示上层(与空响应同通道,可触发上层降级/重试)。
|
|
996
|
+
if _repetition_detected:
|
|
997
|
+
# 熔断发生时尾部截掉复读垃圾:去掉末尾最后一份完整复读单元
|
|
998
|
+
# (从尾部窗口反推最大重复单元),保留正常前文
|
|
999
|
+
cleaned_tail = ai_text_content
|
|
1000
|
+
window = ai_text_content[-600:]
|
|
1001
|
+
for size in range(64, 1, -1):
|
|
1002
|
+
unit = window[-size:]
|
|
1003
|
+
if size >= 6:
|
|
1004
|
+
n, i = 0, len(window)
|
|
1005
|
+
while i >= size and window[i - size:i] == unit:
|
|
1006
|
+
n += 1
|
|
1007
|
+
i -= size
|
|
1008
|
+
if n >= 4:
|
|
1009
|
+
cleaned_tail = ai_text_content[:-len(unit) * 1].rstrip()
|
|
1010
|
+
break
|
|
1011
|
+
elif unit.strip() and window[-(size * 10):] == unit * 10:
|
|
1012
|
+
cleaned_tail = ai_text_content[:-size].rstrip()
|
|
1013
|
+
break
|
|
1014
|
+
ai_text_content = cleaned_tail
|
|
1015
|
+
SYLogger.warning(
|
|
1016
|
+
f"[DeepAgent] 复读熔断生效: 本轮流提前结束,截断前长度 {len(ai_text_content)}")
|
|
1017
|
+
event = ChatEventBuilder.error(
|
|
1018
|
+
"模型输出陷入重复循环,已自动中断(repetition loop detected)",
|
|
1019
|
+
code="repetition_loop",
|
|
1020
|
+
)
|
|
1021
|
+
if on_event:
|
|
1022
|
+
await on_event(event)
|
|
1023
|
+
yield event
|
|
1024
|
+
|
|
930
1025
|
# 空响应检测:模型被调用但没有产出任何文本。
|
|
931
1026
|
# 🔑 治本修复:纯空响应(无文本且无工具调用,常见于用户派生 key 被网关拒、
|
|
932
1027
|
# 网关返回空壳 AIMessage 而非异常)不再静默只打 warning —— 把它翻译成
|
|
@@ -34,10 +34,55 @@ from langchain.agents.middleware.types import (
|
|
|
34
34
|
ModelResponse,
|
|
35
35
|
ResponseT,
|
|
36
36
|
)
|
|
37
|
-
from langchain_core.messages import BaseMessage, HumanMessage
|
|
37
|
+
from langchain_core.messages import AIMessage, BaseMessage, HumanMessage
|
|
38
38
|
|
|
39
39
|
from sycommon.logging.kafka_log import SYLogger
|
|
40
40
|
|
|
41
|
+
# 🔑 回显剥离(9/9 田甜复读事故):模型把注入的备忘块整块回显进输出,回显随
|
|
42
|
+
# ModelResponse 写入 checkpointer → 下轮上下文里旧回显+新注入并存 → 回显越滚
|
|
43
|
+
# 越多 → 贪心解码锁死成句级复读(实测单条 1780 次)。三层标签成对闭合整块删;
|
|
44
|
+
# 未闭合(复读到 max_tokens 等不到闭合)从开标签截断到结尾 —— 复读垃圾只会
|
|
45
|
+
# 出现在开标签之后,前文正常内容保留。
|
|
46
|
+
_ECHO_TAG_PATTERNS = tuple(re.compile(p, re.DOTALL) for p in (
|
|
47
|
+
r'<internal_context_data>.*?</internal_context_data>',
|
|
48
|
+
r'<compressed_history>.*?</compressed_history>',
|
|
49
|
+
r'<system_context>.*?</system_context>',
|
|
50
|
+
r'<internal_context_data>(?!.*</internal_context_data>).*',
|
|
51
|
+
r'<compressed_history>(?!.*</compressed_history>).*',
|
|
52
|
+
r'<system_context>(?!.*</system_context>).*',
|
|
53
|
+
))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _strip_echo_text(text: str) -> str:
|
|
57
|
+
"""剥掉一段文本里的备忘回显块,返回清洗后文本。"""
|
|
58
|
+
for pat in _ECHO_TAG_PATTERNS:
|
|
59
|
+
if pat.search(text):
|
|
60
|
+
text = pat.sub('', text)
|
|
61
|
+
return text.strip()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def dedupe_memo_lines(summary_text: str) -> str:
|
|
65
|
+
"""备忘条目逐行去重(保持首现顺序与空行)。
|
|
66
|
+
|
|
67
|
+
多轮压缩时新备忘把旧备忘 + 历史回显一起总结,重复条目(实测「文件:
|
|
68
|
+
…」相邻出现两次、「事实: 需求大小分布…」逐轮翻倍)被原样折叠进备忘,
|
|
69
|
+
备忘自身开始自我复制——注入前去重断掉这一层。
|
|
70
|
+
"""
|
|
71
|
+
if not summary_text:
|
|
72
|
+
return summary_text
|
|
73
|
+
seen: set[str] = set()
|
|
74
|
+
out: list[str] = []
|
|
75
|
+
for line in summary_text.splitlines():
|
|
76
|
+
key = line.strip()
|
|
77
|
+
if not key:
|
|
78
|
+
out.append(line)
|
|
79
|
+
continue
|
|
80
|
+
if key in seen:
|
|
81
|
+
continue
|
|
82
|
+
seen.add(key)
|
|
83
|
+
out.append(line)
|
|
84
|
+
return "\n".join(out)
|
|
85
|
+
|
|
41
86
|
|
|
42
87
|
class ModelRequestPrepMiddleware(AgentMiddleware):
|
|
43
88
|
"""模型请求预处理:摘要重定位 + 动态压 max_tokens。
|
|
@@ -59,6 +104,30 @@ class ModelRequestPrepMiddleware(AgentMiddleware):
|
|
|
59
104
|
def name(self) -> str:
|
|
60
105
|
return "ModelRequestPrepMiddleware"
|
|
61
106
|
|
|
107
|
+
def _strip_summary_echo(self, response) -> "ModelResponse[Any]":
|
|
108
|
+
"""响应侧剥回显(断环点):ModelResponse.result 里每条 AIMessage 的
|
|
109
|
+
content 先剥回显块再随 checkpoint 持久化 —— 历史里不再躺回显,
|
|
110
|
+
正反馈环在写入侧断掉。无命中返回原对象(零开销);多模态 list
|
|
111
|
+
content 不动(无稳定文本形态,误伤风险大于收益)。
|
|
112
|
+
"""
|
|
113
|
+
result = getattr(response, "result", None)
|
|
114
|
+
if not result:
|
|
115
|
+
return response
|
|
116
|
+
for msg in result:
|
|
117
|
+
content = getattr(msg, "content", None)
|
|
118
|
+
if not isinstance(msg, AIMessage) or not isinstance(content, str):
|
|
119
|
+
continue
|
|
120
|
+
cleaned = _strip_echo_text(content)
|
|
121
|
+
if cleaned != content:
|
|
122
|
+
try:
|
|
123
|
+
msg.content = cleaned
|
|
124
|
+
SYLogger.warning(
|
|
125
|
+
"[ModelRequestPrep] 已剥除模型输出中的备忘回显 "
|
|
126
|
+
f"(len {len(content)} → {len(cleaned)})")
|
|
127
|
+
except Exception:
|
|
128
|
+
pass
|
|
129
|
+
return response
|
|
130
|
+
|
|
62
131
|
def _relocate_summaries(
|
|
63
132
|
self, request: ModelRequest[ContextT]
|
|
64
133
|
) -> ModelRequest[ContextT]:
|
|
@@ -84,6 +153,9 @@ class ModelRequestPrepMiddleware(AgentMiddleware):
|
|
|
84
153
|
if not _summary_text:
|
|
85
154
|
return request
|
|
86
155
|
|
|
156
|
+
# 🔑 注入前去重:多轮压缩的叠加重复条目不进 system(见 dedupe_memo_lines)
|
|
157
|
+
_summary_text = dedupe_memo_lines(_summary_text)
|
|
158
|
+
|
|
87
159
|
from deepagents.middleware._utils import append_to_system_message
|
|
88
160
|
# 🔑 注入形态 = 备忘在前、行为契约在后(recency:靠近对话末端的指令
|
|
89
161
|
# 遵循度最高),且用正向指令替代"不要复述"禁令 —— 负向禁令对
|
|
@@ -148,7 +220,13 @@ class ModelRequestPrepMiddleware(AgentMiddleware):
|
|
|
148
220
|
request: ModelRequest[ContextT],
|
|
149
221
|
handler: Callable[[ModelRequest[ContextT]], Awaitable[ModelResponse[ResponseT]]],
|
|
150
222
|
) -> ModelResponse[ResponseT]:
|
|
151
|
-
"""
|
|
223
|
+
"""拦截模型调用:摘要重定位(注入前去重)→ max_tokens 动态压 →
|
|
224
|
+
响应剥回显(断环),再返回 handler 结果。"""
|
|
152
225
|
request = self._relocate_summaries(request)
|
|
153
226
|
self._clamp_max_tokens(request)
|
|
154
|
-
|
|
227
|
+
response = await handler(request)
|
|
228
|
+
try:
|
|
229
|
+
return self._strip_summary_echo(response)
|
|
230
|
+
except Exception as e:
|
|
231
|
+
SYLogger.warning(f"[ModelRequestPrep] strip echo failed(放行): {e}")
|
|
232
|
+
return response
|