refactor: share non-stream tool event normalization
Deduplicate allowlist filtering and forced-tool fallback parsing across the OpenAI and Anthropic non-stream bridge paths while preserving existing wire behavior. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -58,6 +58,40 @@ def _tool_event_allowed(
|
||||
return bool(forced_tool_name and tool_name == forced_tool_name)
|
||||
|
||||
|
||||
def _allowed_tool_event(
|
||||
tool: Any,
|
||||
*,
|
||||
tool_config: dict[str, Any] | None,
|
||||
forced_tool_name: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
if not isinstance(tool, dict):
|
||||
return None
|
||||
tool_name = str(tool.get("name") or "")
|
||||
if not _tool_event_allowed(tool_name, tool_config, forced_tool_name=forced_tool_name):
|
||||
return None
|
||||
return tool
|
||||
|
||||
|
||||
def _allowed_tool_events(
|
||||
tool_events: Any,
|
||||
*,
|
||||
tool_config: dict[str, Any] | None,
|
||||
forced_tool_name: str | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
if not isinstance(tool_events, list):
|
||||
return []
|
||||
out: list[dict[str, Any]] = []
|
||||
for item in tool_events:
|
||||
allowed = _allowed_tool_event(
|
||||
item,
|
||||
tool_config=tool_config,
|
||||
forced_tool_name=forced_tool_name,
|
||||
)
|
||||
if allowed is not None:
|
||||
out.append(allowed)
|
||||
return out
|
||||
|
||||
|
||||
def _openai_forced_tool_name(tool_choice: Any) -> str | None:
|
||||
if not isinstance(tool_choice, dict):
|
||||
return None
|
||||
@@ -222,6 +256,21 @@ def _forced_tool_event_from_text(
|
||||
return event
|
||||
|
||||
|
||||
def _forced_tool_fallback_event(
|
||||
text: str,
|
||||
*,
|
||||
forced_tool_name: str | None,
|
||||
tools: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
if not forced_tool_name:
|
||||
return None
|
||||
return _forced_tool_event_from_text(
|
||||
text,
|
||||
forced_tool_name,
|
||||
single_arg_name=_tool_code_single_arg_name(tools, forced_tool_name),
|
||||
)
|
||||
|
||||
|
||||
def _openai_tool_call(tool: dict[str, Any], *, forced_id: str | None = None) -> dict[str, Any]:
|
||||
return {
|
||||
"id": str(tool.get("id") or forced_id or f"call_{uuid.uuid4().hex}"),
|
||||
|
||||
Reference in New Issue
Block a user