From fd186eeb0d8941c280878c08d17f918a4e3117ce Mon Sep 17 00:00:00 2001 From: aditya-drizz Date: Thu, 27 Aug 2026 13:42:08 +0530 Subject: [PATCH] feat(llm): reach every provider LiteLLM supports through one adapter The factory could only build Gemini; naming any other provider raised NotImplementedError, so LLMConfiguration's provider field was inert. Adds a gateway adapter rather than one adapter per vendor. LiteLLM already normalises authentication, endpoints and request shape across providers, so the only work left is translating between Fathom's neutral types and the OpenAI-style contract it exposes -- written once, and every provider it supports comes with it. Gemini keeps its native adapter. It is the tuned default and uses provider-specific controls (thinking level, media resolution) that have no gateway equivalent; those are logged as dropped when a gateway run is configured with them, so a quality change is attributable rather than invisible. Four translations carry the weight: prompt parts text and raw image bytes become OpenAI content blocks, with the media type read from the payload's magic bytes history a model turn carrying tool calls becomes an assistant message, its arguments re-encoded as JSON tools declarations are already {name, description, parameters}, so each is wrapped in the tool envelope tool calls the return path, and the one that matters most -- ToolResponseParser reads .name and .args and expects a mapping, while the gateway returns a JSON string That last one reuses FunctionCallPart rather than introducing a type. A call whose arguments will not parse is dropped with a warning instead of raising, so one malformed call cannot discard an otherwise usable response. Cost is deliberately absent from the reported metrics. The gateway prices from its own table, which drifts from the provider invoice most on image and cached tokens -- and every step of a run carries a screenshot. litellm is an optional `gateway` extra, matching the existing per-provider pattern, so installing Fathom for Gemini alone does not pull it in. --- pyproject.toml | 3 + src/fathom/adapters/llm/gateway.py | 453 ++++++++++++++++++ src/fathom/runtime/factories.py | 9 +- .../integration/adapters/llm/test_gateway.py | 396 +++++++++++++++ 4 files changed, 858 insertions(+), 3 deletions(-) create mode 100644 src/fathom/adapters/llm/gateway.py create mode 100644 tests/integration/adapters/llm/test_gateway.py diff --git a/pyproject.toml b/pyproject.toml index 69dc93b7..adfe9275 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -72,6 +72,9 @@ fathom = "fathom.cli:main" gemini = [ "google-generativeai>=0.3.0", ] +gateway = [ + "litellm>=1.49.1", +] temporal = [ "temporalio>=1.0.0", ] diff --git a/src/fathom/adapters/llm/gateway.py b/src/fathom/adapters/llm/gateway.py new file mode 100644 index 00000000..0c5d4fc7 --- /dev/null +++ b/src/fathom/adapters/llm/gateway.py @@ -0,0 +1,453 @@ +from __future__ import annotations + +import asyncio +import json +import random +import time +from logging import getLogger +from typing import Any, Dict, List, Mapping, Optional, Sequence, Union + +from fathom.core.exceptions import VisionError +from fathom.interfaces.llm import LLMPort +from fathom.schemas.configuration import LLMConfiguration +from fathom.schemas.conversation import ConversationTurn +from fathom.schemas.conversation.turns import FunctionCallPart, TurnPart +from fathom.schemas.llm import StructuredOutput +from fathom.schemas.results import GenerateResult + +logger = getLogger(__name__) + + +class GatewayLLM(LLMPort): + """ + Adapter for every provider reachable through the LiteLLM gateway. + + One adapter rather than one per vendor: LiteLLM already normalises + authentication, endpoints and request shape across providers, so the only + work left is translating between Fathom's neutral types and the + OpenAI-style contract LiteLLM exposes. Gemini keeps its own native adapter + because it is the tuned default and uses provider-specific controls + (thinking level, media resolution) that do not survive the gateway. + """ + + __COMPONENT = "adapters.llm.gateway" + + #: Providers whose native controls are dropped when routed through the + #: gateway. Logged once per run so a quality change is attributable + #: rather than invisible. + __LOSSY_FIELDS = ("thinking_level", "include_thoughts", "media_resolution") + + def __init__(self, *, configuration: LLMConfiguration) -> None: + self.__configuration = configuration + self.__client: Optional[Any] = None + self.__initialize() + + @property + def model_name(self) -> str: + """ + The fully qualified model identifier sent to the gateway. + """ + + return self.__qualified_model() + + def derive(self, *, overrides: LLMConfiguration) -> LLMPort: + """ + Build a sibling adapter bound to a different configuration. + """ + + return GatewayLLM(configuration=overrides) + + def __initialize(self) -> None: + """ + Import the gateway lazily and warn about controls it cannot carry. + + The import is deferred so that installing Fathom without the + ``gateway`` extra stays valid for anyone using Gemini alone. + """ + + try: + import litellm + except ImportError as failure: + raise VisionError( + "Provider " + f"'{self.__configuration.provider}' requires the gateway extra. " + "Install fathom[gateway]." + ) from failure + + # Fathom raises its own errors and owns the retry loop below, so the + # gateway must not also retry underneath us or a single logical + # attempt becomes several silent ones. + litellm.drop_params = True + litellm.num_retries = 0 + self.__client = litellm + + dropped = [ + field + for field in self.__LOSSY_FIELDS + if getattr(self.__configuration, field, None) is not None + ] + if dropped: + logger.info( + "Gateway cannot carry provider-specific controls", + extra={ + "component": self.__COMPONENT, + "event": "gateway.controls.dropped", + "llm.model": self.__qualified_model(), + "llm.dropped": dropped, + }, + ) + + def __qualified_model(self) -> str: + """ + Return the model prefixed with its provider. + + LiteLLM routes on a ``provider/model`` identifier. A model that already + carries a prefix is passed through so an explicitly qualified value + (``bedrock/anthropic.claude-...``) is never double-prefixed. + """ + + model = self.__configuration.model + if "/" in model: + return model + return f"{self.__configuration.provider}/{model}" + + @staticmethod + def __detect_mime(*, data: bytes) -> str: + """ + Identify an image payload from its magic bytes. + + Only the formats the capture layer produces are recognised; anything + else falls back to PNG rather than failing, because a wrong media type + degrades the request while a raised error loses the whole step. + """ + + if data.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return "image/png" + if data.startswith(b"RIFF") and data[8:12] == b"WEBP": + return "image/webp" + return "image/png" + + @classmethod + def __image_content(cls, *, data: bytes) -> Dict[str, Any]: + """ + Wrap raw image bytes as an OpenAI-style inline image part. + """ + + import base64 + + encoded = base64.b64encode(data).decode("ascii") + return { + "type": "image_url", + "image_url": {"url": f"data:{cls.__detect_mime(data=data)};base64,{encoded}"}, + } + + @classmethod + def __to_content( + cls, + *, + prompt: Sequence[Union[str, bytes, Dict[str, str]]], + ) -> List[Dict[str, Any]]: + """ + Translate Fathom's prompt parts into OpenAI-style content blocks. + """ + + content: List[Dict[str, Any]] = [] + for item in prompt: + if isinstance(item, bytes): + if not item: + raise VisionError("Received empty image data for analysis") + content.append(cls.__image_content(data=item)) + elif isinstance(item, str): + if item: + content.append({"type": "text", "text": item}) + else: + text = item.get("text", "") + if text: + content.append({"type": "text", "text": text}) + return content + + @classmethod + def __to_message(cls, *, turn: ConversationTurn) -> Dict[str, Any]: + """ + Translate one neutral conversation turn into a gateway message. + + A model turn carrying tool calls becomes an assistant message with + ``tool_calls``; its arguments are re-encoded as JSON because the + OpenAI contract carries them as a string while Fathom holds them as a + mapping. + """ + + role = "assistant" if turn.role == "model" else "user" + content: List[Dict[str, Any]] = [] + calls: List[Dict[str, Any]] = [] + + for index, part in enumerate(turn.parts): + content.extend(cls.__content_for(part=part)) + if part.function_call is not None: + calls.append( + { + "id": f"call_{index}", + "type": "function", + "function": { + "name": part.function_call.name, + "arguments": json.dumps(part.function_call.args), + }, + } + ) + + message: Dict[str, Any] = {"role": role, "content": content} + if calls: + message["tool_calls"] = calls + return message + + @classmethod + def __content_for(cls, *, part: TurnPart) -> List[Dict[str, Any]]: + """ + Translate a single turn part into zero or more content blocks. + """ + + if part.image_data: + return [cls.__image_content(data=part.image_data)] + if part.text: + return [{"type": "text", "text": part.text}] + return [] + + @staticmethod + def __to_tools(*, tools: Optional[Dict[str, Any]]) -> Optional[List[Dict[str, Any]]]: + """ + Translate Fathom's function declarations into the gateway tool schema. + + Declarations are already ``{name, description, parameters}``, so each + one only needs wrapping in the OpenAI envelope. + """ + + if not tools: + return None + declarations = tools.get("function_declarations") + if not declarations: + return None + return [{"type": "function", "function": declaration} for declaration in declarations] + + @staticmethod + def __to_response_format( + *, + structured_output: Optional[StructuredOutput], + ) -> Optional[Dict[str, Any]]: + """ + Translate a structured-output contract into a gateway response format. + """ + + if structured_output is None: + return None + payload = structured_output.payload + return { + "type": "json_schema", + "json_schema": { + "name": payload.__name__, + "schema": payload.model_json_schema(), + "strict": False, + }, + } + + @staticmethod + def __to_tool_calls(*, message: Any) -> List[FunctionCallPart]: + """ + Translate gateway tool calls into Fathom's neutral representation. + + ``ToolResponseParser`` reads ``.name`` and ``.args`` off each call and + expects the arguments as a mapping, while the gateway returns them as + a JSON string. A call whose arguments will not parse is dropped with a + warning rather than raised, so one malformed call cannot discard the + rest of a usable response. + """ + + raw = getattr(message, "tool_calls", None) or [] + calls: List[FunctionCallPart] = [] + + for call in raw: + function = getattr(call, "function", None) + if function is None: + continue + name = getattr(function, "name", None) + if not name: + continue + + arguments = getattr(function, "arguments", None) + if isinstance(arguments, Mapping): + parsed: Dict[str, Any] = dict(arguments) + else: + try: + decoded = json.loads(arguments or "{}") + except (TypeError, ValueError): + logger.warning( + "Gateway returned unparseable tool arguments", + extra={ + "component": GatewayLLM.__COMPONENT, + "event": "gateway.tool.unparseable", + "tool.name": name, + }, + ) + continue + parsed = decoded if isinstance(decoded, dict) else {} + + calls.append(FunctionCallPart(name=name, args=parsed)) + + return calls + + @staticmethod + def __collect_usage_metrics(*, response: Any) -> Dict[str, float]: + """ + Read token counts off a gateway response. + + Cost is deliberately not reported. The gateway prices from its own + table, which drifts from the provider invoice — most on image and + cached tokens, which every step of a run carries. + """ + + usage = getattr(response, "usage", None) + if usage is None: + return {} + + metrics: Dict[str, float] = {} + for source, target in ( + ("prompt_tokens", "prompt_tokens"), + ("completion_tokens", "completion_tokens"), + ("total_tokens", "total_tokens"), + ): + value = getattr(usage, source, None) + if isinstance(value, (int, float)): + metrics[target] = float(value) + return metrics + + async def generate( + self, + *, + use_cache: bool, + prompt: Sequence[Union[str, bytes, Dict[str, str]]], + tools: Optional[Dict[str, Any]] = None, + system_instruction: Optional[str] = None, + structured_output: Optional[StructuredOutput] = None, + conversation_history: Optional[Sequence[ConversationTurn]] = None, + ) -> GenerateResult: + """ + Run one generation through the gateway with bounded retry. + + ``use_cache`` is accepted for interface parity and ignored: context + caching is a Gemini-native feature with no gateway equivalent, so + honouring it here would imply a saving that does not occur. + """ + + if self.__client is None: + raise VisionError("Gateway client not ready") + + if structured_output is not None and tools: + raise VisionError("Structured-output mode cannot be combined with tool calling") + + messages: List[Dict[str, Any]] = [] + if system_instruction: + messages.append({"role": "system", "content": system_instruction}) + if conversation_history: + messages.extend(self.__to_message(turn=turn) for turn in conversation_history) + messages.append({"role": "user", "content": self.__to_content(prompt=prompt)}) + + request: Dict[str, Any] = { + "model": self.__qualified_model(), + "messages": messages, + "timeout": self.__configuration.timeout, + } + if self.__configuration.api_key: + request["api_key"] = self.__configuration.api_key + + translated = self.__to_tools(tools=tools) + if translated: + request["tools"] = translated + + response_format = self.__to_response_format(structured_output=structured_output) + if response_format: + request["response_format"] = response_format + + max_retries = self.__configuration.max_retries + + for attempt in range(max_retries + 1): + started = time.perf_counter() + try: + response = await asyncio.wait_for( + self.__client.acompletion(**request), + timeout=self.__configuration.timeout, + ) + except Exception as failure: + latency = time.perf_counter() - started + logger.warning( + "Gateway request failed", + extra={ + "component": self.__COMPONENT, + "event": "gateway.request.failed", + "llm.model": request["model"], + "llm.attempt": attempt, + "llm.max_retries": max_retries, + "latency": latency, + "error.type": type(failure).__name__, + }, + ) + if attempt >= max_retries: + raise VisionError( + f"Gateway request failed after {max_retries + 1} attempts: {failure}" + ) from failure + + delay = min(2.0**attempt, 8.0) + random.uniform(0.0, 0.5) + await asyncio.sleep(delay) + continue + + latency = time.perf_counter() - started + choices = getattr(response, "choices", None) or [] + if not choices: + raise VisionError("Gateway returned no choices") + + message = choices[0].message + content = getattr(message, "content", None) or "" + calls = self.__to_tool_calls(message=message) + + logger.info( + "Gateway request completed", + extra={ + "component": self.__COMPONENT, + "event": "gateway.request.completed", + "llm.model": request["model"], + "llm.attempt": attempt, + "llm.tool_calls": len(calls), + "latency": latency, + }, + ) + + return GenerateResult( + content=content, + tool_calls=calls, + metrics=self.__collect_usage_metrics(response=response), + ) + + raise VisionError("Gateway retry loop exhausted without a result") + + async def prewarm( + self, + *, + system_instruction: Optional[str], + tools: Optional[Dict[str, Any]] = None, + ) -> None: + """ + No-op. + + Prewarming exists to populate Gemini's context cache. The gateway has + no equivalent, and issuing a throwaway request to imitate one would + cost a call and buy nothing. + """ + + return None + + async def cleanup(self) -> None: + """ + No-op. The gateway holds no client resources of ours to release. + """ + + return None diff --git a/src/fathom/runtime/factories.py b/src/fathom/runtime/factories.py index cd3e3734..c1205217 100644 --- a/src/fathom/runtime/factories.py +++ b/src/fathom/runtime/factories.py @@ -11,6 +11,7 @@ from fathom.adapters.interaction.orm.postgres import ( PostgresInteraction as RepositoryPostgresInteraction, ) +from fathom.adapters.llm.gateway import GatewayLLM from fathom.adapters.llm.gemini import GeminiLLM from fathom.adapters.perception.android import AndroidPerceptionAdapter from fathom.adapters.perception.ios import ( @@ -110,12 +111,14 @@ def create(self, *, configuration: LLMConfiguration) -> LLMPort: Create LLM adapter from runtime LLM configuration. """ + # Gemini keeps its native adapter: it is the tuned default and uses + # provider-specific controls that do not survive the gateway. Every + # other provider routes through LiteLLM, so adding one is a + # configuration change rather than a new adapter. if configuration.provider == "gemini": return GeminiLLM(configuration=configuration) - raise NotImplementedError( - f"LLM adapter for provider {configuration.provider} is not implemented" - ) + return GatewayLLM(configuration=configuration) class PerceptionFactory(PerceptionFactoryPort): diff --git a/tests/integration/adapters/llm/test_gateway.py b/tests/integration/adapters/llm/test_gateway.py new file mode 100644 index 00000000..49fe7171 --- /dev/null +++ b/tests/integration/adapters/llm/test_gateway.py @@ -0,0 +1,396 @@ +from __future__ import annotations + +import json +import unittest +from types import SimpleNamespace +from typing import Any, Dict, List, Optional +from unittest.mock import AsyncMock, patch + +from fathom.adapters.llm.gateway import GatewayLLM +from fathom.core.exceptions import VisionError +from fathom.schemas.configuration import LLMConfiguration +from fathom.schemas.conversation.turns import ConversationTurn, TurnPart + +PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 8 +JPEG = b"\xff\xd8\xff" + b"\x00" * 8 + + +def _response( + *, + content: str = "", + tool_calls: Optional[List[Any]] = None, + usage: Optional[Any] = None, +) -> SimpleNamespace: + """ + Build a gateway response double shaped like the OpenAI contract. + """ + + message = SimpleNamespace(content=content, tool_calls=tool_calls) + return SimpleNamespace(choices=[SimpleNamespace(message=message)], usage=usage) + + +def _call(*, name: str, arguments: Any) -> SimpleNamespace: + """ + Build a gateway tool-call double. + """ + + return SimpleNamespace( + id="call_0", + type="function", + function=SimpleNamespace(name=name, arguments=arguments), + ) + + +class GatewayAdapterTest(unittest.IsolatedAsyncioTestCase): + """ + Translation between Fathom's neutral types and the gateway contract. + """ + + def setUp(self) -> None: + self.configuration = LLMConfiguration( + provider="anthropic", + model="claude-sonnet-5", + max_retries=2, + ) + + def __adapter(self, *, configuration: Optional[LLMConfiguration] = None) -> GatewayLLM: + """ + Build an adapter with the gateway import stubbed out. + """ + + with patch.dict("sys.modules", {"litellm": SimpleNamespace()}): + return GatewayLLM(configuration=configuration or self.configuration) + + async def __generate(self, *, adapter: GatewayLLM, outcome: Any, **kwargs: Any) -> Any: + """ + Run one generation against a recorded gateway double. + """ + + completion = AsyncMock( + side_effect=outcome if isinstance(outcome, list) else [outcome] + ) + adapter._GatewayLLM__client = SimpleNamespace(acompletion=completion) # type: ignore[attr-defined] + result = await adapter.generate(use_cache=False, **kwargs) + return result, completion + + # -- model identity ---------------------------------------------------- + + def test_model_is_qualified_with_its_provider(self) -> None: + """LiteLLM routes on a provider/model identifier.""" + + self.assertEqual(self.__adapter().model_name, "anthropic/claude-sonnet-5") + + def test_an_already_qualified_model_is_not_double_prefixed(self) -> None: + """An explicitly routed model must pass through untouched.""" + + adapter = self.__adapter( + configuration=LLMConfiguration( + provider="anthropic", + model="bedrock/anthropic.claude-v2", + ) + ) + + self.assertEqual(adapter.model_name, "bedrock/anthropic.claude-v2") + + # -- prompt translation ------------------------------------------------ + + async def test_text_and_images_become_content_blocks(self) -> None: + adapter = self.__adapter() + + _, completion = await self.__generate( + adapter=adapter, + outcome=_response(content="ok"), + prompt=["look at this", PNG, JPEG], + ) + + content = completion.await_args.kwargs["messages"][-1]["content"] + + self.assertEqual(content[0], {"type": "text", "text": "look at this"}) + self.assertTrue(content[1]["image_url"]["url"].startswith("data:image/png;base64,")) + self.assertTrue(content[2]["image_url"]["url"].startswith("data:image/jpeg;base64,")) + + async def test_an_empty_image_is_rejected(self) -> None: + """ + An empty capture is a bug upstream; sending it would earn a confusing + provider error instead of naming the real problem. + """ + + adapter = self.__adapter() + adapter._GatewayLLM__client = SimpleNamespace(acompletion=AsyncMock()) # type: ignore[attr-defined] + + with self.assertRaises(VisionError): + await adapter.generate(use_cache=False, prompt=[b""]) + + async def test_system_instruction_leads_the_messages(self) -> None: + adapter = self.__adapter() + + _, completion = await self.__generate( + adapter=adapter, + outcome=_response(content="ok"), + prompt=["go"], + system_instruction="be precise", + ) + + messages = completion.await_args.kwargs["messages"] + + self.assertEqual(messages[0], {"role": "system", "content": "be precise"}) + + async def test_history_is_translated_with_model_mapped_to_assistant(self) -> None: + adapter = self.__adapter() + history = [ + ConversationTurn(role="user", parts=[TurnPart.from_text("first")]), + ConversationTurn( + role="model", + parts=[TurnPart.from_function_call(name="execute_ui", args={"label_id": "4"})], + ), + ] + + _, completion = await self.__generate( + adapter=adapter, + outcome=_response(content="ok"), + prompt=["next"], + conversation_history=history, + ) + + messages = completion.await_args.kwargs["messages"] + + self.assertEqual(messages[0]["role"], "user") + self.assertEqual(messages[1]["role"], "assistant") + # Arguments cross the wire as a JSON string, not a mapping. + self.assertEqual( + json.loads(messages[1]["tool_calls"][0]["function"]["arguments"]), + {"label_id": "4"}, + ) + + # -- tool translation -------------------------------------------------- + + async def test_declarations_are_wrapped_in_the_tool_envelope(self) -> None: + adapter = self.__adapter() + declaration: Dict[str, Any] = { + "name": "execute_ui", + "description": "do a thing", + "parameters": {"type": "object", "properties": {}}, + } + + _, completion = await self.__generate( + adapter=adapter, + outcome=_response(content="ok"), + prompt=["go"], + tools={"function_declarations": [declaration]}, + ) + + self.assertEqual( + completion.await_args.kwargs["tools"], + [{"type": "function", "function": declaration}], + ) + + async def test_no_tools_key_when_none_are_declared(self) -> None: + adapter = self.__adapter() + + _, completion = await self.__generate( + adapter=adapter, + outcome=_response(content="ok"), + prompt=["go"], + tools={"function_declarations": []}, + ) + + self.assertNotIn("tools", completion.await_args.kwargs) + + # -- tool-call translation (the join ToolResponseParser depends on) ---- + + async def test_tool_calls_expose_name_and_parsed_args(self) -> None: + """ + ToolResponseParser reads `.name` and `.args` and expects a mapping, + while the gateway returns arguments as a JSON string. + """ + + adapter = self.__adapter() + + result, _ = await self.__generate( + adapter=adapter, + outcome=_response( + tool_calls=[_call(name="execute_ui", arguments='{"label_id": "7"}')] + ), + prompt=["go"], + ) + + self.assertEqual(len(result.tool_calls), 1) + self.assertEqual(result.tool_calls[0].name, "execute_ui") + self.assertEqual(result.tool_calls[0].args, {"label_id": "7"}) + + async def test_a_mapping_argument_is_accepted_unchanged(self) -> None: + """Some providers hand back a decoded mapping already.""" + + adapter = self.__adapter() + + result, _ = await self.__generate( + adapter=adapter, + outcome=_response(tool_calls=[_call(name="execute_ui", arguments={"label_id": "7"})]), + prompt=["go"], + ) + + self.assertEqual(result.tool_calls[0].args, {"label_id": "7"}) + + async def test_one_unparseable_call_does_not_discard_the_others(self) -> None: + """ + A malformed call is dropped, not raised — losing the whole response + would turn one bad call into a failed step. + """ + + adapter = self.__adapter() + + result, _ = await self.__generate( + adapter=adapter, + outcome=_response( + tool_calls=[ + _call(name="broken", arguments="{not json"), + _call(name="execute_ui", arguments='{"label_id": "7"}'), + ] + ), + prompt=["go"], + ) + + self.assertEqual([call.name for call in result.tool_calls], ["execute_ui"]) + + async def test_a_nameless_call_is_dropped(self) -> None: + adapter = self.__adapter() + + result, _ = await self.__generate( + adapter=adapter, + outcome=_response(tool_calls=[_call(name="", arguments="{}")]), + prompt=["go"], + ) + + self.assertEqual(result.tool_calls, []) + + # -- structured output ------------------------------------------------- + + async def test_structured_output_and_tools_cannot_be_combined(self) -> None: + from fathom.schemas.llm import StructuredOutput + from pydantic import BaseModel + + class Payload(BaseModel): + verdict: str + + adapter = self.__adapter() + adapter._GatewayLLM__client = SimpleNamespace(acompletion=AsyncMock()) # type: ignore[attr-defined] + + with self.assertRaises(VisionError): + await adapter.generate( + use_cache=False, + prompt=["go"], + tools={"function_declarations": [{"name": "x"}]}, + structured_output=StructuredOutput(payload=Payload), + ) + + # -- results and metrics ----------------------------------------------- + + async def test_usage_is_reported_without_a_cost_figure(self) -> None: + """ + The gateway prices from its own table, which drifts from the provider + invoice most on image tokens — which every step carries. + """ + + adapter = self.__adapter() + + result, _ = await self.__generate( + adapter=adapter, + outcome=_response( + content="ok", + usage=SimpleNamespace(prompt_tokens=10, completion_tokens=4, total_tokens=14), + ), + prompt=["go"], + ) + + self.assertEqual(result.metrics["total_tokens"], 14.0) + self.assertNotIn("cost", result.metrics) + + async def test_a_response_without_choices_is_rejected(self) -> None: + adapter = self.__adapter() + adapter._GatewayLLM__client = SimpleNamespace( # type: ignore[attr-defined] + acompletion=AsyncMock(return_value=SimpleNamespace(choices=[])) + ) + + with self.assertRaises(VisionError): + await adapter.generate(use_cache=False, prompt=["go"]) + + # -- retry ------------------------------------------------------------- + + async def test_a_transient_failure_is_retried_then_succeeds(self) -> None: + adapter = self.__adapter() + + with patch("asyncio.sleep", new=AsyncMock()): + result, completion = await self.__generate( + adapter=adapter, + outcome=[RuntimeError("boom"), _response(content="recovered")], + prompt=["go"], + ) + + self.assertEqual(result.content, "recovered") + self.assertEqual(completion.await_count, 2) + + async def test_retries_are_bounded_by_the_configuration(self) -> None: + adapter = self.__adapter() + completion = AsyncMock(side_effect=RuntimeError("boom")) + adapter._GatewayLLM__client = SimpleNamespace(acompletion=completion) # type: ignore[attr-defined] + + with patch("asyncio.sleep", new=AsyncMock()): + with self.assertRaises(VisionError): + await adapter.generate(use_cache=False, prompt=["go"]) + + # max_retries=2 means three attempts in total. + self.assertEqual(completion.await_count, 3) + + # -- key handling ------------------------------------------------------ + + async def test_a_configured_key_is_forwarded(self) -> None: + adapter = self.__adapter( + configuration=LLMConfiguration( + provider="anthropic", + model="claude-sonnet-5", + api_key="sk-test", + ) + ) + + _, completion = await self.__generate( + adapter=adapter, outcome=_response(content="ok"), prompt=["go"] + ) + + self.assertEqual(completion.await_args.kwargs["api_key"], "sk-test") + + async def test_no_key_is_sent_when_none_is_configured(self) -> None: + """ + Omitting it lets the gateway read the ambient provider environment, + which is how the Gemini path already gets its credentials. + """ + + adapter = self.__adapter() + + _, completion = await self.__generate( + adapter=adapter, outcome=_response(content="ok"), prompt=["go"] + ) + + self.assertNotIn("api_key", completion.await_args.kwargs) + + # -- lifecycle --------------------------------------------------------- + + async def test_prewarm_and_cleanup_are_no_ops(self) -> None: + adapter = self.__adapter() + + self.assertIsNone(await adapter.prewarm(system_instruction="x")) + self.assertIsNone(await adapter.cleanup()) + + def test_derive_returns_a_sibling_bound_to_the_overrides(self) -> None: + adapter = self.__adapter() + + with patch.dict("sys.modules", {"litellm": SimpleNamespace()}): + derived = adapter.derive( + overrides=LLMConfiguration(provider="openai", model="gpt-5.2") + ) + + self.assertIsInstance(derived, GatewayLLM) + self.assertEqual(derived.model_name, "openai/gpt-5.2") + + +if __name__ == "__main__": + unittest.main()