__init__.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Transport registry for provider response normalization.
  2. transport = get_transport("anthropic_messages")
  3. result = transport.normalize_response(raw_response)"""
  4. import contextlib
  5. import importlib
  6. from agent.transports.types import (
  7. NormalizedResponse,
  8. ToolCall,
  9. Usage,
  10. build_tool_call,
  11. map_finish_reason,
  12. )
  13. _REGISTRY: dict = {}
  14. _discovered: bool = False
  15. _TRANSPORT_MODULES = ("anthropic", "codex", "chat_completions", "bedrock")
  16. def register_transport(api_mode: str, transport_cls: type) -> None:
  17. """Register a transport class for an api_mode string."""
  18. _REGISTRY[api_mode] = transport_cls
  19. def get_transport(api_mode: str):
  20. """Return a transport instance for ``api_mode``, or None so callers can fall back to the legacy path."""
  21. # A directly-imported transport leaves the registry partial; (re)discover on first use and on misses.
  22. if not _discovered or api_mode not in _REGISTRY:
  23. _discover_transports()
  24. cls = _REGISTRY.get(api_mode)
  25. return None if cls is None else cls()
  26. def _discover_transports() -> None:
  27. """Import all transport modules to trigger auto-registration."""
  28. global _discovered
  29. _discovered = True
  30. for name in _TRANSPORT_MODULES:
  31. with contextlib.suppress(ImportError):
  32. importlib.import_module(f"agent.transports.{name}")
  33. def registered_api_modes() -> frozenset:
  34. """Every api_mode with a registered transport, in-tree and plugin-supplied.
  35. ``register_transport`` is the public seam for a provider plugin that speaks
  36. its own dialect, but the api_mode gates elsewhere are closed literals — a
  37. plugin's mode was rejected there and rewritten to ``chat_completions``, with
  38. the dialect translation dropped and no error raised. Callers that validate an
  39. api_mode use this so a registered transport is accepted on every path.
  40. Discovers first, so a cold registry never reports an empty set.
  41. """
  42. if not _discovered:
  43. _discover_transports()
  44. return frozenset(_REGISTRY)