|
|
@@ -782,10 +782,48 @@ def _tools_json_schema(cfg: Dict, tool_names=None) -> list:
|
|
|
return out
|
|
|
|
|
|
|
|
|
+_OBS_FAIL_MARKERS = (
|
|
|
+ "[tool_error]", "[validation_error]", "[subagent ", " not found",
|
|
|
+ " compile error", " timed out", " timeout", "[claude code error]",
|
|
|
+ "[error]", "[mcp_error", "[mcp_timeout",
|
|
|
+ '"status": "fail"', '"status":"fail"', '"ok": false', '"ok":false',
|
|
|
+)
|
|
|
+
|
|
|
+
|
|
|
+def _observation_failed_text(observation: str) -> bool:
|
|
|
+ """工具观测是否表示失败(loop 计账用)。文本路与 FC 路共用同一套失败标记,
|
|
|
+ 避免两份拷贝漂移。失败的调用不应满足 enforceLoop 的循环要求。"""
|
|
|
+ text = (observation or "").lower()
|
|
|
+ return any(marker in text for marker in _OBS_FAIL_MARKERS)
|
|
|
+
|
|
|
+
|
|
|
+def _fc_complete_cycles(tool_log: list, sequence: list):
|
|
|
+ """按文本路同一算法统计完整循环数。sequence[-1]=边界工具,其余=前置工具;
|
|
|
+ 边界工具成功调用 且 自上一边界以来所有前置都成功出现过 → 记一个完整循环。
|
|
|
+ 返回 (完整循环数, 前置集合, 当前循环已见前置, 边界工具)。"""
|
|
|
+ boundary = sequence[-1]
|
|
|
+ prereqs = set(sequence[:-1])
|
|
|
+ cycles = 0
|
|
|
+ seen: set = set()
|
|
|
+ for e in tool_log:
|
|
|
+ t = e.get("tool")
|
|
|
+ ok = not _observation_failed_text(e.get("observation", ""))
|
|
|
+ if t == boundary:
|
|
|
+ if ok and prereqs.issubset(seen):
|
|
|
+ cycles += 1
|
|
|
+ seen = set()
|
|
|
+ elif ok:
|
|
|
+ seen = set() # 缺前置的成功边界 → 重开一轮
|
|
|
+ elif t in prereqs and ok:
|
|
|
+ seen.add(t)
|
|
|
+ return cycles, prereqs, seen, boundary
|
|
|
+
|
|
|
+
|
|
|
def _run_fc_loop(provider, system_prompt: str, user_input: str, tools: Dict,
|
|
|
tools_schema: list, *, max_steps: int, tool_timeout: int,
|
|
|
on_step=None, cancel=None, ctx=None,
|
|
|
- enforce_tool: str = "", enforce_min: int = 0) -> str:
|
|
|
+ enforce_tool: str = "", enforce_min: int = 0,
|
|
|
+ enforce_sequence: list = None, enforce_min_cycles: int = 0) -> str:
|
|
|
"""原生 function-calling 的 ReAct 循环。用结构化 tool_calls 直接执行,不解析文本——
|
|
|
根治 0 执行/格式飘/路径别名类 bug。见 docs/NATIVE_FUNCTION_CALLING_DESIGN.md。
|
|
|
复用 _timeout_call 工具执行 + on_step(StepEvent);per-tool 写 ctx.trace(可观测);
|
|
|
@@ -807,6 +845,8 @@ def _run_fc_loop(provider, system_prompt: str, user_input: str, tools: Dict,
|
|
|
messages = [{"role": "system", "content": system_prompt},
|
|
|
{"role": "user", "content": user_input}]
|
|
|
tool_counts: Dict[str, int] = {}
|
|
|
+ tool_log: list = [] # 有序 [{tool, observation}],序列模式循环计账用
|
|
|
+ _seq = list(enforce_sequence or [])
|
|
|
final = ""
|
|
|
for step in range(max_steps):
|
|
|
if cancel is not None and cancel.is_cancelled():
|
|
|
@@ -829,13 +869,27 @@ def _run_fc_loop(provider, system_prompt: str, user_input: str, tools: Dict,
|
|
|
name, args = tc["name"], (tc["arguments"] if isinstance(tc["arguments"], dict) else {})
|
|
|
tcid = tc["id"] or f"call_{step}_{i}"
|
|
|
if name == "terminate":
|
|
|
- # enforceLoop 计数模式:enforce_tool 没调够 enforce_min 次 → 禁止结束。
|
|
|
- got = tool_counts.get(enforce_tool, 0)
|
|
|
- if enforce_tool and enforce_min > 0 and got < enforce_min:
|
|
|
- msg = (f"[SYSTEM] 还不能结束:{enforce_tool} 已调用 {got}/{enforce_min} 次,"
|
|
|
- f"还需 {enforce_min - got} 次。请继续完成后再 terminate。")
|
|
|
- messages.append({"role": "tool", "tool_call_id": tcid, "content": msg})
|
|
|
- _emit(STEP_TOOL_RESULT, step, msg, tool="terminate")
|
|
|
+ # enforceLoop 门控(最后一步不拦,避免死锁):序列模式优先于计数模式。
|
|
|
+ block = ""
|
|
|
+ if step < max_steps - 1:
|
|
|
+ if _seq and enforce_min_cycles > 0:
|
|
|
+ # 序列模式:须按 sequence 顺序走够 enforce_min_cycles 个完整循环。
|
|
|
+ cycles, prereqs, seen, boundary = _fc_complete_cycles(tool_log, _seq)
|
|
|
+ if cycles < enforce_min_cycles:
|
|
|
+ missing = sorted(prereqs - seen)
|
|
|
+ nxt = missing[0] if missing else boundary
|
|
|
+ block = (f"[SYSTEM] 循环未完成:已完成 {cycles}/{enforce_min_cycles} 轮。"
|
|
|
+ f"当前轮还缺 {', '.join(missing) if missing else '(只差 ' + boundary + ')'}。"
|
|
|
+ f"禁止 terminate,请按顺序调用 {' → '.join(_seq)},下一步应是 {nxt}。")
|
|
|
+ elif enforce_tool and enforce_min > 0:
|
|
|
+ # 计数模式:enforce_tool 没调够 enforce_min 次 → 禁止结束。
|
|
|
+ got = tool_counts.get(enforce_tool, 0)
|
|
|
+ if got < enforce_min:
|
|
|
+ block = (f"[SYSTEM] 还不能结束:{enforce_tool} 已调用 {got}/{enforce_min} 次,"
|
|
|
+ f"还需 {enforce_min - got} 次。请继续完成后再 terminate。")
|
|
|
+ if block:
|
|
|
+ messages.append({"role": "tool", "tool_call_id": tcid, "content": block})
|
|
|
+ _emit(STEP_TOOL_RESULT, step, block, tool="terminate")
|
|
|
continue # 不 terminate,循环继续
|
|
|
final = (args.get("summary") or "").strip() or content or final
|
|
|
terminated = True
|
|
|
@@ -852,6 +906,7 @@ def _run_fc_loop(provider, system_prompt: str, user_input: str, tools: Dict,
|
|
|
except Exception as e:
|
|
|
obs = f"[TOOL_ERROR] {e}"
|
|
|
tool_counts[name] = tool_counts.get(name, 0) + 1
|
|
|
+ tool_log.append({"tool": name, "observation": obs})
|
|
|
_emit(STEP_TOOL_RESULT, step, obs, tool=name)
|
|
|
if ctx is not None: # per-tool 写 trace → 前端步数/trace 面板可见 FC 过程
|
|
|
try:
|
|
|
@@ -868,18 +923,21 @@ def _run_fc_loop(provider, system_prompt: str, user_input: str, tools: Dict,
|
|
|
class _FCReactTerm(Term):
|
|
|
"""FC react 车道的 Term(apply 收 ctx → 能写 trace)。比 Tool 多带 ctx 与 enforceLoop。"""
|
|
|
def __init__(self, name, *, provider, system_prompt, tools, tools_schema,
|
|
|
- max_steps, tool_timeout, on_step, cancel, enforce_tool, enforce_min):
|
|
|
+ max_steps, tool_timeout, on_step, cancel, enforce_tool, enforce_min,
|
|
|
+ enforce_sequence=None, enforce_min_cycles=0):
|
|
|
super().__init__(name)
|
|
|
self._p = provider; self._sys = system_prompt; self._tools = tools
|
|
|
self._schema = tools_schema; self._ms = max_steps; self._tt = tool_timeout
|
|
|
self._os = on_step; self._c = cancel
|
|
|
self._etool = enforce_tool; self._emin = enforce_min
|
|
|
+ self._eseq = list(enforce_sequence or []); self._emincyc = enforce_min_cycles
|
|
|
|
|
|
def apply(self, input, ctx=None):
|
|
|
return _run_fc_loop(self._p, self._sys, str(input), self._tools, self._schema,
|
|
|
max_steps=self._ms, tool_timeout=self._tt, on_step=self._os,
|
|
|
cancel=self._c, ctx=ctx, enforce_tool=self._etool,
|
|
|
- enforce_min=self._emin)
|
|
|
+ enforce_min=self._emin, enforce_sequence=self._eseq,
|
|
|
+ enforce_min_cycles=self._emincyc)
|
|
|
|
|
|
|
|
|
def _compile_react(cfg: Dict, overrides: Dict) -> Term:
|
|
|
@@ -936,15 +994,19 @@ def _compile_react(cfg: Dict, overrides: Dict) -> Term:
|
|
|
from lambdagent.agentruntime import cancel as _fc_cancel
|
|
|
except Exception:
|
|
|
_fc_cancel = None
|
|
|
- # enforceLoop 计数模式(单体 agent 用):terminate 前 tool 须调够 minCount 次。
|
|
|
- # 序列模式(orchestrator)FC 暂不支持——那些 agent 不设 nativeToolCalls。
|
|
|
+ # enforceLoop:FC 路同时支持两种门控,语义与文本路一致——
|
|
|
+ # 计数模式 {tool, minCount}:terminate 前 tool 须调够 minCount 次(单体 agent)。
|
|
|
+ # 序列模式 {sequence:[t1..tN], minCycles}:须按序走够 minCycles 个完整循环
|
|
|
+ # (orchestrator 派活,每轮所有前置工具都成功出现过才算一个循环)。
|
|
|
_el = react_cfg.get("enforceLoop", {}) or {}
|
|
|
fc_term = _FCReactTerm(
|
|
|
f"{agent_name}.fc_react", provider=_prov, system_prompt=cfg.get("systemPrompt", ""),
|
|
|
tools=tools, tools_schema=_tools_json_schema(cfg, list(tools.keys())),
|
|
|
max_steps=max_steps, tool_timeout=tool_timeout,
|
|
|
on_step=overrides.get("on_step"), cancel=_fc_cancel,
|
|
|
- enforce_tool=_el.get("tool", ""), enforce_min=int(_el.get("minCount", 0) or 0))
|
|
|
+ enforce_tool=_el.get("tool", ""), enforce_min=int(_el.get("minCount", 0) or 0),
|
|
|
+ enforce_sequence=list(_el.get("sequence", []) or []),
|
|
|
+ enforce_min_cycles=int(_el.get("minCycles", 0) or 0))
|
|
|
fc_term._think_ref = think # token/usage 会计沿用 _find_usage_source
|
|
|
return fc_term
|
|
|
|
|
|
@@ -1025,26 +1087,10 @@ def _compile_react(cfg: Dict, overrides: Dict) -> Term:
|
|
|
ReAct tool calls return strings rather than typed status objects. For
|
|
|
enforceLoop sequence mode, a failed sub-agent call must not satisfy a
|
|
|
cycle requirement just because the tool name appeared in the trace.
|
|
|
+ Delegates to module-level `_observation_failed_text` so the text and FC
|
|
|
+ lanes share one set of failure markers.
|
|
|
"""
|
|
|
- text = (observation or "").lower()
|
|
|
- fail_markers = (
|
|
|
- "[tool_error]",
|
|
|
- "[validation_error]",
|
|
|
- "[subagent ",
|
|
|
- " not found",
|
|
|
- " compile error",
|
|
|
- " timed out",
|
|
|
- " timeout",
|
|
|
- "[claude code error]",
|
|
|
- "[error]",
|
|
|
- "[mcp_error",
|
|
|
- "[mcp_timeout",
|
|
|
- '"status": "fail"',
|
|
|
- '"status":"fail"',
|
|
|
- '"ok": false',
|
|
|
- '"ok":false',
|
|
|
- )
|
|
|
- return any(marker in text for marker in fail_markers)
|
|
|
+ return _observation_failed_text(observation)
|
|
|
|
|
|
# Detect if ClaudeLam supports session persistence (--resume).
|
|
|
#
|