feat(context): improve budget validation and XML safety in ranking and Claude adapter

- Added stricter budget validation in ContextRanker with explicit error handling for invalid configurations.
- Introduced `_get_valid_token_count()` helper to validate and safeguard token counts.
- Enhanced XML escaping in Claude adapter to prevent injection risks from scores and unhandled content.
This commit is contained in:
2026-01-04 16:02:18 +01:00
parent 1628eacf2b
commit 758052dcff
2 changed files with 53 additions and 5 deletions

View File

@@ -90,7 +90,9 @@ class ClaudeAdapter(ModelAdapter):
elif context_type == ContextType.TOOL:
return self._format_tool(contexts)
return "\n".join(c.content for c in contexts)
# Fallback for any unhandled context types - still escape content
# to prevent XML injection if new types are added without updating adapter
return "\n".join(self._escape_xml_content(c.content) for c in contexts)
def _format_system(self, contexts: list[BaseContext]) -> str:
"""Format system contexts."""
@@ -119,7 +121,9 @@ class ClaudeAdapter(ModelAdapter):
score = ctx.metadata.get("score", ctx.metadata.get("relevance_score", ""))
if score:
parts.append(f'<document source="{source}" relevance="{score}">')
# Escape score to prevent XML injection via metadata
escaped_score = self._escape_xml(str(score))
parts.append(f'<document source="{source}" relevance="{escaped_score}">')
else:
parts.append(f'<document source="{source}">')