base.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. """Abstract base for provider transports.
  2. A transport owns one api_mode's data path (convert_messages -> convert_tools -> build_kwargs
  3. -> normalize_response), NOT client construction, streaming, credentials, caching, interrupts
  4. or retries — those stay on AIAgent."""
  5. from abc import ABC, abstractmethod
  6. from typing import Any, Dict, List, Optional
  7. from agent.transports.types import NormalizedResponse
  8. class ProviderTransport(ABC):
  9. """Base class for provider-specific format conversion and normalization."""
  10. # Provider stop_reason -> OpenAI finish_reason. ``None`` means the provider
  11. # already speaks OpenAI vocabulary and map_finish_reason passes through.
  12. _STOP_REASON_MAP: Optional[dict[str, str]] = None
  13. @property
  14. @abstractmethod
  15. def api_mode(self) -> str:
  16. """The api_mode string this transport handles (e.g. 'anthropic_messages')."""
  17. @abstractmethod
  18. def convert_messages(self, messages: list[dict[str, Any]], **kwargs) -> Any:
  19. """Convert OpenAI-format messages to the provider-native structure (e.g. (system, messages) for Anthropic)."""
  20. @abstractmethod
  21. def convert_tools(self, tools: list[dict[str, Any]]) -> Any:
  22. """Convert OpenAI-format tool definitions to provider-native format."""
  23. @abstractmethod
  24. def build_kwargs(
  25. self, model: str, messages: list[dict[str, Any]],
  26. tools: Optional[list[dict[str, Any]]] = None, **params,
  27. ) -> dict[str, Any]:
  28. """Primary entry point: convert messages/tools and return kwargs ready for the provider SDK."""
  29. @abstractmethod
  30. def normalize_response(self, response: Any, **kwargs) -> NormalizedResponse:
  31. """Normalize a raw provider response to NormalizedResponse (the only transport-layer return type)."""
  32. def validate_response(self, response: Any) -> bool:
  33. """Optional structural validity check; default accepts everything."""
  34. return True
  35. def extract_cache_stats(self, response: Any) -> Optional[dict[str, int]]:
  36. """Optional: ``{'cached_tokens', 'creation_tokens'}`` or None (default)."""
  37. return None
  38. def map_finish_reason(self, raw_reason: str) -> str:
  39. """Map a provider stop reason via ``_STOP_REASON_MAP`` (unknown -> 'stop'); passthrough when no map."""
  40. return raw_reason if self._STOP_REASON_MAP is None else self._STOP_REASON_MAP.get(raw_reason, "stop")