feat(skill-evolution): add SkillReviewMiddleware to trigger post-turn review

Implements SkillReviewMiddleware that hooks into after_agent to call
maybe_start_review() as a background task after each agent turn, without
blocking the HTTP response. Exceptions are caught and logged only.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
xuhdandClaude Sonnet 4.6 committed 2026-06-05 13:32:19 +08:00
1 parent ef3ef433c1
commit 0e7a1de4db
2 files changed
+126

No files matched your search

@@ -0,0 +1,56 @@
"""SkillReviewMiddleware — triggers background skill review after each agent turn.
Hooks into ``after_agent``: once the lead agent graph has finished a full turn,
this middleware counts the tool calls made and, if the threshold is met, hands
the conversation messages to the SkillReviewWorker as a background asyncio task.
No blocking I/O or LLM calls happen in-band — the review runs fully in the
background and never delays the HTTP response.
"""
from __future__ import annotations
import logging
from typing import Any, override
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware
from langgraph.runtime import Runtime
from deerflow.config.app_config import get_app_config
from deerflow.skills.review_worker import maybe_start_review
logger = logging.getLogger(__name__)
class SkillReviewMiddlewareState(AgentState):
"""Minimal state schema — only needs ``messages``."""
pass
class SkillReviewMiddleware(AgentMiddleware[SkillReviewMiddlewareState]):
"""Dispatch a background skill review after every substantial agent turn.
'Substantial' is defined by ``skill_evolution.review_worker.min_tool_calls``
(default 3). Turns below the threshold are silently skipped to avoid
wasting LLM tokens on trivial exchanges.
"""
state_schema = SkillReviewMiddlewareState
@override
async def after_agent(self, state: Any, runtime: Runtime) -> None:
"""Fire background review; never raises — failures are logged only."""
try:
app_config = get_app_config()
messages = state.get("messages", []) if hasattr(state, "get") else []
thread_id: str = (
(runtime.config or {})
.get("configurable", {})
.get("thread_id", "")
)
if not thread_id:
return
maybe_start_review(thread_id, messages, app_config)
except Exception:
logger.exception("SkillReviewMiddleware.after_agent: unexpected error (ignored)")