Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 43 additions & 3 deletions src/fathom/adapters/llm/gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from google.oauth2 import service_account

from fathom.adapters.llm.cache import CacheService
from fathom.adapters.tools import GeminiToolDialect
from fathom.constants.llm import (
GEMINI_CANCELLED_ERROR_MARKERS,
GEMINI_CANCELLED_STATUS_CODE,
Expand All @@ -33,17 +34,21 @@
GEMINI_VERTEX_REQUEST_TYPE_HEADER,
GEMINI_VERTEX_SHARED_REQUEST_TYPE,
InferenceTier,
ModelProvider,
StructuredOutputMediaType,
)
from fathom.core.exceptions import VisionError
from fathom.core.inference.priority import PriorityInferencePolicy
from fathom.core.services.parsing import ToolResponseParser
from fathom.interfaces.llm import LLMPort
from fathom.interfaces.tools import CanonicalToolPayload
from fathom.schemas.configuration import LLMConfiguration
from fathom.schemas.conversation import ConversationTurn
from fathom.schemas.llm import (
GeminiExceptionKind,
GeminiExceptionMetadata,
InferenceSettings,
ModelIdentity,
PriorityInferenceSignal,
PriorityInferenceTransition,
StructuredOutput,
Expand Down Expand Up @@ -74,6 +79,8 @@ def __init__(
else:
self.__configuration = LLMConfiguration(api_key=api_key, model=model, use_cache=True)

self.__tool_dialect = GeminiToolDialect()

self.__client: Optional[Any] = None
self.__credentials: Optional[Any] = None
self.__priority = PriorityInferencePolicy(configuration=self.__configuration.priority)
Expand All @@ -91,6 +98,22 @@ def model_name(self) -> str:

return self.__configuration.model

@property
def identity(self) -> ModelIdentity:
"""
Declare the configured provider, model, and the settings that affect comparability.
"""

return ModelIdentity(
provider=ModelProvider.declared(value=self.__configuration.provider),
model=self.__configuration.model,
settings=InferenceSettings(
cache=self.__configuration.use_cache,
thinking=self.__configuration.thinking_level,
temperature=self.__configuration.temperature,
),
)

def derive(self, *, overrides: LLMConfiguration) -> LLMPort:
"""
Spawn a sibling adapter sharing credentials and model, applying only the
Expand Down Expand Up @@ -348,10 +371,12 @@ async def generate(
if structured_output is not None and tools:
raise VisionError("Structured-output mode cannot be combined with tool calling")

provider_tools = self.__encode_tools(tools=tools)

if use_cache and self.__cache and system_instruction and structured_output is None:
cache_name = await self.__cache.get_cached_content(
system_instruction=system_instruction,
tools=tools.get("function_declarations") if tools else None,
tools=provider_tools.get("function_declarations") if provider_tools else None,
)
else:
cache_name = None
Expand Down Expand Up @@ -386,7 +411,7 @@ async def generate(

config = self.__get_generation_configuration(
tier=tier,
tools=tools,
tools=provider_tools,
cache_name=active_cache_name,
structured_output=structured_output,
system_instruction=system_instruction,
Expand Down Expand Up @@ -650,13 +675,28 @@ async def prewarm(
if not self.__configuration.use_cache:
return

declarations = tools.get("function_declarations") if tools is not None else None
provider_tools = self.__encode_tools(tools=tools)
declarations = provider_tools.get("function_declarations") if provider_tools else None

await self.__cache.get_cached_content(
tools=declarations,
system_instruction=system_instruction,
)

def __encode_tools(self, *, tools: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
"""
Translate canonical declarations at the Gemini adapter boundary.

Accepting the legacy envelope keeps older integrations working while all migrated runtime
callers use the provider-neutral ``{"tools": [...]}`` shape.
"""

if tools is None or "function_declarations" in tools:
return tools

canonical: CanonicalToolPayload = {"tools": tools.get("tools", [])}
return self.__tool_dialect.encode(payload=canonical)

async def cleanup(self) -> None:
"""
Delete the provider cache, then close the SDK client.
Expand Down
10 changes: 9 additions & 1 deletion src/fathom/adapters/summarization/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,14 @@ def __init__(self, llm: LLMPort) -> None:

self.__llm = llm

@property
def llm(self) -> LLMPort:
"""
The LLM adapter this summarizer was composed with.
"""

return self.__llm

async def summarize_trace(self, trace: List[Dict[str, Any]]) -> str:
"""
Build a milestone summary of the trace via tool calling: the accomplishment, the key actions,
Expand Down Expand Up @@ -77,7 +85,7 @@ async def summarize_trace(self, trace: List[Dict[str, Any]]) -> str:

# Use tool calling for structured summarization
tool_definition = {
"function_declarations": [
"tools": [
{
"name": "create_milestone",
"description": "Create a structured milestone summary of the execution segment",
Expand Down
5 changes: 5 additions & 0 deletions src/fathom/adapters/tools/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Expose provider tool-dialect adapters."""

from fathom.adapters.tools.gemini import GeminiToolDialect

__all__ = ["GeminiToolDialect"]
20 changes: 20 additions & 0 deletions src/fathom/adapters/tools/gemini.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Encode provider-neutral tools for the Gemini SDK."""

from __future__ import annotations

from typing import Any, Dict, List, Mapping

from fathom.interfaces.tools import ToolDeclaration, ToolDialect


class GeminiToolDialect(ToolDialect):
"""
Encode the provider-neutral tool contract as Gemini function declarations.
"""

def encode(self, *, payload: Mapping[str, List[ToolDeclaration]]) -> Dict[str, Any]:
"""
Return the Gemini SDK envelope without mutating the canonical declarations.
"""

return {"function_declarations": list(payload.get("tools", []))}
26 changes: 26 additions & 0 deletions src/fathom/constants/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,29 @@ class StructuredOutputMediaType(StrEnum):
"invalid_argument",
"invalid resource state",
)


class ModelProvider(StrEnum):
"""
Provider identity an LLM adapter declares for itself, never inferred from its class name.

Values mirror the ``LLMConfiguration.provider`` vocabulary and are persisted on recorded
runs, so they keep that literal protocol form rather than the internal upper-case style.
"""

GEMINI = "gemini"
VERTEX_AI = "vertex_ai"
OPENAI = "openai"
ANTHROPIC = "anthropic"
UNKNOWN = "unknown"

@classmethod
def declared(cls, *, value: str) -> "ModelProvider":
"""
Map a configuration-declared provider value onto its typed identity.
"""

try:
return cls(value)
except ValueError:
return cls.UNKNOWN
53 changes: 53 additions & 0 deletions src/fathom/constants/manifest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""Define model-role manifest constants and enums."""

from __future__ import annotations

from enum import StrEnum
from typing import Final

MANIFEST_VERSION: Final[int] = 1


class ModelRole(StrEnum):
"""
A model-consuming role Fathom composes for a run.
"""

PLANNER = "PLANNER"
ARCHITECT = "ARCHITECT"
QUALIFIER = "QUALIFIER"
SUMMARIZER = "SUMMARIZER"
ABORT = "ABORT"
LOCALIZER = "LOCALIZER"
EMBEDDER = "EMBEDDER"
ORACLE = "ORACLE"


class RoleBinding(StrEnum):
"""
How a role obtained its adapter relative to the other roles in the run.
"""

INDEPENDENT = "INDEPENDENT"
DERIVED = "DERIVED"
SHARED = "SHARED"
NONE = "NONE"
UNKNOWN = "UNKNOWN"


SHARED_ARCHITECT_NOTE: Final[str] = (
"derive() returned the planner adapter itself, so the architect is not a deterministic "
"sibling and runs at the planner's temperature and cache setting."
)
SHARED_QUALIFIER_NOTE: Final[str] = (
"Qualifier runs on the planner adapter, so its inference configuration does not apply; a "
"dedicated adapter is built only when the runner is composed with an assembly."
)
UNDECLARED_BINDING_NOTE: Final[str] = (
"Port does not expose the adapter it was composed with, so its relationship to the planner "
"is not determinable."
)
UNREAD_CONFIGURATION_NOTE: Final[str] = (
"Composition ignores this role's configured model and enabled flag; the role runs on the "
"planner adapter."
)
20 changes: 20 additions & 0 deletions src/fathom/core/embedding/capability.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Detect whether an LLM adapter supports embeddings."""

from __future__ import annotations

from fathom.interfaces.embedding import EmbeddingCapable
from fathom.interfaces.llm import LLMPort


class EmbeddingCapability:
"""
Single rule for whether an LLM adapter can back a sibling embedding adapter.
"""

@staticmethod
def available(*, llm: LLMPort) -> bool:
"""
Whether the adapter declares an embedding-capable client and has initialized one.
"""

return isinstance(llm, EmbeddingCapable) and llm.client is not None
8 changes: 8 additions & 0 deletions src/fathom/core/services/qualifier/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ def __init__(
self.__prompt_builder = prompt_builder or GeminiQualifierPromptBuilder()
self.__structured_output = StructuredOutput(payload=QualificationVerdict)

@property
def llm(self) -> LLMPort:
"""
The LLM adapter this qualifier was composed with.
"""

return self.__llm

async def qualify(self, *, intent: str) -> QualificationVerdict:
"""
Classify the intent's executability and return a verdict.
Expand Down
17 changes: 16 additions & 1 deletion src/fathom/interfaces/embedding.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,26 @@
from __future__ import annotations

from abc import ABC, abstractmethod
from typing import Tuple
from typing import Any, Protocol, Tuple, runtime_checkable

from fathom.schemas.embedding import EmbeddingResult


@runtime_checkable
class EmbeddingCapable(Protocol):
"""
Capability for an LLM adapter that exposes a client a sibling embedding adapter can share.
"""

@property
def client(self) -> Any:
"""
Provider client reused for embedding calls; None until the adapter has initialized one.
"""

...


class EmbeddingPort(ABC):
"""
Domain-facing port for producing dense embedding vectors over text.
Expand Down
53 changes: 47 additions & 6 deletions src/fathom/interfaces/llm.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,20 @@
from __future__ import annotations

from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence, Union

from typing import (
TYPE_CHECKING,
Any,
Dict,
Optional,
Protocol,
Sequence,
Union,
runtime_checkable,
)

from fathom.constants.llm import ModelProvider
from fathom.schemas.conversation import ConversationTurn
from fathom.schemas.llm import StructuredOutput
from fathom.schemas.llm import ModelIdentity, StructuredOutput
from fathom.schemas.results import GenerateResult

if TYPE_CHECKING:
Expand All @@ -14,6 +24,24 @@
PromptPart = Union[str, bytes, Dict[str, str]]


@runtime_checkable
class ModelBound(Protocol):
"""
Capability for a port that runs on a language model and exposes the adapter it was given.

Lets the composition root tell whether two roles share one adapter or hold distinct ones,
which a comparison of their reported identities cannot decide.
"""

@property
def llm(self) -> "LLMPort":
"""
The adapter this port was composed with.
"""

...


class LLMPort(ABC):
"""
Provider-neutral port for language-model generation.
Expand All @@ -28,6 +56,17 @@ def model_name(self) -> str:

raise NotImplementedError

@property
def identity(self) -> ModelIdentity:
"""
Provider, model, and settings this adapter declares for itself.

Default declares UNKNOWN: an adapter that does not state its provider is reported as
undeclared rather than guessed from its class name.
"""

return ModelIdentity(provider=ModelProvider.UNKNOWN, model=self.model_name)

@abstractmethod
async def generate(
self,
Expand Down Expand Up @@ -69,12 +108,14 @@ def derive(self, *, overrides: "LLMConfiguration") -> "LLMPort":
Spawn a sibling adapter sharing credentials and model, with only the explicitly-set
fields of ``overrides`` applied on top.

Default returns self; providers that support reconfiguration (e.g. Gemini) override
this to build a genuinely independent sibling.
Every provider adapter must implement this operation. Returning the planner itself would
silently discard role-specific settings such as deterministic temperature and caching.
"""

_ = overrides
return self
raise NotImplementedError(
f"{type(self).__name__} does not implement provider adapter derivation"
)

@abstractmethod
async def cleanup(self) -> None:
Expand Down
Loading
Loading