From 0e3aac39e591a8e5278cf7b73cdda59802137c0b Mon Sep 17 00:00:00 2001 From: Sakib Khan Date: Mon, 24 Aug 2026 18:41:36 +0530 Subject: [PATCH] feat: add OpenAI provider support Signed-off-by: Sakib Khan --- pyproject.toml | 1 + requirements.txt | 1 + src/fathom/adapters/interaction/noop.py | 114 +++- src/fathom/adapters/llm/openai.py | 398 ++++++++++++ src/fathom/adapters/localization/__init__.py | 3 +- .../adapters/localization/gemini/vision.py | 355 +---------- src/fathom/adapters/localization/vision.py | 390 ++++++++++++ src/fathom/adapters/tools/__init__.py | 3 +- src/fathom/adapters/tools/openai.py | 50 ++ src/fathom/base/logger.py | 12 +- src/fathom/core/prompts/factory.py | 96 +-- src/fathom/core/prompts/openai.py | 23 + src/fathom/core/prompts/tools.py | 44 +- src/fathom/core/services/decomposer.py | 5 +- src/fathom/core/services/vision.py | 9 +- src/fathom/runtime/adapters.py | 16 +- src/fathom/runtime/assembly.py | 55 +- src/fathom/runtime/command/application.py | 17 +- src/fathom/runtime/factories.py | 4 + src/fathom/settings/env.py | 12 +- tests/unit/adapters/llm/test_openai.py | 273 +++++++++ .../localization/gemini/test_vision.py | 567 ++---------------- tests/unit/adapters/tools/test_gemini.py | 6 +- tests/unit/adapters/tools/test_openai.py | 34 ++ tests/unit/core/config/test_loader.py | 4 +- tests/unit/core/prompts/test_factory.py | 36 ++ tests/unit/core/prompts/test_tools_schema.py | 11 + tests/unit/runtime/test_adapters.py | 75 ++- tests/unit/runtime/test_assembly.py | 34 ++ 29 files changed, 1659 insertions(+), 989 deletions(-) create mode 100644 src/fathom/adapters/llm/openai.py create mode 100644 src/fathom/adapters/localization/vision.py create mode 100644 src/fathom/adapters/tools/openai.py create mode 100644 src/fathom/core/prompts/openai.py create mode 100644 tests/unit/adapters/llm/test_openai.py create mode 100644 tests/unit/adapters/tools/test_openai.py create mode 100644 tests/unit/core/prompts/test_factory.py diff --git a/pyproject.toml b/pyproject.toml index 69dc93b7..e39b8cf3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -53,6 +53,7 @@ dependencies = [ "structlog>=23.0.0", "google-auth>=2.0.0", "google-genai>=2.10.0", + "openai>=1.0.0", "python-dotenv>=1.0.0", "pydantic-settings>=2.0.0", "opencv-python>=4.13.0.92", diff --git a/requirements.txt b/requirements.txt index debbc325..ee524c5f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -16,6 +16,7 @@ structlog>=23.0.0 google-auth>=2.0.0 python-dotenv>=1.0.0 google-genai>=2.10.0 +openai>=1.0.0 google-cloud-storage>=2.0.0 google-cloud-documentai>=2.20.0 types-PyYAML>=6.0.12.20250915 diff --git a/src/fathom/adapters/interaction/noop.py b/src/fathom/adapters/interaction/noop.py index 646bfd20..16ae2121 100644 --- a/src/fathom/adapters/interaction/noop.py +++ b/src/fathom/adapters/interaction/noop.py @@ -1,7 +1,7 @@ from __future__ import annotations from contextlib import asynccontextmanager -from typing import AsyncGenerator, List, Optional +from typing import AsyncGenerator, Dict, List, Optional from fathom.constants.collaboration import ( IdempotencyState, @@ -89,6 +89,14 @@ class NoopInteraction(InteractionPort): absorbs without crashing the run. Reads return None or empty collections. """ + def __init__(self) -> None: + """Initialize ephemeral task state for the current local run.""" + + self.__executions: Dict[str, Execution] = {} + self.__idempotency: Dict[str, Idempotency] = {} + self.__jobs: Dict[str, Job] = {} + self.__tasks: Dict[str, Task] = {} + async def initialize(self) -> None: """ Realize adapter state. Noop adapter holds no schema or pool. @@ -168,7 +176,7 @@ async def open_task(self, *, request: OpenTask) -> Task: Echo a Task shaped from the request without persisting. """ - return Task( + task = Task( kind=request.kind, plan=request.plan, state=request.state, @@ -180,13 +188,15 @@ async def open_task(self, *, request: OpenTask) -> Task: assignment=request.assignment, timing=Timing(created_at=request.created, updated_at=request.created), ) + self.__tasks[task.identity.id] = task + return task async def start_execution(self, *, request: StartExecution) -> Execution: """ Echo an Execution shaped from the request without persisting. """ - return Execution( + execution = Execution( outcome=Metadata(), state=request.state, thread=request.thread, @@ -199,15 +209,33 @@ async def start_execution(self, *, request: StartExecution) -> Execution: started_at=request.started, ), ) + self.__executions[execution.identity.id] = execution + return execution async def finish_execution(self, *, request: FinishExecution) -> Execution: """ - Finishing an execution requires prior state; not supported without storage. - """ - - _ = request - - raise InteractionError("Finish execution requires durable storage; noop is not supported") + Finish an ephemeral execution so local runs can terminate cleanly. + """ + + execution = self.__executions.get(request.execution) + if execution is None: + raise InteractionError( + f"Execution {request.execution} was not opened in this noop session" + ) + + finished = execution.model_copy( + update={ + "state": request.state, + "terminal": request.terminal, + "summary": request.summary, + "outcome": request.outcome, + "timing": execution.timing.model_copy( + update={"updated_at": request.completed, "ended_at": request.completed} + ), + } + ) + self.__executions[request.execution] = finished + return finished async def get_execution(self, *, query: ExecutionQuery) -> Optional[Execution]: """ @@ -248,12 +276,29 @@ async def sanitize_message(self, *, request: Sanitize) -> Message: async def finish_task(self, *, request: FinishTask) -> Task: """ - Finishing requires the prior task; not supported without state. - """ - - _ = request - - raise InteractionError("Finish task requires durable storage; noop is not supported") + Finish an ephemeral task so local runs can terminate cleanly. + """ + + task = self.__tasks.get(request.task) + if task is None: + raise InteractionError(f"Task {request.task} was not opened in this noop session") + + finished = task.model_copy( + update={ + "state": request.state, + "terminal": request.terminal, + "summary": request.summary, + "timing": task.timing.model_copy( + update={ + "updated_at": request.ended, + "ended_at": request.ended, + "elapsed": request.elapsed, + } + ), + } + ) + self.__tasks[request.task] = finished + return finished async def get_thread(self, *, query: ThreadQuery) -> Optional[Thread]: """ @@ -509,7 +554,7 @@ async def schedule_job(self, *, request: ScheduleJob) -> Job: Echo a pending Job shaped from the request without persisting. """ - return Job( + job = Job( attempts=0, task=request.task, kind=request.kind, @@ -521,6 +566,8 @@ async def schedule_job(self, *, request: ScheduleJob) -> Job: available_at=request.available, timing=Timing(created_at=request.created, updated_at=request.created), ) + self.__jobs[job.identity.id] = job + return job async def claim_job(self, *, request: ClaimJob) -> Optional[Job]: """ @@ -533,12 +580,25 @@ async def claim_job(self, *, request: ClaimJob) -> Optional[Job]: async def finish_job(self, *, request: FinishJob) -> Job: """ - Finishing requires the prior job; not supported without state. + Finish an ephemeral job so local runs can terminate cleanly. """ - _ = request + job = self.__jobs.get(request.job) + if job is None: + raise InteractionError(f"Job {request.job} was not scheduled in this noop session") - raise InteractionError("Finish job requires durable storage; noop is not supported") + finished = job.model_copy( + update={ + "state": request.state, + "owner": request.owner, + "outcome": request.outcome, + "timing": job.timing.model_copy( + update={"updated_at": request.finished, "ended_at": request.finished} + ), + } + ) + self.__jobs[request.job] = finished + return finished async def recover_jobs(self, *, request: RecoverJob) -> List[Job]: """ @@ -572,7 +632,7 @@ async def begin_request(self, *, request: BeginRequest) -> Idempotency: Echo an active Idempotency record without persisting. """ - return Idempotency( + record = Idempotency( key=request.key, hash=request.hash, tenant=request.tenant, @@ -581,15 +641,23 @@ async def begin_request(self, *, request: BeginRequest) -> Idempotency: metadata=request.metadata, state=IdempotencyState.STARTED, ) + self.__idempotency[request.key] = record + return record async def finish_request(self, *, request: FinishRequest) -> Idempotency: """ - Finishing requires the prior idempotency record; not supported. + Finish an ephemeral idempotency record so local runs can terminate cleanly. """ - _ = request + record = self.__idempotency.get(request.key) + if record is None: + raise InteractionError( + f"Idempotency key {request.key} was not started in this noop session" + ) - raise InteractionError("Finish request requires durable storage; noop is not supported") + finished = record.model_copy(update={"state": request.state, "response": request.response}) + self.__idempotency[request.key] = finished + return finished async def get_idempotency(self, *, query: IdempotencyQuery) -> Optional[Idempotency]: """ diff --git a/src/fathom/adapters/llm/openai.py b/src/fathom/adapters/llm/openai.py new file mode 100644 index 00000000..da47988d --- /dev/null +++ b/src/fathom/adapters/llm/openai.py @@ -0,0 +1,398 @@ +from __future__ import annotations + +import asyncio +import base64 +import json +import time +from logging import getLogger +from typing import Any, Dict, List, Optional, Sequence, cast + +from pydantic import BaseModel, ConfigDict, Field + +from fathom.adapters.tools import OpenAIToolDialect +from fathom.constants.llm import ModelProvider +from fathom.core.exceptions import VisionError +from fathom.interfaces.llm import LLMPort, PromptPart +from fathom.interfaces.tools import CanonicalToolPayload +from fathom.schemas.configuration import LLMConfiguration +from fathom.schemas.conversation import ConversationTurn, TurnPart +from fathom.schemas.llm import InferenceSettings, ModelIdentity, StructuredOutput +from fathom.schemas.results import GenerateResult + +logger = getLogger(__name__) + + +class OpenAIToolCall(BaseModel): + """ + Provider-neutral tool-call shape consumed by Fathom's existing parser. + """ + + model_config = ConfigDict(frozen=True) + + name: str = Field(description="Canonical tool name returned by OpenAI.") + args: Dict[str, Any] = Field(description="Decoded JSON arguments supplied to the tool.") + + +class OpenAILLM(LLMPort): + """ + OpenAI adapter for Fathom's provider-neutral language-model port. + + The SDK import is lazy so Gemini-only installations can still import Fathom. Selecting the + OpenAI provider produces a clear setup error when the optional dependency is absent. + """ + + def __init__(self, *, configuration: LLMConfiguration) -> None: + """ + Bind configuration and construct the async OpenAI client. + """ + + self.__configuration = configuration + + try: + from openai import AsyncOpenAI + except ImportError as exception: + raise VisionError( + "OpenAI support requires the 'openai' package; install Fathom with OpenAI support" + ) from exception + + if not self.__configuration.api_key: + raise VisionError("OpenAI initialization failed: missing API key") + + self.__client = AsyncOpenAI( + api_key=self.__configuration.api_key, + timeout=self.__configuration.timeout, + max_retries=0, + ) + self.__dialect = OpenAIToolDialect() + + @property + def model_name(self) -> str: + """ + Name of the OpenAI model being used. + """ + + return self.__configuration.model + + @property + def identity(self) -> ModelIdentity: + """ + Declare the configured OpenAI model and comparable inference settings. + """ + + return ModelIdentity( + provider=ModelProvider.OPENAI, + model=self.__configuration.model, + settings=InferenceSettings( + cache=None, + temperature=( + None if self.__is_reasoning_model else self.__configuration.temperature + ), + ), + ) + + def derive(self, *, overrides: LLMConfiguration) -> LLMPort: + """ + Create a sibling adapter with explicit role overrides and shared API credentials. + """ + + return OpenAILLM( + configuration=self.__configuration.model_copy( + update=overrides.model_dump(exclude_unset=True) + ) + ) + + async def generate( + self, + *, + use_cache: bool, + prompt: Sequence[PromptPart], + tools: Optional[Dict[str, Any]] = None, + system_instruction: Optional[str] = None, + conversation_history: Optional[Sequence[ConversationTurn]] = None, + structured_output: Optional[StructuredOutput] = None, + ) -> GenerateResult: + """ + Generate one response and normalize OpenAI output into Fathom's result contract. + """ + + _ = use_cache # OpenAI prompt caching is provider-managed and has no local prewarm call. + + if structured_output is not None and tools: + raise VisionError("Structured-output mode cannot be combined with tool calling") + + messages = self.__messages( + prompt=prompt, + system_instruction=system_instruction, + conversation_history=conversation_history, + ) + request: Dict[str, Any] = { + "model": self.__configuration.model, + "messages": messages, + } + + # GPT-5 reasoning models reject the legacy sampling parameter. Keep + # temperature for older/non-reasoning models, while allowing GPT-5.2 + # (and its dated/role variants) to use the provider default reasoning + # configuration. + if not self.__is_reasoning_model: + request["temperature"] = self.__configuration.temperature + + if tools: + request.update(self.__dialect.encode(payload=self.__canonical_tools(tools=tools))) + request["tool_choice"] = "required" + + if structured_output is not None: + request["response_format"] = { + "type": "json_schema", + "json_schema": { + "name": structured_output.payload.__name__.lower(), + "strict": True, + "schema": self.__openai_schema( + schema=structured_output.payload.model_json_schema() + ), + }, + } + + last_exception: Optional[Exception] = None + for attempt in range(self.__configuration.max_retries + 1): + started = time.perf_counter() + try: + response = await asyncio.wait_for( + self.__client.chat.completions.create(**request), + timeout=self.__configuration.timeout, + ) + latency = time.perf_counter() - started + choice = response.choices[0].message + tool_calls = [ + self.__normalize_tool_call(call=call) for call in (choice.tool_calls or []) + ] + usage = getattr(response, "usage", None) + + return GenerateResult( + content=choice.content or "", + tool_calls=tool_calls, + metrics=self.__usage_metrics(usage=usage, latency=latency), + ) + except asyncio.CancelledError: + raise + except Exception as exception: + last_exception = exception + if attempt >= self.__configuration.max_retries: + break + await asyncio.sleep(self.__configuration.retry_delay * (2**attempt)) + + raise VisionError(f"OpenAI generation failed: {last_exception}") from last_exception + + @property + def __is_reasoning_model(self) -> bool: + """ + Return whether this model uses OpenAI's reasoning-model request semantics. + """ + + model = self.__configuration.model.lower() + return model.startswith("gpt-5") or model.startswith(("o1", "o3", "o4")) + + @classmethod + def __openai_schema(cls, *, schema: Dict[str, Any]) -> Dict[str, Any]: + """ + Convert Pydantic JSON Schema into OpenAI strict Structured Outputs schema. + + OpenAI's strict subset does not accept several validation-only Pydantic + keywords, and every object property must be required. Optional values + are represented as required nullable properties so the response can + still be validated by the original Pydantic model. + """ + + unsupported = { + "default", + "exclusiveMaximum", + "exclusiveMinimum", + "format", + "maxItems", + "maxLength", + "maximum", + "minItems", + "minLength", + "minimum", + "pattern", + "title", + "uniqueItems", + } + + def transform(value: Any) -> Any: + if isinstance(value, list): + return [transform(item) for item in value] + if not isinstance(value, dict): + return value + + result = { + key: transform(item) + for key, item in value.items() + if key not in unsupported and key != "const" + } + + # OpenAI requires a $ref node to contain no sibling keywords, + # while Pydantic emits descriptions beside references. + if "$ref" in result: + return {"$ref": result["$ref"]} + + if "const" in value: + result["enum"] = [value["const"]] + + properties = result.get("properties") + if isinstance(properties, dict): + original_required = set(result.get("required", [])) + required = [] + for name, property_schema in properties.items(): + required.append(name) + if name not in original_required: + original_property = value["properties"][name] + if original_property.get("default") is None: + properties[name] = cls.__nullable_schema(schema=property_schema) + result["required"] = required + result["additionalProperties"] = False + + return result + + return cast("Dict[str, Any]", transform(schema)) + + @staticmethod + def __nullable_schema(*, schema: Dict[str, Any]) -> Dict[str, Any]: + """ + Add nullability without disturbing an existing nullable union. + """ + + if schema.get("type") == "null": + return schema + if any( + item.get("type") == "null" for item in schema.get("anyOf", []) if isinstance(item, dict) + ): + return schema + return {"anyOf": [schema, {"type": "null"}]} + + async def cleanup(self) -> None: + """ + Close the OpenAI async client transport. + """ + + await self.__client.close() + + @staticmethod + def __canonical_tools(*, tools: Dict[str, Any]) -> CanonicalToolPayload: + """ + Accept canonical tools and translate the old Gemini envelope during migration. + """ + + if "tools" in tools: + return {"tools": list(tools.get("tools", []))} + + return {"tools": list(tools.get("function_declarations", []))} + + @classmethod + def __messages( + cls, + *, + prompt: Sequence[PromptPart], + system_instruction: Optional[str], + conversation_history: Optional[Sequence[ConversationTurn]], + ) -> List[Dict[str, Any]]: + """ + Convert Fathom turns and multimodal prompt parts into Chat Completions messages. + """ + + messages: List[Dict[str, Any]] = [] + if system_instruction: + messages.append({"role": "system", "content": system_instruction}) + + for turn in conversation_history or (): + messages.append( + { + "role": "assistant" if turn.role == "model" else "user", + "content": cls.__parts(parts=turn.parts), + } + ) + + messages.append({"role": "user", "content": cls.__parts(parts=prompt)}) + return messages + + @classmethod + def __parts(cls, *, parts: Sequence[Any]) -> Any: + """ + Encode text and raw image bytes as OpenAI message content parts. + """ + + encoded: List[Dict[str, Any]] = [] + for part in parts: + if isinstance(part, bytes): + encoded.append( + { + "type": "image_url", + "image_url": { + "url": f"data:image/png;base64,{base64.b64encode(part).decode('ascii')}" + }, + } + ) + elif isinstance(part, str): + encoded.append({"type": "text", "text": part}) + elif isinstance(part, TurnPart): + if part.text is not None: + encoded.append({"type": "text", "text": part.text}) + elif part.image_data is not None: + mime = part.mime_type or "image/png" + encoded.append( + { + "type": "image_url", + "image_url": { + "url": f"data:{mime};base64,{base64.b64encode(part.image_data).decode('ascii')}" + }, + } + ) + elif part.function_call is not None: + encoded.append( + { + "type": "text", + "text": json.dumps( + { + "tool": part.function_call.name, + "arguments": part.function_call.args, + } + ), + } + ) + elif isinstance(part, dict): + encoded.append({"type": "text", "text": str(part.get("text", part))}) + + return encoded + + @staticmethod + def __normalize_tool_call(*, call: Any) -> OpenAIToolCall: + """ + Normalize an OpenAI function call to the attributes expected by ToolResponseParser. + """ + + try: + arguments = json.loads(call.function.arguments or "{}") + except (TypeError, ValueError) as exception: + raise VisionError(f"OpenAI returned invalid tool arguments: {exception}") from exception + + if not isinstance(arguments, dict): + raise VisionError("OpenAI returned tool arguments that are not a JSON object") + + return OpenAIToolCall(name=call.function.name, args=arguments) + + @staticmethod + def __usage_metrics(*, usage: Any, latency: float) -> Dict[str, float]: + """ + Normalize OpenAI usage counters into Fathom metrics. + """ + + prompt_tokens = float(getattr(usage, "prompt_tokens", 0) or 0) + completion_tokens = float(getattr(usage, "completion_tokens", 0) or 0) + cached = getattr(getattr(usage, "prompt_tokens_details", None), "cached_tokens", 0) or 0 + return { + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens, + "cached_tokens": float(cached), + "total_tokens": prompt_tokens + completion_tokens, + "latency_seconds": latency, + } diff --git a/src/fathom/adapters/localization/__init__.py b/src/fathom/adapters/localization/__init__.py index 83eaa2cb..3439ee71 100644 --- a/src/fathom/adapters/localization/__init__.py +++ b/src/fathom/adapters/localization/__init__.py @@ -2,5 +2,6 @@ from fathom.adapters.localization.document import DocumentAiLayoutLocalizer from fathom.adapters.localization.gemini import GeminiVisionLocalizer +from fathom.adapters.localization.vision import VisionLLMLocalizer -__all__ = ["DocumentAiLayoutLocalizer", "GeminiVisionLocalizer"] +__all__ = ["DocumentAiLayoutLocalizer", "GeminiVisionLocalizer", "VisionLLMLocalizer"] diff --git a/src/fathom/adapters/localization/gemini/vision.py b/src/fathom/adapters/localization/gemini/vision.py index 28d6613f..d1e9ccfa 100644 --- a/src/fathom/adapters/localization/gemini/vision.py +++ b/src/fathom/adapters/localization/gemini/vision.py @@ -1,358 +1,19 @@ from __future__ import annotations -import asyncio -import io -from logging import getLogger -from typing import Any, Dict, Optional, Tuple +from fathom.adapters.localization.vision import VisionLLMLocalizer -from PIL import Image -from pydantic import ValidationError -from tenacity import ( - AsyncRetrying, - retry_if_exception_type, - stop_after_attempt, - wait_exponential, -) -from fathom.constants.localization import LocalizationGridScale -from fathom.constants.runtime import MILLISECONDS_PER_SECOND -from fathom.core.prompts.localization import VisionLocalizationPrompt -from fathom.interfaces.llm import LLMPort -from fathom.interfaces.localization import TargetLocalizerPort -from fathom.schemas.actions import Action, Bounds, CoordinateSource, CoordinateSystem -from fathom.schemas.budgets import LocalizationBudget -from fathom.schemas.llm import StructuredOutput -from fathom.schemas.localization import ( - LocalizationProposal, - VisionLocalizationConfiguration, - VisionLocalizationPayload, -) -from fathom.schemas.observation import ScreenObservation -from fathom.schemas.screens import ScreenCapture - -logger = getLogger(__name__) - - -class GeminiVisionLocalizer(TargetLocalizerPort): +class GeminiVisionLocalizer(VisionLLMLocalizer): """ - Ensemble member that asks Gemini for a normalized bounding rectangle. - """ - - def __init__( - self, - *, - llm: LLMPort, - workflow_id: Optional[str] = None, - prompt: Optional[VisionLocalizationPrompt] = None, - configuration: Optional[VisionLocalizationConfiguration] = None, - ) -> None: - """ - Initialize the member with its LLM port, prompt builder, timeout + retry policy, and run context. - """ + Backward-compatible import for the former Gemini-named localizer. - self.__llm = llm - self.__workflow_id = workflow_id - self.__prompt = prompt if prompt is not None else VisionLocalizationPrompt() - self.__structured_output = StructuredOutput(payload=VisionLocalizationPayload) - self.__configuration = ( - configuration if configuration is not None else VisionLocalizationConfiguration() - ) + The implementation is now provider-neutral and uses whichever ``LLMPort`` is bound by the + runtime. Existing callers can keep the old import while new composition uses + :class:`VisionLLMLocalizer` directly. + """ @property def name(self) -> str: - """ - Stable identifier used in logs and ensemble proposals. - """ + """Preserve the legacy ensemble identifier for compatibility callers.""" return "gemini.vision" - - async def locate( - self, - *, - action: Action, - capture: ScreenCapture, - budget: LocalizationBudget, - observation: ScreenObservation, - ) -> Optional[LocalizationProposal]: - """ - Run the vision-LLM locate request inside a bounded retry loop. - """ - - _ = observation - _ = budget - - if not (target := self.__target_text(action=action)): - return None - - context = self.__context(target=target, activity=capture.activity) - return await self.__attempt_with_retries(target=target, capture=capture, context=context) - - async def __attempt_with_retries( - self, - *, - target: str, - capture: ScreenCapture, - context: Dict[str, Any], - ) -> Optional[LocalizationProposal]: - """ - Retry the vision call on timeout using the configured policy. - """ - - attempts = self.__configuration.retry.attempts - timeout = self.__configuration.timeout / MILLISECONDS_PER_SECOND - - retrying = AsyncRetrying( - reraise=True, - stop=stop_after_attempt(attempts), - wait=wait_exponential( - min=0, - multiplier=timeout, - exp_base=self.__configuration.retry.backoff, - ), - retry=retry_if_exception_type(asyncio.TimeoutError), - ) - - try: - async for attempt in retrying: - with attempt: - proposal = await self.__bounded_call( - target=target, capture=capture, context=context, attempt=attempt - ) - return proposal - except asyncio.TimeoutError: - logger.warning( - "Vision localizer exhausted attempt budget", - extra={ - **context, - "attempt.budget": attempts, - "event": "localizer.vision.exhausted", - }, - ) - return None - - async def __bounded_call( - self, - *, - target: str, - attempt: Any, - capture: ScreenCapture, - context: Dict[str, Any], - ) -> Optional[LocalizationProposal]: - """ - Wrap one Gemini call in a per-attempt timeout and log start/timeout. - """ - - attempt_index = attempt.retry_state.attempt_number - 1 - timeout = self.__configuration.timeout / MILLISECONDS_PER_SECOND - - logger.info( - "Vision localizer call started", - extra={ - **context, - "timeout.seconds": timeout, - "attempt.index": attempt_index, - "event": "localizer.vision.started", - }, - ) - try: - return await asyncio.wait_for( - self.__single_call(target=target, capture=capture, context=context), - timeout=timeout, - ) - except asyncio.TimeoutError: - logger.warning( - "Vision localizer attempt timed out", - extra={ - **context, - "timeout.seconds": timeout, - "attempt.index": attempt_index, - "event": "localizer.vision.timeout", - }, - ) - raise - - async def __single_call( - self, - *, - target: str, - capture: ScreenCapture, - context: Dict[str, Any], - ) -> Optional[LocalizationProposal]: - """ - Execute one Gemini call and project the payload into pixel bounds. - """ - - result = await self.__llm.generate( - use_cache=False, - structured_output=self.__structured_output, - system_instruction=self.__prompt.SYSTEM_INSTRUCTION, - prompt=self.__prompt.build(target=target, image=capture.image), - ) - if (payload := self.__try_parse(content=result.content, context=context)) is None: - return None - - if payload.refused: - logger.info( - "Vision localizer reported target not visible", - extra={**context, "event": "localizer.vision.refusal"}, - ) - return None - - bounds = self.__bounds_from_payload( - payload=payload, width=capture.width, height=capture.height - ) - if bounds is None: - logger.warning( - "Vision localizer payload yielded zero-area bounds after projection", - extra={ - **context, - "payload.raw": self.__payload_log(payload=payload), - "event": "localizer.vision.payload.invalid", - }, - ) - return None - - pixel_width, pixel_height = self.__pixel_dimensions(image=capture.image) - - logger.info( - "Vision localizer proposal returned", - extra={ - **context, - "confidence": payload.confidence, - "payload.system": ( - f"normalized.{LocalizationGridScale.MINIMUM}.{LocalizationGridScale.MAXIMUM}" - ), - "bounds.system": bounds.system.value, - "event": "localizer.vision.completed", - "conversion": "normalized_to_logical", - "payload.raw": self.__payload_log(payload=payload), - "capture.pixel": {"width": pixel_width, "height": pixel_height}, - "capture.logical": {"width": capture.width, "height": capture.height}, - "bounds.resolved": { - "x": bounds.x, - "y": bounds.y, - "width": bounds.width, - "height": bounds.height, - }, - }, - ) - return LocalizationProposal( - bounds=bounds, - source=self.name, - confidence=payload.confidence, - rationale=f"Gemini vision proposal for target '{target}'.", - ) - - def __try_parse( - self, - *, - content: str, - context: Dict[str, Any], - ) -> Optional[VisionLocalizationPayload]: - """ - Validate the JSON response against the published schema. - """ - - if not (stripped := (content or "").strip()): - return None - - try: - return VisionLocalizationPayload.model_validate_json(stripped) - except ValidationError: - logger.warning( - "Vision localizer response did not match the published schema", - extra={ - **context, - "response.length": len(stripped), - "response.preview": stripped[:512], - "event": "localizer.vision.payload.invalid", - }, - ) - return None - - @staticmethod - def __bounds_from_payload( - *, - width: int, - height: int, - payload: VisionLocalizationPayload, - ) -> Optional[Bounds]: - """ - Project the grid bbox onto the capture's logical canvas. - """ - - x_min = (payload.x1 * width) // LocalizationGridScale.MAXIMUM - y_min = (payload.y1 * height) // LocalizationGridScale.MAXIMUM - x_max = (payload.x2 * width) // LocalizationGridScale.MAXIMUM - y_max = (payload.y2 * height) // LocalizationGridScale.MAXIMUM - - bound_width = x_max - x_min - bound_height = y_max - y_min - - if bound_width <= 0 or bound_height <= 0: - return None - - return Bounds( - x=x_min, - y=y_min, - width=bound_width, - height=bound_height, - source=CoordinateSource.MODEL, - coordinate_system=CoordinateSystem.LOGICAL, - ) - - @staticmethod - def __pixel_dimensions(*, image: bytes) -> Tuple[Optional[int], Optional[int]]: - """ - Decode the capture PNG header and return its pixel dimensions. - """ - - if not image: - return None, None - - try: - with Image.open(io.BytesIO(image)) as decoded: - return decoded.width, decoded.height - except (OSError, ValueError): - return None, None - - @staticmethod - def __payload_log(*, payload: VisionLocalizationPayload) -> Dict[str, Any]: - """ - Build a log-safe snapshot of the payload edges. - """ - - return { - "x1": payload.x1, - "y1": payload.y1, - "x2": payload.x2, - "y2": payload.y2, - "confidence": payload.confidence, - } - - @staticmethod - def __target_text(*, action: Action) -> str: - """ - Return the semantic target text from the action. - """ - - return ( - action.natural_language_target - or action.export_target - or action.script_target - or action.target - or "" - ).strip() - - def __context(self, *, target: str, activity: str) -> Dict[str, Any]: - """ - Return shared structured-logging context for this invocation. - """ - - return { - "member": self.name, - "activity": activity, - "target": target[:80], - "workflow.id": self.__workflow_id, - "component": "adapter.localizer.vision", - } diff --git a/src/fathom/adapters/localization/vision.py b/src/fathom/adapters/localization/vision.py new file mode 100644 index 00000000..36bf6e7f --- /dev/null +++ b/src/fathom/adapters/localization/vision.py @@ -0,0 +1,390 @@ +from __future__ import annotations + +import asyncio +import io +import json +from logging import getLogger +from typing import Any, Dict, List, Optional, Tuple + +from PIL import Image +from pydantic import ValidationError +from tenacity import ( + AsyncRetrying, + retry_if_exception_type, + stop_after_attempt, + wait_exponential, +) + +from fathom.constants.localization import LocalizationGridScale +from fathom.constants.runtime import MILLISECONDS_PER_SECOND +from fathom.core.prompts.localization import VisionLocalizationPrompt +from fathom.interfaces.llm import LLMPort +from fathom.interfaces.localization import TargetLocalizerPort +from fathom.schemas.actions import Action, Bounds, CoordinateSource, CoordinateSystem +from fathom.schemas.budgets import LocalizationBudget +from fathom.schemas.llm import StructuredOutput +from fathom.schemas.localization import ( + LocalizationProposal, + VisionLocalizationConfiguration, + VisionLocalizationPayload, +) +from fathom.schemas.observation import ScreenObservation +from fathom.schemas.screens import ScreenCapture + +logger = getLogger(__name__) + + +class VisionLLMLocalizer(TargetLocalizerPort): + """ + Provider-neutral vision localizer backed by the run's configured ``LLMPort``. + + The localizer owns the provider-independent vision contract: it asks the bound model for a + normalized rectangle, validates the response, clamps only grid-edge overshoots, and projects + the result onto the device's logical canvas. Provider SDK details stay behind ``LLMPort``. + """ + + def __init__( + self, + *, + llm: LLMPort, + workflow_id: Optional[str] = None, + prompt: Optional[VisionLocalizationPrompt] = None, + configuration: Optional[VisionLocalizationConfiguration] = None, + ) -> None: + """Initialize the localizer with its model port and bounded call policy.""" + + self.__llm = llm + self.__workflow_id = workflow_id + self.__prompt = prompt if prompt is not None else VisionLocalizationPrompt() + self.__structured_output = StructuredOutput(payload=VisionLocalizationPayload) + self.__configuration = ( + configuration if configuration is not None else VisionLocalizationConfiguration() + ) + + @property + def name(self) -> str: + """Stable identifier used in logs and ensemble proposals.""" + + return "vision.llm" + + async def locate( + self, + *, + action: Action, + capture: ScreenCapture, + budget: LocalizationBudget, + observation: ScreenObservation, + ) -> Optional[LocalizationProposal]: + """Run the vision-LLM locate request inside a bounded retry loop.""" + + _ = observation + _ = budget + + if not (target := self.__target_text(action=action)): + return None + + context = self.__context(target=target, activity=capture.activity) + return await self.__attempt_with_retries(target=target, capture=capture, context=context) + + async def __attempt_with_retries( + self, + *, + target: str, + capture: ScreenCapture, + context: Dict[str, Any], + ) -> Optional[LocalizationProposal]: + """Retry the vision call on timeout using the configured policy.""" + + attempts = self.__configuration.retry.attempts + timeout = self.__configuration.timeout / MILLISECONDS_PER_SECOND + + retrying = AsyncRetrying( + reraise=True, + stop=stop_after_attempt(attempts), + wait=wait_exponential( + min=0, + multiplier=timeout, + exp_base=self.__configuration.retry.backoff, + ), + retry=retry_if_exception_type(asyncio.TimeoutError), + ) + + try: + async for attempt in retrying: + with attempt: + proposal = await self.__bounded_call( + target=target, capture=capture, context=context, attempt=attempt + ) + return proposal + except asyncio.TimeoutError: + logger.warning( + "Vision localizer exhausted attempt budget", + extra={ + **context, + "attempt.budget": attempts, + "event": "localizer.vision.exhausted", + }, + ) + return None + + async def __bounded_call( + self, + *, + target: str, + attempt: Any, + capture: ScreenCapture, + context: Dict[str, Any], + ) -> Optional[LocalizationProposal]: + """Wrap one model call in a per-attempt timeout and log its lifecycle.""" + + attempt_index = attempt.retry_state.attempt_number - 1 + timeout = self.__configuration.timeout / MILLISECONDS_PER_SECOND + + logger.info( + "Vision localizer call started", + extra={ + **context, + "timeout.seconds": timeout, + "attempt.index": attempt_index, + "event": "localizer.vision.started", + }, + ) + try: + return await asyncio.wait_for( + self.__single_call(target=target, capture=capture, context=context), + timeout=timeout, + ) + except asyncio.TimeoutError: + logger.warning( + "Vision localizer attempt timed out", + extra={ + **context, + "timeout.seconds": timeout, + "attempt.index": attempt_index, + "event": "localizer.vision.timeout", + }, + ) + raise + + async def __single_call( + self, + *, + target: str, + capture: ScreenCapture, + context: Dict[str, Any], + ) -> Optional[LocalizationProposal]: + """Execute the provider-neutral vision call and project its result into pixel bounds.""" + + result = await self.__llm.generate( + use_cache=False, + structured_output=self.__structured_output, + system_instruction=self.__prompt.SYSTEM_INSTRUCTION, + prompt=self.__prompt.build(target=target, image=capture.image), + ) + if (payload := self.__try_parse(content=result.content, context=context)) is None: + return None + + if payload.refused: + logger.info( + "Vision localizer reported target not visible", + extra={**context, "event": "localizer.vision.refusal"}, + ) + return None + + bounds = self.__bounds_from_payload( + payload=payload, width=capture.width, height=capture.height + ) + if bounds is None: + logger.warning( + "Vision localizer payload yielded zero-area bounds after projection", + extra={ + **context, + "payload.raw": self.__payload_log(payload=payload), + "event": "localizer.vision.payload.invalid", + }, + ) + return None + + pixel_width, pixel_height = self.__pixel_dimensions(image=capture.image) + + logger.info( + "Vision localizer proposal returned", + extra={ + **context, + "confidence": payload.confidence, + "payload.system": ( + f"normalized.{LocalizationGridScale.MINIMUM}.{LocalizationGridScale.MAXIMUM}" + ), + "bounds.system": bounds.system.value, + "event": "localizer.vision.completed", + "conversion": "normalized_to_logical", + "payload.raw": self.__payload_log(payload=payload), + "capture.pixel": {"width": pixel_width, "height": pixel_height}, + "capture.logical": {"width": capture.width, "height": capture.height}, + "bounds.resolved": { + "x": bounds.x, + "y": bounds.y, + "width": bounds.width, + "height": bounds.height, + }, + }, + ) + return LocalizationProposal( + bounds=bounds, + source=self.name, + confidence=payload.confidence, + rationale=f"Vision LLM proposal for target '{target}'.", + ) + + def __try_parse( + self, + *, + content: str, + context: Dict[str, Any], + ) -> Optional[VisionLocalizationPayload]: + """Validate the JSON response against the published schema.""" + + if not (stripped := (content or "").strip()): + return None + + try: + document = json.loads(stripped) + except ValueError: + logger.warning( + "Vision localizer response was not valid JSON", + extra={ + **context, + "response.length": len(stripped), + "response.preview": stripped[:512], + "event": "localizer.vision.payload.invalid", + }, + ) + return None + + document, clamped = self.__within_grid(document=document) + if clamped: + logger.info( + "Vision localizer edges clamped into the published grid", + extra={ + **context, + "edges.clamped": list(clamped), + "event": "localizer.vision.payload.clamped", + }, + ) + + try: + return VisionLocalizationPayload.model_validate(document) + except ValidationError: + logger.warning( + "Vision localizer response did not match the published schema", + extra={ + **context, + "response.length": len(stripped), + "response.preview": stripped[:512], + "event": "localizer.vision.payload.invalid", + }, + ) + return None + + @staticmethod + def __within_grid(*, document: Any) -> Tuple[Any, Tuple[str, ...]]: + """Clamp grid edges into the published range and report which edges moved.""" + + if not isinstance(document, dict): + return document, () + + bounded = dict(document) + moved: List[str] = [] + + for edge in ("x1", "y1", "x2", "y2"): + value = bounded.get(edge) + if not isinstance(value, int) or isinstance(value, bool): + continue + limited = int( + min(max(value, LocalizationGridScale.MINIMUM), LocalizationGridScale.MAXIMUM) + ) + if limited != value: + bounded[edge] = limited + moved.append(edge) + + return bounded, tuple(moved) + + @staticmethod + def __bounds_from_payload( + *, + width: int, + height: int, + payload: VisionLocalizationPayload, + ) -> Optional[Bounds]: + """Project the normalized grid bbox onto the capture's logical canvas.""" + + x_min = (payload.x1 * width) // LocalizationGridScale.MAXIMUM + y_min = (payload.y1 * height) // LocalizationGridScale.MAXIMUM + x_max = (payload.x2 * width) // LocalizationGridScale.MAXIMUM + y_max = (payload.y2 * height) // LocalizationGridScale.MAXIMUM + + bound_width = x_max - x_min + bound_height = y_max - y_min + + if bound_width <= 0 or bound_height <= 0: + return None + + return Bounds( + x=x_min, + y=y_min, + width=bound_width, + height=bound_height, + source=CoordinateSource.MODEL, + coordinate_system=CoordinateSystem.LOGICAL, + ) + + @staticmethod + def __pixel_dimensions(*, image: bytes) -> Tuple[Optional[int], Optional[int]]: + """Decode the capture PNG header and return its pixel dimensions.""" + + if not image: + return None, None + + try: + with Image.open(io.BytesIO(image)) as decoded: + return decoded.width, decoded.height + except (OSError, ValueError): + return None, None + + @staticmethod + def __payload_log(*, payload: VisionLocalizationPayload) -> Dict[str, Any]: + """Build a log-safe snapshot of payload edges without logging image bytes.""" + + return { + "x1": payload.x1, + "y1": payload.y1, + "x2": payload.x2, + "y2": payload.y2, + "confidence": payload.confidence, + } + + @staticmethod + def __target_text(*, action: Action) -> str: + """Return the semantic target text from the action.""" + + return ( + action.natural_language_target + or action.export_target + or action.script_target + or action.target + or "" + ).strip() + + def __context(self, *, target: str, activity: str) -> Dict[str, Any]: + """Return structured logging context for this invocation.""" + + identity = self.__llm.identity + return { + "member": self.name, + "provider": identity.provider.value, + "model": identity.model, + "activity": activity, + "target": target[:80], + "workflow.id": self.__workflow_id, + "component": "adapter.localizer.vision", + } diff --git a/src/fathom/adapters/tools/__init__.py b/src/fathom/adapters/tools/__init__.py index ac74cd26..78df420d 100644 --- a/src/fathom/adapters/tools/__init__.py +++ b/src/fathom/adapters/tools/__init__.py @@ -1,3 +1,4 @@ from fathom.adapters.tools.gemini import GeminiToolDialect +from fathom.adapters.tools.openai import OpenAIToolDialect -__all__ = ["GeminiToolDialect"] +__all__ = ["GeminiToolDialect", "OpenAIToolDialect"] diff --git a/src/fathom/adapters/tools/openai.py b/src/fathom/adapters/tools/openai.py new file mode 100644 index 00000000..198861b5 --- /dev/null +++ b/src/fathom/adapters/tools/openai.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import Any, Dict, List, Mapping + +from fathom.interfaces.tools import ToolDeclaration, ToolDialect + + +class OpenAIToolDialect(ToolDialect): + """ + Encode Fathom's canonical tool declarations for OpenAI Chat Completions. + """ + + def encode(self, *, payload: Mapping[str, List[ToolDeclaration]]) -> Dict[str, Any]: + """ + Wrap each canonical function in OpenAI's function-tool envelope. + """ + + return { + "tools": [ + { + "type": "function", + "function": { + "name": declaration["name"], + "description": declaration.get("description", ""), + "parameters": self.__schema( + schema=declaration.get( + "parameters", {"type": "object", "properties": {}} + ) + ), + }, + } + for declaration in payload.get("tools", []) + ] + } + + @classmethod + def __schema(cls, *, schema: Any) -> Any: + """ + Normalize canonical/Gemini JSON Schema types for OpenAI tools. + """ + + if isinstance(schema, list): + return [cls.__schema(schema=item) for item in schema] + if not isinstance(schema, dict): + return schema + + normalized = {key: cls.__schema(schema=value) for key, value in schema.items()} + if isinstance(normalized.get("type"), str): + normalized["type"] = normalized["type"].lower() + return normalized diff --git a/src/fathom/base/logger.py b/src/fathom/base/logger.py index 43621c4f..088c7c9b 100644 --- a/src/fathom/base/logger.py +++ b/src/fathom/base/logger.py @@ -85,7 +85,17 @@ def configure(cls, settings: Optional[FathomSettings] = None) -> None: root_logger.setLevel(level_name) # Silence noisy libraries - for lib in ["httpx", "httpcore", "urllib3", "asyncio", "parso", "aiosqlite"]: + for lib in [ + "httpx", + "httpcore", + "httpcore2", + "urllib3", + "asyncio", + "parso", + "aiosqlite", + "openai", + "openai._base_client", + ]: getLogger(lib).setLevel(WARNING) cls.__configured = True diff --git a/src/fathom/core/prompts/factory.py b/src/fathom/core/prompts/factory.py index ef5d0ca1..acb3315f 100644 --- a/src/fathom/core/prompts/factory.py +++ b/src/fathom/core/prompts/factory.py @@ -1,7 +1,9 @@ from __future__ import annotations -from typing import Dict, Type +from typing import Dict, Optional, Type +from fathom.constants.llm import ModelProvider +from fathom.core.exceptions import ConfigurationError from fathom.core.prompts.base import PromptBuilder from fathom.core.prompts.decomposition import ( DecompositionPromptBuilder, @@ -9,6 +11,11 @@ ) from fathom.core.prompts.export import ExportPromptBuilder, GeminiExportPromptBuilder from fathom.core.prompts.gemini import GeminiPromptBuilder +from fathom.core.prompts.openai import ( + OpenAIDecompositionPromptBuilder, + OpenAIExportPromptBuilder, + OpenAIPromptBuilder, +) class PromptFactory: @@ -18,30 +25,32 @@ class PromptFactory: __builders: Dict[str, Type[PromptBuilder]] = { "gemini": GeminiPromptBuilder, + "openai": OpenAIPromptBuilder, } __export_builders: Dict[str, Type[ExportPromptBuilder]] = { "gemini": GeminiExportPromptBuilder, + "openai": OpenAIExportPromptBuilder, } __decomposition_builders: Dict[str, Type[DecompositionPromptBuilder]] = { "gemini": GeminiDecompositionPromptBuilder, + "openai": OpenAIDecompositionPromptBuilder, } @classmethod - def get_builder(cls, model_name: str) -> PromptBuilder: - """ - Resolve the system-prompt builder for the model. Only Gemini is wired today; - gpt and claude are placeholders that fall back to the Gemini builder. + def get_builder( + cls, model_name: str, *, provider: Optional[ModelProvider] = None + ) -> PromptBuilder: """ + Resolve the system-prompt builder from the declared provider. - kind = "gemini" - - if "gpt" in model_name.lower(): - kind = "openai" # Placeholder - - elif "claude" in model_name.lower(): - kind = "anthropic" # Placeholder + ``model_name`` remains for prompt-tier selection and legacy callers. It is never used to + silently select a different provider when one has been declared. + """ - builder_class = cls.__builders.get(kind, GeminiPromptBuilder) + kind = cls.__provider_kind(provider=provider, model_name=model_name) + builder_class = cls.__builders.get(kind) + if builder_class is None: + raise ConfigurationError(f"Prompt builder for provider {kind} is not implemented") return builder_class() @staticmethod @@ -58,37 +67,54 @@ def resolve_version(model_name: str, use_xml: bool) -> str: return f"{tier}_{strategy}" @classmethod - def get_export_builder(cls, model_name: str) -> ExportPromptBuilder: + def get_export_builder( + cls, model_name: str, *, provider: Optional[ModelProvider] = None + ) -> ExportPromptBuilder: """ - Resolve the export-prompt builder for the model. Only Gemini is wired today; - gpt and claude are placeholders that fall back to the Gemini builder. + Resolve the export-prompt builder from the declared provider. """ - kind = "gemini" - - if "gpt" in model_name.lower(): - kind = "openai" # Placeholder - - elif "claude" in model_name.lower(): - kind = "anthropic" # Placeholder - - builder_class = cls.__export_builders.get(kind, GeminiExportPromptBuilder) + kind = cls.__provider_kind(provider=provider, model_name=model_name) + builder_class = cls.__export_builders.get(kind) + if builder_class is None: + raise ConfigurationError( + f"Export prompt builder for provider {kind} is not implemented" + ) return builder_class() @classmethod - def get_decomposition_builder(cls, model_name: str) -> DecompositionPromptBuilder: + def get_decomposition_builder( + cls, model_name: str, *, provider: Optional[ModelProvider] = None + ) -> DecompositionPromptBuilder: """ - Resolve the decomposition-prompt builder for the model. Only Gemini is wired today; - gpt and claude are placeholders that fall back to the Gemini builder. + Resolve the decomposition prompt builder from the declared provider. """ - kind = "gemini" + kind = cls.__provider_kind(provider=provider, model_name=model_name) + builder_class = cls.__decomposition_builders.get(kind) + if builder_class is None: + raise ConfigurationError( + f"Decomposition prompt builder for provider {kind} is not implemented" + ) + return builder_class() - if "gpt" in model_name.lower(): - kind = "openai" # Placeholder + @staticmethod + def __provider_kind(*, provider: Optional[ModelProvider], model_name: str) -> str: + """ + Resolve a provider without pretending that a model name is an adapter declaration. - elif "claude" in model_name.lower(): - kind = "anthropic" # Placeholder + Legacy callers with no declared provider retain Gemini behavior unless the model name + explicitly identifies an unsupported provider; those calls fail closed instead of using a + Gemini prompt for an OpenAI or Anthropic model. + """ - builder_class = cls.__decomposition_builders.get(kind, GeminiDecompositionPromptBuilder) - return builder_class() + if provider is not None and provider is not ModelProvider.UNKNOWN: + return "gemini" if provider is ModelProvider.VERTEX_AI else provider.value + + lowered = model_name.lower() + if "gpt" in lowered or "claude" in lowered: + raise ConfigurationError( + f"Provider must be declared for non-Gemini model {model_name!r}" + ) + + return "gemini" diff --git a/src/fathom/core/prompts/openai.py b/src/fathom/core/prompts/openai.py new file mode 100644 index 00000000..74cbabb9 --- /dev/null +++ b/src/fathom/core/prompts/openai.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +from fathom.core.prompts.decomposition import GeminiDecompositionPromptBuilder +from fathom.core.prompts.export import GeminiExportPromptBuilder +from fathom.core.prompts.gemini import GeminiPromptBuilder + + +class OpenAIPromptBuilder(GeminiPromptBuilder): + """ + OpenAI planner prompt builder using provider-neutral semantic instructions. + """ + + +class OpenAIDecompositionPromptBuilder(GeminiDecompositionPromptBuilder): + """ + OpenAI decomposition prompt builder using shared semantic instructions. + """ + + +class OpenAIExportPromptBuilder(GeminiExportPromptBuilder): + """ + OpenAI export prompt builder using shared semantic instructions. + """ diff --git a/src/fathom/core/prompts/tools.py b/src/fathom/core/prompts/tools.py index 3ffd5bd3..008b70b3 100644 --- a/src/fathom/core/prompts/tools.py +++ b/src/fathom/core/prompts/tools.py @@ -4,6 +4,7 @@ from fathom.constants.assessment import VisualVerdict from fathom.constants.tools import ToolName +from fathom.interfaces.tools import CanonicalToolPayload class ToolRegistry: @@ -17,19 +18,40 @@ class ToolRegistry: ) @classmethod - def get_all_definitions(cls) -> Dict[str, List[Dict[str, Any]]]: + def canonical_definitions(cls) -> CanonicalToolPayload: + """ + Return all tool declarations in Fathom's provider-neutral payload shape. + """ + + return cls.canonical_definitions_for(names=frozenset(cls.__factories())) + + @classmethod + def canonical_definitions_for(cls, *, names: FrozenSet[ToolName]) -> CanonicalToolPayload: """ - Returns all tool definitions in a format compatible with Gemini API. + Return the requested declarations without a provider-specific envelope. """ factories = cls.__factories() return { - "function_declarations": [ - cls.__with_assessment(name=name, declaration=factory()) - for name, factory in factories.items() + "tools": [ + cls.__with_assessment(name=name, declaration=factories[name]()) + for name in factories + if name in names ] } + @classmethod + def get_all_definitions(cls) -> Dict[str, List[Dict[str, Any]]]: + """ + Return the legacy Gemini envelope for callers that have not migrated yet. + + New runtime code must use :meth:`canonical_definitions` or + :meth:`canonical_definitions_for` and let the provider adapter encode it. + """ + + canonical = cls.canonical_definitions() + return {"function_declarations": canonical["tools"]} + @classmethod def definitions( cls, @@ -37,17 +59,11 @@ def definitions( names: FrozenSet[ToolName], ) -> Dict[str, List[Dict[str, Any]]]: """ - Return the function-declarations payload for the requested tools. + Return the legacy Gemini function-declarations payload for the requested tools. """ - factories = cls.__factories() - ordered = [ - cls.__with_assessment(name=name, declaration=factories[name]()) - for name in factories - if name in names - ] - - return {"function_declarations": ordered} + canonical = cls.canonical_definitions_for(names=names) + return {"function_declarations": canonical["tools"]} @classmethod def __with_assessment(cls, *, name: ToolName, declaration: Dict[str, Any]) -> Dict[str, Any]: diff --git a/src/fathom/core/services/decomposer.py b/src/fathom/core/services/decomposer.py index b48ca6ce..ad4d8362 100644 --- a/src/fathom/core/services/decomposer.py +++ b/src/fathom/core/services/decomposer.py @@ -56,7 +56,10 @@ def __init__(self, llm: LLMPort, *, translator: ProposalTranslator) -> None: self.__llm = llm self.__translator = translator self.__configuration = LLMConfiguration() - self.__prompt_builder = PromptFactory.get_decomposition_builder(model_name=llm.model_name) + self.__prompt_builder = PromptFactory.get_decomposition_builder( + model_name=llm.model_name, + provider=llm.identity.provider, + ) @classmethod def with_configuration( diff --git a/src/fathom/core/services/vision.py b/src/fathom/core/services/vision.py index c13f315e..de4bf6aa 100644 --- a/src/fathom/core/services/vision.py +++ b/src/fathom/core/services/vision.py @@ -81,7 +81,10 @@ def __init__( self.__capabilities = capabilities self.__tool_scope = tool_scope or ToolScope(policies=DEFAULT_TOOL_POLICIES) - self.__builder = PromptFactory.get_builder(model_name=self.__llm.model_name) + self.__builder = PromptFactory.get_builder( + model_name=self.__llm.model_name, + provider=self.__llm.identity.provider, + ) async def prewarm(self) -> None: """ @@ -92,7 +95,7 @@ async def prewarm(self) -> None: for variant in self.__prewarm_variants(): instruction = self.__builder.build(tools=variant) - payload = ToolRegistry.definitions(names=variant.names) + payload = ToolRegistry.canonical_definitions_for(names=variant.names) await self.__llm.prewarm(tools=payload, system_instruction=instruction) await self.__telemetry.debug( @@ -279,7 +282,7 @@ async def analyze( ) tool_scope_start = time.time() - allowed_tools = ToolRegistry.definitions(names=tools.names) + allowed_tools = ToolRegistry.canonical_definitions_for(names=tools.names) tool_scope_duration = time.time() - tool_scope_start manifest_start = time.time() diff --git a/src/fathom/runtime/adapters.py b/src/fathom/runtime/adapters.py index ac0d60d8..a84d6ae8 100644 --- a/src/fathom/runtime/adapters.py +++ b/src/fathom/runtime/adapters.py @@ -1,7 +1,7 @@ from __future__ import annotations from logging import getLogger -from typing import TYPE_CHECKING, Any, Dict, List, Optional +from typing import TYPE_CHECKING, Any, Dict, List, Optional, cast if TYPE_CHECKING: from pathlib import Path @@ -14,7 +14,7 @@ from fathom.adapters.journal.jsonl import JsonRuntimeJournal from fathom.adapters.journal.noop import NoopRuntimeJournal from fathom.adapters.localization.document import DocumentAiLayoutLocalizer -from fathom.adapters.localization.gemini import GeminiVisionLocalizer +from fathom.adapters.localization.vision import VisionLLMLocalizer from fathom.adapters.ocr.document import DocumentAiOcr from fathom.adapters.ocr.noop import NoopOcr from fathom.adapters.perception.overlay.noop import NoopOverlayDetector @@ -33,10 +33,11 @@ VerificationRenderer, ) from fathom.core.config.loader import RuntimeConfigLoader +from fathom.core.embedding.capability import EmbeddingCapability from fathom.core.localization.ensemble import EnsembleLocalizerService from fathom.infrastructure.storage.cloud import GCSImageStorage from fathom.interfaces.artifact import ArtifactRendererPort, ArtifactSinkPort -from fathom.interfaces.embedding import EmbeddingPort +from fathom.interfaces.embedding import EmbeddingCapable, EmbeddingPort from fathom.interfaces.icon import IconDetectorPort from fathom.interfaces.journal import RuntimeJournalPort from fathom.interfaces.llm import LLMPort @@ -157,8 +158,7 @@ def embedder(self) -> Optional[EmbeddingPort]: Build the Gemini embedding adapter sharing auth with the chat LLM; ``None`` when unavailable. """ - client = getattr(self.__llm, "client", None) - if client is None: + if not EmbeddingCapability.available(llm=self.__llm): logger.info( "LLM port does not expose an embedding-capable client; embeddings disabled", extra={ @@ -169,7 +169,7 @@ def embedder(self) -> Optional[EmbeddingPort]: return None adapter = GeminiEmbeddingAdapter( - client=client, + client=cast("EmbeddingCapable", self.__llm).client, workflow_id=self.__workflow_id, ) self.__log_embedder_wired(adapter=adapter) @@ -319,8 +319,8 @@ def __build_member(self, *, name: EnsembleMemberName) -> Optional[TargetLocalize disabled or un-configured rather than carrying a member that can only ever return ``None``. """ - if name == EnsembleMemberName.GEMINI_VISION: - return GeminiVisionLocalizer(llm=self.__llm, workflow_id=self.__workflow_id) + if name in (EnsembleMemberName.VISION_LLM, EnsembleMemberName.GEMINI_VISION): + return VisionLLMLocalizer(llm=self.__llm, workflow_id=self.__workflow_id) if name == EnsembleMemberName.DOCUMENT_AI_LAYOUT: if not self.__perception.ocr.enabled or self.__perception.ocr.document_ai is None: diff --git a/src/fathom/runtime/assembly.py b/src/fathom/runtime/assembly.py index c0e7cce6..d2484312 100644 --- a/src/fathom/runtime/assembly.py +++ b/src/fathom/runtime/assembly.py @@ -1,8 +1,9 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, Any, Dict, Optional from fathom.constants.llm import InferencePriorityMode +from fathom.constants.qualification import DEFAULT_QUALIFIER_MODEL from fathom.constants.run import TargetKind from fathom.constants.storage import InteractionBackend from fathom.core.exceptions import ConfigurationError, StorageConfigurationError @@ -69,10 +70,6 @@ def build_planner_model_configuration(self, *, request: RunRequest) -> LLMConfig Resolve planner model configuration using request values with environment defaults. """ - credentials = ( - self.__settings.google_credentials_dict - or self.__settings.google_application_credentials - ) request_values = ( request.resources.language_model_configuration.planner_configuration.model_dump( exclude_none=True, @@ -80,12 +77,7 @@ def build_planner_model_configuration(self, *, request: RunRequest) -> LLMConfig ) ) default_values = { - "credentials": credentials, - "model": self.__settings.gemini_model, - "api_key": self.__settings.gemini_api_key, - "location": self.__settings.vertex_location, - "priority": self.__priority_configuration(), - "project_id": self.__settings.vertex_project_id, + **self.__provider_defaults(), "use_cache": getattr(self.__settings, "use_cache", True), } default_values.update(request_values) @@ -99,26 +91,47 @@ def build_qualifier_model_configuration( Resolve qualifier model configuration from settings and the qualifier knobs. """ - credentials = ( - self.__settings.google_credentials_dict - or self.__settings.google_application_credentials - ) + defaults = self.__provider_defaults() + configured_model = configuration.inference.model + if defaults["provider"] == "openai" and configured_model == DEFAULT_QUALIFIER_MODEL: + configured_model = self.__settings.openai_model return LLMConfiguration.model_validate( { - "credentials": credentials, - "model": configuration.inference.model, - "api_key": self.__settings.gemini_api_key, + **defaults, + "model": configured_model, "timeout": configuration.inference.timeout, - "location": self.__settings.vertex_location, "use_cache": configuration.inference.use_cache, - "project_id": self.__settings.vertex_project_id, "temperature": configuration.inference.temperature, "max_retries": configuration.inference.max_retries, "thinking_level": configuration.inference.thinking_level, - "priority": self.__priority_configuration(), } ) + def __provider_defaults(self) -> Dict[str, Any]: + """ + Return the provider-shaped default kwargs the two model-configuration builders share. + """ + + provider = self.__settings.llm_provider + is_openai = provider == "openai" + + return { + "provider": provider, + "model": self.__settings.openai_model if is_openai else self.__settings.gemini_model, + "api_key": ( + self.__settings.openai_api_key if is_openai else self.__settings.gemini_api_key + ), + "credentials": None + if is_openai + else ( + self.__settings.google_credentials_dict + or self.__settings.google_application_credentials + ), + "location": None if is_openai else self.__settings.vertex_location, + "project_id": None if is_openai else self.__settings.vertex_project_id, + "priority": self.__priority_configuration(), + } + def __priority_configuration(self) -> PriorityInferenceConfiguration: """ Resolve provider-neutral elevated-capacity inference policy from settings. diff --git a/src/fathom/runtime/command/application.py b/src/fathom/runtime/command/application.py index 087971e7..a884b103 100644 --- a/src/fathom/runtime/command/application.py +++ b/src/fathom/runtime/command/application.py @@ -239,7 +239,7 @@ def __configure_run_parser( default=None, help="Path to adb executable for Android local adapter", ) - run_parser.add_argument("--api-key", "-k", type=str, help="Gemini API Key") + run_parser.add_argument("--api-key", "-k", type=str, help="Active LLM provider API key") run_parser.add_argument("--max-steps", type=int, default=50, help="Maximum steps allowed") run_parser.add_argument( "--verbose", @@ -262,7 +262,15 @@ def __configure_run_parser( "--use-xml", "-x", action="store_true", - help="Use XML bounding boxes", + dest="use_xml", + default=True, + help="Use XML/accessibility bounding boxes (default)", + ) + run_parser.add_argument( + "--no-xml", + action="store_false", + dest="use_xml", + help="Disable XML/accessibility grounding and use visual perception only", ) run_parser.add_argument( "--interactive", @@ -560,7 +568,10 @@ def __apply_run_overrides( """ if command_input.api_key: - settings.gemini_api_key = command_input.api_key + if settings.llm_provider == "openai": + settings.openai_api_key = command_input.api_key + else: + settings.gemini_api_key = command_input.api_key if command_input.verbose: settings.log_level = "DEBUG" diff --git a/src/fathom/runtime/factories.py b/src/fathom/runtime/factories.py index cd3e3734..30bc824f 100644 --- a/src/fathom/runtime/factories.py +++ b/src/fathom/runtime/factories.py @@ -12,6 +12,7 @@ PostgresInteraction as RepositoryPostgresInteraction, ) from fathom.adapters.llm.gemini import GeminiLLM +from fathom.adapters.llm.openai import OpenAILLM from fathom.adapters.perception.android import AndroidPerceptionAdapter from fathom.adapters.perception.ios import ( IOSEnhancedPerceptionAdapter, @@ -113,6 +114,9 @@ def create(self, *, configuration: LLMConfiguration) -> LLMPort: if configuration.provider == "gemini": return GeminiLLM(configuration=configuration) + if configuration.provider == "openai": + return OpenAILLM(configuration=configuration) + raise NotImplementedError( f"LLM adapter for provider {configuration.provider} is not implemented" ) diff --git a/src/fathom/settings/env.py b/src/fathom/settings/env.py index a93d1e51..94d06679 100644 --- a/src/fathom/settings/env.py +++ b/src/fathom/settings/env.py @@ -34,9 +34,15 @@ class FathomSettings(BaseSettings): Global settings loaded from environment variables and the .env file. """ - # Gemini settings + # LLM settings + llm_provider: Literal["gemini", "openai"] = Field( + default="gemini", + validation_alias=AliasChoices("FATHOM_LLM_PROVIDER", "LLM_PROVIDER"), + ) gemini_api_key: Optional[str] = Field(default=None, alias="GEMINI_API_KEY") gemini_model: str = Field(default="gemini-3.5-flash", alias="GEMINI_MODEL") + openai_api_key: Optional[str] = Field(default=None, alias="OPENAI_API_KEY") + openai_model: str = Field(default="gpt-4.1-mini", alias="OPENAI_MODEL") capacity_enabled: bool = Field( default=True, @@ -249,12 +255,12 @@ class FathomSettings(BaseSettings): observation_overlay_enabled: bool = Field(default=True, alias="FATHOM_OBSERVATION_OVERLAY") observation_keyboard_enabled: bool = Field(default=False, alias="FATHOM_OBSERVATION_KEYBOARD") - # Ensemble vision-localizer (Gemini-vision + DocumentAI-layout) toggles. Enabled with both members so the + # Ensemble vision-localizer (provider-neutral LLM vision + DocumentAI-layout) toggles. Enabled with both members so the # supervise cascade can fall back to name-based localization when the XML manifest snap fails or returns a # generic container. ensemble_localizer_enabled: bool = Field(default=True, alias="FATHOM_ENSEMBLE_LOCALIZER") ensemble_localizer_members: Optional[str] = Field( - default="gemini_vision,document_ai_layout", + default="vision_llm,document_ai_layout", alias="FATHOM_ENSEMBLE_LOCALIZER_MEMBERS", ) diff --git a/tests/unit/adapters/llm/test_openai.py b/tests/unit/adapters/llm/test_openai.py new file mode 100644 index 00000000..68ddd74d --- /dev/null +++ b/tests/unit/adapters/llm/test_openai.py @@ -0,0 +1,273 @@ +from __future__ import annotations + +from types import SimpleNamespace +from unittest import IsolatedAsyncioTestCase + +from pydantic import BaseModel + +from fathom.adapters.llm.openai import OpenAILLM +from fathom.schemas.configuration import LLMConfiguration +from fathom.schemas.llm import StructuredOutput + + +class _FakeCompletions: + """ + Minimal async Chat Completions surface used to test adapter normalization without network I/O. + """ + + def __init__(self, response: object) -> None: + self.response = response + self.request = None + + async def create(self, **request: object) -> object: + self.request = request + return self.response + + +class _FakeClient: + """ + Minimal client surface matching the adapter's async SDK usage. + """ + + def __init__(self, completions: _FakeCompletions) -> None: + self.chat = SimpleNamespace(completions=completions) + + async def close(self) -> None: + return None + + +class OpenAILLMTest(IsolatedAsyncioTestCase): + """ + OpenAI adapter contract tests over a fake SDK client. + """ + + @staticmethod + def __adapter(*, response: object) -> tuple[OpenAILLM, _FakeCompletions]: + """ + Construct the adapter and replace only its transport with a deterministic fake. + """ + + adapter = OpenAILLM( + configuration=LLMConfiguration( + provider="openai", + api_key="test-key", + model="gpt-4.1-mini", + max_retries=0, + ) + ) + completions = _FakeCompletions(response=response) + adapter._OpenAILLM__client = _FakeClient(completions) # type: ignore[attr-defined] + return adapter, completions + + async def test_tool_calls_and_usage_are_normalized(self) -> None: + """ + OpenAI function calls become the provider-neutral name/args shape consumed by the parser. + """ + + response = SimpleNamespace( + choices=[ + SimpleNamespace( + message=SimpleNamespace( + content="", + tool_calls=[ + SimpleNamespace( + function=SimpleNamespace( + name="execute_ui", + arguments='{"action_type":"tap"}', + ) + ) + ], + ) + ) + ], + usage=SimpleNamespace( + prompt_tokens=10, + completion_tokens=4, + prompt_tokens_details=SimpleNamespace(cached_tokens=2), + ), + ) + adapter, completions = self.__adapter(response=response) + + result = await adapter.generate( + use_cache=False, + prompt=["Open the app"], + tools={ + "tools": [ + { + "name": "execute_ui", + "description": "Execute UI action", + "parameters": {"type": "object", "properties": {}}, + } + ] + }, + ) + + self.assertEqual(result.tool_calls[0].name, "execute_ui") + self.assertEqual(result.tool_calls[0].args, {"action_type": "tap"}) + self.assertEqual(result.metrics["total_tokens"], 14) + self.assertEqual(completions.request["tools"][0]["type"], "function") + self.assertEqual(completions.request["tool_choice"], "required") + + async def test_structured_output_is_mapped_to_json_schema(self) -> None: + """ + Fathom's Pydantic structured-output contract becomes OpenAI's JSON-schema response format. + """ + + response = SimpleNamespace( + choices=[ + SimpleNamespace(message=SimpleNamespace(content='{"ok":true}', tool_calls=[])) + ], + usage=SimpleNamespace(prompt_tokens=2, completion_tokens=3), + ) + adapter, completions = self.__adapter(response=response) + + # Use a real structured-output Pydantic model while keeping this test local. + class ResultPayload(BaseModel): + ok: bool + + result = await adapter.generate( + use_cache=False, + prompt=["Return JSON"], + structured_output=StructuredOutput(payload=ResultPayload), + ) + + self.assertEqual(result.content, '{"ok":true}') + self.assertEqual( + completions.request["response_format"]["type"], + "json_schema", + ) + + async def test_structured_output_removes_pydantic_keywords_rejected_by_openai(self) -> None: + """Strict schemas contain only the OpenAI-supported structural constraints.""" + + response = SimpleNamespace( + choices=[ + SimpleNamespace(message=SimpleNamespace(content='{"ok":true}', tool_calls=[])) + ], + usage=SimpleNamespace(prompt_tokens=2, completion_tokens=3), + ) + adapter, completions = self.__adapter(response=response) + + class ResultPayload(BaseModel): + ok: bool = True + + await adapter.generate( + use_cache=False, + prompt=["Return JSON"], + structured_output=StructuredOutput(payload=ResultPayload), + ) + + schema = completions.request["response_format"]["json_schema"]["schema"] + self.assertNotIn("default", schema["properties"]["ok"]) + self.assertEqual(schema["required"], ["ok"]) + + async def test_structured_output_converts_const_and_removes_titles(self) -> None: + """OpenAI strict schemas use enum for fixed values and omit Pydantic titles.""" + + response = SimpleNamespace( + choices=[ + SimpleNamespace(message=SimpleNamespace(content='{"kind":"fixed"}', tool_calls=[])) + ], + usage=SimpleNamespace(prompt_tokens=2, completion_tokens=3), + ) + adapter, completions = self.__adapter(response=response) + + class ResultPayload(BaseModel): + kind: str = "fixed" + + await adapter.generate( + use_cache=False, + prompt=["Return JSON"], + structured_output=StructuredOutput(payload=ResultPayload), + ) + + schema = completions.request["response_format"]["json_schema"]["schema"] + self.assertNotIn("title", schema) + + async def test_structured_output_makes_refs_standalone(self) -> None: + """OpenAI rejects descriptions emitted beside JSON Schema references.""" + + response = SimpleNamespace( + choices=[ + SimpleNamespace( + message=SimpleNamespace(content='{"child":{"value":"ok"}}', tool_calls=[]) + ) + ], + usage=SimpleNamespace(prompt_tokens=2, completion_tokens=3), + ) + adapter, completions = self.__adapter(response=response) + + class Child(BaseModel): + value: str + + class ResultPayload(BaseModel): + child: Child + + await adapter.generate( + use_cache=False, + prompt=["Return JSON"], + structured_output=StructuredOutput(payload=ResultPayload), + ) + + schema = completions.request["response_format"]["json_schema"]["schema"] + self.assertEqual(list(schema["properties"]["child"]), ["$ref"]) + + async def test_reasoning_models_do_not_receive_temperature(self) -> None: + """ + GPT-5.2-compatible requests omit the unsupported temperature parameter. + """ + + response = SimpleNamespace( + choices=[SimpleNamespace(message=SimpleNamespace(content="ok", tool_calls=[]))], + usage=SimpleNamespace(prompt_tokens=1, completion_tokens=1), + ) + adapter = OpenAILLM( + configuration=LLMConfiguration( + provider="openai", + api_key="test-key", + model="gpt-5.2", + max_retries=0, + ) + ) + completions = _FakeCompletions(response=response) + adapter._OpenAILLM__client = _FakeClient(completions) # type: ignore[attr-defined] + + await adapter.generate(use_cache=False, prompt=["Hello"]) + + self.assertNotIn("temperature", completions.request) + + def test_reasoning_identity_reports_only_settings_sent_to_openai(self) -> None: + """ + Reasoning-model identity must not claim controls the adapter does not transmit. + """ + + adapter = OpenAILLM( + configuration=LLMConfiguration( + provider="openai", + api_key="test-key", + model="gpt-5.2", + temperature=0.7, + use_cache=True, + ) + ) + + self.assertIsNone(adapter.identity.settings.temperature) + self.assertIsNone(adapter.identity.settings.cache) + + def test_non_reasoning_identity_reports_transmitted_temperature(self) -> None: + """ + Non-reasoning identity reports temperature while leaving provider-managed cache unknown. + """ + + adapter = OpenAILLM( + configuration=LLMConfiguration( + provider="openai", + api_key="test-key", + model="gpt-4.1-mini", + temperature=0.4, + use_cache=True, + ) + ) + + self.assertEqual(adapter.identity.settings.temperature, 0.4) + self.assertIsNone(adapter.identity.settings.cache) diff --git a/tests/unit/adapters/localization/gemini/test_vision.py b/tests/unit/adapters/localization/gemini/test_vision.py index 6f0a731c..38c31449 100644 --- a/tests/unit/adapters/localization/gemini/test_vision.py +++ b/tests/unit/adapters/localization/gemini/test_vision.py @@ -2,569 +2,96 @@ import json import unittest -from typing import Any, Dict, Optional -from fathom.adapters.localization.gemini.vision import GeminiVisionLocalizer -from fathom.constants.observation import KeyboardVisibility -from fathom.interfaces.llm import LLMPort -from fathom.schemas.actions import Action, CoordinateSource, CoordinateSystem -from fathom.schemas.budgets import LocalizationBudget -from fathom.schemas.observation import KeyboardObservation, ScreenObservation -from fathom.schemas.results import GenerateResult -from fathom.schemas.screens import ScreenCapture, ScreenHashBundle +from fathom.adapters.localization.vision import VisionLLMLocalizer +from fathom.constants.localization import LocalizationGridScale +from fathom.schemas.localization import VisionLocalizationPayload -class _StaticLlm(LLMPort): +class VisionPayloadGridClampTest(unittest.TestCase): """ - :class:`LLMPort` test double that returns a frozen payload. - - Production paths read ``model_name`` for cache routing and call - ``generate`` exactly once per localizer turn. The double records the - call count so the empty-target test can pin that the localizer never - reaches the LLM. ``cleanup`` is required by the port contract and is a - no-op here. - """ - - def __init__( - self, - *, - payload: Optional[Dict[str, Any]] = None, - raw: Optional[str] = None, - ) -> None: - """ - Initialise with either a JSON-serialisable ``payload`` (encoded on - demand) or a verbatim ``raw`` body. ``raw`` wins when both are set - — used by the malformed-JSON test. - """ - - self.__payload = payload - self.__raw = raw - self.calls: int = 0 - - @property - def model_name(self) -> str: - """ - Stable identifier surfaced in cache keys and structured logs. - """ - - return "static-llm" - - async def generate( # type: ignore[no-untyped-def] - self, - *, - use_cache, - prompt, - tools=None, - system_instruction=None, - conversation_history=None, - structured_output=None, - ): - """ - Return the preconfigured :class:`GenerateResult` and increment the - call counter so callers can verify dispatch happened (or didn't). - """ - - _ = structured_output - self.calls += 1 - content = self.__raw if self.__raw is not None else json.dumps(self.__payload) - return GenerateResult(content=content, metrics={}) - - async def cleanup(self) -> None: - """ - Port-required teardown hook. No resources are held by this double. - """ - - return None - - -class GeminiVisionLocalizerTest(unittest.IsolatedAsyncioTestCase): - """ - Pins the Gemini vision localizer's payload-decoding and refusal handling. - - The localizer issues exactly one LLM call, parses a normalized - bounding-box payload, and returns a :class:`LocalizationProposal` — - or ``None`` for refusals, malformed JSON, blank targets, and zero-area - payloads. Confidence is clamped to the closed unit interval. + A proposal that overshoots one grid edge still localizes the target, so the edge is clamped + rather than the whole proposal discarded. """ @staticmethod - def __capture(*, width: int = 200, height: int = 400) -> ScreenCapture: + def __within_grid(*, raw: str): """ - :class:`ScreenCapture` fixture with overridable dimensions so the - zero-width-pixel test can drive a small canvas where rounding pins - the rejection path. + Invoke the adapter's private grid-clamp over a raw model response. """ - return ScreenCapture( - width=width, - height=height, - activity="app", - image=b"PNGFAKE", - timestamp=0, + return VisionLLMLocalizer._VisionLLMLocalizer__within_grid( # type: ignore[attr-defined] + document=json.loads(raw) ) - @staticmethod - def __action(*, target: str = "Continue button") -> Action: + def test_overshooting_edge_is_clamped_and_reported(self) -> None: """ - :class:`Action` fixture parameterised on the semantic target. The - empty-target test passes whitespace to exercise the short-circuit. + Regression: the real gpt-4.1 response overshot y2 by 50 and was discarded entirely. """ - return Action( # type: ignore[arg-type] - action_type="tap", - target=target, - rationale="test", - confidence=1.0, + document, clamped = self.__within_grid( + raw='{"x1":825,"y1":933,"x2":950,"y2":1050,"confidence":0.98,"rationale":"cog icon"}' ) - @staticmethod - def __budget() -> LocalizationBudget: - """ - :class:`LocalizationBudget` with paid vision enabled and a generous - local window so the budget never gates the test. - """ - - return LocalizationBudget(vision=True, attempts=1, local=2000, threshold=0.5) - - @staticmethod - def __observation() -> ScreenObservation: - """ - Minimal :class:`ScreenObservation` fixture. The vision localizer - ignores the observation entirely; it exists only to satisfy the - port signature. - """ - - return ScreenObservation( - activity="app", - hashes=ScreenHashBundle( - visual_hash="0" * 16, - xml_hash="a" * 16, - interaction_hash="b" * 16, - ), - elements=(), - keyboard=KeyboardObservation(visibility=KeyboardVisibility.HIDDEN), - ) + self.assertEqual(clamped, ("y2",)) + self.assertEqual(document["y2"], int(LocalizationGridScale.MAXIMUM)) + self.assertEqual(document["x1"], 825) + self.assertIsInstance(document["y2"], int) - async def test_valid_payload_renders_logical_bounds(self) -> None: + def test_clamped_document_passes_the_published_schema(self) -> None: """ - A grid-bbox payload is projected onto the capture's logical dims and stamped LOGICAL with source MODEL. + The clamped document validates, so the localizer returns a proposal instead of abstaining. """ - llm = _StaticLlm( - payload={ - "x1": 250, - "y1": 500, - "x2": 750, - "y2": 750, - "confidence": 0.8, - "rationale": "tight match", - }, + document, _ = self.__within_grid( + raw='{"x1":825,"y1":933,"x2":950,"y2":1050,"confidence":0.98,"rationale":"cog icon"}' ) - localizer = GeminiVisionLocalizer(llm=llm) - proposal = await localizer.locate( - action=self.__action(), - capture=self.__capture(width=200, height=400), - budget=self.__budget(), - observation=self.__observation(), - ) + payload = VisionLocalizationPayload.model_validate(document) - self.assertIsNotNone(proposal) - assert proposal is not None - self.assertEqual(proposal.bounds.x, 50) - self.assertEqual(proposal.bounds.y, 200) - self.assertEqual(proposal.bounds.width, 100) - self.assertEqual(proposal.bounds.height, 100) - self.assertIs(proposal.bounds.system, CoordinateSystem.LOGICAL) - self.assertIs(proposal.bounds.source, CoordinateSource.MODEL) - self.assertAlmostEqual(proposal.confidence, 0.8) - self.assertEqual(proposal.source, "gemini.vision") + self.assertEqual(payload.y2, int(LocalizationGridScale.MAXIMUM)) - async def test_grid_payload_survives_dispatch_translation_on_retina(self) -> None: + def test_negative_edge_is_clamped_to_the_grid_floor(self) -> None: """ - Grid-bbox payload on a 3x retina capture must dispatch at the logical region the localizer named. - Mislabelling the bounds as DEVICE_PIXEL would divide by the 3x scale and shrink the target ninefold. + Undershoot is clamped symmetrically with overshoot. """ - llm = _StaticLlm( - payload={ - "x1": 344, - "y1": 465, - "x2": 656, - "y2": 518, - "confidence": 0.9, - "rationale": "tight overlay button", - }, - ) - localizer = GeminiVisionLocalizer(llm=llm) - - logical_width = 375 - logical_height = 812 - pixel_width = 1125 - pixel_height = 2436 - - proposal = await localizer.locate( - action=self.__action(target="Alright, got it"), - capture=self.__capture(width=logical_width, height=logical_height), - budget=self.__budget(), - observation=self.__observation(), + document, clamped = self.__within_grid( + raw='{"x1":-20,"y1":10,"x2":950,"y2":900,"confidence":0.5,"rationale":"r"}' ) - self.assertIsNotNone(proposal) - assert proposal is not None - self.assertIs(proposal.bounds.system, CoordinateSystem.LOGICAL) + self.assertEqual(clamped, ("x1",)) + self.assertEqual(document["x1"], int(LocalizationGridScale.MINIMUM)) - dispatch_x, dispatch_y, dispatch_width, dispatch_height = ( - proposal.bounds.to_logical_dispatch( - logical_width=logical_width, - logical_height=logical_height, - pixel_width=pixel_width, - pixel_height=pixel_height, - ) - ) - - self.assertEqual(dispatch_x, 129) - self.assertEqual(dispatch_y, 377) - self.assertEqual(dispatch_width, 117) - self.assertEqual(dispatch_height, 43) - - async def test_all_zero_payload_is_refusal_not_zero_bound_proposal(self) -> None: - """ - The all-zero coordinate/confidence payload is the refusal protocol marker. - """ - - llm = _StaticLlm( - payload={ - "x1": 0, - "y1": 0, - "x2": 0, - "y2": 0, - "confidence": 0.0, - "rationale": "Target not visible.", - }, - ) - localizer = GeminiVisionLocalizer(llm=llm) - - result = await localizer.locate( - action=self.__action(), - capture=self.__capture(), - budget=self.__budget(), - observation=self.__observation(), - ) - - self.assertIsNone(result) - - async def test_malformed_json_response_returns_none(self) -> None: - """ - A non-JSON response body must not raise. The localizer logs a - structured ``payload.invalid_json`` event and returns ``None`` so - the ensemble can poll the next member. - """ - - localizer = GeminiVisionLocalizer(llm=_StaticLlm(raw="not json")) - - result = await localizer.locate( - action=self.__action(), - capture=self.__capture(), - budget=self.__budget(), - observation=self.__observation(), - ) - - self.assertIsNone(result) - - async def test_blank_target_short_circuits_before_llm_call(self) -> None: + def test_in_range_payload_is_untouched(self) -> None: """ - A whitespace-only target text must short-circuit before the LLM - call. The call-count assertion pins that no provider quota is - spent on requests the model cannot resolve. + A well-formed proposal reports no clamping and keeps every value. """ - llm = _StaticLlm( - payload={ - "x1": 100, - "y1": 100, - "x2": 600, - "y2": 600, - "confidence": 0.9, - "rationale": "would never be sent", - }, - ) - localizer = GeminiVisionLocalizer(llm=llm) - - result = await localizer.locate( - action=self.__action(target=" "), - capture=self.__capture(), - budget=self.__budget(), - observation=self.__observation(), - ) + raw = '{"x1":774,"y1":793,"x2":934,"y2":875,"confidence":0.9,"rationale":"r"}' + document, clamped = self.__within_grid(raw=raw) - self.assertIsNone(result) - self.assertEqual(llm.calls, 0) + self.assertEqual(clamped, ()) + self.assertEqual(document, json.loads(raw)) - async def test_zero_pixel_box_rejected_as_invalid(self) -> None: + def test_non_object_response_passes_through_unclamped(self) -> None: """ - Payloads whose projected width or height rounds to zero pixels are rejected even when the grid coordinates are non-zero. + A response that is not a JSON object is left for schema validation to reject. """ - llm = _StaticLlm( - payload={ - "x1": 100, - "y1": 100, - "x2": 101, - "y2": 600, - "confidence": 0.9, - "rationale": "narrow rectangle for projection rounding", - }, - ) - localizer = GeminiVisionLocalizer(llm=llm) + document, clamped = self.__within_grid(raw="[1, 2, 3]") - result = await localizer.locate( - action=self.__action(), - capture=self.__capture(width=10, height=10), - budget=self.__budget(), - observation=self.__observation(), - ) + self.assertEqual(clamped, ()) + self.assertEqual(document, [1, 2, 3]) - self.assertIsNone(result) - - async def test_confidence_out_of_range_returns_none(self) -> None: + def test_boolean_edge_is_not_treated_as_an_integer(self) -> None: """ - Provider-reported confidence outside the closed unit interval is rejected at the schema boundary. + ``True`` is an ``int`` in Python; it must not be silently clamped into a coordinate. """ - llm = _StaticLlm( - payload={ - "x1": 100, - "y1": 100, - "x2": 600, - "y2": 600, - "confidence": 2.5, - "rationale": "model overshoots the unit interval", - }, - ) - localizer = GeminiVisionLocalizer(llm=llm) - - proposal = await localizer.locate( - action=self.__action(), - capture=self.__capture(), - budget=self.__budget(), - observation=self.__observation(), + document, clamped = self.__within_grid( + raw='{"x1":true,"y1":10,"x2":950,"y2":900,"confidence":0.5,"rationale":"r"}' ) - self.assertIsNone(proposal) - - -class _DelayedLlm(LLMPort): - """ - Test double whose ``generate`` sleeps for a configurable duration before - returning a frozen payload — drives the retry/timeout invariants of the - vision adapter. - """ - - def __init__( - self, - *, - delays_seconds: tuple, - payload: Optional[Dict[str, Any]] = None, - ) -> None: - """ - Initialise with a per-attempt delay tuple and a fixed payload. - """ - - import asyncio - - self.__asyncio = asyncio - self.__delays = list(delays_seconds) - self.__payload = payload or { - "x1": 100, - "y1": 100, - "x2": 200, - "y2": 200, - "confidence": 0.9, - "rationale": "test", - } - self.calls: int = 0 - - @property - def model_name(self) -> str: - """ - Stable identifier surfaced in cache keys and structured logs. - """ - - return "delayed-llm" - - async def generate( # type: ignore[no-untyped-def] - self, - *, - use_cache, - prompt, - tools=None, - system_instruction=None, - conversation_history=None, - structured_output=None, - ): - """ - Sleep for the next configured delay then return the fixed payload. - """ - - index = self.calls - self.calls += 1 - delay = self.__delays[index] if index < len(self.__delays) else 0.0 - await self.__asyncio.sleep(delay) - return GenerateResult(content=json.dumps(self.__payload), metrics={}) - - async def cleanup(self) -> None: - """ - Port-required teardown hook. No resources are held by this double. - """ - - return None - - -class GeminiVisionLocalizerTimeoutTest(unittest.IsolatedAsyncioTestCase): - """ - Pins the per-attempt timeout and retry-with-backoff behaviour of the - vision adapter. Uses a sub-millisecond timeout so the tests stay fast. - """ - - @staticmethod - def __capture() -> ScreenCapture: - """ - Minimal capture fixture; the adapter ignores its bytes in these tests. - """ - - return ScreenCapture( - width=200, - height=400, - activity="app", - image=b"PNGFAKE", - timestamp=0, - ) - - @staticmethod - def __action() -> Action: - """ - Minimal action fixture with a non-empty target so the adapter does not - short-circuit before reaching the retry loop. - """ - - return Action( # type: ignore[arg-type] - action_type="tap", - target="Continue button", - rationale="test", - confidence=1.0, - ) - - @staticmethod - def __budget() -> LocalizationBudget: - """ - Localization budget fixture; the adapter owns its own timeout now - and ignores ``budget.local`` for per-attempt waits. - """ - - return LocalizationBudget(vision=True, attempts=1, local=10_000, threshold=0.5) - - @staticmethod - def __observation() -> ScreenObservation: - """ - Minimal observation fixture; vision localizer reads no fields off it. - """ - - return ScreenObservation( - activity="app", - hashes=ScreenHashBundle( - visual_hash="0" * 16, - xml_hash="a" * 16, - interaction_hash="b" * 16, - ), - elements=(), - keyboard=KeyboardObservation(visibility=KeyboardVisibility.HIDDEN), - ) - - @staticmethod - def __configuration(*, timeout_milliseconds: int, attempts: int) -> Any: - """ - Build a vision localization configuration with the requested timeout - and attempts; backoff stays at the default 1.5x multiplier. - """ - - from fathom.schemas.localization import ( - VisionLocalizationConfiguration, - VisionRetryPolicy, - ) - - return VisionLocalizationConfiguration( - timeout=timeout_milliseconds, - retry=VisionRetryPolicy(attempts=attempts, backoff=1.0), - ) - - async def test_first_attempt_timeout_is_retried_and_succeeds(self) -> None: - """ - First attempt sleeps longer than the per-attempt timeout, second - attempt returns within the window — the adapter must retry and - return the proposal from the second call. - """ - - llm = _DelayedLlm(delays_seconds=(0.1, 0.0)) - localizer = GeminiVisionLocalizer( - llm=llm, - configuration=self.__configuration(timeout_milliseconds=50, attempts=2), - ) - - proposal = await localizer.locate( - action=self.__action(), - capture=self.__capture(), - budget=self.__budget(), - observation=self.__observation(), - ) - - self.assertIsNotNone(proposal) - self.assertEqual(llm.calls, 2) - - async def test_all_attempts_timeout_returns_none(self) -> None: - """ - Every attempt exceeds the per-attempt timeout; after the configured - attempt budget is exhausted the adapter abstains by returning ``None``. - """ - - llm = _DelayedLlm(delays_seconds=(0.1, 0.1)) - localizer = GeminiVisionLocalizer( - llm=llm, - configuration=self.__configuration(timeout_milliseconds=20, attempts=2), - ) - - result = await localizer.locate( - action=self.__action(), - capture=self.__capture(), - budget=self.__budget(), - observation=self.__observation(), - ) - - self.assertIsNone(result) - self.assertEqual(llm.calls, 2) - - async def test_single_attempt_when_attempts_is_one(self) -> None: - """ - With ``attempts=1`` the adapter must not retry on timeout; exactly one - LLM call happens and a timeout yields ``None``. - """ - - llm = _DelayedLlm(delays_seconds=(0.05,)) - localizer = GeminiVisionLocalizer( - llm=llm, - configuration=self.__configuration(timeout_milliseconds=10, attempts=1), - ) - - result = await localizer.locate( - action=self.__action(), - capture=self.__capture(), - budget=self.__budget(), - observation=self.__observation(), - ) - - self.assertIsNone(result) - self.assertEqual(llm.calls, 1) - - -if __name__ == "__main__": - unittest.main() + self.assertEqual(clamped, ()) + self.assertIs(document["x1"], True) diff --git a/tests/unit/adapters/tools/test_gemini.py b/tests/unit/adapters/tools/test_gemini.py index 85c132b7..e16cf627 100644 --- a/tests/unit/adapters/tools/test_gemini.py +++ b/tests/unit/adapters/tools/test_gemini.py @@ -11,12 +11,12 @@ class GeminiToolDialectTest(unittest.TestCase): Gemini tool translation remains self-contained in the provider-neutral foundation. """ - def test_foundation_exports_only_the_available_dialect(self) -> None: + def test_package_exports_the_gemini_dialect(self) -> None: """ - The foundation package must not import a dialect introduced by a child PR. + The adapter package continues to expose the Gemini dialect after adding providers. """ - self.assertEqual(tools.__all__, ["GeminiToolDialect"]) + self.assertIn("GeminiToolDialect", tools.__all__) self.assertIs(tools.GeminiToolDialect, GeminiToolDialect) def test_encode_wraps_canonical_declarations_without_mutating_them(self) -> None: diff --git a/tests/unit/adapters/tools/test_openai.py b/tests/unit/adapters/tools/test_openai.py new file mode 100644 index 00000000..8d3bff03 --- /dev/null +++ b/tests/unit/adapters/tools/test_openai.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +import unittest + +from fathom.adapters.tools import OpenAIToolDialect + + +class OpenAIToolDialectTest(unittest.TestCase): + """ + OpenAI tool translation stays at the provider adapter boundary. + """ + + def test_schema_types_are_normalized_for_openai(self) -> None: + """ + Gemini-style uppercase schema types become OpenAI lowercase types. + """ + + encoded = OpenAIToolDialect().encode( + payload={ + "tools": [ + { + "name": "execute_ui", + "parameters": { + "type": "OBJECT", + "properties": {"x": {"type": "NUMBER"}}, + }, + } + ] + } + ) + + parameters = encoded["tools"][0]["function"]["parameters"] + self.assertEqual(parameters["type"], "object") + self.assertEqual(parameters["properties"]["x"]["type"], "number") diff --git a/tests/unit/core/config/test_loader.py b/tests/unit/core/config/test_loader.py index 248f2b2c..3a0fc540 100644 --- a/tests/unit/core/config/test_loader.py +++ b/tests/unit/core/config/test_loader.py @@ -205,7 +205,7 @@ def test_journal_local_flag_routes_through(self) -> None: def test_localization_defaults_enable_full_ensemble(self) -> None: """ Bring-up default: the ensemble vision-localizer is enabled with - both members (Gemini-vision + DocumentAI-layout) so the supervise + both members (provider-neutral vision + DocumentAI-layout) so the supervise cascade has a name-based fallback when snap fails. """ @@ -214,7 +214,7 @@ def test_localization_defaults_enable_full_ensemble(self) -> None: self.assertTrue(config.enabled) self.assertEqual( config.members, - (EnsembleMemberName.GEMINI_VISION, EnsembleMemberName.DOCUMENT_AI_LAYOUT), + (EnsembleMemberName.VISION_LLM, EnsembleMemberName.DOCUMENT_AI_LAYOUT), ) def test_localization_can_be_flipped_off_via_env(self) -> None: diff --git a/tests/unit/core/prompts/test_factory.py b/tests/unit/core/prompts/test_factory.py new file mode 100644 index 00000000..caaa34d6 --- /dev/null +++ b/tests/unit/core/prompts/test_factory.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +import unittest + +from fathom.constants.llm import ModelProvider +from fathom.core.prompts.factory import PromptFactory + + +class PromptFactoryProviderTest(unittest.TestCase): + """ + Prompt selection follows the explicitly declared provider. + """ + + def test_openai_uses_an_explicit_prompt_builder(self) -> None: + """ + An OpenAI declaration selects the OpenAI prompt adapter explicitly. + """ + + builder = PromptFactory.get_builder( + model_name="gpt-5", + provider=ModelProvider.OPENAI, + ) + + self.assertEqual(type(builder).__name__, "OpenAIPromptBuilder") + + def test_vertex_ai_uses_gemini_prompt_dialect_explicitly(self) -> None: + """ + Vertex AI selects the Gemini prompt dialect through an explicit mapping. + """ + + builder = PromptFactory.get_builder( + model_name="gemini-3.5-flash", + provider=ModelProvider.VERTEX_AI, + ) + + self.assertEqual(type(builder).__name__, "GeminiPromptBuilder") diff --git a/tests/unit/core/prompts/test_tools_schema.py b/tests/unit/core/prompts/test_tools_schema.py index 97fafe85..ef494f09 100644 --- a/tests/unit/core/prompts/test_tools_schema.py +++ b/tests/unit/core/prompts/test_tools_schema.py @@ -12,6 +12,17 @@ class ToolRegistryTest(unittest.TestCase): Pins the tool catalog filtering and ordering contracts. """ + def test_canonical_definitions_have_no_provider_envelope(self) -> None: + """ + Canonical declarations use the provider-neutral tools key. + """ + + payload = ToolRegistry.canonical_definitions_for(names=frozenset({ToolName.EXECUTE_UI})) + + self.assertIn("tools", payload) + self.assertNotIn("function_declarations", payload) + self.assertEqual(payload["tools"][0]["name"], "execute_ui") + def test_execute_ui_action_requires_confidence(self) -> None: """ execute_ui's schema must require action.confidence on every tool call. diff --git a/tests/unit/runtime/test_adapters.py b/tests/unit/runtime/test_adapters.py index 87063ed3..3535e9ae 100644 --- a/tests/unit/runtime/test_adapters.py +++ b/tests/unit/runtime/test_adapters.py @@ -5,12 +5,13 @@ from typing import Optional from unittest import mock +from fathom.adapters.embedding.gemini import GeminiEmbeddingAdapter from fathom.adapters.icon.noop import NoopIconDetector from fathom.adapters.icon.template import TemplateIconDetector from fathom.adapters.journal.jsonl import JsonRuntimeJournal from fathom.adapters.journal.noop import NoopRuntimeJournal from fathom.adapters.localization.document.layout import DocumentAiLayoutLocalizer -from fathom.adapters.localization.gemini.vision import GeminiVisionLocalizer +from fathom.adapters.localization.vision import VisionLLMLocalizer from fathom.adapters.ocr.document.adapter import DocumentAiOcr from fathom.adapters.ocr.noop import NoopOcr from fathom.adapters.perception.overlay.noop import NoopOverlayDetector @@ -205,7 +206,7 @@ def test_ensemble_builds_configured_members(self) -> None: members = assembly.ensemble().members self.assertEqual(len(members), 2) - self.assertIsInstance(members[0], GeminiVisionLocalizer) + self.assertIsInstance(members[0], VisionLLMLocalizer) self.assertIsInstance(members[1], DocumentAiLayoutLocalizer) def test_ensemble_drops_document_ai_layout_when_ocr_disabled(self) -> None: @@ -223,7 +224,7 @@ def test_ensemble_drops_document_ai_layout_when_ocr_disabled(self) -> None: members = assembly.ensemble().members self.assertEqual(len(members), 1) - self.assertIsInstance(members[0], GeminiVisionLocalizer) + self.assertIsInstance(members[0], VisionLLMLocalizer) def test_journal_returns_noop_when_local_disabled(self) -> None: """ @@ -252,3 +253,71 @@ def test_journal_returns_jsonl_when_enabled_with_directory(self) -> None: ) self.assertIsInstance(assembly.journal(), JsonRuntimeJournal) + + +class _ClientLlm(_FakeLlm): + """ + LLM double exposing a provider client, as the Gemini adapter does after initialization. + """ + + def __init__(self, *, client: Optional[object]) -> None: + """ + Record the client this double exposes. + """ + + self.__client = client + + @property + def client(self) -> Optional[object]: + """ + Provider client a sibling embedding adapter would share. + """ + + return self.__client + + +class AdapterAssemblyEmbedderTest(unittest.TestCase): + """ + Embedder composition is decided by the typed port capability, so a custom LLMPort that + exposes no client disables embeddings instead of raising. + """ + + @staticmethod + def __assemble(*, llm: LLMPort) -> AdapterAssembly: + """ + Build an assembly around the supplied LLM with env isolated from the developer's shell. + """ + + with mock.patch.dict("os.environ", {}, clear=True): + settings = FathomSettings(_env_file=None) + return AdapterAssembly( + loader=RuntimeConfigLoader(settings=settings), + llm=llm, + workflow_id="run-abc", + ) + + def test_custom_llm_without_a_client_disables_embeddings(self) -> None: + """ + A third-party LLMPort that declares no client yields no embedder rather than failing. + """ + + self.assertIsNone(self.__assemble(llm=_FakeLlm()).embedder()) + + def test_uninitialized_client_disables_embeddings(self) -> None: + """ + An adapter whose client never initialized yields no embedder. + """ + + self.assertIsNone(self.__assemble(llm=_ClientLlm(client=None)).embedder()) + + def test_client_bearing_llm_builds_the_gemini_embedding_adapter(self) -> None: + """ + An adapter exposing a live client backs a Gemini embedding adapter sharing that client. + """ + + client = object() + + embedder = self.__assemble(llm=_ClientLlm(client=client)).embedder() + + self.assertIsInstance(embedder, GeminiEmbeddingAdapter) + self.assertIs(embedder._GeminiEmbeddingAdapter__client, client) # type: ignore[attr-defined] diff --git a/tests/unit/runtime/test_assembly.py b/tests/unit/runtime/test_assembly.py index b9958e60..20d5a3b5 100644 --- a/tests/unit/runtime/test_assembly.py +++ b/tests/unit/runtime/test_assembly.py @@ -43,6 +43,40 @@ def __principal(self) -> Principal: conversation="conversation", ) + def test_openai_settings_resolve_without_google_credentials(self) -> None: + """ + OpenAI runs use the OpenAI key/model and do not inherit Google credentials. + """ + + assembly = RunAssemblyBuilder( + settings=FathomSettings( + _env_file=None, + llm_provider="openai", + openai_api_key="openai-test-key", + openai_model="gpt-4.1-mini", + google_application_credentials="/should/not/be-used.json", + ) + ) + request = IntentRunRequest( + principal=self.__principal(), + objective=IntentObjectiveConfiguration(intent="Open the app"), + resources=ResourceConfiguration( + targets=[ + TargetConfiguration( + kind=TargetKind.DEVICE, + device_configuration=DeviceConfiguration(), + ) + ] + ), + ) + + configuration = assembly.build_planner_model_configuration(request=request) + + self.assertEqual(configuration.provider, "openai") + self.assertEqual(configuration.api_key, "openai-test-key") + self.assertEqual(configuration.model, "gpt-4.1-mini") + self.assertIsNone(configuration.credentials) + def test_qualifier_llm_inherits_credentials_from_bound_settings(self) -> None: """ Credentials must come from the settings bound to this assembly builder.