fix(backend): make clarification messages idempotent (#2350) (#2351)

This commit is contained in:
Nan Gao
2026-04-19 16:00:58 +02:00
committed by GitHub
parent 7c87dc5bca
commit f514e35a36
2 changed files with 68 additions and 0 deletions
@@ -3,6 +3,7 @@
import json
import logging
from collections.abc import Callable
from hashlib import sha256
from typing import override
from langchain.agents import AgentState
@@ -36,6 +37,13 @@ class ClarificationMiddleware(AgentMiddleware[ClarificationMiddlewareState]):
state_schema = ClarificationMiddlewareState
def _stable_message_id(self, tool_call_id: str, formatted_message: str) -> str:
"""Build a deterministic message ID so retried clarification calls replace, not append."""
if tool_call_id:
return f"clarification:{tool_call_id}"
digest = sha256(formatted_message.encode("utf-8")).hexdigest()[:16]
return f"clarification:{digest}"
def _is_chinese(self, text: str) -> bool:
"""Check if text contains Chinese characters.
@@ -131,6 +139,7 @@ class ClarificationMiddleware(AgentMiddleware[ClarificationMiddlewareState]):
# Create a ToolMessage with the formatted question
# This will be added to the message history
tool_message = ToolMessage(
id=self._stable_message_id(tool_call_id, formatted_message),
content=formatted_message,
tool_call_id=tool_call_id,
name="ask_clarification",