auxiliary_async_rebuild.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """Carry a sync OpenAI client's credential and configured headers onto its async rebuild.
  2. ``_to_async_client`` recreates ``AsyncOpenAI`` from a resolved sync client. Two things do not
  3. live on ``.api_key`` / the header set it recomputes: a per-request token provider (``key_cmd``,
  4. Entra ID — the SDK parks the callable in ``_api_key_provider`` and leaves ``.api_key`` empty, so
  5. an ``auth_headers`` built from the snapshot is ``{}`` and the request carries NO Authorization at
  6. all) and the ``default_headers`` the client was constructed with (a named provider's
  7. ``extra_headers``). See #109595.
  8. """
  9. from __future__ import annotations
  10. import asyncio
  11. from collections.abc import Mapping
  12. from typing import Any, Dict
  13. from openai import OpenAI
  14. def async_api_key(sync_client: Any) -> Any:
  15. """Credential for the async twin: the sync token provider wrapped for ``await``, else the static key.
  16. The sync provider is ``Callable[[], str]``; ``AsyncOpenAI`` awaits its provider before every request,
  17. so the callable is run off-loop (it may shell out to a ``key_cmd``).
  18. """
  19. provider = getattr(sync_client, "_api_key_provider", None) if isinstance(sync_client, OpenAI) else None
  20. if not callable(provider):
  21. return sync_client.api_key
  22. async def _provide() -> str:
  23. return str(await asyncio.to_thread(provider))
  24. return _provide
  25. def configured_default_headers(sync_client: Any) -> dict[str, str]:
  26. """The ``default_headers`` mapping the sync client was constructed with (SDK ``_custom_headers``).
  27. SECURITY: values may carry credentials — never log them.
  28. """
  29. configured = getattr(sync_client, "_custom_headers", None) if isinstance(sync_client, OpenAI) else None
  30. return dict(configured) if isinstance(configured, Mapping) else {}