Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

Separate Chat transport from provider ownership (#1782)

Ali Khokharbaa8f983b788
diff --git a/pyproject.toml b/pyproject.toml
index a2ad511e..7b8481b2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "free-claude-code"
-version = "6.2.19"
+version = "6.2.20"
description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"
readme = "README.md"
requires-python = ">=3.14.0"
diff --git a/src/free_claude_code/providers/base.py b/src/free_claude_code/providers/base.py
index 7edb1e04..f04289f6 100644
--- a/src/free_claude_code/providers/base.py
+++ b/src/free_claude_code/providers/base.py
@@ -4,17 +4,10 @@ from abc import ABC, abstractmethod
from collections.abc import AsyncIterator, Mapping
from dataclasses import dataclass
-from loguru import logger
-
from free_claude_code.application.model_metadata import ProviderModelInfo
from free_claude_code.core.anthropic.models import MessagesRequest
-from free_claude_code.core.diagnostics import (
- exception_cause_types,
- redacted_exception_traceback,
-)
from free_claude_code.core.openai_responses import OpenAIResponsesRequest
from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy
-from free_claude_code.core.trace import trace_event
@dataclass(frozen=True, slots=True)
@@ -63,49 +56,6 @@ class BaseProvider(ABC):
) -> None:
"""Validate a Responses request before opening its SSE stream."""
- def _log_stream_transport_error(
- self,
- tag: str,
- req_tag: str,
- error: Exception,
- *,
- request_id: str | None = None,
- ) -> None:
- """Log streaming transport failures (metadata-only unless verbose is enabled)."""
- response = getattr(error, "response", None)
- http_status = (
- getattr(response, "status_code", None) if response is not None else None
- )
- cause_types = exception_cause_types(error)
- trace_event(
- stage="provider",
- event="provider.response.transport_error",
- source="provider",
- provider=tag,
- request_id=request_id,
- exc_type=type(error).__name__,
- http_status=http_status,
- cause_types=cause_types,
- )
-
- if self._config.log_api_error_tracebacks:
- logger.error(
- "{}_ERROR:{} exc_type={}\n{}",
- tag,
- req_tag,
- type(error).__name__,
- redacted_exception_traceback(error),
- )
- return
- logger.error(
- "{}_ERROR:{} exc_type={} http_status={} cause_types={}",
- tag,
- req_tag,
- type(error).__name__,
- http_status,
- ",".join(cause_types) if cause_types else None,
- )
-
@abstractmethod
async def cleanup(self) -> None:
"""Release any resources held by this provider."""
diff --git a/src/free_claude_code/providers/cloudflare/client.py b/src/free_claude_code/providers/cloudflare/client.py
index d9fbe367..3d8a9b8e 100644
--- a/src/free_claude_code/providers/cloudflare/client.py
+++ b/src/free_claude_code/providers/cloudflare/client.py
@@ -24,6 +24,7 @@ from free_claude_code.providers.model_listing import (
from free_claude_code.providers.openai_chat import (
ChatStreamOutput,
ChatTemplateReasoning,
+ OpenAIChatBehavior,
OpenAIChatProfile,
OpenAIChatProvider,
OpenAIChatRequestPolicy,
@@ -65,6 +66,20 @@ def _cloudflare_account_api_url(api_root: str | None, account_id: str) -> str:
return f"{root}/accounts/{encoded_account}"
+class CloudflareChatBehavior(OpenAIChatBehavior):
+ """Cloudflare Chat adaptation without HTTP ownership."""
+
+ def extra_reasoning_events(
+ self, delta: Any, output: ChatStreamOutput, *, output_reasoning: bool
+ ) -> Iterator[str]:
+ """Map Cloudflare's ``reasoning`` delta field to Anthropic thinking."""
+ reasoning = _cloudflare_reasoning(delta)
+ if not output_reasoning or not reasoning:
+ return
+ yield from output.ensure_reasoning_block()
+ yield output.emit_reasoning_delta(reasoning)
+
+
class CloudflareProvider(OpenAIChatProvider):
"""Cloudflare Workers AI OpenAI-compatible chat provider."""
@@ -90,7 +105,7 @@ class CloudflareProvider(OpenAIChatProvider):
)
super().__init__(
replace(config, base_url=base_url),
- profile=_PROFILE,
+ behavior=CloudflareChatBehavior(_PROFILE),
admission=admission,
)
@@ -131,16 +146,6 @@ class CloudflareProvider(OpenAIChatProvider):
finally:
await maybe_await_aclose(response)
- def _handle_extra_reasoning(
- self, delta: Any, output: ChatStreamOutput, *, output_reasoning: bool
- ) -> Iterator[str]:
- """Map Cloudflare's ``reasoning`` delta field to Anthropic thinking."""
- reasoning = _cloudflare_reasoning(delta)
- if not output_reasoning or not reasoning:
- return
- yield from output.ensure_reasoning_block()
- yield output.emit_reasoning_delta(reasoning)
-
def _model_list_headers(self) -> dict[str, str]:
if self._api_key is None:
raise AssertionError("Cloudflare requires a static API token")
diff --git a/src/free_claude_code/providers/deepseek/client.py b/src/free_claude_code/providers/deepseek/client.py
index 450093bb..92e8f9ba 100644
--- a/src/free_claude_code/providers/deepseek/client.py
+++ b/src/free_claude_code/providers/deepseek/client.py
@@ -3,7 +3,6 @@
from collections.abc import Mapping
from typing import Any
-from free_claude_code.application.model_metadata import ProviderModelInfo
from free_claude_code.config.constants import ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
from free_claude_code.core.anthropic.models import MessagesRequest
from free_claude_code.core.history_replay import HistoryScope
@@ -12,6 +11,7 @@ from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.openai_chat import (
NO_REASONING,
+ OpenAIChatBehavior,
OpenAIChatProfile,
OpenAIChatProvider,
usage_int,
@@ -51,45 +51,32 @@ def _deepseek_cache_partition(
return cache_hit_tokens, cache_miss_tokens, prompt_tokens
-class DeepSeekProvider(OpenAIChatProvider):
- """DeepSeek using ``https://api.deepseek.com`` Chat Completions."""
+class DeepSeekChatBehavior(OpenAIChatBehavior):
+ """DeepSeek Chat adaptation without HTTP ownership."""
- def _history_scope(self, body: Mapping[str, Any]) -> HistoryScope:
+ def history_scope(self, body: Mapping[str, Any]) -> HistoryScope:
return HistoryScope.ALL if body.get("tools") else HistoryScope.UNKNOWN
@property
- def _reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:
+ def reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:
return (("extra_body", "thinking"),)
@property
- def _normal_max_tokens(self) -> int:
+ def normal_max_tokens(self) -> int:
return ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
- def __init__(
- self, config: ProviderConfig, *, admission: ProviderAdmissionController
- ):
- super().__init__(
- config,
- profile=_PROFILE,
- admission=admission,
- )
-
- def _build_request_body(
+ def build_messages_body(
self,
request: MessagesRequest,
*,
reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
- model_info: ProviderModelInfo | None = None,
) -> dict:
- request, reasoning = self._prepare_messages_reasoning(
- request, reasoning, model_info
- )
return build_deepseek_request_body(
request,
reasoning=reasoning,
)
- def _finalize_chat_body(
+ def finalize_chat_body(
self,
body: dict[str, Any],
*,
@@ -99,14 +86,14 @@ class DeepSeekProvider(OpenAIChatProvider):
finalize_deepseek_chat_body(body, reasoning)
return body
- def _cached_input_tokens(self, usage_info: object) -> int | None:
+ def cached_input_tokens(self, usage_info: object) -> int | None:
cache_partition = _deepseek_cache_partition(usage_info)
if cache_partition is None:
return None
cache_hit_tokens, _, prompt_tokens = cache_partition
return cache_hit_tokens if prompt_tokens is not None else None
- def _anthropic_usage_fields(self, usage_info: Any) -> dict[str, int]:
+ def anthropic_usage_fields(self, usage_info: Any) -> dict[str, int]:
cache_partition = _deepseek_cache_partition(usage_info)
if cache_partition is None:
return {}
@@ -115,3 +102,16 @@ class DeepSeekProvider(OpenAIChatProvider):
"input_tokens": cache_miss_tokens,
"cache_read_input_tokens": cache_hit_tokens,
}
+
+
+class DeepSeekProvider(OpenAIChatProvider):
+ """DeepSeek using ``https://api.deepseek.com`` Chat Completions."""
+
+ def __init__(
+ self, config: ProviderConfig, *, admission: ProviderAdmissionController
+ ):
+ super().__init__(
+ config,
+ behavior=DeepSeekChatBehavior(_PROFILE),
+ admission=admission,
+ )
diff --git a/src/free_claude_code/providers/github_copilot/provider.py b/src/free_claude_code/providers/github_copilot/provider.py
index 3520187a..cce07161 100644
--- a/src/free_claude_code/providers/github_copilot/provider.py
+++ b/src/free_claude_code/providers/github_copilot/provider.py
@@ -22,7 +22,10 @@ from free_claude_code.providers.anthropic_messages.transport import (
from free_claude_code.providers.base import BaseProvider, ProviderConfig
from free_claude_code.providers.endpoint import EndpointContext, HttpEndpoint
from free_claude_code.providers.http import close_provider_stream
-from free_claude_code.providers.openai_chat import OpenAIChatProvider
+from free_claude_code.providers.openai_chat import (
+ OpenAIChatBehavior,
+ OpenAIChatTransport,
+)
from free_claude_code.providers.openai_responses import OpenAIResponsesTransport
from .auth import CopilotAuthManager
@@ -98,7 +101,7 @@ class GitHubCopilotProvider(BaseProvider):
endpoint_transport=self._openai_pool,
event_adapter_factory=CopilotResponsesEvents,
)
- self._chats: dict[str, tuple[CopilotModel, OpenAIChatProvider]] = {}
+ self._chats: dict[str, tuple[CopilotModel, OpenAIChatTransport]] = {}
self._condition = asyncio.Condition()
self._active = 0
self._closing = False
@@ -182,18 +185,20 @@ class GitHubCopilotProvider(BaseProvider):
reasoning,
)
- def _chat(self, model: CopilotModel) -> OpenAIChatProvider:
+ def _chat(self, model: CopilotModel) -> OpenAIChatTransport:
cached = self._chats.get(model.info.model_id)
if cached is None or cached[0] != model:
- provider = OpenAIChatProvider(
- self._config,
- profile=chat_profile(model),
+ transport = OpenAIChatTransport(
+ behavior=OpenAIChatBehavior(chat_profile(model)),
+ read_timeout_s=self._config.http_read_timeout,
+ log_raw_sse_events=self._config.log_raw_sse_events,
+ log_api_error_tracebacks=self._config.log_api_error_tracebacks,
admission=self._admission,
client=self._client,
endpoint_transport=self._openai_pool,
)
- self._chats[model.info.model_id] = (model, provider)
- return provider
+ self._chats[model.info.model_id] = (model, transport)
+ return transport
return cached[1]
async def _dispatch(
diff --git a/src/free_claude_code/providers/google_openai/provider.py b/src/free_claude_code/providers/google_openai/provider.py
index b9b1b2cf..560a38cf 100644
--- a/src/free_claude_code/providers/google_openai/provider.py
+++ b/src/free_claude_code/providers/google_openai/provider.py
@@ -9,6 +9,7 @@ from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.openai_chat import (
OpenAIAsyncCredentialProvider,
+ OpenAIChatBehavior,
OpenAIChatProfile,
OpenAIChatProvider,
)
@@ -18,28 +19,14 @@ from .thought_signatures import apply_google_thought_signatures
_MAX_TOOL_CALL_EXTRA_CONTENT_CACHE = 4096
-class GoogleOpenAIProvider(OpenAIChatProvider):
- """Shared thought-signature and request behavior for Google Gemini APIs."""
+class GoogleChatBehavior(OpenAIChatBehavior):
+ """Google Chat adaptation without HTTP ownership."""
- def __init__(
- self,
- config: ProviderConfig,
- *,
- profile: OpenAIChatProfile,
- admission: ProviderAdmissionController,
- api_key_provider: OpenAIAsyncCredentialProvider | None = None,
- default_headers: Mapping[str, str] | None = None,
- ) -> None:
- super().__init__(
- config,
- profile=profile,
- admission=admission,
- api_key_provider=api_key_provider,
- default_headers=default_headers,
- )
+ def __init__(self, profile: OpenAIChatProfile) -> None:
+ super().__init__(profile)
self._tool_call_extra_content_by_id: dict[str, dict[str, Any]] = {}
- def _record_tool_call_extra_content(
+ def record_tool_call_extra_content(
self, tool_call_id: str, extra_content: dict[str, Any]
) -> None:
if (
@@ -52,7 +39,7 @@ class GoogleOpenAIProvider(OpenAIChatProvider):
)
self._tool_call_extra_content_by_id[tool_call_id] = deepcopy(extra_content)
- def _finalize_chat_body(
+ def finalize_chat_body(
self,
body: dict[str, Any],
*,
@@ -63,3 +50,24 @@ class GoogleOpenAIProvider(OpenAIChatProvider):
tool_call_extra_content_by_id=self._tool_call_extra_content_by_id,
)
return body
+
+
+class GoogleOpenAIProvider(OpenAIChatProvider):
+ """Shared thought-signature and request behavior for Google Gemini APIs."""
+
+ def __init__(
+ self,
+ config: ProviderConfig,
+ *,
+ profile: OpenAIChatProfile,
+ admission: ProviderAdmissionController,
+ api_key_provider: OpenAIAsyncCredentialProvider | None = None,
+ default_headers: Mapping[str, str] | None = None,
+ ) -> None:
+ super().__init__(
+ config,
+ behavior=GoogleChatBehavior(profile),
+ admission=admission,
+ api_key_provider=api_key_provider,
+ default_headers=default_headers,
+ )
diff --git a/src/free_claude_code/providers/groq/client.py b/src/free_claude_code/providers/groq/client.py
index 4fda86a0..1c480190 100644
--- a/src/free_claude_code/providers/groq/client.py
+++ b/src/free_claude_code/providers/groq/client.py
@@ -19,13 +19,13 @@ from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.openai_chat import (
NamedEffortReasoning,
+ OpenAIChatBehavior,
OpenAIChatProfile,
OpenAIChatProvider,
OpenAIChatRequestPolicy,
OpenAIModelListing,
validate_extra_body_does_not_override_reasoning_fields,
)
-from free_claude_code.providers.reasoning_compatibility import ReasoningCorrection
from .tpm import correct_tpm_completion_budget
@@ -95,16 +95,14 @@ class _ErrorCandidate:
field_context: bool = False
-class GroqProvider(OpenAIChatProvider):
- """Groq API with model-agnostic reasoning-vocabulary learning."""
+class GroqChatBehavior(OpenAIChatBehavior):
+ """Groq Chat adaptation without HTTP ownership."""
- def __init__(
- self, config: ProviderConfig, *, admission: ProviderAdmissionController
- ) -> None:
- super().__init__(config, profile=_PROFILE, admission=admission)
+ def __init__(self) -> None:
+ super().__init__(_PROFILE)
self._model_reasoning_vocabularies: dict[str, frozenset[str]] = {}
- def _finalize_chat_body(
+ def finalize_chat_body(
self,
body: dict[str, Any],
*,
@@ -118,11 +116,11 @@ class GroqProvider(OpenAIChatProvider):
return body
return _rewrite_reasoning_effort(body, accepted) or body
- def _reasoning_disable_rejected(self, error: Exception) -> bool:
+ def reasoning_disable_rejected(self, error: Exception) -> bool:
accepted = _parse_reasoning_vocabulary(error)
return accepted is not None and "none" not in accepted
- def _get_retry_request_body(
+ def retry_request_body(
self, error: Exception, body: dict[str, Any]
) -> dict[str, Any] | None:
accepted = _parse_reasoning_vocabulary(error)
@@ -143,24 +141,14 @@ class GroqProvider(OpenAIChatProvider):
logger.warning("GROQ_STREAM: {} after upstream rejection", action)
return retry_body
- def _next_create_retry_body(
+ def retry_after_standard_corrections(
self,
error: Exception,
body: JsonObject,
used_retry_kinds: set[str],
- *,
- reasoning_correction: ReasoningCorrection | None = None,
- sent_body: Mapping[str, Any] | None = None,
) -> JsonObject | None:
- retry_body = super()._next_create_retry_body(
- error,
- body,
- used_retry_kinds,
- reasoning_correction=reasoning_correction,
- sent_body=sent_body,
- )
- if retry_body is not None or "groq_tpm" in used_retry_kinds:
- return retry_body
+ if "groq_tpm" in used_retry_kinds:
+ return None
correction = correct_tpm_completion_budget(error, body)
if correction is None:
@@ -177,6 +165,15 @@ class GroqProvider(OpenAIChatProvider):
return correction.body
+class GroqProvider(OpenAIChatProvider):
+ """Groq API with model-agnostic reasoning-vocabulary learning."""
+
+ def __init__(
+ self, config: ProviderConfig, *, admission: ProviderAdmissionController
+ ) -> None:
+ super().__init__(config, behavior=GroqChatBehavior(), admission=admission)
+
+
def _parse_reasoning_vocabulary(error: Exception) -> frozenset[str] | None:
"""Return Groq's accepted known values, or an understood empty vocabulary."""
if not _is_bad_request(error):
diff --git a/src/free_claude_code/providers/mistral/client.py b/src/free_claude_code/providers/mistral/client.py
index ccb5109c..cc311ae0 100644
--- a/src/free_claude_code/providers/mistral/client.py
+++ b/src/free_claude_code/providers/mistral/client.py
@@ -12,6 +12,7 @@ from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.openai_chat import (
NO_REASONING,
+ OpenAIChatBehavior,
OpenAIChatProfile,
OpenAIChatProvider,
OpenAIChatRequestPolicy,
@@ -45,23 +46,14 @@ _PROFILE = OpenAIChatProfile(
)
-class MistralProvider(OpenAIChatProvider):
- """Mistral API using ``https://api.mistral.ai/v1/chat/completions``."""
+class MistralChatBehavior(OpenAIChatBehavior):
+ """Mistral Chat adaptation without HTTP ownership."""
@property
- def _reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:
+ def reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:
return (("reasoning_effort",),)
- def __init__(
- self, config: ProviderConfig, *, admission: ProviderAdmissionController
- ):
- super().__init__(
- config,
- profile=_PROFILE,
- admission=admission,
- )
-
- def _finalize_chat_body(
+ def finalize_chat_body(
self,
body: dict[str, Any],
*,
@@ -70,7 +62,7 @@ class MistralProvider(OpenAIChatProvider):
apply_mistral_reasoning_request_shape(body, reasoning=reasoning)
return body
- def _get_retry_request_body(self, error: Exception, body: dict) -> dict | None:
+ def retry_request_body(self, error: Exception, body: dict) -> dict | None:
"""Retry once without Mistral reasoning fields when a model rejects them."""
if not is_mistral_reasoning_rejection(error):
return None
@@ -82,5 +74,18 @@ class MistralProvider(OpenAIChatProvider):
)
return retry_body
- def _normalize_stream(self, stream: Any, _body: Mapping[str, Any]) -> Any:
+ def normalize_stream(self, stream: Any, _body: Mapping[str, Any]) -> Any:
return normalize_mistral_stream(stream)
+
+
+class MistralProvider(OpenAIChatProvider):
+ """Mistral API using ``https://api.mistral.ai/v1/chat/completions``."""
+
+ def __init__(
+ self, config: ProviderConfig, *, admission: ProviderAdmissionController
+ ):
+ super().__init__(
+ config,
+ behavior=MistralChatBehavior(_PROFILE),
+ admission=admission,
+ )
diff --git a/src/free_claude_code/providers/nvidia_nim/client.py b/src/free_claude_code/providers/nvidia_nim/client.py
index 1d3e6085..441331f9 100644
--- a/src/free_claude_code/providers/nvidia_nim/client.py
+++ b/src/free_claude_code/providers/nvidia_nim/client.py
@@ -8,7 +8,6 @@ from typing import Any
import openai
from loguru import logger
-from free_claude_code.application.model_metadata import ProviderModelInfo
from free_claude_code.config.nim import NimSettings
from free_claude_code.core.anthropic.models import MessagesRequest
from free_claude_code.core.failures import ExecutionFailure
@@ -21,6 +20,7 @@ from free_claude_code.providers.failure_policy import (
)
from free_claude_code.providers.openai_chat import (
NO_REASONING,
+ OpenAIChatBehavior,
OpenAIChatProfile,
OpenAIChatProvider,
)
@@ -52,52 +52,38 @@ _PROFILE = OpenAIChatProfile(
)
-class NvidiaNimProvider(OpenAIChatProvider):
- """NVIDIA NIM provider using official OpenAI client."""
+class NvidiaNimChatBehavior(OpenAIChatBehavior):
+ """NVIDIA NIM Chat adaptation without HTTP ownership."""
+
+ def __init__(self, nim_settings: NimSettings) -> None:
+ super().__init__(_PROFILE)
+ self._nim_settings = nim_settings
@property
- def _reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:
+ def reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:
return (
("extra_body", "chat_template_kwargs", "thinking"),
("extra_body", "chat_template_kwargs", "enable_thinking"),
)
@property
- def _normal_max_tokens(self) -> int | None:
+ def normal_max_tokens(self) -> int | None:
return self._nim_settings.max_tokens
- def __init__(
- self,
- config: ProviderConfig,
- *,
- nim_settings: NimSettings,
- admission: ProviderAdmissionController,
- ):
- super().__init__(
- config,
- profile=_PROFILE,
- admission=admission,
- )
- self._nim_settings = nim_settings
-
- def _build_request_body(
+ def build_messages_body(
self,
request: MessagesRequest,
*,
reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
- model_info: ProviderModelInfo | None = None,
) -> dict:
"""Internal helper for tests and shared building."""
- request, reasoning = self._prepare_messages_reasoning(
- request, reasoning, model_info
- )
return build_nim_request_body(
request,
self._nim_settings,
reasoning=reasoning,
)
- def _finalize_chat_body(
+ def finalize_chat_body(
self,
body: dict[str, Any],
*,
@@ -107,19 +93,19 @@ class NvidiaNimProvider(OpenAIChatProvider):
apply_nim_request_options(body, reasoning, nim=self._nim_settings)
return body
- def _prepare_create_body(self, body: dict[str, Any]) -> dict[str, Any]:
+ def prepare_create_body(self, body: dict[str, Any]) -> dict[str, Any]:
"""Strip private request metadata before calling NVIDIA NIM."""
return body_without_nim_tool_argument_aliases(body)
- def _normalize_stream(self, stream: Any, _body: Mapping[str, Any]) -> Any:
+ def normalize_stream(self, stream: Any, _body: Mapping[str, Any]) -> Any:
"""Repair model-native MiniMax tool markup leaked by NVIDIA NIM."""
return normalize_nim_native_tool_stream(stream, _body)
- def _tool_argument_aliases(self, body: dict[str, Any]) -> dict[str, dict[str, str]]:
+ def tool_argument_aliases(self, body: dict[str, Any]) -> dict[str, dict[str, str]]:
"""Return NIM tool argument aliases captured while building this request."""
return nim_tool_argument_aliases_from_body(body)
- def _get_retry_request_body(self, error: Exception, body: dict) -> dict | None:
+ def retry_request_body(self, error: Exception, body: dict) -> dict | None:
"""Retry once with a downgraded body when NIM rejects a known field."""
status_code = getattr(error, "status_code", None)
bad_request_like = isinstance(error, openai.BadRequestError) or (
@@ -164,7 +150,7 @@ class NvidiaNimProvider(OpenAIChatProvider):
return None
- def _provider_failure_override(self, error: Exception) -> ExecutionFailure | None:
+ def failure_override(self, error: Exception) -> ExecutionFailure | None:
"""Classify NVIDIA-specific 400/500 responses by their actual semantics."""
if not isinstance(error, openai.BadRequestError | openai.InternalServerError):
return None
@@ -181,6 +167,23 @@ class NvidiaNimProvider(OpenAIChatProvider):
return None
+class NvidiaNimProvider(OpenAIChatProvider):
+ """NVIDIA NIM provider using official OpenAI client."""
+
+ def __init__(
+ self,
+ config: ProviderConfig,
+ *,
+ nim_settings: NimSettings,
+ admission: ProviderAdmissionController,
+ ):
+ super().__init__(
+ config,
+ behavior=NvidiaNimChatBehavior(nim_settings),
+ admission=admission,
+ )
+
+
def _nim_error_bodies(error: Exception) -> tuple[Mapping[str, Any], ...]:
body = getattr(error, "body", None)
if not isinstance(body, Mapping):
diff --git a/src/free_claude_code/providers/open_router/client.py b/src/free_claude_code/providers/open_router/client.py
index 1aff6fd8..27666398 100644
--- a/src/free_claude_code/providers/open_router/client.py
+++ b/src/free_claude_code/providers/open_router/client.py
@@ -11,6 +11,7 @@ from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
from free_claude_code.providers.model_listing import extract_tool_capable_model_infos
from free_claude_code.providers.openai_chat import (
+ OpenAIChatBehavior,
OpenAIChatProfile,
OpenAIChatProvider,
OpenAIChatRequestPolicy,
@@ -30,19 +31,10 @@ _REQUEST_POLICY = OpenAIChatRequestPolicy(
)
-class OpenRouterProvider(OpenAIChatProvider):
- """OpenRouter provider using the OpenAI-compatible Chat Completions API."""
+class OpenRouterChatBehavior(OpenAIChatBehavior):
+ """OpenRouter Chat adaptation without HTTP ownership."""
- def __init__(
- self, config: ProviderConfig, *, admission: ProviderAdmissionController
- ):
- super().__init__(
- config,
- profile=_PROFILE,
- admission=admission,
- )
-
- def _reasoning_disable_rejected(self, error: Exception) -> bool:
+ def reasoning_disable_rejected(self, error: Exception) -> bool:
detail = extract_upstream_error_detail(error)
if detail.status_code not in {None, 200}:
return False
@@ -62,6 +54,19 @@ class OpenRouterProvider(OpenAIChatProvider):
and reasoning_control_rejected(error_body, ("reasoning",))
)
+
+class OpenRouterProvider(OpenAIChatProvider):
+ """OpenRouter provider using the OpenAI-compatible Chat Completions API."""
+
+ def __init__(
+ self, config: ProviderConfig, *, admission: ProviderAdmissionController
+ ):
+ super().__init__(
+ config,
+ behavior=OpenRouterChatBehavior(_PROFILE),
+ admission=admission,
+ )
+
async def list_model_infos(self) -> frozenset[ProviderModelInfo]:
"""Advertise OpenRouter tool models with reasoning capability metadata."""
payload = await self._list_models_payload()
diff --git a/src/free_claude_code/providers/openai_chat/__init__.py b/src/free_claude_code/providers/openai_chat/__init__.py
index 123b80d8..f555d0ea 100644
--- a/src/free_claude_code/providers/openai_chat/__init__.py
+++ b/src/free_claude_code/providers/openai_chat/__init__.py
@@ -4,12 +4,14 @@ from free_claude_code.providers.admission import ProviderAdmissionController
from free_claude_code.providers.base import ProviderConfig
from .base_url import openai_v1_base_url
+from .behavior import OpenAIChatBehavior
+from .client import OpenAIAsyncCredentialProvider, create_chat_client
from .extra_body import (
validate_extra_body_does_not_override_canonical_fields,
validate_extra_body_does_not_override_reasoning_fields,
)
from .profiles import OPENAI_CHAT_PROFILES, OpenAIChatProfile, OpenAIModelListing
-from .provider import OpenAIAsyncCredentialProvider, OpenAIChatProvider
+from .provider import OpenAIChatProvider
from .reasoning import (
NO_REASONING,
ChatTemplateReasoning,
@@ -22,6 +24,7 @@ from .request_policy import (
build_openai_chat_request_body,
)
from .stream_output import ChatStreamOutput
+from .transport import OpenAIChatTransport
from .usage import usage_int
@@ -51,13 +54,16 @@ __all__ = [
"ChatTemplateReasoning",
"NamedEffortReasoning",
"OpenAIAsyncCredentialProvider",
+ "OpenAIChatBehavior",
"OpenAIChatProfile",
"OpenAIChatProvider",
"OpenAIChatRequestPolicy",
+ "OpenAIChatTransport",
"OpenAIModelListing",
"ReasoningObject",
"apply_openai_chat_body_policy",
"build_openai_chat_request_body",
+ "create_chat_client",
"create_openai_chat_provider",
"openai_v1_base_url",
"usage_int",
diff --git a/src/free_claude_code/providers/openai_chat/behavior.py b/src/free_claude_code/providers/openai_chat/behavior.py
new file mode 100644
index 00000000..df2343ea
--- /dev/null
+++ b/src/free_claude_code/providers/openai_chat/behavior.py
@@ -0,0 +1,133 @@
+"""Provider-specific Chat adaptation, independent of HTTP resource ownership."""
+
+from collections.abc import Iterator, Mapping
+from typing import Any
+
+from free_claude_code.core.anthropic.models import MessagesRequest
+from free_claude_code.core.anthropic.usage import anthropic_input_usage_fields
+from free_claude_code.core.failures import ExecutionFailure
+from free_claude_code.core.history_replay import HistoryScope
+from free_claude_code.core.reasoning import (
+ DEFAULT_REASONING_POLICY,
+ ReasoningPolicy,
+)
+
+from .profiles import OpenAIChatProfile
+from .request_policy import (
+ build_openai_chat_request_body,
+)
+from .stream_output import (
+ ChatStreamOutput,
+)
+from .usage import (
+ nested_usage_int,
+ usage_int,
+)
+
+
+class OpenAIChatBehavior:
+ """Default Chat behavior; exceptional providers override only their quirks."""
+
+ def __init__(self, profile: OpenAIChatProfile) -> None:
+ self.profile = profile
+
+ def build_messages_body(
+ self,
+ request: MessagesRequest,
+ *,
+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
+ ) -> dict[str, Any]:
+ """Build a provider request from the immutable profile."""
+ body = build_openai_chat_request_body(
+ request,
+ reasoning=reasoning,
+ policy=self.profile.request_policy,
+ postprocessors=self.profile.request_postprocessors,
+ )
+ return self.finalize_chat_body(body, reasoning=reasoning)
+
+ @property
+ def reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:
+ field = self.profile.reasoning.off_field
+ return (field,) if field is not None else ()
+
+ @property
+ def normal_max_tokens(self) -> int | None:
+ return self.profile.request_policy.default_max_tokens
+
+ def finalize_chat_body(
+ self,
+ body: dict[str, Any],
+ *,
+ reasoning: ReasoningPolicy,
+ ) -> dict[str, Any]:
+ """Apply provider behavior that is independent of client protocol."""
+ return body
+
+ def history_scope(self, body: Mapping[str, Any]) -> HistoryScope:
+ return self.profile.history_scope
+
+ def extra_reasoning_events(
+ self, delta: Any, output: ChatStreamOutput, *, output_reasoning: bool
+ ) -> Iterator[str]:
+ """Hook for provider-specific reasoning."""
+ return iter(())
+
+ def retry_request_body(self, error: Exception, body: dict) -> dict | None:
+ """Return a modified request body for one retry, or None."""
+ return None
+
+ def reasoning_disable_rejected(self, error: Exception) -> bool:
+ """Recognize provider-owned OFF rejection formats without learning state."""
+ return False
+
+ def failure_override(self, error: Exception) -> ExecutionFailure | None:
+ """Return provider-specific failure semantics, or defer to shared policy."""
+ return None
+
+ def prepare_create_body(self, body: dict[str, Any]) -> dict[str, Any]:
+ """Return the body passed to the upstream OpenAI-compatible client."""
+ return body
+
+ def normalize_stream(self, stream: Any, _body: Mapping[str, Any]) -> Any:
+ """Return the provider-specific stream view consumed by the base runner."""
+ return stream
+
+ def record_tool_call_extra_content(
+ self, tool_call_id: str, extra_content: dict[str, Any]
+ ) -> None:
+ """Hook for providers that must replay OpenAI tool-call metadata later."""
+
+ def tool_argument_aliases(self, body: dict[str, Any]) -> dict[str, dict[str, str]]:
+ """Return provider-specific per-tool argument aliases for this request."""
+ return {}
+
+ def cached_input_tokens(self, usage_info: object) -> int | None:
+ """Return the provider's cached-input count from final Chat usage."""
+ return nested_usage_int(
+ usage_info,
+ "prompt_tokens_details",
+ "cached_tokens",
+ )
+
+ def cache_write_input_tokens(self, usage_info: object) -> int | None:
+ """Return the provider's cache-write count from final Chat usage."""
+ return nested_usage_int(
+ usage_info,
+ "prompt_tokens_details",
+ "cache_write_tokens",
+ )
+
+ def anthropic_usage_fields(self, usage_info: Any) -> dict[str, int]:
+ """Split standard prompt cache counts for final Anthropic usage."""
+ return anthropic_input_usage_fields(
+ usage_int(usage_info, "prompt_tokens"),
+ cache_read_tokens=self.cached_input_tokens(usage_info),
+ cache_creation_tokens=self.cache_write_input_tokens(usage_info),
+ )
+
+ def retry_after_standard_corrections(
+ self, error: Exception, body: dict[str, Any], used_retry_kinds: set[str]
+ ) -> dict[str, Any] | None:
+ """Offer a provider correction after the standard correction sequence."""
+ return None
diff --git a/src/free_claude_code/providers/openai_chat/client.py b/src/free_claude_code/providers/openai_chat/client.py
new file mode 100644
index 00000000..83e6c96a
--- /dev/null
+++ b/src/free_claude_code/providers/openai_chat/client.py
@@ -0,0 +1,40 @@
+"""SDK client construction for Chat provider resource owners."""
+
+from collections.abc import Awaitable, Callable, Mapping
+
+import httpx2
+from openai import AsyncOpenAI, DefaultAsyncHttpx2Client
+
+from free_claude_code.providers.base import ProviderConfig
+
+OpenAIAsyncCredentialProvider = Callable[[], Awaitable[str]]
+
+
+def create_chat_client(
+ config: ProviderConfig,
+ *,
+ base_url: str,
+ provider_name: str,
+ default_headers: Mapping[str, str] | None = None,
+ api_key_provider: OpenAIAsyncCredentialProvider | None = None,
+) -> AsyncOpenAI:
+ """Create a provider-owned SDK client with FCC's existing HTTP policy."""
+ if config.api_key is None and api_key_provider is None:
+ raise ValueError(f"{provider_name} requires an API key or credential provider")
+ timeout = httpx2.Timeout(
+ config.http_read_timeout,
+ connect=config.http_connect_timeout,
+ read=config.http_read_timeout,
+ write=config.http_write_timeout,
+ )
+ http_client = None
+ if config.proxy:
+ http_client = DefaultAsyncHttpx2Client(proxy=config.proxy, timeout=timeout)
+ return AsyncOpenAI(
+ api_key=api_key_provider or config.api_key,
+ base_url=base_url,
+ max_retries=0,
+ default_headers=default_headers,
+ timeout=timeout,
+ http_client=http_client,
+ )
diff --git a/src/free_claude_code/providers/openai_chat/provider.py b/src/free_claude_code/providers/openai_chat/provider.py
index e4ab9c13..c3e7fdf5 100644
--- a/src/free_claude_code/providers/openai_chat/provider.py
+++ b/src/free_claude_code/providers/openai_chat/provider.py
@@ -1,570 +1,84 @@
-"""Concrete OpenAI-compatible provider and per-request stream execution."""
+"""Provider identity, HTTP resource ownership, and model discovery."""
-import asyncio
-import sys
-import uuid
-from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping
-from dataclasses import dataclass, replace
-from enum import StrEnum
-from typing import Any, cast
+from collections.abc import AsyncIterator, Mapping
+from dataclasses import replace
+from typing import Any
import httpx2
-from loguru import logger
-from openai import AsyncOpenAI, DefaultAsyncHttpx2Client
+from openai import AsyncOpenAI
-from free_claude_code.application.errors import InvalidRequestError
from free_claude_code.application.model_metadata import ProviderModelInfo
-from free_claude_code.core.anthropic import (
- ContentBlockToolUse,
- ContentType,
- FunctionTagToolParser,
- HeuristicToolParser,
- ThinkTagParser,
-)
from free_claude_code.core.anthropic.models import MessagesRequest
-from free_claude_code.core.anthropic.streaming import (
- ToolSchema,
- accept_tool_json_repair,
- continuation_suffix,
- make_response_recovery_body,
- make_text_recovery_body,
- make_tool_repair_body,
- map_stop_reason,
- parse_complete_tool_input,
- tool_schemas_by_name,
-)
-from free_claude_code.core.anthropic.usage import anthropic_input_usage_fields
-from free_claude_code.core.failures import ExecutionFailure, FailureKind
-from free_claude_code.core.history_replay import HistoryScope, prepare_history
-from free_claude_code.core.json_types import JsonObject
from free_claude_code.core.openai_responses import (
OpenAIResponsesRequest,
- ResponsesChatRequest,
- ResponsesConversionError,
- build_responses_chat_request,
-)
-from free_claude_code.core.openai_tool_names import (
- OpenAIToolNameCodec,
- encode_openai_chat_tool_names,
)
from free_claude_code.core.reasoning import (
DEFAULT_REASONING_POLICY,
- ReasoningControl,
ReasoningPolicy,
)
-from free_claude_code.core.trace import provider_chat_body_snapshot, trace_event
from free_claude_code.providers.admission import (
ProviderAdmissionController,
- ProviderAttempt,
- ProviderCorrectionAction,
- ProviderExecution,
ProviderOperationKind,
)
from free_claude_code.providers.base import BaseProvider, ProviderConfig
-from free_claude_code.providers.endpoint import EndpointContext, RequestEndpoint
-from free_claude_code.providers.failure_policy import (
- RetryableToolProtocolError,
- classify_provider_failure,
- context_window_exceeded_provider_failure,
- is_context_window_finish_reason,
- is_retryable_stream_error,
- underlying_provider_error,
-)
-from free_claude_code.providers.history_replay import (
- history_retry_body,
- replay_origin,
- validate_history,
-)
-from free_claude_code.providers.http import (
- ProviderAttemptScope,
- close_provider_stream,
- maybe_await_aclose,
-)
+from free_claude_code.providers.endpoint import EndpointContext
from free_claude_code.providers.model_listing import (
extract_openai_model_infos,
merge_model_list_pages,
model_infos_from_ids,
validate_model_list_page,
)
-from free_claude_code.providers.reasoning_compatibility import (
- ReasoningCorrection,
- prepare_messages_reasoning,
-)
-from free_claude_code.providers.stream_recovery import (
- RecoveryController,
- RecoveryFailureAction,
- TruncatedProviderStreamError,
-)
-from .output_cap import clamp_output_tokens, parse_output_token_cap
+from .behavior import OpenAIChatBehavior
+from .client import OpenAIAsyncCredentialProvider, create_chat_client
from .profiles import OpenAIChatProfile
-from .reasoning_details import StructuredReasoningStream
-from .request_policy import (
- apply_openai_chat_body_policy,
- build_openai_chat_request_body,
-)
-from .stream_output import (
- AnthropicChatStreamOutput,
- ChatStreamOutput,
- ChatStreamUsage,
- ResponsesChatStreamOutput,
-)
-from .tool_calls import (
- CompletedOpenAIToolCall,
- OpenAIToolCallAssembler,
- OpenAIToolCallCollector,
- iter_heuristic_tool_use_events,
- tool_call_extra_content,
-)
-from .usage import (
- clone_without_stream_usage,
- is_stream_usage_rejection,
- nested_usage_int,
- request_stream_usage,
- usage_int,
-)
-
-OpenAIAsyncCredentialProvider = Callable[[], Awaitable[str]]
-_ExtraReasoningEvents = Callable[[Any, ChatStreamOutput], Iterator[str]]
-_ChatOutputFactory = Callable[[], ChatStreamOutput]
-
-
-@dataclass(frozen=True, slots=True)
-class _CollectedRecoveryOutput:
- text: str
- thinking: str
- tool_calls: tuple[CompletedOpenAIToolCall, ...]
- request_body: JsonObject
-
-
-def _iter_visible_text_events(
- output: ChatStreamOutput,
- text: str,
-) -> Iterator[str]:
- yield from output.ensure_text_block()
- yield output.emit_text_delta(text)
-
-
-def _iter_text_parser_events(
- output: ChatStreamOutput,
- parser: HeuristicToolParser,
- text: str,
- *,
- tool_names: OpenAIToolNameCodec,
-) -> Iterator[str]:
- """Route visible text through the established heuristic tool parser."""
- filtered_text, detected_tools = parser.feed(text)
- if filtered_text:
- yield from _iter_visible_text_events(output, filtered_text)
- for tool_use in detected_tools:
- yield from iter_heuristic_tool_use_events(
- output,
- tool_use,
- tool_names=tool_names,
- )
-
-
-def _iter_text_tool_use_events(
- output: ChatStreamOutput,
- tool_uses: tuple[dict[str, Any], ...] | list[dict[str, Any]],
- *,
- tool_names: OpenAIToolNameCodec,
-) -> Iterator[str]:
- for tool_use in tool_uses:
- yield from iter_heuristic_tool_use_events(
- output,
- tool_use,
- tool_names=tool_names,
- )
-
-
-@dataclass(frozen=True, slots=True)
-class _OpenAIChatCompletion:
- finish_reason: Any
- output_tokens: int
- input_tokens: int
- provider_input_tokens: int | None
-
-
-class _OpenAIChatFailureOutcome(StrEnum):
- RETRY = "retry"
- COMPLETE = "complete"
- RAISE = "raise"
-
-
-@dataclass(frozen=True, slots=True)
-class _OpenAIChatFailureResolution:
- outcome: _OpenAIChatFailureOutcome
- events: tuple[str, ...] = ()
- failure: ExecutionFailure | None = None
-
-
-def _reserved_anthropic_tool_ids(request: MessagesRequest) -> frozenset[str]:
- """Return prior tool-use IDs that generated output must not reuse."""
- return frozenset(
- block.id
- for message in request.messages
- if isinstance(message.content, list)
- for block in message.content
- if isinstance(block, ContentBlockToolUse) and block.id.strip()
- )
-
-
-class _OpenAIChatStreamAssembler:
- """Own one discardable OpenAI-chat replay epoch."""
-
- def __init__(
- self,
- *,
- output: ChatStreamOutput,
- profile: OpenAIChatProfile,
- provider_name: str,
- output_reasoning: bool,
- tool_names: OpenAIToolNameCodec,
- tool_schemas: dict[str, ToolSchema],
- tool_choice_enabled: bool,
- tool_calls: OpenAIToolCallAssembler,
- extra_reasoning_events: _ExtraReasoningEvents,
- ) -> None:
- self._output = output
- self._profile = profile
- self._provider_name = provider_name
- self._output_reasoning = output_reasoning
- self._tool_names = tool_names
- self._tool_schemas = tool_schemas
- self._tool_calls = tool_calls
- self._extra_reasoning_events = extra_reasoning_events
- self._think_parser = ThinkTagParser()
- self._function_tag_parser = FunctionTagToolParser.from_schemas(
- tool_names=tool_names,
- schemas={
- name: schema.input_schema for name, schema in tool_schemas.items()
- },
- enabled=tool_choice_enabled,
- )
- self._heuristic_parser = HeuristicToolParser()
- self._structured_reasoning = (
- StructuredReasoningStream()
- if profile.structured_reasoning_details
- else None
- )
- if self._structured_reasoning is not None:
- self._output.reasoning_replay_events = self._structured_reasoning.flush
- self._finish_reason: Any = None
- self._usage_info: Any = None
- self._native_reasoning_seen = False
- self._tool_argument_aliases: dict[str, dict[str, str]] = {}
- self._tool_argument_alias_buffers: dict[int, str] = {}
- self._tool_name_buffers: dict[int, str] = {}
- self._started = False
- self._aliases_bound = False
- self._upstream_finished = False
- self._completion: _OpenAIChatCompletion | None = None
- self._completed = False
-
- @property
- def output(self) -> ChatStreamOutput:
- return self._output
-
- @property
- def usage_info(self) -> Any:
- return self._usage_info
-
- @property
- def completion(self) -> _OpenAIChatCompletion:
- if self._completion is None:
- raise RuntimeError("stream completion has not been prepared")
- return self._completion
-
- @property
- def generated_output(self) -> bool:
- return self._output.committed_output
-
- @property
- def complete_tool_salvageable(self) -> bool:
- return (
- self.generated_output
- and self._output.has_emitted_tool_block()
- and self._output.can_salvage_tool_use(self._tool_schemas)
- )
-
- @property
- def tool_argument_alias_buffers(self) -> Mapping[int, str]:
- return self._tool_argument_alias_buffers
-
- def recovered_tool_call_events(
- self, tool_call: CompletedOpenAIToolCall
- ) -> Iterator[str]:
- """Emit one buffered recovery call through this attempt's ID scope."""
- yield from self._tool_calls.process_tool_call(tool_call, self._output)
-
- def start_events(self) -> Iterator[str]:
- if self._started:
- return
- self._started = True
- yield from self._output.start_events()
-
- def bind_tool_argument_aliases(self, aliases: dict[str, dict[str, str]]) -> None:
- if self._aliases_bound:
- raise RuntimeError("tool argument aliases already bound")
- self._aliases_bound = True
- self._tool_argument_aliases = aliases
-
- def feed(self, chunk: Any) -> Iterator[str]:
- if not self._started or self._upstream_finished:
- raise RuntimeError("stream assembler is not accepting chunks")
-
- chunk_usage = getattr(chunk, "usage", None)
- if chunk_usage is not None:
- self._usage_info = chunk_usage
-
- if not chunk.choices:
- return
-
- if (
- self._output.replay_origin is not None
- and isinstance(getattr(chunk, "model", None), str)
- and chunk.model
- ):
- self._output.replay_origin = replace(
- self._output.replay_origin, model=chunk.model
- )
- choice = chunk.choices[0]
- delta = choice.delta
- if choice.finish_reason:
- self._finish_reason = choice.finish_reason
- if delta is None:
- return
-
- if choice.finish_reason:
- self._finish_reason = choice.finish_reason
- logger.debug(
- "{} finish_reason: {}",
- self._provider_name,
- self._finish_reason,
- )
-
- reasoning = self._profile.reasoning_delta(delta)
- if self._output_reasoning:
- if self._structured_reasoning is not None:
- yield from self._structured_reasoning.events(
- delta,
- self._output,
- native_reasoning=reasoning,
- )
- elif reasoning is not None and (
- reasoning or not self._native_reasoning_seen
- ):
- # Preserve initial empty reasoning for replay; later empty fields
- # are placeholders and must not interrupt text or tool output.
- self._native_reasoning_seen = True
- yield from self._output.ensure_reasoning_block()
- if reasoning:
- yield self._output.emit_reasoning_delta(reasoning)
-
- yield from self._extra_reasoning_events(delta, self._output)
-
- native_tool_calls = delta.tool_calls
- if native_tool_calls:
- released_text = self._function_tag_parser.disable()
- if released_text:
- yield from _iter_visible_text_events(self._output, released_text)
-
- if delta.content:
- for part in self._think_parser.feed(delta.content):
- if part.type == ContentType.THINKING:
- if not self._output_reasoning:
- continue
- yield from self._output.ensure_reasoning_block()
- yield self._output.emit_reasoning_delta(part.content)
- else:
- safe_text = self._function_tag_parser.feed(part.content)
- if safe_text:
- yield from _iter_text_parser_events(
- self._output,
- self._heuristic_parser,
- safe_text,
- tool_names=self._tool_names,
- )
-
- if native_tool_calls:
- yield from self._output.close_content_blocks()
- for tool_call in native_tool_calls:
- extra_content = tool_call_extra_content(tool_call)
- tool_call_info = {
- "index": tool_call.index,
- "id": tool_call.id,
- "function": {
- "name": tool_call.function.name,
- "arguments": tool_call.function.arguments,
- },
- }
- if extra_content:
- tool_call_info["extra_content"] = extra_content
- yield from self._tool_calls.process_tool_call(
- tool_call_info,
- self._output,
- tool_names=self._tool_names,
- tool_name_buffers=self._tool_name_buffers,
- tool_argument_aliases=self._tool_argument_aliases,
- tool_argument_alias_buffers=self._tool_argument_alias_buffers,
- )
-
- def finish_upstream(self) -> Iterator[str]:
- if self._upstream_finished:
- return
- if self._finish_reason is None:
- raise TruncatedProviderStreamError(
- "Provider stream ended without finish_reason."
- )
- if is_context_window_finish_reason(self._finish_reason):
- raise context_window_exceeded_provider_failure()
- if any(
- not self._tool_names.is_unchanged_name(name)
- for name in self._tool_name_buffers.values()
- ):
- raise TruncatedProviderStreamError(
- "Provider stream ended with an incomplete tool name."
- )
-
- remaining = self._think_parser.flush()
- if remaining:
- if remaining.type == ContentType.THINKING:
- if self._output_reasoning:
- yield from self._output.ensure_reasoning_block()
- yield self._output.emit_reasoning_delta(remaining.content)
- else:
- safe_text = self._function_tag_parser.feed(remaining.content)
- if safe_text:
- yield from _iter_text_parser_events(
- self._output,
- self._heuristic_parser,
- safe_text,
- tool_names=self._tool_names,
- )
-
- fallback_text, function_tag_tools = self._function_tag_parser.finish()
- if fallback_text:
- yield from _iter_visible_text_events(self._output, fallback_text)
- yield from _iter_text_tool_use_events(
- self._output,
- function_tag_tools,
- tool_names=self._tool_names,
- )
- yield from _iter_text_tool_use_events(
- self._output,
- self._heuristic_parser.flush(),
- tool_names=self._tool_names,
- )
- yield from self._output.flush_reasoning_replay()
- self._upstream_finished = True
-
- def prepare_completion(self) -> Iterator[str]:
- if not self._upstream_finished or self._completion is not None:
- raise RuntimeError("stream completion cannot be prepared")
-
- yield from self._tool_calls.flush_tool_name_buffers(
- self._output,
- tool_names=self._tool_names,
- tool_name_buffers=self._tool_name_buffers,
- tool_argument_aliases=self._tool_argument_aliases,
- tool_argument_alias_buffers=self._tool_argument_alias_buffers,
- )
-
- has_emitted_tool = self._output.has_emitted_tool_block()
- has_content_blocks = self._output.has_content_block()
- if not has_content_blocks or (
- not has_emitted_tool
- and not self._output.accumulated_text.strip()
- and self._output.accumulated_reasoning.strip()
- ):
- yield from self._output.ensure_text_block()
- yield self._output.emit_text_delta(" ")
-
- yield from self._tool_calls.flush_tool_argument_alias_buffers(
- self._output,
- self._tool_argument_aliases,
- self._tool_argument_alias_buffers,
- )
- yield from self._tool_calls.flush_task_arg_buffers(self._output)
- yield from self._output.close_all_blocks()
-
- completion = usage_int(self._usage_info, "completion_tokens")
- output_tokens = (
- completion
- if isinstance(completion, int)
- else self._output.estimate_output_tokens()
- )
- provider_input = usage_int(self._usage_info, "prompt_tokens")
- input_tokens = (
- provider_input if provider_input is not None else self._output.input_tokens
- )
- self._completion = _OpenAIChatCompletion(
- finish_reason=self._finish_reason,
- output_tokens=output_tokens,
- input_tokens=input_tokens,
- provider_input_tokens=provider_input,
- )
-
- def terminal_events(self, *, usage: ChatStreamUsage) -> Iterator[str]:
- if self._completed:
- return
- completion = self.completion
- yield from self._output.finish_success(
- stop_reason=map_stop_reason(completion.finish_reason),
- usage=usage,
- )
- self._completed = True
+from .transport import OpenAIChatTransport
class OpenAIChatProvider(BaseProvider):
- """OpenAI-compatible ``/chat/completions`` provider configured by a profile."""
+ """Own a Chat provider's client and discovery; compose its wire transport."""
def __init__(
self,
config: ProviderConfig,
*,
- profile: OpenAIChatProfile,
+ profile: OpenAIChatProfile | None = None,
+ behavior: OpenAIChatBehavior | None = None,
admission: ProviderAdmissionController,
default_headers: Mapping[str, str] | None = None,
api_key_provider: OpenAIAsyncCredentialProvider | None = None,
client: AsyncOpenAI | None = None,
endpoint_transport: httpx2.AsyncBaseTransport | None = None,
- ):
+ ) -> None:
super().__init__(config)
- self._profile = profile
- self._endpoint_transport = endpoint_transport
- self._provider_name = profile.provider_name
- if client is None and config.api_key is None and api_key_provider is None:
- raise ValueError(
- f"{profile.provider_name} requires an API key or credential provider"
- )
+ if behavior is None:
+ if profile is None:
+ raise ValueError("A Chat profile or behavior is required")
+ behavior = OpenAIChatBehavior(profile)
+ elif profile is not None:
+ raise ValueError("Pass a Chat profile or behavior, not both")
+ self._behavior = behavior
+ self._profile = behavior.profile
+ self._provider_name = self._profile.provider_name
self._api_key = config.api_key
- self._base_url = profile.base_url(config.base_url).rstrip("/")
- # Learned per-model output-token caps from upstream 400 rejections, so
- # later requests clamp proactively instead of paying the 400 each time.
- self._model_output_caps: dict[str, int] = {}
+ self._base_url = self._profile.base_url(config.base_url).rstrip("/")
self._admission = admission
- timeout = httpx2.Timeout(
- config.http_read_timeout,
- connect=config.http_connect_timeout,
- read=config.http_read_timeout,
- write=config.http_write_timeout,
- )
- http_client = None
- if client is None and config.proxy:
- http_client = DefaultAsyncHttpx2Client(
- proxy=config.proxy,
- timeout=timeout,
- )
self._owns_client = client is None
- self._client = client or AsyncOpenAI(
- api_key=api_key_provider or self._api_key,
+ self._client = client or create_chat_client(
+ config,
base_url=self._base_url,
- max_retries=0,
+ provider_name=self._provider_name,
default_headers=default_headers,
- timeout=timeout,
- http_client=http_client,
+ api_key_provider=api_key_provider,
+ )
+ self._chat = OpenAIChatTransport(
+ client=self._client,
+ admission=admission,
+ behavior=behavior,
+ read_timeout_s=config.http_read_timeout,
+ log_raw_sse_events=config.log_raw_sse_events,
+ log_api_error_tracebacks=config.log_api_error_tracebacks,
+ endpoint_transport=endpoint_transport,
)
async def cleanup(self) -> None:
@@ -629,7 +143,7 @@ class OpenAIChatProvider(BaseProvider):
return await execution.run_call(
self._fetch_models_payload_once,
operation_kind=ProviderOperationKind.MODEL_DISCOVERY,
- provider_failure_override=self._provider_failure_override,
+ provider_failure_override=self._behavior.failure_override,
)
async def _fetch_models_payload_once(self) -> Any:
@@ -667,7 +181,7 @@ class OpenAIChatProvider(BaseProvider):
options={"params": params},
),
operation_kind=ProviderOperationKind.MODEL_DISCOVERY,
- provider_failure_override=self._provider_failure_override,
+ provider_failure_override=self._behavior.failure_override,
)
total_pages = validate_model_list_page(
payload,
@@ -687,91 +201,6 @@ class OpenAIChatProvider(BaseProvider):
collection_field=listing.collection_field,
)
- def _build_request_body(
- self,
- request: MessagesRequest,
- *,
- reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
- model_info: ProviderModelInfo | None = None,
- ) -> dict[str, Any]:
- """Build a provider request from the immutable profile."""
- request, reasoning = self._prepare_messages_reasoning(
- request, reasoning, model_info
- )
- body = build_openai_chat_request_body(
- request,
- reasoning=reasoning,
- policy=self._profile.request_policy,
- postprocessors=self._profile.request_postprocessors,
- )
- return self._finalize_chat_body(body, reasoning=reasoning)
-
- @property
- def _reasoning_off_fields(self) -> tuple[tuple[str, ...], ...]:
- field = self._profile.reasoning.off_field
- return (field,) if field is not None else ()
-
- @property
- def _normal_max_tokens(self) -> int | None:
- return self._profile.request_policy.default_max_tokens
-
- def _prepare_messages_reasoning(
- self,
- request: MessagesRequest,
- reasoning: ReasoningPolicy,
- model_info: ProviderModelInfo | None,
- ) -> tuple[MessagesRequest, ReasoningPolicy]:
- return prepare_messages_reasoning(
- request,
- reasoning,
- model_info=model_info,
- can_disable=bool(self._reasoning_off_fields),
- normal_max_tokens=self._normal_max_tokens,
- )
-
- def _build_responses_request_body(
- self,
- request: OpenAIResponsesRequest,
- *,
- reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
- ) -> ResponsesChatRequest:
- """Build a Chat body directly from Responses ingress."""
- validate_history(request.model_dump(mode="json"))
- try:
- translated = build_responses_chat_request(
- request,
- reasoning_replay=self._profile.request_policy.reasoning_replay,
- structured_reasoning_details=(
- self._profile.structured_reasoning_details
- ),
- )
- except ResponsesConversionError as exc:
- raise InvalidRequestError(str(exc)) from exc
- body = translated.body
- apply_openai_chat_body_policy(body, self._profile.request_policy)
- self._profile.apply_reasoning_to_body(body, reasoning)
- body = self._finalize_chat_body(body, reasoning=reasoning)
- encode_openai_chat_tool_names(body, translated.tool_names)
- return ResponsesChatRequest(
- body=body,
- tool_names=translated.tool_names,
- tool_schemas=translated.tool_schemas,
- reserved_tool_ids=translated.reserved_tool_ids,
- tool_adapter=translated.tool_adapter,
- )
-
- def _finalize_chat_body(
- self,
- body: dict[str, Any],
- *,
- reasoning: ReasoningPolicy,
- ) -> dict[str, Any]:
- """Apply provider behavior that is independent of client protocol."""
- return body
-
- def _history_scope(self, body: Mapping[str, Any]) -> HistoryScope:
- return self._profile.history_scope
-
def preflight_messages(
self,
request: MessagesRequest,
@@ -779,8 +208,9 @@ class OpenAIChatProvider(BaseProvider):
reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
model_info: ProviderModelInfo | None = None,
) -> None:
- """Validate OpenAI-chat request conversion before streaming."""
- self._build_request_body(request, reasoning=reasoning, model_info=model_info)
+ self._chat.preflight_messages(
+ request, reasoning=reasoning, model_info=model_info
+ )
def preflight_responses(
self,
@@ -788,250 +218,7 @@ class OpenAIChatProvider(BaseProvider):
*,
reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
) -> None:
- """Validate direct Responses-to-Chat conversion before streaming."""
- self._build_responses_request_body(request, reasoning=reasoning)
-
- def _handle_extra_reasoning(
- self, delta: Any, output: ChatStreamOutput, *, output_reasoning: bool
- ) -> Iterator[str]:
- """Hook for provider-specific reasoning."""
- return iter(())
-
- def _get_retry_request_body(self, error: Exception, body: dict) -> dict | None:
- """Return a modified request body for one retry, or None."""
- return None
-
- def _reasoning_disable_rejected(self, error: Exception) -> bool:
- """Recognize provider-owned OFF rejection formats without learning state."""
- return False
-
- def _provider_failure_override(self, error: Exception) -> ExecutionFailure | None:
- """Return provider-specific failure semantics, or defer to shared policy."""
- return None
-
- def _prepare_create_body(self, body: dict[str, Any]) -> dict[str, Any]:
- """Return the body passed to the upstream OpenAI-compatible client."""
- return body
-
- def _upstream_headers(
- self, request_headers: Mapping[str, str]
- ) -> Mapping[str, str]:
- """Select provider-specific headers from this request's client metadata."""
- return {}
-
- def _record_tool_call_extra_content(
- self, tool_call_id: str, extra_content: dict[str, Any]
- ) -> None:
- """Hook for providers that must replay OpenAI tool-call metadata later."""
-
- def _tool_argument_aliases(self, body: dict[str, Any]) -> dict[str, dict[str, str]]:
- """Return provider-specific per-tool argument aliases for this request."""
- return {}
-
- def _cached_input_tokens(self, usage_info: object) -> int | None:
- """Return the provider's cached-input count from final Chat usage."""
- return nested_usage_int(
- usage_info,
- "prompt_tokens_details",
- "cached_tokens",
- )
-
- def _cache_write_input_tokens(self, usage_info: object) -> int | None:
- """Return the provider's cache-write count from final Chat usage."""
- return nested_usage_int(
- usage_info,
- "prompt_tokens_details",
- "cache_write_tokens",
- )
-
- def _anthropic_usage_fields(self, usage_info: Any) -> dict[str, int]:
- """Split standard prompt cache counts for final Anthropic usage."""
- return anthropic_input_usage_fields(
- usage_int(usage_info, "prompt_tokens"),
- cache_read_tokens=self._cached_input_tokens(usage_info),
- cache_creation_tokens=self._cache_write_input_tokens(usage_info),
- )
-
- async def _create_stream(
- self,
- body: dict,
- execution: ProviderExecution,
- operation_kind: ProviderOperationKind,
- *,
- used_retry_kinds: set[str] | None = None,
- endpoint: RequestEndpoint | None = None,
- extra_headers: Mapping[str, str] | None = None,
- reasoning_correction: ReasoningCorrection | None = None,
- ) -> tuple[Any, dict, ProviderAttempt, dict]:
- """Create a streaming chat completion with bounded request fallbacks."""
- body = self._apply_learned_output_cap(body)
- if used_retry_kinds is None:
- used_retry_kinds = set()
-
- while execution.can_attempt:
- attempt = await execution.open_attempt(operation_kind)
- stream: Any | None = None
- retain_attempt = False
- create_body = body
- try:
- create_body = self._prepare_create_body(body)
- client = (
- await endpoint.openai_client(self._client)
- if endpoint is not None
- else self._client
- )
- if extra_headers or endpoint is not None:
- create_body = create_body.copy()
- create_body["extra_headers"] = {
- **(create_body.get("extra_headers") or {}),
- **(extra_headers or {}),
- **(endpoint.openai_headers() if endpoint is not None else {}),
- }
- origin = replay_origin(
- self._provider_name,
- "chat",
- str(body["model"]),
- client=client,
- endpoint=endpoint.snapshot if endpoint is not None else None,
- )
- create_body = cast(
- dict[str, Any],
- prepare_history(
- create_body,
- origin,
- scope=self._history_scope(body),
- reasoning_field=self._profile.request_policy.reasoning_replay.value,
- structured_details=self._profile.structured_reasoning_details,
- ),
- )
- stream = await client.chat.completions.create(
- **create_body,
- stream=True,
- )
- stream = self._normalize_stream(stream, body)
- retain_attempt = True
- return stream, body, attempt, create_body
- except asyncio.CancelledError:
- raise
- except Exception as error:
- if endpoint is not None and await endpoint.retry_authentication(
- error, attempt, execution
- ):
- continue
- retry_body = self._next_create_retry_body(
- error,
- body,
- used_retry_kinds,
- reasoning_correction=reasoning_correction,
- sent_body=create_body,
- )
- if retry_body is not None:
- correction = await attempt.correct(error)
- if correction is ProviderCorrectionAction.RETRY:
- body = self._apply_learned_output_cap(retry_body)
- continue
- raise
- decision = await attempt.fail(
- error,
- provider_failure_override=self._provider_failure_override,
- )
- if not decision.retry_allowed:
- raise
- finally:
- if not retain_attempt:
- if stream is not None:
- await close_provider_stream(
- stream,
- active_error=sys.exception(),
- provider_name=self._provider_name,
- request_id=execution.request_id,
- )
- await attempt.aclose()
-
- if execution.last_failure is not None:
- raise execution.last_failure
- raise RuntimeError("provider execution ended without a final error")
-
- def _normalize_stream(self, stream: Any, _body: Mapping[str, Any]) -> Any:
- """Return the provider-specific stream view consumed by the base runner."""
- return stream
-
- def _next_create_retry_body(
- self,
- error: Exception,
- body: dict,
- used_retry_kinds: set[str],
- *,
- reasoning_correction: ReasoningCorrection | None = None,
- sent_body: Mapping[str, Any] | None = None,
- ) -> dict | None:
- corrected_history = history_retry_body(
- error, sent_body if sent_body is not None else body, "chat"
- )
- if corrected_history is not None:
- return corrected_history
- if reasoning_correction is not None and "reasoning" not in used_retry_kinds:
- retry_body = reasoning_correction.retry_body(
- error, body, sent_body=sent_body
- )
- if retry_body is not None:
- used_retry_kinds.add("reasoning")
- return retry_body
- retry_body = self._retry_body_for_output_cap(error, body)
- if retry_body is not None:
- return retry_body
-
- if "stream_usage" not in used_retry_kinds and is_stream_usage_rejection(error):
- retry_body = clone_without_stream_usage(body)
- if retry_body is not None:
- used_retry_kinds.add("stream_usage")
- logger.warning(
- "{}_STREAM: retrying without stream_options.include_usage "
- "after upstream rejection",
- self._provider_name,
- )
- return retry_body
-
- if "provider_specific" not in used_retry_kinds:
- retry_body = self._get_retry_request_body(
- error, dict(sent_body) if sent_body is not None else body
- )
- if retry_body is not None:
- used_retry_kinds.add("provider_specific")
- return retry_body
-
- return None
-
- def _apply_learned_output_cap(self, body: dict) -> dict:
- """Clamp output tokens to a previously learned cap for this model."""
- model = body.get("model")
- if not isinstance(model, str):
- return body
- cap = self._model_output_caps.get(model)
- if cap is None:
- return body
- clamped = clamp_output_tokens(body, cap)
- return clamped if clamped is not None else body
-
- def _retry_body_for_output_cap(self, error: Exception, body: dict) -> dict | None:
- """Learn an upstream output-token cap from a 400 and clamp for one retry."""
- cap = parse_output_token_cap(error)
- if cap is None:
- return None
- model = body.get("model")
- if isinstance(model, str):
- previous = self._model_output_caps.get(model)
- cap = cap if previous is None else min(previous, cap)
- self._model_output_caps[model] = cap
- clamped = clamp_output_tokens(body, cap)
- if clamped is None:
- return None
- logger.warning(
- "{}_STREAM: clamping output tokens to {} after upstream cap rejection",
- self._provider_name,
- cap,
- )
- return clamped
+ self._chat.preflight_responses(request, reasoning=reasoning)
def stream_messages(
self,
@@ -1045,49 +232,15 @@ class OpenAIChatProvider(BaseProvider):
endpoint_context: EndpointContext | None = None,
request_headers: Mapping[str, str] | None = None,
) -> AsyncIterator[str]:
- """Stream response in Anthropic SSE format."""
- prepared_request, wire_reasoning = self._prepare_messages_reasoning(
- request, reasoning, model_info
- )
- body = self._build_request_body(prepared_request, reasoning=wire_reasoning)
- off_fields = self._reasoning_off_fields
- correction = (
- ReasoningCorrection(
- off_fields,
- self._profile.request_policy.max_tokens_field,
- self._normal_max_tokens,
- provider_rejection=self._reasoning_disable_rejected,
- )
- if reasoning.control is ReasoningControl.PREFER_OFF
- and wire_reasoning.control is ReasoningControl.OFF
- and off_fields
- else None
- )
- tool_names = OpenAIToolNameCodec.from_request(request)
- message_id = f"msg_{uuid.uuid4()}"
- runner = _OpenAIChatStreamRunner(
- self,
- body=body,
- tool_names=tool_names,
- tool_schemas=tool_schemas_by_name(request),
- reserved_tool_ids=_reserved_anthropic_tool_ids(request),
- output_factory=lambda: AnthropicChatStreamOutput(
- message_id=message_id,
- model=request.model if response_model is None else response_model,
- input_tokens=input_tokens,
- log_raw_events=self._config.log_raw_sse_events,
- ),
+ return self._chat.stream_messages(
+ request,
input_tokens=input_tokens,
request_id=request_id,
- response_model=(
- request.model if response_model is None else response_model
- ),
+ response_model=response_model,
reasoning=reasoning,
endpoint_context=endpoint_context,
- extra_headers=self._upstream_headers(request_headers or {}),
- reasoning_correction=correction,
+ model_info=model_info,
)
- return runner.run()
def stream_responses(
self,
@@ -1100,762 +253,11 @@ class OpenAIChatProvider(BaseProvider):
endpoint_context: EndpointContext | None = None,
request_headers: Mapping[str, str] | None = None,
) -> AsyncIterator[str]:
- """Stream a Chat upstream directly as OpenAI Responses SSE."""
- translated = self._build_responses_request_body(request, reasoning=reasoning)
- public_model = request.model if response_model is None else response_model
- tool_schemas = {
- name: ToolSchema(name=name, input_schema=schema)
- for name, schema in translated.tool_schemas.items()
- }
- runner = _OpenAIChatStreamRunner(
- self,
- body=translated.body,
- tool_names=translated.tool_names,
- tool_schemas=tool_schemas,
- reserved_tool_ids=translated.reserved_tool_ids,
- output_factory=lambda: ResponsesChatStreamOutput(
- translated.tool_adapter,
- input_tokens=input_tokens,
- response_model=public_model,
- ),
+ return self._chat.stream_responses(
+ request,
input_tokens=input_tokens,
request_id=request_id,
- response_model=public_model,
+ response_model=response_model,
reasoning=reasoning,
endpoint_context=endpoint_context,
- extra_headers=self._upstream_headers(request_headers or {}),
- )
- return runner.run()
-
-
-class _OpenAIChatStreamRunner:
- """Orchestrate one OpenAI-chat request and its recovery lifecycle."""
-
- def __init__(
- self,
- provider: OpenAIChatProvider,
- *,
- body: dict[str, Any],
- tool_names: OpenAIToolNameCodec,
- tool_schemas: dict[str, ToolSchema],
- reserved_tool_ids: frozenset[str],
- output_factory: _ChatOutputFactory,
- input_tokens: int,
- request_id: str | None,
- response_model: str,
- reasoning: ReasoningPolicy,
- endpoint_context: EndpointContext | None = None,
- extra_headers: Mapping[str, str] | None = None,
- reasoning_correction: ReasoningCorrection | None = None,
- ) -> None:
- self._provider = provider
- self._body = body
- self._tool_argument_aliases = provider._tool_argument_aliases(body)
- self._tool_names = tool_names
- self._tool_schemas = tool_schemas
- self._reserved_tool_ids = reserved_tool_ids
- self._output_factory = output_factory
- self._input_tokens = input_tokens
- self._request_id = request_id
- self._response_model = response_model
- self._reasoning = reasoning
- self._reasoning_correction = reasoning_correction
- self._extra_headers = dict(extra_headers or {})
- self._terminal_failure: ExecutionFailure | None = None
- self._endpoint = (
- RequestEndpoint(endpoint_context, provider._endpoint_transport)
- if endpoint_context is not None
- else None
- )
-
- async def run(self) -> AsyncIterator[str]:
- """Convert the upstream OpenAI-chat stream into Anthropic SSE."""
- execution = self._provider._admission.start_execution(
- request_id=self._request_id
- )
- provider_stream = self._run_execution(execution)
- try:
- async for event in provider_stream:
- if self._endpoint is not None:
- self._endpoint.commit()
- yield event
- except asyncio.CancelledError:
- raise
- except Exception as error:
- execution.fail(error)
- raise
- else:
- if self._terminal_failure is None:
- execution.succeed()
- else:
- execution.fail(self._terminal_failure)
- finally:
- try:
- await maybe_await_aclose(provider_stream)
- finally:
- try:
- if self._endpoint is not None:
- await self._endpoint.aclose()
- finally:
- execution.abandon()
-
- async def _run_execution(
- self,
- execution: ProviderExecution,
- ) -> AsyncIterator[str]:
- """Run one provider execution while retaining transport-owned state."""
- tag = self._provider._provider_name
- req_tag = f" request_id={self._request_id}" if self._request_id else ""
- recovery = RecoveryController()
-
- def hold_event(event: str) -> Iterator[str]:
- yield from recovery.push(event)
-
- body = self._body
- request_stream_usage(body)
- output_reasoning = self._reasoning.output_enabled
- used_retry_kinds: set[str] = set()
- trace_event(
- stage="provider",
- event="provider.request.sent",
- source="provider",
- provider=tag,
- request_id=self._request_id,
- execution_id=execution.execution_id,
- gateway_model=self._response_model,
- downstream_model=body.get("model"),
- message_count=len(body.get("messages", [])),
- tool_count=len(body.get("tools", [])),
- body=provider_chat_body_snapshot(body),
- )
-
- while True:
- assembler = self._new_stream_assembler(output_reasoning=output_reasoning)
- scope: ProviderAttemptScope | None = None
- try:
- stream, body, attempt, sent_body = await self._provider._create_stream(
- body,
- execution,
- ProviderOperationKind.GENERATION,
- used_retry_kinds=used_retry_kinds,
- endpoint=self._endpoint,
- extra_headers=self._extra_headers,
- reasoning_correction=self._reasoning_correction,
- )
- scope = ProviderAttemptScope(
- attempt,
- provider_name=tag,
- request_id=self._request_id,
- )
- stream = scope.retain(stream)
- assembler.output.replay_origin = replay_origin(
- tag,
- "chat",
- str(body["model"]),
- client=self._provider._client,
- endpoint=self._endpoint.snapshot
- if self._endpoint is not None
- else None,
- )
- assembler.bind_tool_argument_aliases(self._tool_argument_aliases)
- async for chunk in stream:
- if not scope.attempt.accepted:
- await scope.attempt.accept()
- for event in assembler.start_events():
- for out_event in hold_event(event):
- yield out_event
- for event in assembler.feed(chunk):
- for out_event in hold_event(event):
- yield out_event
-
- for event in assembler.finish_upstream():
- for out_event in hold_event(event):
- yield out_event
- break
-
- except asyncio.CancelledError, GeneratorExit:
- raise
- except Exception as error:
- if scope is not None and not recovery.committed:
- corrected_history = history_retry_body(error, sent_body, "chat")
- if corrected_history is not None:
- retry = (
- execution.can_attempt
- if scope.attempt.accepted
- else await scope.attempt.correct(error)
- is ProviderCorrectionAction.RETRY
- )
- if retry:
- body = corrected_history
- recovery.discard()
- continue
- if (
- scope is not None
- and not recovery.committed
- and self._reasoning_correction is not None
- and "reasoning" not in used_retry_kinds
- ):
- corrected_body = self._reasoning_correction.retry_body(
- error, body, sent_body=sent_body
- )
- if corrected_body is not None:
- used_retry_kinds.add("reasoning")
- retry = (
- execution.can_attempt
- if scope.attempt.accepted
- else await scope.attempt.correct(error)
- is ProviderCorrectionAction.RETRY
- )
- if retry:
- body = self._provider._apply_learned_output_cap(
- corrected_body
- )
- recovery.discard()
- continue
- resolution = await self._resolve_attempt_failure(
- error=error,
- scope=scope,
- assembler=assembler,
- body=body,
- execution=execution,
- recovery=recovery,
- req_tag=req_tag,
- )
- if resolution.outcome is _OpenAIChatFailureOutcome.RETRY:
- continue
- for event in resolution.events:
- yield event
- if resolution.outcome is _OpenAIChatFailureOutcome.COMPLETE:
- self._terminal_failure = resolution.failure
- return
- if resolution.failure is None:
- raise AssertionError(
- "raise resolution requires a failure"
- ) from error
- raise resolution.failure from error
- finally:
- if scope is not None:
- await scope.aclose(active_error=sys.exception())
-
- for event in assembler.prepare_completion():
- for out_event in hold_event(event):
- yield out_event
- completion = assembler.completion
- if completion.provider_input_tokens is not None:
- logger.debug(
- "TOKEN_ESTIMATE: our={} provider={} diff={:+d}",
- self._input_tokens,
- completion.provider_input_tokens,
- completion.provider_input_tokens - self._input_tokens,
- )
- trace_event(
- stage="provider",
- event="provider.response.completed",
- source="provider",
- provider=tag,
- request_id=self._request_id,
- finish_reason=(
- None
- if completion.finish_reason is None
- else str(completion.finish_reason)
- ),
- output_tokens=completion.output_tokens,
- prompt_tokens=completion.input_tokens,
- prompt_tokens_estimate=self._input_tokens,
- )
- usage = ChatStreamUsage(
- input_tokens=completion.input_tokens,
- output_tokens=completion.output_tokens,
- cached_tokens=self._provider._cached_input_tokens(assembler.usage_info)
- or 0,
- cache_write_tokens=self._provider._cache_write_input_tokens(
- assembler.usage_info
- ),
- reasoning_tokens=(
- nested_usage_int(
- assembler.usage_info,
- "completion_tokens_details",
- "reasoning_tokens",
- )
- or 0
- ),
- anthropic_fields=self._provider._anthropic_usage_fields(
- assembler.usage_info
- ),
- )
- for event in assembler.terminal_events(usage=usage):
- for out_event in hold_event(event):
- yield out_event
- for event in recovery.flush():
- yield event
-
- async def _resolve_attempt_failure(
- self,
- *,
- error: Exception,
- scope: ProviderAttemptScope | None,
- assembler: _OpenAIChatStreamAssembler,
- body: dict[str, Any],
- execution: ProviderExecution,
- recovery: RecoveryController,
- req_tag: str,
- ) -> _OpenAIChatFailureResolution:
- """Resolve one failed generation attempt without owning retry policy."""
- if (
- scope is not None
- and self._endpoint is not None
- and await self._endpoint.retry_authentication(
- error, scope.attempt, execution
- )
- ):
- recovery.discard()
- return _OpenAIChatFailureResolution(outcome=_OpenAIChatFailureOutcome.RETRY)
- attempt_failure = None
- if scope is not None and not scope.attempt.accepted:
- attempt_failure = await scope.attempt.fail(
- error,
- provider_failure_override=self._provider._provider_failure_override,
- )
-
- retryable = (
- attempt_failure.retryable
- if attempt_failure is not None
- else is_retryable_stream_error(error)
- )
- generated_output = assembler.generated_output
- complete_tool_salvageable = assembler.complete_tool_salvageable
- decision = recovery.advance_failure(
- retryable=retryable,
- stream_opened=scope is not None,
- generated_output=generated_output,
- complete_tool_salvageable=complete_tool_salvageable,
- attempts_remaining=execution.attempts_remaining,
- )
- tag = self._provider._provider_name
- if decision.action == RecoveryFailureAction.EARLY_RETRY:
- trace_event(
- stage="provider",
- event="provider.recovery.early_retry",
- source="provider",
- provider=tag,
- request_id=self._request_id,
- attempts_started=execution.attempts_started,
- max_attempts=execution.max_attempts,
- retryable=True,
- )
- return _OpenAIChatFailureResolution(outcome=_OpenAIChatFailureOutcome.RETRY)
-
- if decision.action == RecoveryFailureAction.MIDSTREAM_RECOVERY:
- if scope is not None:
- await scope.aclose(active_error=error)
- try:
- recovery_events = await self._recovery_events(
- body=body,
- assembler=assembler,
- error=error,
- tool_argument_alias_buffers=(assembler.tool_argument_alias_buffers),
- output_reasoning=self._reasoning.output_enabled,
- execution=execution,
- )
- except Exception as recovery_error:
- trace_event(
- stage="provider",
- event="provider.recovery.failed",
- source="provider",
- provider=tag,
- request_id=self._request_id,
- exc_type=type(recovery_error).__name__,
- )
- recovery_failure = classify_provider_failure(
- underlying_provider_error(recovery_error),
- provider_name=tag,
- read_timeout_s=self._provider._config.http_read_timeout,
- request_id=self._request_id,
- provider_failure_override=(
- self._provider._provider_failure_override
- ),
- )
- if recovery_failure.kind is FailureKind.CONTEXT_WINDOW_EXCEEDED:
- error = recovery_failure
- recovery_events = None
- if recovery_events is not None:
- return _OpenAIChatFailureResolution(
- outcome=_OpenAIChatFailureOutcome.COMPLETE,
- events=(
- *recovery.flush_uncommitted(decision),
- *recovery_events,
- ),
- )
-
- reported_error = underlying_provider_error(error)
- self._provider._log_stream_transport_error(
- tag,
- req_tag,
- reported_error,
- request_id=self._request_id,
- )
- failure = classify_provider_failure(
- reported_error,
- provider_name=tag,
- read_timeout_s=self._provider._config.http_read_timeout,
- request_id=self._request_id,
- provider_failure_override=self._provider._provider_failure_override,
- )
- error_trace: dict[str, Any] = {
- "stage": "provider",
- "event": "provider.response.error",
- "source": "provider",
- "provider": tag,
- "request_id": self._request_id,
- "exc_type": type(reported_error).__name__,
- "failure_kind": failure.kind.value,
- "status_code": failure.status_code,
- "provider_retryable": failure.retryable,
- }
- if self._provider._config.log_api_error_tracebacks:
- error_trace["error_message"] = failure.message
- trace_event(**error_trace)
-
- failure_events: list[str] = []
- if (
- not decision.committed
- and decision.has_buffered
- and complete_tool_salvageable
- ):
- failure_events.extend(recovery.flush())
- elif not decision.committed:
- recovery.discard()
- return _OpenAIChatFailureResolution(
- outcome=_OpenAIChatFailureOutcome.RAISE,
- failure=failure,
- )
- output = assembler.output
- if output.consumes_terminal_failure:
- failure_events.extend(output.finish_failure(failure))
- return _OpenAIChatFailureResolution(
- outcome=_OpenAIChatFailureOutcome.COMPLETE,
- events=tuple(failure_events),
- failure=failure,
- )
- failure_events.extend(output.close_unclosed_blocks())
- return _OpenAIChatFailureResolution(
- outcome=_OpenAIChatFailureOutcome.RAISE,
- events=tuple(failure_events),
- failure=failure,
- )
-
- async def _collect_recovery_output(
- self,
- body: dict[str, Any],
- *,
- include_reasoning: bool,
- execution: ProviderExecution,
- operation_kind: ProviderOperationKind,
- used_retry_kinds: set[str] | None = None,
- ) -> _CollectedRecoveryOutput:
- """Collect one complete buffered continuation response."""
- if used_retry_kinds is None:
- used_retry_kinds = set()
- last_error: Exception | None = None
- while execution.can_attempt:
- scope: ProviderAttemptScope | None = None
- try:
- stream, body, attempt, _sent_body = await self._provider._create_stream(
- body,
- execution,
- operation_kind,
- used_retry_kinds=used_retry_kinds,
- endpoint=self._endpoint,
- )
- scope = ProviderAttemptScope(
- attempt,
- provider_name=self._provider._provider_name,
- request_id=self._request_id,
- )
- stream = scope.retain(stream)
- text_parts: list[str] = []
- thinking_parts: list[str] = []
- tool_calls = OpenAIToolCallCollector()
- terminal_seen = False
- async for chunk in stream:
- if not scope.attempt.accepted:
- await scope.attempt.accept()
- if not getattr(chunk, "choices", None):
- continue
- choice = chunk.choices[0]
- finish_reason = choice.finish_reason
- if is_context_window_finish_reason(finish_reason):
- raise context_window_exceeded_provider_failure()
- if finish_reason is not None:
- terminal_seen = True
- delta = choice.delta
- if delta is None:
- continue
- if include_reasoning:
- reasoning = self._provider._profile.reasoning_delta(delta)
- if reasoning:
- thinking_parts.append(reasoning)
- content = getattr(delta, "content", None)
- if isinstance(content, str) and content:
- text_parts.append(content)
- native_tool_calls = getattr(delta, "tool_calls", None)
- if isinstance(native_tool_calls, list | tuple):
- for tool_call in native_tool_calls:
- tool_calls.add(tool_call)
-
- completed_tool_calls = tool_calls.completed_calls(
- self._tool_schemas,
- tool_names=self._tool_names,
- tool_argument_aliases=self._tool_argument_aliases,
- )
- if tool_calls.has_calls and completed_tool_calls is None:
- raise TruncatedProviderStreamError(
- "Recovery stream ended with an incomplete tool call."
- )
- if not terminal_seen and not completed_tool_calls:
- raise TruncatedProviderStreamError(
- "Recovery stream ended without finish_reason."
- )
- return _CollectedRecoveryOutput(
- text="".join(text_parts),
- thinking="".join(thinking_parts),
- tool_calls=completed_tool_calls or (),
- request_body=body,
- )
- except Exception as error:
- last_error = error
- retryable = is_retryable_stream_error(error)
- if scope is not None and not scope.attempt.accepted:
- failure = await scope.attempt.fail(
- error,
- provider_failure_override=(
- self._provider._provider_failure_override
- ),
- )
- retryable = failure.retryable
- if not retryable or not execution.can_attempt:
- raise
- trace_event(
- stage="provider",
- event="provider.recovery.retry",
- source="provider",
- provider=self._provider._provider_name,
- recovery_kind="openai_text",
- attempts_started=execution.attempts_started,
- max_attempts=execution.max_attempts,
- exc_type=type(error).__name__,
- )
- finally:
- if scope is not None:
- await scope.aclose(active_error=sys.exception())
- if last_error is not None:
- raise last_error
- return _CollectedRecoveryOutput(
- text="",
- thinking="",
- tool_calls=(),
- request_body=body,
- )
-
- async def _recovery_events(
- self,
- *,
- body: dict[str, Any],
- assembler: _OpenAIChatStreamAssembler,
- error: Exception,
- tool_argument_alias_buffers: Mapping[int, str],
- output_reasoning: bool,
- execution: ProviderExecution,
- ) -> list[str] | None:
- """Build terminal recovery events when the interrupted stream permits it."""
- output = assembler.output
- if output.has_emitted_tool_block():
- if not output.can_salvage_tool_use(self._tool_schemas):
- repair_events = await self._repair_tool_args(
- body=body,
- output=output,
- tool_argument_alias_buffers=tool_argument_alias_buffers,
- execution=execution,
- )
- if repair_events is None:
- return None
- else:
- repair_events = []
- events = list(repair_events)
- events.extend(
- output.finish_success(
- stop_reason="end_turn",
- usage=ChatStreamUsage(
- input_tokens=self._input_tokens,
- output_tokens=output.estimate_output_tokens(),
- ),
- )
- )
- trace_event(
- stage="provider",
- event="provider.recovery.tool_salvaged",
- source="provider",
- provider=self._provider._provider_name,
- request_id=self._request_id,
- )
- return events
-
- partial_text = output.accumulated_text
- partial_thinking = output.accumulated_reasoning
- if not partial_text and not partial_thinking:
- return None
-
- if isinstance(error, RetryableToolProtocolError):
- recovery_body = make_response_recovery_body(
- body,
- partial_text,
- partial_thinking,
- )
- else:
- recovery_body = make_text_recovery_body(
- body,
- partial_text,
- partial_thinking,
- )
- recovered = await self._collect_recovery_output(
- recovery_body,
- include_reasoning=output_reasoning,
- execution=execution,
- operation_kind=ProviderOperationKind.CONTINUATION,
- )
- text_suffix = continuation_suffix(partial_text, recovered.text)
- thinking_suffix = continuation_suffix(partial_thinking, recovered.thinking)
- events: list[str] = []
- if thinking_suffix:
- events.extend(output.ensure_reasoning_block())
- events.append(output.emit_reasoning_delta(thinking_suffix))
- if text_suffix:
- events.extend(output.ensure_text_block())
- events.append(output.emit_text_delta(text_suffix))
- if recovered.tool_calls:
- events.extend(output.close_content_blocks())
- for tool_call in recovered.tool_calls:
- events.extend(assembler.recovered_tool_call_events(tool_call))
- if not events:
- return None
- events.extend(
- output.finish_success(
- stop_reason="end_turn",
- usage=ChatStreamUsage(
- input_tokens=self._input_tokens,
- output_tokens=output.estimate_output_tokens(),
- ),
- )
- )
- trace_event(
- stage="provider",
- event="provider.recovery.continued",
- source="provider",
- provider=self._provider._provider_name,
- request_id=self._request_id,
- )
- return events
-
- async def _repair_tool_args(
- self,
- *,
- body: dict[str, Any],
- output: ChatStreamOutput,
- tool_argument_alias_buffers: Mapping[int, str],
- execution: ProviderExecution,
- ) -> list[str] | None:
- schemas = self._tool_schemas
- events: list[str] = []
- for tool_index, state in output.started_tool_states():
- block = output.tool_block_for_tool_index(tool_index)
- emitted_prefix = block.content if block is not None else ""
- repair_prefix = emitted_prefix
- if not repair_prefix and state.name == "Task" and state.task_arg_buffer:
- repair_prefix = state.task_arg_buffer
- if not repair_prefix and tool_index in tool_argument_alias_buffers:
- repair_prefix = tool_argument_alias_buffers[tool_index]
- if (
- parse_complete_tool_input(repair_prefix, state.name, schemas)
- is not None
- ):
- if not emitted_prefix and repair_prefix:
- events.append(output.emit_tool_delta(tool_index, repair_prefix))
- continue
-
- schema = schemas.get(state.name)
- recovery_body = make_tool_repair_body(
- body,
- tool_name=state.name,
- prefix=repair_prefix,
- input_schema=schema.input_schema if schema is not None else None,
- )
- accepted_suffix: str | None = None
- repair_attempt = 0
- used_retry_kinds: set[str] = set()
- while execution.can_attempt:
- repair_attempt += 1
- recovered = await self._collect_recovery_output(
- recovery_body,
- include_reasoning=False,
- execution=execution,
- operation_kind=ProviderOperationKind.TOOL_REPAIR,
- used_retry_kinds=used_retry_kinds,
- )
- repair = accept_tool_json_repair(
- repair_prefix,
- recovered.text,
- tool_name=state.name,
- schemas=schemas,
- )
- if repair is not None:
- accepted_suffix = repair.suffix
- trace_event(
- stage="provider",
- event="provider.recovery.tool_repaired",
- source="provider",
- provider=self._provider._provider_name,
- tool_name=state.name,
- attempt=repair_attempt,
- )
- break
- recovery_body = recovered.request_body
- if accepted_suffix is None:
- return None
- to_emit = (
- accepted_suffix if emitted_prefix else repair_prefix + accepted_suffix
- )
- if to_emit:
- events.append(output.emit_tool_delta(tool_index, to_emit))
- if not output.can_salvage_tool_use(schemas):
- return None
- return events
-
- def _new_stream_assembler(
- self, *, output_reasoning: bool
- ) -> _OpenAIChatStreamAssembler:
- def extra_reasoning_events(
- delta: Any, output: ChatStreamOutput
- ) -> Iterator[str]:
- yield from self._provider._handle_extra_reasoning(
- delta,
- output,
- output_reasoning=output_reasoning,
- )
-
- return _OpenAIChatStreamAssembler(
- output=self._output_factory(),
- profile=self._provider._profile,
- provider_name=self._provider._provider_name,
- output_reasoning=output_reasoning,
- tool_names=self._tool_names,
- tool_schemas=self._tool_schemas,
- tool_choice_enabled=(
- bool(self._body.get("tools"))
- and self._body.get("tool_choice") != "none"
- ),
- tool_calls=OpenAIToolCallAssembler(
- reserved_tool_ids=self._reserved_tool_ids,
- record_extra_content=self._provider._record_tool_call_extra_content,
- ),
- extra_reasoning_events=extra_reasoning_events,
)
diff --git a/src/free_claude_code/providers/openai_chat/transport.py b/src/free_claude_code/providers/openai_chat/transport.py
new file mode 100644
index 00000000..3b33337f
--- /dev/null
+++ b/src/free_claude_code/providers/openai_chat/transport.py
@@ -0,0 +1,1672 @@
+"""Shared Chat Completions transport and per-request stream execution."""
+
+import asyncio
+import sys
+import uuid
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping
+from dataclasses import dataclass, replace
+from enum import StrEnum
+from typing import Any, cast
+
+import httpx2
+from loguru import logger
+from openai import AsyncOpenAI
+
+from free_claude_code.application.errors import InvalidRequestError
+from free_claude_code.application.model_metadata import ProviderModelInfo
+from free_claude_code.core.anthropic import (
+ ContentBlockToolUse,
+ ContentType,
+ FunctionTagToolParser,
+ HeuristicToolParser,
+ ThinkTagParser,
+)
+from free_claude_code.core.anthropic.models import MessagesRequest
+from free_claude_code.core.anthropic.streaming import (
+ ToolSchema,
+ accept_tool_json_repair,
+ continuation_suffix,
+ make_response_recovery_body,
+ make_text_recovery_body,
+ make_tool_repair_body,
+ map_stop_reason,
+ parse_complete_tool_input,
+ tool_schemas_by_name,
+)
+from free_claude_code.core.diagnostics import (
+ exception_cause_types,
+ redacted_exception_traceback,
+)
+from free_claude_code.core.failures import ExecutionFailure, FailureKind
+from free_claude_code.core.history_replay import prepare_history
+from free_claude_code.core.json_types import JsonObject
+from free_claude_code.core.openai_responses import (
+ OpenAIResponsesRequest,
+ ResponsesChatRequest,
+ ResponsesConversionError,
+ build_responses_chat_request,
+)
+from free_claude_code.core.openai_tool_names import (
+ OpenAIToolNameCodec,
+ encode_openai_chat_tool_names,
+)
+from free_claude_code.core.reasoning import (
+ DEFAULT_REASONING_POLICY,
+ ReasoningControl,
+ ReasoningPolicy,
+)
+from free_claude_code.core.trace import provider_chat_body_snapshot, trace_event
+from free_claude_code.providers.admission import (
+ ProviderAdmissionController,
+ ProviderAttempt,
+ ProviderCorrectionAction,
+ ProviderExecution,
+ ProviderOperationKind,
+)
+from free_claude_code.providers.endpoint import EndpointContext, RequestEndpoint
+from free_claude_code.providers.failure_policy import (
+ RetryableToolProtocolError,
+ classify_provider_failure,
+ context_window_exceeded_provider_failure,
+ is_context_window_finish_reason,
+ is_retryable_stream_error,
+ underlying_provider_error,
+)
+from free_claude_code.providers.history_replay import (
+ history_retry_body,
+ replay_origin,
+ validate_history,
+)
+from free_claude_code.providers.http import (
+ ProviderAttemptScope,
+ close_provider_stream,
+ maybe_await_aclose,
+)
+from free_claude_code.providers.reasoning_compatibility import (
+ ReasoningCorrection,
+ prepare_messages_reasoning,
+)
+from free_claude_code.providers.stream_recovery import (
+ RecoveryController,
+ RecoveryFailureAction,
+ TruncatedProviderStreamError,
+)
+
+from .behavior import OpenAIChatBehavior
+from .output_cap import clamp_output_tokens, parse_output_token_cap
+from .profiles import OpenAIChatProfile
+from .reasoning_details import StructuredReasoningStream
+from .request_policy import (
+ apply_openai_chat_body_policy,
+)
+from .stream_output import (
+ AnthropicChatStreamOutput,
+ ChatStreamOutput,
+ ChatStreamUsage,
+ ResponsesChatStreamOutput,
+)
+from .tool_calls import (
+ CompletedOpenAIToolCall,
+ OpenAIToolCallAssembler,
+ OpenAIToolCallCollector,
+ iter_heuristic_tool_use_events,
+ tool_call_extra_content,
+)
+from .usage import (
+ clone_without_stream_usage,
+ is_stream_usage_rejection,
+ nested_usage_int,
+ request_stream_usage,
+ usage_int,
+)
+
+OpenAIAsyncCredentialProvider = Callable[[], Awaitable[str]]
+_ExtraReasoningEvents = Callable[[Any, ChatStreamOutput], Iterator[str]]
+_ChatOutputFactory = Callable[[], ChatStreamOutput]
+
+
+@dataclass(frozen=True, slots=True)
+class _CollectedRecoveryOutput:
+ text: str
+ thinking: str
+ tool_calls: tuple[CompletedOpenAIToolCall, ...]
+ request_body: JsonObject
+
+
+def _iter_visible_text_events(
+ output: ChatStreamOutput,
+ text: str,
+) -> Iterator[str]:
+ yield from output.ensure_text_block()
+ yield output.emit_text_delta(text)
+
+
+def _iter_text_parser_events(
+ output: ChatStreamOutput,
+ parser: HeuristicToolParser,
+ text: str,
+ *,
+ tool_names: OpenAIToolNameCodec,
+) -> Iterator[str]:
+ """Route visible text through the established heuristic tool parser."""
+ filtered_text, detected_tools = parser.feed(text)
+ if filtered_text:
+ yield from _iter_visible_text_events(output, filtered_text)
+ for tool_use in detected_tools:
+ yield from iter_heuristic_tool_use_events(
+ output,
+ tool_use,
+ tool_names=tool_names,
+ )
+
+
+def _iter_text_tool_use_events(
+ output: ChatStreamOutput,
+ tool_uses: tuple[dict[str, Any], ...] | list[dict[str, Any]],
+ *,
+ tool_names: OpenAIToolNameCodec,
+) -> Iterator[str]:
+ for tool_use in tool_uses:
+ yield from iter_heuristic_tool_use_events(
+ output,
+ tool_use,
+ tool_names=tool_names,
+ )
+
+
+@dataclass(frozen=True, slots=True)
+class _OpenAIChatCompletion:
+ finish_reason: Any
+ output_tokens: int
+ input_tokens: int
+ provider_input_tokens: int | None
+
+
+class _OpenAIChatFailureOutcome(StrEnum):
+ RETRY = "retry"
+ COMPLETE = "complete"
+ RAISE = "raise"
+
+
+@dataclass(frozen=True, slots=True)
+class _OpenAIChatFailureResolution:
+ outcome: _OpenAIChatFailureOutcome
+ events: tuple[str, ...] = ()
+ failure: ExecutionFailure | None = None
+
+
+def _reserved_anthropic_tool_ids(request: MessagesRequest) -> frozenset[str]:
+ """Return prior tool-use IDs that generated output must not reuse."""
+ return frozenset(
+ block.id
+ for message in request.messages
+ if isinstance(message.content, list)
+ for block in message.content
+ if isinstance(block, ContentBlockToolUse) and block.id.strip()
+ )
+
+
+class _OpenAIChatStreamAssembler:
+ """Own one discardable OpenAI-chat replay epoch."""
+
+ def __init__(
+ self,
+ *,
+ output: ChatStreamOutput,
+ profile: OpenAIChatProfile,
+ provider_name: str,
+ output_reasoning: bool,
+ tool_names: OpenAIToolNameCodec,
+ tool_schemas: dict[str, ToolSchema],
+ tool_choice_enabled: bool,
+ tool_calls: OpenAIToolCallAssembler,
+ extra_reasoning_events: _ExtraReasoningEvents,
+ ) -> None:
+ self._output = output
+ self._profile = profile
+ self._provider_name = provider_name
+ self._output_reasoning = output_reasoning
+ self._tool_names = tool_names
+ self._tool_schemas = tool_schemas
+ self._tool_calls = tool_calls
+ self._extra_reasoning_events = extra_reasoning_events
+ self._think_parser = ThinkTagParser()
+ self._function_tag_parser = FunctionTagToolParser.from_schemas(
+ tool_names=tool_names,
+ schemas={
+ name: schema.input_schema for name, schema in tool_schemas.items()
+ },
+ enabled=tool_choice_enabled,
+ )
+ self._heuristic_parser = HeuristicToolParser()
+ self._structured_reasoning = (
+ StructuredReasoningStream()
+ if profile.structured_reasoning_details
+ else None
+ )
+ if self._structured_reasoning is not None:
+ self._output.reasoning_replay_events = self._structured_reasoning.flush
+ self._finish_reason: Any = None
+ self._usage_info: Any = None
+ self._native_reasoning_seen = False
+ self._tool_argument_aliases: dict[str, dict[str, str]] = {}
+ self._tool_argument_alias_buffers: dict[int, str] = {}
+ self._tool_name_buffers: dict[int, str] = {}
+ self._started = False
+ self._aliases_bound = False
+ self._upstream_finished = False
+ self._completion: _OpenAIChatCompletion | None = None
+ self._completed = False
+
+ @property
+ def output(self) -> ChatStreamOutput:
+ return self._output
+
+ @property
+ def usage_info(self) -> Any:
+ return self._usage_info
+
+ @property
+ def completion(self) -> _OpenAIChatCompletion:
+ if self._completion is None:
+ raise RuntimeError("stream completion has not been prepared")
+ return self._completion
+
+ @property
+ def generated_output(self) -> bool:
+ return self._output.committed_output
+
+ @property
+ def complete_tool_salvageable(self) -> bool:
+ return (
+ self.generated_output
+ and self._output.has_emitted_tool_block()
+ and self._output.can_salvage_tool_use(self._tool_schemas)
+ )
+
+ @property
+ def tool_argument_alias_buffers(self) -> Mapping[int, str]:
+ return self._tool_argument_alias_buffers
+
+ def recovered_tool_call_events(
+ self, tool_call: CompletedOpenAIToolCall
+ ) -> Iterator[str]:
+ """Emit one buffered recovery call through this attempt's ID scope."""
+ yield from self._tool_calls.process_tool_call(tool_call, self._output)
+
+ def start_events(self) -> Iterator[str]:
+ if self._started:
+ return
+ self._started = True
+ yield from self._output.start_events()
+
+ def bind_tool_argument_aliases(self, aliases: dict[str, dict[str, str]]) -> None:
+ if self._aliases_bound:
+ raise RuntimeError("tool argument aliases already bound")
+ self._aliases_bound = True
+ self._tool_argument_aliases = aliases
+
+ def feed(self, chunk: Any) -> Iterator[str]:
+ if not self._started or self._upstream_finished:
+ raise RuntimeError("stream assembler is not accepting chunks")
+
+ chunk_usage = getattr(chunk, "usage", None)
+ if chunk_usage is not None:
+ self._usage_info = chunk_usage
+
+ if not chunk.choices:
+ return
+
+ if (
+ self._output.replay_origin is not None
+ and isinstance(getattr(chunk, "model", None), str)
+ and chunk.model
+ ):
+ self._output.replay_origin = replace(
+ self._output.replay_origin, model=chunk.model
+ )
+ choice = chunk.choices[0]
+ delta = choice.delta
+ if choice.finish_reason:
+ self._finish_reason = choice.finish_reason
+ if delta is None:
+ return
+
+ if choice.finish_reason:
+ self._finish_reason = choice.finish_reason
+ logger.debug(
+ "{} finish_reason: {}",
+ self._provider_name,
+ self._finish_reason,
+ )
+
+ reasoning = self._profile.reasoning_delta(delta)
+ if self._output_reasoning:
+ if self._structured_reasoning is not None:
+ yield from self._structured_reasoning.events(
+ delta,
+ self._output,
+ native_reasoning=reasoning,
+ )
+ elif reasoning is not None and (
+ reasoning or not self._native_reasoning_seen
+ ):
+ # Preserve initial empty reasoning for replay; later empty fields
+ # are placeholders and must not interrupt text or tool output.
+ self._native_reasoning_seen = True
+ yield from self._output.ensure_reasoning_block()
+ if reasoning:
+ yield self._output.emit_reasoning_delta(reasoning)
+
+ yield from self._extra_reasoning_events(delta, self._output)
+
+ native_tool_calls = delta.tool_calls
+ if native_tool_calls:
+ released_text = self._function_tag_parser.disable()
+ if released_text:
+ yield from _iter_visible_text_events(self._output, released_text)
+
+ if delta.content:
+ for part in self._think_parser.feed(delta.content):
+ if part.type == ContentType.THINKING:
+ if not self._output_reasoning:
+ continue
+ yield from self._output.ensure_reasoning_block()
+ yield self._output.emit_reasoning_delta(part.content)
+ else:
+ safe_text = self._function_tag_parser.feed(part.content)
+ if safe_text:
+ yield from _iter_text_parser_events(
+ self._output,
+ self._heuristic_parser,
+ safe_text,
+ tool_names=self._tool_names,
+ )
+
+ if native_tool_calls:
+ yield from self._output.close_content_blocks()
+ for tool_call in native_tool_calls:
+ extra_content = tool_call_extra_content(tool_call)
+ tool_call_info = {
+ "index": tool_call.index,
+ "id": tool_call.id,
+ "function": {
+ "name": tool_call.function.name,
+ "arguments": tool_call.function.arguments,
+ },
+ }
+ if extra_content:
+ tool_call_info["extra_content"] = extra_content
+ yield from self._tool_calls.process_tool_call(
+ tool_call_info,
+ self._output,
+ tool_names=self._tool_names,
+ tool_name_buffers=self._tool_name_buffers,
+ tool_argument_aliases=self._tool_argument_aliases,
+ tool_argument_alias_buffers=self._tool_argument_alias_buffers,
+ )
+
+ def finish_upstream(self) -> Iterator[str]:
+ if self._upstream_finished:
+ return
+ if self._finish_reason is None:
+ raise TruncatedProviderStreamError(
+ "Provider stream ended without finish_reason."
+ )
+ if is_context_window_finish_reason(self._finish_reason):
+ raise context_window_exceeded_provider_failure()
+ if any(
+ not self._tool_names.is_unchanged_name(name)
+ for name in self._tool_name_buffers.values()
+ ):
+ raise TruncatedProviderStreamError(
+ "Provider stream ended with an incomplete tool name."
+ )
+
+ remaining = self._think_parser.flush()
+ if remaining:
+ if remaining.type == ContentType.THINKING:
+ if self._output_reasoning:
+ yield from self._output.ensure_reasoning_block()
+ yield self._output.emit_reasoning_delta(remaining.content)
+ else:
+ safe_text = self._function_tag_parser.feed(remaining.content)
+ if safe_text:
+ yield from _iter_text_parser_events(
+ self._output,
+ self._heuristic_parser,
+ safe_text,
+ tool_names=self._tool_names,
+ )
+
+ fallback_text, function_tag_tools = self._function_tag_parser.finish()
+ if fallback_text:
+ yield from _iter_visible_text_events(self._output, fallback_text)
+ yield from _iter_text_tool_use_events(
+ self._output,
+ function_tag_tools,
+ tool_names=self._tool_names,
+ )
+ yield from _iter_text_tool_use_events(
+ self._output,
+ self._heuristic_parser.flush(),
+ tool_names=self._tool_names,
+ )
+ yield from self._output.flush_reasoning_replay()
+ self._upstream_finished = True
+
+ def prepare_completion(self) -> Iterator[str]:
+ if not self._upstream_finished or self._completion is not None:
+ raise RuntimeError("stream completion cannot be prepared")
+
+ yield from self._tool_calls.flush_tool_name_buffers(
+ self._output,
+ tool_names=self._tool_names,
+ tool_name_buffers=self._tool_name_buffers,
+ tool_argument_aliases=self._tool_argument_aliases,
+ tool_argument_alias_buffers=self._tool_argument_alias_buffers,
+ )
+
+ has_emitted_tool = self._output.has_emitted_tool_block()
+ has_content_blocks = self._output.has_content_block()
+ if not has_content_blocks or (
+ not has_emitted_tool
+ and not self._output.accumulated_text.strip()
+ and self._output.accumulated_reasoning.strip()
+ ):
+ yield from self._output.ensure_text_block()
+ yield self._output.emit_text_delta(" ")
+
+ yield from self._tool_calls.flush_tool_argument_alias_buffers(
+ self._output,
+ self._tool_argument_aliases,
+ self._tool_argument_alias_buffers,
+ )
+ yield from self._tool_calls.flush_task_arg_buffers(self._output)
+ yield from self._output.close_all_blocks()
+
+ completion = usage_int(self._usage_info, "completion_tokens")
+ output_tokens = (
+ completion
+ if isinstance(completion, int)
+ else self._output.estimate_output_tokens()
+ )
+ provider_input = usage_int(self._usage_info, "prompt_tokens")
+ input_tokens = (
+ provider_input if provider_input is not None else self._output.input_tokens
+ )
+ self._completion = _OpenAIChatCompletion(
+ finish_reason=self._finish_reason,
+ output_tokens=output_tokens,
+ input_tokens=input_tokens,
+ provider_input_tokens=provider_input,
+ )
+
+ def terminal_events(self, *, usage: ChatStreamUsage) -> Iterator[str]:
+ if self._completed:
+ return
+ completion = self.completion
+ yield from self._output.finish_success(
+ stop_reason=map_stop_reason(completion.finish_reason),
+ usage=usage,
+ )
+ self._completed = True
+
+
+class OpenAIChatTransport:
+ """Execute Chat requests while borrowing provider-owned HTTP resources."""
+
+ def __init__(
+ self,
+ *,
+ client: AsyncOpenAI,
+ admission: ProviderAdmissionController,
+ behavior: OpenAIChatBehavior,
+ read_timeout_s: float,
+ log_raw_sse_events: bool,
+ log_api_error_tracebacks: bool,
+ endpoint_transport: httpx2.AsyncBaseTransport | None = None,
+ ) -> None:
+ self._client = client
+ self._admission = admission
+ self._behavior = behavior
+ self._profile = behavior.profile
+ self._provider_name = self._profile.provider_name
+ self._read_timeout_s = read_timeout_s
+ self._log_raw_sse_events = log_raw_sse_events
+ self._log_api_error_tracebacks = log_api_error_tracebacks
+ self._endpoint_transport = endpoint_transport
+ self._model_output_caps: dict[str, int] = {}
+
+ def _log_stream_transport_error(
+ self,
+ tag: str,
+ req_tag: str,
+ error: Exception,
+ *,
+ request_id: str | None = None,
+ ) -> None:
+ """Log streaming transport failures (metadata-only unless verbose is enabled)."""
+ response = getattr(error, "response", None)
+ http_status = (
+ getattr(response, "status_code", None) if response is not None else None
+ )
+ cause_types = exception_cause_types(error)
+ trace_event(
+ stage="provider",
+ event="provider.response.transport_error",
+ source="provider",
+ provider=tag,
+ request_id=request_id,
+ exc_type=type(error).__name__,
+ http_status=http_status,
+ cause_types=cause_types,
+ )
+
+ if self._log_api_error_tracebacks:
+ logger.error(
+ "{}_ERROR:{} exc_type={}\n{}",
+ tag,
+ req_tag,
+ type(error).__name__,
+ redacted_exception_traceback(error),
+ )
+ return
+ logger.error(
+ "{}_ERROR:{} exc_type={} http_status={} cause_types={}",
+ tag,
+ req_tag,
+ type(error).__name__,
+ http_status,
+ ",".join(cause_types) if cause_types else None,
+ )
+
+ def _build_request_body(
+ self,
+ request: MessagesRequest,
+ *,
+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
+ model_info: ProviderModelInfo | None = None,
+ ) -> dict[str, Any]:
+ """Build a provider request from the immutable profile."""
+ request, reasoning = self._prepare_messages_reasoning(
+ request, reasoning, model_info
+ )
+ return self._behavior.build_messages_body(request, reasoning=reasoning)
+
+ def _prepare_messages_reasoning(
+ self,
+ request: MessagesRequest,
+ reasoning: ReasoningPolicy,
+ model_info: ProviderModelInfo | None,
+ ) -> tuple[MessagesRequest, ReasoningPolicy]:
+ return prepare_messages_reasoning(
+ request,
+ reasoning,
+ model_info=model_info,
+ can_disable=bool(self._behavior.reasoning_off_fields),
+ normal_max_tokens=self._behavior.normal_max_tokens,
+ )
+
+ def _build_responses_request_body(
+ self,
+ request: OpenAIResponsesRequest,
+ *,
+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
+ ) -> ResponsesChatRequest:
+ """Build a Chat body directly from Responses ingress."""
+ validate_history(request.model_dump(mode="json"))
+ try:
+ translated = build_responses_chat_request(
+ request,
+ reasoning_replay=self._profile.request_policy.reasoning_replay,
+ structured_reasoning_details=(
+ self._profile.structured_reasoning_details
+ ),
+ )
+ except ResponsesConversionError as exc:
+ raise InvalidRequestError(str(exc)) from exc
+ body = translated.body
+ apply_openai_chat_body_policy(body, self._profile.request_policy)
+ self._profile.apply_reasoning_to_body(body, reasoning)
+ body = self._behavior.finalize_chat_body(body, reasoning=reasoning)
+ encode_openai_chat_tool_names(body, translated.tool_names)
+ return ResponsesChatRequest(
+ body=body,
+ tool_names=translated.tool_names,
+ tool_schemas=translated.tool_schemas,
+ reserved_tool_ids=translated.reserved_tool_ids,
+ tool_adapter=translated.tool_adapter,
+ )
+
+ def preflight_messages(
+ self,
+ request: MessagesRequest,
+ *,
+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
+ model_info: ProviderModelInfo | None = None,
+ ) -> None:
+ """Validate OpenAI-chat request conversion before streaming."""
+ self._build_request_body(request, reasoning=reasoning, model_info=model_info)
+
+ def preflight_responses(
+ self,
+ request: OpenAIResponsesRequest,
+ *,
+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
+ ) -> None:
+ """Validate direct Responses-to-Chat conversion before streaming."""
+ self._build_responses_request_body(request, reasoning=reasoning)
+
+ async def _create_stream(
+ self,
+ body: dict,
+ execution: ProviderExecution,
+ operation_kind: ProviderOperationKind,
+ *,
+ used_retry_kinds: set[str] | None = None,
+ endpoint: RequestEndpoint | None = None,
+ extra_headers: Mapping[str, str] | None = None,
+ reasoning_correction: ReasoningCorrection | None = None,
+ ) -> tuple[Any, dict, ProviderAttempt, dict]:
+ """Create a streaming chat completion with bounded request fallbacks."""
+ body = self._apply_learned_output_cap(body)
+ if used_retry_kinds is None:
+ used_retry_kinds = set()
+
+ while execution.can_attempt:
+ attempt = await execution.open_attempt(operation_kind)
+ stream: Any | None = None
+ retain_attempt = False
+ create_body = body
+ try:
+ create_body = self._behavior.prepare_create_body(body)
+ client = (
+ await endpoint.openai_client(self._client)
+ if endpoint is not None
+ else self._client
+ )
+ if extra_headers or endpoint is not None:
+ create_body = create_body.copy()
+ create_body["extra_headers"] = {
+ **(create_body.get("extra_headers") or {}),
+ **(extra_headers or {}),
+ **(endpoint.openai_headers() if endpoint is not None else {}),
+ }
+ origin = replay_origin(
+ self._provider_name,
+ "chat",
+ str(body["model"]),
+ client=client,
+ endpoint=endpoint.snapshot if endpoint is not None else None,
+ )
+ create_body = cast(
+ dict[str, Any],
+ prepare_history(
+ create_body,
+ origin,
+ scope=self._behavior.history_scope(body),
+ reasoning_field=self._profile.request_policy.reasoning_replay.value,
+ structured_details=self._profile.structured_reasoning_details,
+ ),
+ )
+ stream = await client.chat.completions.create(
+ **create_body,
+ stream=True,
+ )
+ stream = self._behavior.normalize_stream(stream, body)
+ retain_attempt = True
+ return stream, body, attempt, create_body
+ except asyncio.CancelledError:
+ raise
+ except Exception as error:
+ if endpoint is not None and await endpoint.retry_authentication(
+ error, attempt, execution
+ ):
+ continue
+ retry_body = self._next_create_retry_body(
+ error,
+ body,
+ used_retry_kinds,
+ reasoning_correction=reasoning_correction,
+ sent_body=create_body,
+ )
+ if retry_body is not None:
+ correction = await attempt.correct(error)
+ if correction is ProviderCorrectionAction.RETRY:
+ body = self._apply_learned_output_cap(retry_body)
+ continue
+ raise
+ decision = await attempt.fail(
+ error,
+ provider_failure_override=self._behavior.failure_override,
+ )
+ if not decision.retry_allowed:
+ raise
+ finally:
+ if not retain_attempt:
+ if stream is not None:
+ await close_provider_stream(
+ stream,
+ active_error=sys.exception(),
+ provider_name=self._provider_name,
+ request_id=execution.request_id,
+ )
+ await attempt.aclose()
+
+ if execution.last_failure is not None:
+ raise execution.last_failure
+ raise RuntimeError("provider execution ended without a final error")
+
+ def _next_create_retry_body(
+ self,
+ error: Exception,
+ body: dict,
+ used_retry_kinds: set[str],
+ *,
+ reasoning_correction: ReasoningCorrection | None = None,
+ sent_body: Mapping[str, Any] | None = None,
+ ) -> dict | None:
+ corrected_history = history_retry_body(
+ error, sent_body if sent_body is not None else body, "chat"
+ )
+ if corrected_history is not None:
+ return corrected_history
+ if reasoning_correction is not None and "reasoning" not in used_retry_kinds:
+ retry_body = reasoning_correction.retry_body(
+ error, body, sent_body=sent_body
+ )
+ if retry_body is not None:
+ used_retry_kinds.add("reasoning")
+ return retry_body
+ retry_body = self._retry_body_for_output_cap(error, body)
+ if retry_body is not None:
+ return retry_body
+
+ if "stream_usage" not in used_retry_kinds and is_stream_usage_rejection(error):
+ retry_body = clone_without_stream_usage(body)
+ if retry_body is not None:
+ used_retry_kinds.add("stream_usage")
+ logger.warning(
+ "{}_STREAM: retrying without stream_options.include_usage "
+ "after upstream rejection",
+ self._provider_name,
+ )
+ return retry_body
+
+ if "provider_specific" not in used_retry_kinds:
+ retry_body = self._behavior.retry_request_body(
+ error, dict(sent_body) if sent_body is not None else body
+ )
+ if retry_body is not None:
+ used_retry_kinds.add("provider_specific")
+ return retry_body
+
+ return self._behavior.retry_after_standard_corrections(
+ error, body, used_retry_kinds
+ )
+
+ def _apply_learned_output_cap(self, body: dict) -> dict:
+ """Clamp output tokens to a previously learned cap for this model."""
+ model = body.get("model")
+ if not isinstance(model, str):
+ return body
+ cap = self._model_output_caps.get(model)
+ if cap is None:
+ return body
+ clamped = clamp_output_tokens(body, cap)
+ return clamped if clamped is not None else body
+
+ def _retry_body_for_output_cap(self, error: Exception, body: dict) -> dict | None:
+ """Learn an upstream output-token cap from a 400 and clamp for one retry."""
+ cap = parse_output_token_cap(error)
+ if cap is None:
+ return None
+ model = body.get("model")
+ if isinstance(model, str):
+ previous = self._model_output_caps.get(model)
+ cap = cap if previous is None else min(previous, cap)
+ self._model_output_caps[model] = cap
+ clamped = clamp_output_tokens(body, cap)
+ if clamped is None:
+ return None
+ logger.warning(
+ "{}_STREAM: clamping output tokens to {} after upstream cap rejection",
+ self._provider_name,
+ cap,
+ )
+ return clamped
+
+ def stream_messages(
+ self,
+ request: MessagesRequest,
+ input_tokens: int = 0,
+ *,
+ request_id: str | None = None,
+ response_model: str | None = None,
+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
+ model_info: ProviderModelInfo | None = None,
+ endpoint_context: EndpointContext | None = None,
+ extra_headers: Mapping[str, str] | None = None,
+ ) -> AsyncIterator[str]:
+ """Stream response in Anthropic SSE format."""
+ prepared_request, wire_reasoning = self._prepare_messages_reasoning(
+ request, reasoning, model_info
+ )
+ body = self._build_request_body(prepared_request, reasoning=wire_reasoning)
+ off_fields = self._behavior.reasoning_off_fields
+ correction = (
+ ReasoningCorrection(
+ off_fields,
+ self._profile.request_policy.max_tokens_field,
+ self._behavior.normal_max_tokens,
+ provider_rejection=self._behavior.reasoning_disable_rejected,
+ )
+ if reasoning.control is ReasoningControl.PREFER_OFF
+ and wire_reasoning.control is ReasoningControl.OFF
+ and off_fields
+ else None
+ )
+ tool_names = OpenAIToolNameCodec.from_request(request)
+ message_id = f"msg_{uuid.uuid4()}"
+ runner = _OpenAIChatStreamRunner(
+ self,
+ body=body,
+ tool_names=tool_names,
+ tool_schemas=tool_schemas_by_name(request),
+ reserved_tool_ids=_reserved_anthropic_tool_ids(request),
+ output_factory=lambda: AnthropicChatStreamOutput(
+ message_id=message_id,
+ model=request.model if response_model is None else response_model,
+ input_tokens=input_tokens,
+ log_raw_events=self._log_raw_sse_events,
+ ),
+ input_tokens=input_tokens,
+ request_id=request_id,
+ response_model=(
+ request.model if response_model is None else response_model
+ ),
+ reasoning=reasoning,
+ endpoint_context=endpoint_context,
+ extra_headers=extra_headers or {},
+ reasoning_correction=correction,
+ )
+ return runner.run()
+
+ def stream_responses(
+ self,
+ request: OpenAIResponsesRequest,
+ input_tokens: int = 0,
+ *,
+ request_id: str | None = None,
+ response_model: str | None = None,
+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
+ endpoint_context: EndpointContext | None = None,
+ extra_headers: Mapping[str, str] | None = None,
+ ) -> AsyncIterator[str]:
+ """Stream a Chat upstream directly as OpenAI Responses SSE."""
+ translated = self._build_responses_request_body(request, reasoning=reasoning)
+ public_model = request.model if response_model is None else response_model
+ tool_schemas = {
+ name: ToolSchema(name=name, input_schema=schema)
+ for name, schema in translated.tool_schemas.items()
+ }
+ runner = _OpenAIChatStreamRunner(
+ self,
+ body=translated.body,
+ tool_names=translated.tool_names,
+ tool_schemas=tool_schemas,
+ reserved_tool_ids=translated.reserved_tool_ids,
+ output_factory=lambda: ResponsesChatStreamOutput(
+ translated.tool_adapter,
+ input_tokens=input_tokens,
+ response_model=public_model,
+ ),
+ input_tokens=input_tokens,
+ request_id=request_id,
+ response_model=public_model,
+ reasoning=reasoning,
+ endpoint_context=endpoint_context,
+ extra_headers=extra_headers or {},
+ )
+ return runner.run()
+
+
+class _OpenAIChatStreamRunner:
+ """Orchestrate one OpenAI-chat request and its recovery lifecycle."""
+
+ def __init__(
+ self,
+ transport: OpenAIChatTransport,
+ *,
+ body: dict[str, Any],
+ tool_names: OpenAIToolNameCodec,
+ tool_schemas: dict[str, ToolSchema],
+ reserved_tool_ids: frozenset[str],
+ output_factory: _ChatOutputFactory,
+ input_tokens: int,
+ request_id: str | None,
+ response_model: str,
+ reasoning: ReasoningPolicy,
+ endpoint_context: EndpointContext | None = None,
+ extra_headers: Mapping[str, str] | None = None,
+ reasoning_correction: ReasoningCorrection | None = None,
+ ) -> None:
+ self._transport = transport
+ self._body = body
+ self._tool_argument_aliases = transport._behavior.tool_argument_aliases(body)
+ self._tool_names = tool_names
+ self._tool_schemas = tool_schemas
+ self._reserved_tool_ids = reserved_tool_ids
+ self._output_factory = output_factory
+ self._input_tokens = input_tokens
+ self._request_id = request_id
+ self._response_model = response_model
+ self._reasoning = reasoning
+ self._reasoning_correction = reasoning_correction
+ self._extra_headers = dict(extra_headers or {})
+ self._terminal_failure: ExecutionFailure | None = None
+ self._endpoint = (
+ RequestEndpoint(endpoint_context, transport._endpoint_transport)
+ if endpoint_context is not None
+ else None
+ )
+
+ async def run(self) -> AsyncIterator[str]:
+ """Convert the upstream OpenAI-chat stream into Anthropic SSE."""
+ execution = self._transport._admission.start_execution(
+ request_id=self._request_id
+ )
+ provider_stream = self._run_execution(execution)
+ try:
+ async for event in provider_stream:
+ if self._endpoint is not None:
+ self._endpoint.commit()
+ yield event
+ except asyncio.CancelledError:
+ raise
+ except Exception as error:
+ execution.fail(error)
+ raise
+ else:
+ if self._terminal_failure is None:
+ execution.succeed()
+ else:
+ execution.fail(self._terminal_failure)
+ finally:
+ try:
+ await maybe_await_aclose(provider_stream)
+ finally:
+ try:
+ if self._endpoint is not None:
+ await self._endpoint.aclose()
+ finally:
+ execution.abandon()
+
+ async def _run_execution(
+ self,
+ execution: ProviderExecution,
+ ) -> AsyncIterator[str]:
+ """Run one provider execution while retaining transport-owned state."""
+ tag = self._transport._provider_name
+ req_tag = f" request_id={self._request_id}" if self._request_id else ""
+ recovery = RecoveryController()
+
+ def hold_event(event: str) -> Iterator[str]:
+ yield from recovery.push(event)
+
+ body = self._body
+ request_stream_usage(body)
+ output_reasoning = self._reasoning.output_enabled
+ used_retry_kinds: set[str] = set()
+ trace_event(
+ stage="provider",
+ event="provider.request.sent",
+ source="provider",
+ provider=tag,
+ request_id=self._request_id,
+ execution_id=execution.execution_id,
+ gateway_model=self._response_model,
+ downstream_model=body.get("model"),
+ message_count=len(body.get("messages", [])),
+ tool_count=len(body.get("tools", [])),
+ body=provider_chat_body_snapshot(body),
+ )
+
+ while True:
+ assembler = self._new_stream_assembler(output_reasoning=output_reasoning)
+ scope: ProviderAttemptScope | None = None
+ try:
+ stream, body, attempt, sent_body = await self._transport._create_stream(
+ body,
+ execution,
+ ProviderOperationKind.GENERATION,
+ used_retry_kinds=used_retry_kinds,
+ endpoint=self._endpoint,
+ extra_headers=self._extra_headers,
+ reasoning_correction=self._reasoning_correction,
+ )
+ scope = ProviderAttemptScope(
+ attempt,
+ provider_name=tag,
+ request_id=self._request_id,
+ )
+ stream = scope.retain(stream)
+ assembler.output.replay_origin = replay_origin(
+ tag,
+ "chat",
+ str(body["model"]),
+ client=self._transport._client,
+ endpoint=self._endpoint.snapshot
+ if self._endpoint is not None
+ else None,
+ )
+ assembler.bind_tool_argument_aliases(self._tool_argument_aliases)
+ async for chunk in stream:
+ if not scope.attempt.accepted:
+ await scope.attempt.accept()
+ for event in assembler.start_events():
+ for out_event in hold_event(event):
+ yield out_event
+ for event in assembler.feed(chunk):
+ for out_event in hold_event(event):
+ yield out_event
+
+ for event in assembler.finish_upstream():
+ for out_event in hold_event(event):
+ yield out_event
+ break
+
+ except asyncio.CancelledError, GeneratorExit:
+ raise
+ except Exception as error:
+ if scope is not None and not recovery.committed:
+ corrected_history = history_retry_body(error, sent_body, "chat")
+ if corrected_history is not None:
+ retry = (
+ execution.can_attempt
+ if scope.attempt.accepted
+ else await scope.attempt.correct(error)
+ is ProviderCorrectionAction.RETRY
+ )
+ if retry:
+ body = corrected_history
+ recovery.discard()
+ continue
+ if (
+ scope is not None
+ and not recovery.committed
+ and self._reasoning_correction is not None
+ and "reasoning" not in used_retry_kinds
+ ):
+ corrected_body = self._reasoning_correction.retry_body(
+ error, body, sent_body=sent_body
+ )
+ if corrected_body is not None:
+ used_retry_kinds.add("reasoning")
+ retry = (
+ execution.can_attempt
+ if scope.attempt.accepted
+ else await scope.attempt.correct(error)
+ is ProviderCorrectionAction.RETRY
+ )
+ if retry:
+ body = self._transport._apply_learned_output_cap(
+ corrected_body
+ )
+ recovery.discard()
+ continue
+ resolution = await self._resolve_attempt_failure(
+ error=error,
+ scope=scope,
+ assembler=assembler,
+ body=body,
+ execution=execution,
+ recovery=recovery,
+ req_tag=req_tag,
+ )
+ if resolution.outcome is _OpenAIChatFailureOutcome.RETRY:
+ continue
+ for event in resolution.events:
+ yield event
+ if resolution.outcome is _OpenAIChatFailureOutcome.COMPLETE:
+ self._terminal_failure = resolution.failure
+ return
+ if resolution.failure is None:
+ raise AssertionError(
+ "raise resolution requires a failure"
+ ) from error
+ raise resolution.failure from error
+ finally:
+ if scope is not None:
+ await scope.aclose(active_error=sys.exception())
+
+ for event in assembler.prepare_completion():
+ for out_event in hold_event(event):
+ yield out_event
+ completion = assembler.completion
+ if completion.provider_input_tokens is not None:
+ logger.debug(
+ "TOKEN_ESTIMATE: our={} provider={} diff={:+d}",
+ self._input_tokens,
+ completion.provider_input_tokens,
+ completion.provider_input_tokens - self._input_tokens,
+ )
+ trace_event(
+ stage="provider",
+ event="provider.response.completed",
+ source="provider",
+ provider=tag,
+ request_id=self._request_id,
+ finish_reason=(
+ None
+ if completion.finish_reason is None
+ else str(completion.finish_reason)
+ ),
+ output_tokens=completion.output_tokens,
+ prompt_tokens=completion.input_tokens,
+ prompt_tokens_estimate=self._input_tokens,
+ )
+ usage = ChatStreamUsage(
+ input_tokens=completion.input_tokens,
+ output_tokens=completion.output_tokens,
+ cached_tokens=self._transport._behavior.cached_input_tokens(
+ assembler.usage_info
+ )
+ or 0,
+ cache_write_tokens=self._transport._behavior.cache_write_input_tokens(
+ assembler.usage_info
+ ),
+ reasoning_tokens=(
+ nested_usage_int(
+ assembler.usage_info,
+ "completion_tokens_details",
+ "reasoning_tokens",
+ )
+ or 0
+ ),
+ anthropic_fields=self._transport._behavior.anthropic_usage_fields(
+ assembler.usage_info
+ ),
+ )
+ for event in assembler.terminal_events(usage=usage):
+ for out_event in hold_event(event):
+ yield out_event
+ for event in recovery.flush():
+ yield event
+
+ async def _resolve_attempt_failure(
+ self,
+ *,
+ error: Exception,
+ scope: ProviderAttemptScope | None,
+ assembler: _OpenAIChatStreamAssembler,
+ body: dict[str, Any],
+ execution: ProviderExecution,
+ recovery: RecoveryController,
+ req_tag: str,
+ ) -> _OpenAIChatFailureResolution:
+ """Resolve one failed generation attempt without owning retry policy."""
+ if (
+ scope is not None
+ and self._endpoint is not None
+ and await self._endpoint.retry_authentication(
+ error, scope.attempt, execution
+ )
+ ):
+ recovery.discard()
+ return _OpenAIChatFailureResolution(outcome=_OpenAIChatFailureOutcome.RETRY)
+ attempt_failure = None
+ if scope is not None and not scope.attempt.accepted:
+ attempt_failure = await scope.attempt.fail(
+ error,
+ provider_failure_override=self._transport._behavior.failure_override,
+ )
+
+ retryable = (
+ attempt_failure.retryable
+ if attempt_failure is not None
+ else is_retryable_stream_error(error)
+ )
+ generated_output = assembler.generated_output
+ complete_tool_salvageable = assembler.complete_tool_salvageable
+ decision = recovery.advance_failure(
+ retryable=retryable,
+ stream_opened=scope is not None,
+ generated_output=generated_output,
+ complete_tool_salvageable=complete_tool_salvageable,
+ attempts_remaining=execution.attempts_remaining,
+ )
+ tag = self._transport._provider_name
+ if decision.action == RecoveryFailureAction.EARLY_RETRY:
+ trace_event(
+ stage="provider",
+ event="provider.recovery.early_retry",
+ source="provider",
+ provider=tag,
+ request_id=self._request_id,
+ attempts_started=execution.attempts_started,
+ max_attempts=execution.max_attempts,
+ retryable=True,
+ )
+ return _OpenAIChatFailureResolution(outcome=_OpenAIChatFailureOutcome.RETRY)
+
+ if decision.action == RecoveryFailureAction.MIDSTREAM_RECOVERY:
+ if scope is not None:
+ await scope.aclose(active_error=error)
+ try:
+ recovery_events = await self._recovery_events(
+ body=body,
+ assembler=assembler,
+ error=error,
+ tool_argument_alias_buffers=(assembler.tool_argument_alias_buffers),
+ output_reasoning=self._reasoning.output_enabled,
+ execution=execution,
+ )
+ except Exception as recovery_error:
+ trace_event(
+ stage="provider",
+ event="provider.recovery.failed",
+ source="provider",
+ provider=tag,
+ request_id=self._request_id,
+ exc_type=type(recovery_error).__name__,
+ )
+ recovery_failure = classify_provider_failure(
+ underlying_provider_error(recovery_error),
+ provider_name=tag,
+ read_timeout_s=self._transport._read_timeout_s,
+ request_id=self._request_id,
+ provider_failure_override=(
+ self._transport._behavior.failure_override
+ ),
+ )
+ if recovery_failure.kind is FailureKind.CONTEXT_WINDOW_EXCEEDED:
+ error = recovery_failure
+ recovery_events = None
+ if recovery_events is not None:
+ return _OpenAIChatFailureResolution(
+ outcome=_OpenAIChatFailureOutcome.COMPLETE,
+ events=(
+ *recovery.flush_uncommitted(decision),
+ *recovery_events,
+ ),
+ )
+
+ reported_error = underlying_provider_error(error)
+ self._transport._log_stream_transport_error(
+ tag,
+ req_tag,
+ reported_error,
+ request_id=self._request_id,
+ )
+ failure = classify_provider_failure(
+ reported_error,
+ provider_name=tag,
+ read_timeout_s=self._transport._read_timeout_s,
+ request_id=self._request_id,
+ provider_failure_override=self._transport._behavior.failure_override,
+ )
+ error_trace: dict[str, Any] = {
+ "stage": "provider",
+ "event": "provider.response.error",
+ "source": "provider",
+ "provider": tag,
+ "request_id": self._request_id,
+ "exc_type": type(reported_error).__name__,
+ "failure_kind": failure.kind.value,
+ "status_code": failure.status_code,
+ "provider_retryable": failure.retryable,
+ }
+ if self._transport._log_api_error_tracebacks:
+ error_trace["error_message"] = failure.message
+ trace_event(**error_trace)
+
+ failure_events: list[str] = []
+ if (
+ not decision.committed
+ and decision.has_buffered
+ and complete_tool_salvageable
+ ):
+ failure_events.extend(recovery.flush())
+ elif not decision.committed:
+ recovery.discard()
+ return _OpenAIChatFailureResolution(
+ outcome=_OpenAIChatFailureOutcome.RAISE,
+ failure=failure,
+ )
+ output = assembler.output
+ if output.consumes_terminal_failure:
+ failure_events.extend(output.finish_failure(failure))
+ return _OpenAIChatFailureResolution(
+ outcome=_OpenAIChatFailureOutcome.COMPLETE,
+ events=tuple(failure_events),
+ failure=failure,
+ )
+ failure_events.extend(output.close_unclosed_blocks())
+ return _OpenAIChatFailureResolution(
+ outcome=_OpenAIChatFailureOutcome.RAISE,
+ events=tuple(failure_events),
+ failure=failure,
+ )
+
+ async def _collect_recovery_output(
+ self,
+ body: dict[str, Any],
+ *,
+ include_reasoning: bool,
+ execution: ProviderExecution,
+ operation_kind: ProviderOperationKind,
+ used_retry_kinds: set[str] | None = None,
+ ) -> _CollectedRecoveryOutput:
+ """Collect one complete buffered continuation response."""
+ if used_retry_kinds is None:
+ used_retry_kinds = set()
+ last_error: Exception | None = None
+ while execution.can_attempt:
+ scope: ProviderAttemptScope | None = None
+ try:
+ (
+ stream,
+ body,
+ attempt,
+ _sent_body,
+ ) = await self._transport._create_stream(
+ body,
+ execution,
+ operation_kind,
+ used_retry_kinds=used_retry_kinds,
+ endpoint=self._endpoint,
+ )
+ scope = ProviderAttemptScope(
+ attempt,
+ provider_name=self._transport._provider_name,
+ request_id=self._request_id,
+ )
+ stream = scope.retain(stream)
+ text_parts: list[str] = []
+ thinking_parts: list[str] = []
+ tool_calls = OpenAIToolCallCollector()
+ terminal_seen = False
+ async for chunk in stream:
+ if not scope.attempt.accepted:
+ await scope.attempt.accept()
+ if not getattr(chunk, "choices", None):
+ continue
+ choice = chunk.choices[0]
+ finish_reason = choice.finish_reason
+ if is_context_window_finish_reason(finish_reason):
+ raise context_window_exceeded_provider_failure()
+ if finish_reason is not None:
+ terminal_seen = True
+ delta = choice.delta
+ if delta is None:
+ continue
+ if include_reasoning:
+ reasoning = self._transport._profile.reasoning_delta(delta)
+ if reasoning:
+ thinking_parts.append(reasoning)
+ content = getattr(delta, "content", None)
+ if isinstance(content, str) and content:
+ text_parts.append(content)
+ native_tool_calls = getattr(delta, "tool_calls", None)
+ if isinstance(native_tool_calls, list | tuple):
+ for tool_call in native_tool_calls:
+ tool_calls.add(tool_call)
+
+ completed_tool_calls = tool_calls.completed_calls(
+ self._tool_schemas,
+ tool_names=self._tool_names,
+ tool_argument_aliases=self._tool_argument_aliases,
+ )
+ if tool_calls.has_calls and completed_tool_calls is None:
+ raise TruncatedProviderStreamError(
+ "Recovery stream ended with an incomplete tool call."
+ )
+ if not terminal_seen and not completed_tool_calls:
+ raise TruncatedProviderStreamError(
+ "Recovery stream ended without finish_reason."
+ )
+ return _CollectedRecoveryOutput(
+ text="".join(text_parts),
+ thinking="".join(thinking_parts),
+ tool_calls=completed_tool_calls or (),
+ request_body=body,
+ )
+ except Exception as error:
+ last_error = error
+ retryable = is_retryable_stream_error(error)
+ if scope is not None and not scope.attempt.accepted:
+ failure = await scope.attempt.fail(
+ error,
+ provider_failure_override=(
+ self._transport._behavior.failure_override
+ ),
+ )
+ retryable = failure.retryable
+ if not retryable or not execution.can_attempt:
+ raise
+ trace_event(
+ stage="provider",
+ event="provider.recovery.retry",
+ source="provider",
+ provider=self._transport._provider_name,
+ recovery_kind="openai_text",
+ attempts_started=execution.attempts_started,
+ max_attempts=execution.max_attempts,
+ exc_type=type(error).__name__,
+ )
+ finally:
+ if scope is not None:
+ await scope.aclose(active_error=sys.exception())
+ if last_error is not None:
+ raise last_error
+ return _CollectedRecoveryOutput(
+ text="",
+ thinking="",
+ tool_calls=(),
+ request_body=body,
+ )
+
+ async def _recovery_events(
+ self,
+ *,
+ body: dict[str, Any],
+ assembler: _OpenAIChatStreamAssembler,
+ error: Exception,
+ tool_argument_alias_buffers: Mapping[int, str],
+ output_reasoning: bool,
+ execution: ProviderExecution,
+ ) -> list[str] | None:
+ """Build terminal recovery events when the interrupted stream permits it."""
+ output = assembler.output
+ if output.has_emitted_tool_block():
+ if not output.can_salvage_tool_use(self._tool_schemas):
+ repair_events = await self._repair_tool_args(
+ body=body,
+ output=output,
+ tool_argument_alias_buffers=tool_argument_alias_buffers,
+ execution=execution,
+ )
+ if repair_events is None:
+ return None
+ else:
+ repair_events = []
+ events = list(repair_events)
+ events.extend(
+ output.finish_success(
+ stop_reason="end_turn",
+ usage=ChatStreamUsage(
+ input_tokens=self._input_tokens,
+ output_tokens=output.estimate_output_tokens(),
+ ),
+ )
+ )
+ trace_event(
+ stage="provider",
+ event="provider.recovery.tool_salvaged",
+ source="provider",
+ provider=self._transport._provider_name,
+ request_id=self._request_id,
+ )
+ return events
+
+ partial_text = output.accumulated_text
+ partial_thinking = output.accumulated_reasoning
+ if not partial_text and not partial_thinking:
+ return None
+
+ if isinstance(error, RetryableToolProtocolError):
+ recovery_body = make_response_recovery_body(
+ body,
+ partial_text,
+ partial_thinking,
+ )
+ else:
+ recovery_body = make_text_recovery_body(
+ body,
+ partial_text,
+ partial_thinking,
+ )
+ recovered = await self._collect_recovery_output(
+ recovery_body,
+ include_reasoning=output_reasoning,
+ execution=execution,
+ operation_kind=ProviderOperationKind.CONTINUATION,
+ )
+ text_suffix = continuation_suffix(partial_text, recovered.text)
+ thinking_suffix = continuation_suffix(partial_thinking, recovered.thinking)
+ events: list[str] = []
+ if thinking_suffix:
+ events.extend(output.ensure_reasoning_block())
+ events.append(output.emit_reasoning_delta(thinking_suffix))
+ if text_suffix:
+ events.extend(output.ensure_text_block())
+ events.append(output.emit_text_delta(text_suffix))
+ if recovered.tool_calls:
+ events.extend(output.close_content_blocks())
+ for tool_call in recovered.tool_calls:
+ events.extend(assembler.recovered_tool_call_events(tool_call))
+ if not events:
+ return None
+ events.extend(
+ output.finish_success(
+ stop_reason="end_turn",
+ usage=ChatStreamUsage(
+ input_tokens=self._input_tokens,
+ output_tokens=output.estimate_output_tokens(),
+ ),
+ )
+ )
+ trace_event(
+ stage="provider",
+ event="provider.recovery.continued",
+ source="provider",
+ provider=self._transport._provider_name,
+ request_id=self._request_id,
+ )
+ return events
+
+ async def _repair_tool_args(
+ self,
+ *,
+ body: dict[str, Any],
+ output: ChatStreamOutput,
+ tool_argument_alias_buffers: Mapping[int, str],
+ execution: ProviderExecution,
+ ) -> list[str] | None:
+ schemas = self._tool_schemas
+ events: list[str] = []
+ for tool_index, state in output.started_tool_states():
+ block = output.tool_block_for_tool_index(tool_index)
+ emitted_prefix = block.content if block is not None else ""
+ repair_prefix = emitted_prefix
+ if not repair_prefix and state.name == "Task" and state.task_arg_buffer:
+ repair_prefix = state.task_arg_buffer
+ if not repair_prefix and tool_index in tool_argument_alias_buffers:
+ repair_prefix = tool_argument_alias_buffers[tool_index]
+ if (
+ parse_complete_tool_input(repair_prefix, state.name, schemas)
+ is not None
+ ):
+ if not emitted_prefix and repair_prefix:
+ events.append(output.emit_tool_delta(tool_index, repair_prefix))
+ continue
+
+ schema = schemas.get(state.name)
+ recovery_body = make_tool_repair_body(
+ body,
+ tool_name=state.name,
+ prefix=repair_prefix,
+ input_schema=schema.input_schema if schema is not None else None,
+ )
+ accepted_suffix: str | None = None
+ repair_attempt = 0
+ used_retry_kinds: set[str] = set()
+ while execution.can_attempt:
+ repair_attempt += 1
+ recovered = await self._collect_recovery_output(
+ recovery_body,
+ include_reasoning=False,
+ execution=execution,
+ operation_kind=ProviderOperationKind.TOOL_REPAIR,
+ used_retry_kinds=used_retry_kinds,
+ )
+ repair = accept_tool_json_repair(
+ repair_prefix,
+ recovered.text,
+ tool_name=state.name,
+ schemas=schemas,
+ )
+ if repair is not None:
+ accepted_suffix = repair.suffix
+ trace_event(
+ stage="provider",
+ event="provider.recovery.tool_repaired",
+ source="provider",
+ provider=self._transport._provider_name,
+ tool_name=state.name,
+ attempt=repair_attempt,
+ )
+ break
+ recovery_body = recovered.request_body
+ if accepted_suffix is None:
+ return None
+ to_emit = (
+ accepted_suffix if emitted_prefix else repair_prefix + accepted_suffix
+ )
+ if to_emit:
+ events.append(output.emit_tool_delta(tool_index, to_emit))
+ if not output.can_salvage_tool_use(schemas):
+ return None
+ return events
+
+ def _new_stream_assembler(
+ self, *, output_reasoning: bool
+ ) -> _OpenAIChatStreamAssembler:
+ def extra_reasoning_events(
+ delta: Any, output: ChatStreamOutput
+ ) -> Iterator[str]:
+ yield from self._transport._behavior.extra_reasoning_events(
+ delta,
+ output,
+ output_reasoning=output_reasoning,
+ )
+
+ return _OpenAIChatStreamAssembler(
+ output=self._output_factory(),
+ profile=self._transport._profile,
+ provider_name=self._transport._provider_name,
+ output_reasoning=output_reasoning,
+ tool_names=self._tool_names,
+ tool_schemas=self._tool_schemas,
+ tool_choice_enabled=(
+ bool(self._body.get("tools"))
+ and self._body.get("tool_choice") != "none"
+ ),
+ tool_calls=OpenAIToolCallAssembler(
+ reserved_tool_ids=self._reserved_tool_ids,
+ record_extra_content=self._transport._behavior.record_tool_call_extra_content,
+ ),
+ extra_reasoning_events=extra_reasoning_events,
+ )
diff --git a/src/free_claude_code/providers/opencode/provider.py b/src/free_claude_code/providers/opencode/provider.py
index bad27a61..82f70083 100644
--- a/src/free_claude_code/providers/opencode/provider.py
+++ b/src/free_claude_code/providers/opencode/provider.py
@@ -16,14 +16,16 @@ from free_claude_code.core.openai_responses import (
)
from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy
from free_claude_code.providers.admission import ProviderAdmissionController
-from free_claude_code.providers.base import ProviderConfig
+from free_claude_code.providers.base import BaseProvider, ProviderConfig
from free_claude_code.providers.endpoint import EndpointContext
from free_claude_code.providers.http import close_provider_stream
from free_claude_code.providers.openai_chat import (
NO_REASONING,
+ OpenAIChatBehavior,
OpenAIChatProfile,
- OpenAIChatProvider,
OpenAIChatRequestPolicy,
+ OpenAIChatTransport,
+ create_chat_client,
)
from free_claude_code.providers.openai_responses import OpenAIResponsesTransport
@@ -71,7 +73,7 @@ _PROFILES = {
}
-class OpenCodeProvider(OpenAIChatProvider):
+class OpenCodeProvider(BaseProvider):
"""Route OpenCode models through their catalog-declared OpenAI endpoint."""
def __init__(
@@ -82,12 +84,21 @@ class OpenCodeProvider(OpenAIChatProvider):
admission: ProviderAdmissionController,
catalog_client: httpx.AsyncClient | None = None,
) -> None:
- super().__init__(
+ super().__init__(config)
+ self._client = create_chat_client(
config,
- profile=profile.chat_profile,
- admission=admission,
+ base_url=profile.chat_profile.base_url(config.base_url).rstrip("/"),
+ provider_name=profile.provider_name,
default_headers={"User-Agent": "opencode"},
)
+ self._chat = OpenAIChatTransport(
+ client=self._client,
+ admission=admission,
+ behavior=OpenAIChatBehavior(profile.chat_profile),
+ read_timeout_s=config.http_read_timeout,
+ log_raw_sse_events=config.log_raw_sse_events,
+ log_api_error_tracebacks=config.log_api_error_tracebacks,
+ )
self._opencode_profile = profile
self._catalog = OpenCodeCatalog(
config,
@@ -115,7 +126,7 @@ class OpenCodeProvider(OpenAIChatProvider):
"""Close both owned clients even when one cleanup fails."""
errors: list[Exception] = []
try:
- await super().cleanup()
+ await self._client.close()
except Exception as exc:
errors.append(exc)
try:
@@ -169,7 +180,7 @@ class OpenCodeProvider(OpenAIChatProvider):
routed, reasoning=reasoning, model_info=route.model_info
)
return
- super().preflight_messages(
+ self._chat.preflight_messages(
routed, reasoning=reasoning, model_info=route.model_info
)
@@ -188,7 +199,7 @@ class OpenCodeProvider(OpenAIChatProvider):
if route.transport is OpenCodeUpstreamTransport.RESPONSES:
self._responses.preflight_responses(routed, reasoning=reasoning)
return
- super().preflight_responses(routed, reasoning=reasoning)
+ self._chat.preflight_responses(routed, reasoning=reasoning)
def stream_messages(
self,
@@ -243,17 +254,17 @@ class OpenCodeProvider(OpenAIChatProvider):
model_info=route.model_info,
)
else:
- super().preflight_messages(
+ self._chat.preflight_messages(
routed, reasoning=reasoning, model_info=route.model_info
)
- selected_stream = super().stream_messages(
+ selected_stream = self._chat.stream_messages(
routed,
input_tokens=input_tokens,
request_id=request_id,
response_model=response_model,
reasoning=reasoning,
endpoint_context=endpoint_context,
- request_headers=request_headers,
+ extra_headers=self._upstream_headers(request_headers or {}),
model_info=route.model_info,
)
async for event in selected_stream:
@@ -316,15 +327,15 @@ class OpenCodeProvider(OpenAIChatProvider):
extra_headers=self._upstream_headers(request_headers or {}),
)
else:
- super().preflight_responses(routed, reasoning=reasoning)
- selected_stream = super().stream_responses(
+ self._chat.preflight_responses(routed, reasoning=reasoning)
+ selected_stream = self._chat.stream_responses(
routed,
input_tokens=input_tokens,
request_id=request_id,
response_model=response_model,
reasoning=reasoning,
endpoint_context=endpoint_context,
- request_headers=request_headers,
+ extra_headers=self._upstream_headers(request_headers or {}),
)
async for event in selected_stream:
yield event
diff --git a/tests/api/test_api.py b/tests/api/test_api.py
index a148d61c..7ff3c71c 100644
--- a/tests/api/test_api.py
+++ b/tests/api/test_api.py
@@ -211,7 +211,7 @@ def test_create_message_ingress_error_has_request_id_without_terminal_header(
def test_create_message_rejects_unportable_image_as_invalid_request() -> None:
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
return_value=MagicMock(),
):
provider = OpenAIChatProvider(
diff --git a/tests/api/test_classifier_provider_compatibility.py b/tests/api/test_classifier_provider_compatibility.py
index 24c71d05..954b8bb7 100644
--- a/tests/api/test_classifier_provider_compatibility.py
+++ b/tests/api/test_classifier_provider_compatibility.py
@@ -130,21 +130,23 @@ async def test_openrouter_numeric_sse_rejection_uses_classifier_correction(
text=f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n",
)
- provider = OpenRouterProvider(
- make_provider_config("test", "https://provider.invalid/v1"),
- admission=immediate_admission(),
- )
- try:
- async with AsyncOpenAI(
+ with patch(
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
+ return_value=AsyncOpenAI(
api_key="test",
base_url="https://provider.invalid/v1",
max_retries=0,
http_client=httpx.AsyncClient(transport=httpx.MockTransport(upstream)),
- ) as client:
- with patch.object(provider, "_client", client):
- response = await MessagesHandler(
- Settings(), provider_resolver=lambda _: provider
- ).create(classifier_request())
+ ),
+ ):
+ provider = OpenRouterProvider(
+ make_provider_config("test", "https://provider.invalid/v1"),
+ admission=immediate_admission(),
+ )
+ try:
+ response = await MessagesHandler(
+ Settings(), provider_resolver=lambda _: provider
+ ).create(classifier_request())
assert isinstance(response, JSONResponse)
assert len(bodies) == (2 if corrects else 1)
if corrects:
diff --git a/tests/api/test_openai_responses.py b/tests/api/test_openai_responses.py
index 51e16c7d..5b116a9e 100644
--- a/tests/api/test_openai_responses.py
+++ b/tests/api/test_openai_responses.py
@@ -190,7 +190,7 @@ def test_create_response_preflight_rejection_stays_an_ordinary_http_error() -> N
def test_create_response_rejects_unportable_image_as_invalid_request() -> None:
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
return_value=MagicMock(),
):
provider = OpenAIChatProvider(
diff --git a/tests/api/test_opencode_session_headers.py b/tests/api/test_opencode_session_headers.py
index f77977da..b2f652db 100644
--- a/tests/api/test_opencode_session_headers.py
+++ b/tests/api/test_opencode_session_headers.py
@@ -70,7 +70,7 @@ async def wire_client(provider_id="opencode_zen", handler=None):
return AsyncOpenAI(**kwargs)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI", side_effect=sdk
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI", side_effect=sdk
):
provider = create_opencode_provider(
provider_id,
diff --git a/tests/contracts/test_protocol_matrix.py b/tests/contracts/test_protocol_matrix.py
index 0d1e64ef..70d75c8f 100644
--- a/tests/contracts/test_protocol_matrix.py
+++ b/tests/contracts/test_protocol_matrix.py
@@ -270,7 +270,7 @@ async def test_chat_upstream_accepts_both_ingress_protocols_directly() -> None:
base_url="https://provider.invalid/v1",
)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
return_value=client,
):
provider = OpenAIChatProvider(
@@ -411,7 +411,7 @@ async def test_image_tool_output_remains_visual_across_all_protocol_cells() -> N
base_url="https://provider.invalid/v1",
)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
return_value=chat_client,
):
chat_provider = OpenAIChatProvider(
diff --git a/tests/core/test_history_switching.py b/tests/core/test_history_switching.py
index b3391a10..3a9f091a 100644
--- a/tests/core/test_history_switching.py
+++ b/tests/core/test_history_switching.py
@@ -140,7 +140,7 @@ def test_opaque_details_stay_with_the_assistant_that_produced_them():
original = request.model_dump()
assistants = [
message
- for message in provider._build_request_body(request)["messages"]
+ for message in provider._chat._build_request_body(request)["messages"]
if message["role"] == "assistant"
]
assert "reasoning_details" not in assistants[0]
@@ -216,7 +216,9 @@ def test_deepseek_off_to_on_preserves_effort_and_all_available_history(wire):
}
)
original = deepcopy(request.model_dump())
- body = provider._build_request_body(request, reasoning=ReasoningPolicy.on())
+ body = provider._chat._build_request_body(
+ request, reasoning=ReasoningPolicy.on()
+ )
else:
request = OpenAIResponsesRequest(
model="synthetic",
@@ -238,7 +240,7 @@ def test_deepseek_off_to_on_preserves_effort_and_all_available_history(wire):
original = deepcopy(request.model_dump())
body = cast(
dict[str, Any],
- provider._build_responses_request_body(
+ provider._chat._build_responses_request_body(
request, reasoning=ReasoningPolicy.on()
).body,
)
@@ -328,7 +330,7 @@ def test_messages_interleaved_reasoning_belongs_to_the_tool_group():
],
}
)
- messages = provider._build_request_body(request)["messages"]
+ messages = provider._chat._build_request_body(request)["messages"]
assistant = next(message for message in messages if message.get("tool_calls"))
assert assistant["reasoning_content"] == "first\nsecond"
assert assistant["reasoning_details"] == [
@@ -367,7 +369,7 @@ def test_completed_native_hosted_tools_become_readable_chat_history():
],
}
)
- body = provider._build_request_body(request)
+ body = provider._chat._build_request_body(request)
rendered = json.dumps(body["messages"])
assert "[Earlier tool record]" in rendered
assert "sample" in rendered and "web_search_tool_result" in rendered
diff --git a/tests/provider_request_mocks.py b/tests/provider_request_mocks.py
index a8ae0369..261f3011 100644
--- a/tests/provider_request_mocks.py
+++ b/tests/provider_request_mocks.py
@@ -6,7 +6,7 @@ from unittest.mock import MagicMock
def make_openai_compat_stream_request(
*, model: str = "test-model", stream: bool = True
) -> MagicMock:
- """Minimal request stub matching :meth:`OpenAIChatProvider._build_request_body` needs."""
+ """Minimal request stub matching :meth:`OpenAIChatProvider._chat._build_request_body` needs."""
req = MagicMock()
req.model = model
req.stream = stream
diff --git a/tests/providers/test_agnes.py b/tests/providers/test_agnes.py
index 53e62e26..77dc384b 100644
--- a/tests/providers/test_agnes.py
+++ b/tests/providers/test_agnes.py
@@ -88,7 +88,7 @@ def test_build_request_body_preserves_common_chat_tools_and_images(
],
)
- body = agnes_provider._build_request_body(
+ body = agnes_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -117,7 +117,7 @@ def test_build_request_body_encodes_documented_thinking_control(
) -> None:
request = _request()
- body = agnes_provider._build_request_body(request, reasoning=reasoning)
+ body = agnes_provider._chat._build_request_body(request, reasoning=reasoning)
assert body["extra_body"] == {"chat_template_kwargs": {"enable_thinking": enabled}}
@@ -127,7 +127,7 @@ def test_build_request_body_omits_thinking_control_for_provider_default(
) -> None:
request = _request()
- body = agnes_provider._build_request_body(
+ body = agnes_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.provider_default(),
)
@@ -152,7 +152,7 @@ def test_build_request_body_replays_reasoning_in_content_not_undocumented_field(
]
)
- body = agnes_provider._build_request_body(
+ body = agnes_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -172,7 +172,7 @@ def test_build_request_body_rejects_caller_reasoning_override(
request = _request(extra_body={field: "caller-owned"})
with pytest.raises(InvalidRequestError, match="must not override reasoning"):
- agnes_provider._build_request_body(request, reasoning=REASONING_ON)
+ agnes_provider._chat._build_request_body(request, reasoning=REASONING_ON)
@pytest.mark.asyncio
@@ -203,7 +203,7 @@ async def test_model_catalog_uses_documented_endpoint_and_auth() -> None:
return AsyncOpenAI(*args, **kwargs)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
side_effect=build_client,
):
provider = profiled_provider(
diff --git a/tests/providers/test_azure_openai.py b/tests/providers/test_azure_openai.py
index edbda2be..2db8af7e 100644
--- a/tests/providers/test_azure_openai.py
+++ b/tests/providers/test_azure_openai.py
@@ -31,7 +31,7 @@ def _provider() -> OpenAIChatProvider:
def test_init_uses_resource_v1_url_and_api_key() -> None:
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as openai_client:
provider = _provider()
@@ -62,7 +62,7 @@ def test_request_uses_deployment_name_modern_token_field_tools_and_reasoning() -
],
)
- body = _provider()._build_request_body(
+ body = _provider()._chat._build_request_body(
request,
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -88,7 +88,7 @@ def test_reasoning_uses_azure_supported_provider_vocabulary(
policy: ReasoningPolicy,
expected: str,
) -> None:
- body = _provider()._build_request_body(
+ body = _provider()._chat._build_request_body(
make_messages_request(
AZURE_OPENAI_DEPLOYMENT,
temperature=None,
@@ -117,7 +117,7 @@ def test_reasoning_history_replays_as_portable_think_tags() -> None:
],
)
- body = _provider()._build_request_body(request)
+ body = _provider()._chat._build_request_body(request)
assistant = next(
message for message in body["messages"] if message["role"] == "assistant"
)
diff --git a/tests/providers/test_bedrock.py b/tests/providers/test_bedrock.py
index d7562ce2..4429fc90 100644
--- a/tests/providers/test_bedrock.py
+++ b/tests/providers/test_bedrock.py
@@ -47,7 +47,7 @@ def test_init_uses_bearer_key_and_normalizes_regional_openai_base(
configured: str, expected: str
) -> None:
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as openai_client:
provider = _provider(configured)
@@ -75,7 +75,7 @@ def test_request_uses_portable_chat_fields_without_invented_reasoning() -> None:
],
)
- body = _provider()._build_request_body(request)
+ body = _provider()._chat._build_request_body(request)
assert body["model"] == BEDROCK_MODEL
assert body["messages"][0] == {"role": "system", "content": "System prompt"}
@@ -116,7 +116,7 @@ def test_reasoning_history_replays_as_portable_think_tags() -> None:
],
)
- body = _provider()._build_request_body(request)
+ body = _provider()._chat._build_request_body(request)
assistant = next(
message for message in body["messages"] if message["role"] == "assistant"
)
diff --git a/tests/providers/test_cerebras.py b/tests/providers/test_cerebras.py
index a2a1cb0e..61ed2403 100644
--- a/tests/providers/test_cerebras.py
+++ b/tests/providers/test_cerebras.py
@@ -71,7 +71,7 @@ def cerebras_provider(cerebras_config):
def test_init(cerebras_config):
"""Test provider initialization."""
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = profiled_provider(
"cerebras", cerebras_config, admission=immediate_admission()
@@ -88,7 +88,9 @@ def test_default_base_url_constant():
def test_build_request_body_basic(cerebras_provider):
"""Basic request body conversion attaches system message from Claude request."""
req = make_request()
- body = cerebras_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = cerebras_provider._chat._build_request_body(
+ req, reasoning=reasoning_for(req)
+ )
assert body["model"] == "llama3.1-8b"
assert body["messages"][0]["role"] == "system"
@@ -96,7 +98,9 @@ def test_build_request_body_basic(cerebras_provider):
def test_build_request_body_replays_reasoning_as_tagged_content(cerebras_provider):
- body = cerebras_provider._build_request_body(make_reasoning_tool_history_request())
+ body = cerebras_provider._chat._build_request_body(
+ make_reasoning_tool_history_request()
+ )
assistant = next(
message for message in body["messages"] if message["role"] == "assistant"
@@ -127,7 +131,7 @@ def test_replay_is_independent_of_current_turn_reasoning_control():
),
admission=immediate_admission(),
)
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
make_reasoning_tool_history_request(), reasoning=REASONING_OFF
)
@@ -152,7 +156,9 @@ def test_build_request_body_remaps_max_tokens_preserves_message_name(cerebras_pr
"max_tokens": 42,
}
req = make_request()
- body = cerebras_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = cerebras_provider._chat._build_request_body(
+ req, reasoning=reasoning_for(req)
+ )
assert body["messages"][0].get("name") == "alice"
assert body.get("max_tokens") is None
@@ -169,7 +175,7 @@ def test_build_request_body_prefers_existing_max_completion_tokens(cerebras_prov
"max_completion_tokens": 77,
"max_tokens": 999,
}
- body = cerebras_provider._build_request_body(make_request())
+ body = cerebras_provider._chat._build_request_body(make_request())
assert body["max_completion_tokens"] == 77
assert "max_tokens" not in body
@@ -178,7 +184,9 @@ def test_build_request_body_prefers_existing_max_completion_tokens(cerebras_prov
def test_build_request_body_preserves_caller_extra_body(cerebras_provider):
req = make_request(extra_body={"clear_thinking": False})
- body = cerebras_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = cerebras_provider._chat._build_request_body(
+ req, reasoning=reasoning_for(req)
+ )
eb = body.get("extra_body")
assert isinstance(eb, dict)
diff --git a/tests/providers/test_chutes.py b/tests/providers/test_chutes.py
index 785d484c..eb8692e3 100644
--- a/tests/providers/test_chutes.py
+++ b/tests/providers/test_chutes.py
@@ -66,7 +66,7 @@ def test_preserves_upstream_reasoning_default(
}
)
- body = chutes_provider._build_request_body(request, reasoning=reasoning)
+ body = chutes_provider._chat._build_request_body(request, reasoning=reasoning)
assert "reasoning_effort" not in body
assert "reasoning" not in body
@@ -108,7 +108,7 @@ def test_does_not_replay_reasoning_but_preserves_tool_history(
}
)
- body = chutes_provider._build_request_body(
+ body = chutes_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_cline_pass.py b/tests/providers/test_cline_pass.py
index c513b73f..09da153f 100644
--- a/tests/providers/test_cline_pass.py
+++ b/tests/providers/test_cline_pass.py
@@ -58,7 +58,7 @@ def _provider_with_transport(
http_client=httpx2.AsyncClient(transport=transport),
)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
return_value=client,
):
return profiled_provider(
@@ -181,7 +181,7 @@ def test_build_request_body_preserves_nested_model_images_tools_and_results(
extra_body={"provider_option": "must-not-pass-through"},
)
- body = cline_pass_provider._build_request_body(
+ body = cline_pass_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.on(),
)
@@ -228,7 +228,7 @@ def test_build_request_body_adds_no_undocumented_reasoning_control_or_default_ca
cline_pass_provider: OpenAIChatProvider,
reasoning: ReasoningPolicy,
) -> None:
- body = cline_pass_provider._build_request_body(
+ body = cline_pass_provider._chat._build_request_body(
_request(),
reasoning=reasoning,
)
@@ -271,7 +271,7 @@ def test_build_request_body_replays_only_opaque_reasoning_details(
]
)
- body = cline_pass_provider._build_request_body(
+ body = cline_pass_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.on(),
)
diff --git a/tests/providers/test_cloudflare.py b/tests/providers/test_cloudflare.py
index 52d823ce..62eacfac 100644
--- a/tests/providers/test_cloudflare.py
+++ b/tests/providers/test_cloudflare.py
@@ -87,7 +87,7 @@ def test_init_composes_account_scoped_openai_chat_base_url(
) -> None:
with (
patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai,
patch("httpx.AsyncClient") as mock_httpx_client,
):
@@ -126,7 +126,7 @@ def test_build_request_body_preserves_literal_cf_model_id_and_controls_thinking(
}
)
- body = cloudflare_provider._build_request_body(
+ body = cloudflare_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -147,7 +147,7 @@ def test_build_request_body_disabled_thinking_sets_cloudflare_template_flag(
}
)
- body = cloudflare_provider._build_request_body(
+ body = cloudflare_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -165,7 +165,7 @@ def test_build_request_body_preserves_user_extra_body_without_overriding_thinkin
}
)
- body = cloudflare_provider._build_request_body(
+ body = cloudflare_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
diff --git a/tests/providers/test_codestral.py b/tests/providers/test_codestral.py
index 6910b0a5..ca10871c 100644
--- a/tests/providers/test_codestral.py
+++ b/tests/providers/test_codestral.py
@@ -39,7 +39,7 @@ def codestral_provider(codestral_config):
def test_init(codestral_config):
"""Test provider initialization."""
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = profiled_provider(
"mistral_codestral",
@@ -58,7 +58,7 @@ def test_default_base_url():
def test_build_request_body_basic(codestral_provider):
"""Basic request body conversion works for Codestral."""
req = make_request()
- body = codestral_provider._build_request_body(req)
+ body = codestral_provider._chat._build_request_body(req)
assert body["model"] == "devstral-small-latest"
assert body["messages"][0]["role"] == "system"
@@ -77,7 +77,7 @@ def test_build_request_body_global_disable_blocks_reasoning_mapping():
admission=immediate_admission(),
)
req = make_request()
- body = provider._build_request_body(req)
+ body = provider._chat._build_request_body(req)
roles = [m.get("role") for m in body.get("messages", [])]
assert "assistant_reasoning_content" not in roles
diff --git a/tests/providers/test_cohere.py b/tests/providers/test_cohere.py
index 040ea0c3..7de58eed 100644
--- a/tests/providers/test_cohere.py
+++ b/tests/providers/test_cohere.py
@@ -41,7 +41,7 @@ def test_default_base_url_constant():
def test_init_uses_default_base_url_and_api_key(cohere_config):
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = profiled_provider(
"cohere", cohere_config, admission=immediate_admission()
@@ -55,7 +55,7 @@ def test_init_uses_default_base_url_and_api_key(cohere_config):
def test_init_strips_trailing_slash(cohere_config):
config = replace(cohere_config, base_url=f"{COHERE_DEFAULT_BASE}/")
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = profiled_provider("cohere", config, admission=immediate_admission())
assert provider._base_url == COHERE_DEFAULT_BASE
@@ -81,7 +81,7 @@ def test_build_request_body_sanitizes_documented_unsupported_fields(cohere_provi
"parallel_tool_calls": True,
}
- body = cohere_provider._build_request_body(make_request())
+ body = cohere_provider._chat._build_request_body(make_request())
assert body["messages"][0].get("name") is None
assert body["max_tokens"] == 42
@@ -103,7 +103,7 @@ def test_build_request_body_sanitizes_documented_unsupported_fields(cohere_provi
def test_build_request_body_maps_reasoning_on_to_high(cohere_provider):
request = make_request()
- body = cohere_provider._build_request_body(
+ body = cohere_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -126,7 +126,7 @@ def test_build_request_body_preserves_replayed_reasoning_content(cohere_provider
}
request = make_request()
- body = cohere_provider._build_request_body(
+ body = cohere_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -153,7 +153,7 @@ def test_build_request_body_maps_reasoning_off_to_none():
)
request = make_request(thinking={"type": "disabled"})
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
assert body["reasoning_effort"] == "none"
@@ -168,7 +168,7 @@ def test_build_request_body_promotes_allowed_extra_body(cohere_provider):
}
)
- body = cohere_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = cohere_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assert body["frequency_penalty"] == 0.1
assert body["presence_penalty"] == 0.2
@@ -181,7 +181,7 @@ def test_build_request_body_rejects_unsupported_extra_body(cohere_provider):
req = make_request(extra_body={"documents": [{"text": "x"}]})
with pytest.raises(InvalidRequestError, match="Unsupported"):
- cohere_provider._build_request_body(req, reasoning=reasoning_for(req))
+ cohere_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
@pytest.mark.asyncio
diff --git a/tests/providers/test_deepinfra.py b/tests/providers/test_deepinfra.py
index 8fd3700c..b2734849 100644
--- a/tests/providers/test_deepinfra.py
+++ b/tests/providers/test_deepinfra.py
@@ -122,7 +122,7 @@ def test_build_request_body_preserves_common_chat_tools_and_images(
}
)
- body = deepinfra_provider._build_request_body(
+ body = deepinfra_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -158,7 +158,7 @@ def test_build_request_body_encodes_documented_reasoning_effort(
) -> None:
request = _request()
- body = deepinfra_provider._build_request_body(request, reasoning=reasoning)
+ body = deepinfra_provider._chat._build_request_body(request, reasoning=reasoning)
assert body["extra_body"] == {"reasoning_effort": expected}
@@ -168,7 +168,7 @@ def test_build_request_body_preserves_extra_body_without_reasoning_override(
) -> None:
request = _request(extra_body={"service_tier": "priority"})
- body = deepinfra_provider._build_request_body(request, reasoning=REASONING_ON)
+ body = deepinfra_provider._chat._build_request_body(request, reasoning=REASONING_ON)
assert body["extra_body"] == {
"service_tier": "priority",
@@ -184,7 +184,7 @@ def test_build_request_body_rejects_caller_reasoning_override(
request = _request(extra_body={field: "caller-owned"})
with pytest.raises(InvalidRequestError, match="must not override reasoning"):
- deepinfra_provider._build_request_body(request, reasoning=REASONING_ON)
+ deepinfra_provider._chat._build_request_body(request, reasoning=REASONING_ON)
def test_build_request_body_replays_documented_reasoning_content(
@@ -207,7 +207,7 @@ def test_build_request_body_replays_documented_reasoning_content(
}
)
- body = deepinfra_provider._build_request_body(
+ body = deepinfra_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -282,7 +282,7 @@ async def test_model_catalog_uses_absolute_public_url() -> None:
return AsyncOpenAI(*args, **kwargs)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
side_effect=build_client,
):
provider = profiled_provider(
diff --git a/tests/providers/test_deepseek.py b/tests/providers/test_deepseek.py
index 7fc89cca..4e49951f 100644
--- a/tests/providers/test_deepseek.py
+++ b/tests/providers/test_deepseek.py
@@ -50,7 +50,7 @@ def test_default_base_url_alias():
def test_init(deepseek_config):
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_client:
provider = DeepSeekProvider(deepseek_config, admission=immediate_admission())
assert provider._api_key == "test_deepseek_key"
@@ -90,7 +90,7 @@ def test_responses_request_uses_deepseek_chat_policy(deepseek_provider):
}
)
- translated = deepseek_provider._build_responses_request_body(
+ translated = deepseek_provider._chat._build_responses_request_body(
request, reasoning=REASONING_ON
)
@@ -125,7 +125,7 @@ def test_responses_tool_history_keeps_deepseek_replayable_reasoning(
}
)
- translated = deepseek_provider._build_responses_request_body(
+ translated = deepseek_provider._chat._build_responses_request_body(
request, reasoning=REASONING_ON
)
@@ -237,8 +237,10 @@ def test_responses_tool_history_keeps_deepseek_replayable_reasoning(
def test_maps_only_complete_consistent_cache_usage(
deepseek_provider, usage, anthropic_expected, responses_cached
) -> None:
- assert deepseek_provider._anthropic_usage_fields(usage) == anthropic_expected
- assert deepseek_provider._cached_input_tokens(usage) == responses_cached
+ assert (
+ deepseek_provider._behavior.anthropic_usage_fields(usage) == anthropic_expected
+ )
+ assert deepseek_provider._behavior.cached_input_tokens(usage) == responses_cached
def test_build_request_body_openai_chat_shape(deepseek_provider):
@@ -248,7 +250,7 @@ def test_build_request_body_openai_chat_shape(deepseek_provider):
messages=[Message(role="user", content="Hello")],
system="S",
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["model"] == "deepseek-v4-pro"
@@ -265,7 +267,7 @@ def test_build_request_body_default_max_tokens(deepseek_provider):
model="m",
messages=[Message(role="user", content="x")],
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
@@ -279,7 +281,7 @@ def test_build_request_body_thinking_enabled(deepseek_provider):
"thinking": {"type": "enabled", "budget_tokens": 2000},
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["extra_body"]["thinking"] == {"type": "enabled"}
@@ -301,7 +303,7 @@ def test_build_request_body_tool_list_keeps_thinking(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -319,7 +321,7 @@ def test_build_request_body_tool_choice_keeps_thinking(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -346,7 +348,7 @@ def test_build_request_body_forced_tool_choice_downgrades_to_auto(
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -371,7 +373,7 @@ def test_build_request_body_encodes_reasoning_off():
"thinking": {"type": "enabled", "budget_tokens": 1},
}
)
- body = provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["extra_body"]["thinking"] == {"type": "disabled"}
assert "stream_options" not in body
@@ -395,7 +397,7 @@ def test_non_tool_thinking_survives_conversion(deepseek_provider):
],
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["messages"][0] == {
@@ -420,7 +422,7 @@ def test_redacted_thinking_is_kept_until_destination_preparation(deepseek_provid
],
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["messages"][0]["reasoning_details"] == [
@@ -470,7 +472,7 @@ def test_tool_history_with_replayable_thinking_preserves_thinking(deepseek_provi
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -521,7 +523,7 @@ def test_tool_history_with_unsigned_thinking_preserves_thinking(deepseek_provide
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -576,7 +578,7 @@ def test_tool_history_without_thinking_keeps_selected_effort(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -623,7 +625,7 @@ def test_tool_history_with_empty_thinking_preserves_reasoning_state(deepseek_pro
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -666,7 +668,7 @@ def test_tool_history_with_empty_top_level_reasoning_preserves_reasoning_state(
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -699,7 +701,7 @@ def test_thinking_off_preserves_historical_reasoning():
],
}
)
- body = provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["extra_body"]["thinking"] == {"type": "disabled"}
assert body["messages"][0]["reasoning_content"] == "sec"
@@ -744,7 +746,7 @@ def test_thinking_off_still_replays_required_tool_reasoning():
}
)
- body = provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["extra_body"]["thinking"] == {"type": "disabled"}
assert body["messages"][0]["reasoning_content"] == "required"
@@ -779,7 +781,7 @@ def test_passthrough_tool_use_and_result(deepseek_provider):
],
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["messages"][0]["tool_calls"][0]["function"]["name"] == "n"
@@ -817,7 +819,7 @@ def test_preflight_strips_user_image():
)
# Should not raise; image is stripped.
provider.preflight_messages(request, reasoning=REASONING_ON)
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
content = body["messages"][0]["content"]
assert "attachment omitted" in content.lower()
assert "image or document inputs" in content.lower()
@@ -855,7 +857,7 @@ def test_vision_model_forwards_user_image():
)
# Must not raise on preflight (no InvalidRequestError for image blocks).
provider.preflight_messages(request, reasoning=REASONING_ON)
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
content = body["messages"][0]["content"]
assert isinstance(content, list)
image_parts = [
@@ -903,7 +905,7 @@ def test_vision_model_strips_user_document():
admission=immediate_admission(),
)
provider.preflight_messages(request, reasoning=REASONING_ON)
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
content = body["messages"][0]["content"]
assert content
if isinstance(content, str):
@@ -995,7 +997,7 @@ def test_preflight_preserves_completed_server_tool_history():
admission=immediate_admission(),
)
provider.preflight_messages(request)
- body = provider._build_request_body(request)
+ body = provider._chat._build_request_body(request)
assert "[Earlier tool record]" in body["messages"][0]["content"]
@@ -1010,7 +1012,7 @@ def test_non_tool_top_level_reasoning_survives_conversion(deepseek_provider):
)
],
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
assert body["messages"][0] == {
@@ -1051,7 +1053,7 @@ def test_tool_call_top_level_reasoning_is_replayed(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1129,7 +1131,7 @@ async def test_wire_messages_keep_prefix_and_effort_when_old_reasoning_is_absent
"thinking": {"type": "enabled"},
}
)
- return deepseek_provider._build_request_body(
+ return deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1286,7 +1288,7 @@ def test_preserves_extra_body_for_openai_chat_request(deepseek_provider):
"extra_body": {"note": 1},
}
r = MessagesRequest.model_validate(raw)
- body = deepseek_provider._build_request_body(r, reasoning=reasoning_for(r))
+ body = deepseek_provider._chat._build_request_body(r, reasoning=reasoning_for(r))
assert body["extra_body"] == {"note": 1}
@@ -1324,7 +1326,7 @@ def test_normalizes_tool_result_content_array_to_string(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1360,7 +1362,7 @@ def test_strips_document_blocks_for_deepseek(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1395,7 +1397,7 @@ def test_strips_image_blocks_for_deepseek(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1433,7 +1435,7 @@ def test_normalizes_tool_result_content_dict_to_string(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1485,7 +1487,7 @@ def test_strips_image_block_inside_tool_result(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1538,7 +1540,7 @@ def test_image_only_tool_result_replaced_with_placeholder(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1591,7 +1593,7 @@ def test_document_only_tool_result_replaced_with_generic_placeholder(
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1626,7 +1628,7 @@ def test_image_only_message_replaced_with_placeholder(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1654,7 +1656,7 @@ def test_document_only_message_replaced_with_placeholder(deepseek_provider):
}
)
- body = deepseek_provider._build_request_body(
+ body = deepseek_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -1718,7 +1720,9 @@ def test_warns_when_stripping_attachment_blocks(deepseek_provider, caplog):
)
with caplog.at_level(logging.WARNING):
- deepseek_provider._build_request_body(request, reasoning=reasoning_for(request))
+ deepseek_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
assert any("stripped unsupported attachment blocks" in r.message for r in warnings)
@@ -1734,7 +1738,9 @@ def test_no_warning_when_no_attachments(deepseek_provider, caplog):
)
with caplog.at_level(logging.WARNING):
- deepseek_provider._build_request_body(request, reasoning=reasoning_for(request))
+ deepseek_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert not any(
"stripped unsupported attachment blocks" in r.message
diff --git a/tests/providers/test_featherless.py b/tests/providers/test_featherless.py
index e6aaebe6..4dd33ea0 100644
--- a/tests/providers/test_featherless.py
+++ b/tests/providers/test_featherless.py
@@ -120,7 +120,7 @@ def test_build_request_body_preserves_shared_chat_contract(
],
)
- body = featherless_provider._build_request_body(
+ body = featherless_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -147,7 +147,7 @@ def test_build_request_body_encodes_documented_thinking_control(
reasoning: ReasoningPolicy,
enabled: bool,
) -> None:
- body = featherless_provider._build_request_body(
+ body = featherless_provider._chat._build_request_body(
_request(),
reasoning=reasoning,
)
@@ -158,7 +158,7 @@ def test_build_request_body_encodes_documented_thinking_control(
def test_build_request_body_omits_thinking_control_for_provider_default(
featherless_provider: OpenAIChatProvider,
) -> None:
- body = featherless_provider._build_request_body(
+ body = featherless_provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.provider_default(),
)
@@ -177,7 +177,7 @@ def test_build_request_body_rejects_caller_reasoning_override(
request = _request(extra_body={field: "caller-owned"})
with pytest.raises(InvalidRequestError, match="must not override reasoning"):
- featherless_provider._build_request_body(request, reasoning=REASONING_ON)
+ featherless_provider._chat._build_request_body(request, reasoning=REASONING_ON)
def test_build_request_body_replays_reasoning_and_tool_history(
@@ -212,7 +212,7 @@ def test_build_request_body_replays_reasoning_and_tool_history(
]
)
- body = featherless_provider._build_request_body(
+ body = featherless_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_fireworks.py b/tests/providers/test_fireworks.py
index 1229e8db..36f32ed9 100644
--- a/tests/providers/test_fireworks.py
+++ b/tests/providers/test_fireworks.py
@@ -50,7 +50,7 @@ def test_build_request_body_openai_chat_shape(fireworks_provider):
system="System prompt",
)
- body = fireworks_provider._build_request_body(
+ body = fireworks_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -68,7 +68,7 @@ def test_build_request_body_default_max_tokens(fireworks_provider):
messages=[Message(role="user", content="x")],
)
- body = fireworks_provider._build_request_body(
+ body = fireworks_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -98,7 +98,7 @@ def test_replay_is_independent_of_current_turn_reasoning_control():
}
)
- body = provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["messages"][0]["reasoning_content"] == "hidden"
assert body["reasoning_effort"] == "none"
@@ -113,7 +113,7 @@ def test_build_request_body_preserves_validated_extra_body(fireworks_provider):
}
)
- body = fireworks_provider._build_request_body(
+ body = fireworks_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -130,7 +130,7 @@ def test_build_request_body_rejects_reserved_extra_body_keys(fireworks_provider)
)
with pytest.raises(InvalidRequestError, match="extra_body must not override"):
- fireworks_provider._build_request_body(
+ fireworks_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
diff --git a/tests/providers/test_gemini.py b/tests/providers/test_gemini.py
index a10ec55c..26854c62 100644
--- a/tests/providers/test_gemini.py
+++ b/tests/providers/test_gemini.py
@@ -61,7 +61,7 @@ def gemini_provider(gemini_config):
def test_init(gemini_config):
"""Test provider initialization."""
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = GeminiProvider(gemini_config, admission=immediate_admission())
assert provider._api_key == "test_gemini_key"
@@ -81,7 +81,7 @@ def test_default_base_url_constant():
def test_build_request_body_basic(gemini_provider):
"""Basic body conversion attaches Gemini thinking fields when thinking is on."""
req = make_request()
- body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = gemini_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assert body["model"] == "models/gemini-3.1-flash-lite"
assert body["messages"][0]["role"] == "system"
@@ -102,7 +102,7 @@ def test_build_request_body_sdk_wire_json_has_literal_extra_body(gemini_provider
"""Regression for issue #542: SDK merge must not send top-level google."""
req = make_request()
- body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = gemini_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
wire_json = _simulate_openai_sdk_wire_json(body)
assert "reasoning_effort" not in wire_json
@@ -128,7 +128,7 @@ def test_build_request_body_reasoning_off_sets_reasoning_none():
admission=immediate_admission(),
)
req = make_request(thinking={"type": "disabled"})
- body = provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assert body["reasoning_effort"] == "none"
roles = [m.get("role") for m in body.get("messages", [])]
@@ -167,7 +167,7 @@ def test_gemini_reasoning_uses_exactly_one_wire_channel(
expected_effort: str | None,
expected_thinking_config: dict | None,
) -> None:
- body = gemini_provider._build_request_body(
+ body = gemini_provider._chat._build_request_body(
make_request(thinking=None),
reasoning=reasoning,
)
@@ -189,7 +189,7 @@ def test_gemini_adaptive_thinking_with_effort_does_not_emit_custom_config(
output_config={"effort": "high"},
)
- body = gemini_provider._build_request_body(
+ body = gemini_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -204,7 +204,7 @@ def test_build_request_body_preserves_caller_extra_body(gemini_provider):
# imply that Gemini accepts an undocumented "custom_tag" wire field.
req = make_request(extra_body={"custom_tag": {"user": "u1"}})
- body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = gemini_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assert "reasoning_effort" not in body
eb = body.get("extra_body")
@@ -224,7 +224,7 @@ def test_build_request_body_strips_unsupported_metadata_key(gemini_provider):
"""
req = make_request(extra_body={"metadata": {"user_id": "u1"}})
- body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = gemini_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
wire_json = _simulate_openai_sdk_wire_json(body)
assert "metadata" not in body
@@ -248,7 +248,7 @@ def test_build_request_body_merges_caller_nested_google(gemini_provider):
},
)
- body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = gemini_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assert "reasoning_effort" not in body
eb = body.get("extra_body")
@@ -277,7 +277,7 @@ def test_gemini_rejects_caller_thinking_config_with_fcc_reasoning_control(
)
with pytest.raises(InvalidRequestError, match="thinking_config"):
- gemini_provider._build_request_body(
+ gemini_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -292,7 +292,7 @@ def test_gemini_rejects_malformed_google_extension_container(
)
with pytest.raises(InvalidRequestError, match="thinking_config must be an object"):
- gemini_provider._build_request_body(
+ gemini_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.provider_default(),
)
@@ -330,7 +330,7 @@ def test_build_request_body_preserves_tool_call_extra_content(gemini_provider):
],
)
- body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = gemini_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
tool_call = body["messages"][1]["tool_calls"][0]
assert tool_call["extra_content"] == {
@@ -339,7 +339,7 @@ def test_build_request_body_preserves_tool_call_extra_content(gemini_provider):
def test_build_request_body_uses_cached_tool_call_signature(gemini_provider):
- gemini_provider._record_tool_call_extra_content(
+ gemini_provider._behavior.record_tool_call_extra_content(
"function-call-1", {"google": {"thought_signature": "sig-from-cache"}}
)
req = make_request(
@@ -370,7 +370,7 @@ def test_build_request_body_uses_cached_tool_call_signature(gemini_provider):
],
)
- body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = gemini_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
tool_call = body["messages"][1]["tool_calls"][0]
assert tool_call["extra_content"] == {
@@ -420,7 +420,7 @@ def test_build_request_body_adds_current_turn_fallback_signature(
],
)
- body = gemini_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = gemini_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
tool_calls = body["messages"][1]["tool_calls"]
assert tool_calls[0]["extra_content"] == {
@@ -520,9 +520,9 @@ async def test_stream_messages_preserves_tool_call_extra_content(gemini_provider
assert any(
'"extra_content"' in event and "sig-stream" in event for event in tool_starts
)
- assert gemini_provider._tool_call_extra_content_by_id["function-call-1"] == {
- "google": {"thought_signature": "sig-stream"}
- }
+ assert gemini_provider._behavior._tool_call_extra_content_by_id[
+ "function-call-1"
+ ] == {"google": {"thought_signature": "sig-stream"}}
@pytest.mark.asyncio
@@ -598,7 +598,7 @@ async def test_colliding_stream_tool_id_rekeys_cached_thought_signature(
[start] = starts
public_id = start["id"]
assert public_id != "function-call-1"
- assert gemini_provider._tool_call_extra_content_by_id[public_id] == {
+ assert gemini_provider._behavior._tool_call_extra_content_by_id[public_id] == {
"google": {"thought_signature": "sig-stream"}
}
@@ -629,7 +629,7 @@ async def test_colliding_stream_tool_id_rekeys_cached_thought_signature(
},
],
)
- body = gemini_provider._build_request_body(
+ body = gemini_provider._chat._build_request_body(
replay,
reasoning=reasoning_for(replay),
)
diff --git a/tests/providers/test_groq.py b/tests/providers/test_groq.py
index 87075b94..615fccde 100644
--- a/tests/providers/test_groq.py
+++ b/tests/providers/test_groq.py
@@ -36,7 +36,7 @@ def groq_provider(groq_config):
def test_init(groq_config):
"""Test provider initialization."""
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = GroqProvider(groq_config, admission=immediate_admission())
assert provider._api_key == "test_groq_key"
@@ -81,7 +81,7 @@ async def test_model_catalog_extracts_documented_token_limits(groq_provider) ->
def test_build_request_body_basic(groq_provider):
"""Basic request body conversion attaches system message from Claude request."""
req = make_request()
- body = groq_provider._build_request_body(req)
+ body = groq_provider._chat._build_request_body(req)
assert body["model"] == "llama-3.3-70b-versatile"
assert body["messages"][0]["role"] == "system"
@@ -118,7 +118,7 @@ def test_build_request_body_replays_reasoning_as_tagged_content(groq_provider):
]
)
- body = groq_provider._build_request_body(request)
+ body = groq_provider._chat._build_request_body(request)
assistant = next(
message for message in body["messages"] if message["role"] == "assistant"
@@ -149,7 +149,7 @@ def test_build_request_body_global_disable_blocks_reasoning_mapping():
admission=immediate_admission(),
)
req = make_request()
- body = provider._build_request_body(req)
+ body = provider._chat._build_request_body(req)
roles = [m.get("role") for m in body.get("messages", [])]
assert "assistant_reasoning_content" not in roles
@@ -177,7 +177,7 @@ def test_build_request_body_sanitizes_and_remaps_via_mock_converter(groq_provide
"n": 4,
}
req = make_request()
- body = groq_provider._build_request_body(req)
+ body = groq_provider._chat._build_request_body(req)
msgs = body["messages"]
assert msgs[0].get("name") is None and msgs[1].get("name") is None
@@ -198,7 +198,7 @@ def test_build_request_body_prefers_existing_max_completion_tokens(groq_provider
"max_completion_tokens": 77,
"max_tokens": 999,
}
- body = groq_provider._build_request_body(make_request())
+ body = groq_provider._chat._build_request_body(make_request())
assert body["max_completion_tokens"] == 77
assert "max_tokens" not in body
@@ -207,7 +207,7 @@ def test_build_request_body_prefers_existing_max_completion_tokens(groq_provider
def test_build_request_body_preserves_caller_extra_body(groq_provider):
req = make_request(extra_body={"metadata": {"user": "u1"}})
- body = groq_provider._build_request_body(req)
+ body = groq_provider._chat._build_request_body(req)
eb = body.get("extra_body")
assert isinstance(eb, dict)
diff --git a/tests/providers/test_groq_reasoning.py b/tests/providers/test_groq_reasoning.py
index 8095845e..80e36fbc 100644
--- a/tests/providers/test_groq_reasoning.py
+++ b/tests/providers/test_groq_reasoning.py
@@ -22,6 +22,7 @@ from free_claude_code.core.reasoning import (
from free_claude_code.providers.admission import ProviderOperationKind
from free_claude_code.providers.groq import GroqProvider
from free_claude_code.providers.groq.client import (
+ GroqChatBehavior,
_parse_reasoning_vocabulary,
_rewrite_reasoning_effort,
)
@@ -51,6 +52,11 @@ class _BadRequest(Exception):
self.response = response
+def _reasoning_vocabularies(provider: GroqProvider) -> dict[str, frozenset[str]]:
+ assert isinstance(provider._behavior, GroqChatBehavior)
+ return provider._behavior._model_reasoning_vocabularies
+
+
def _provider(*, max_attempts: int = 5) -> GroqProvider:
return GroqProvider(
make_provider_config(
@@ -394,7 +400,7 @@ async def test_initial_reasoning_policy_reaches_sdk_wire(
policy: ReasoningPolicy,
expected: str | None,
) -> None:
- body = _provider()._build_request_body(_request(), reasoning=policy)
+ body = _provider()._chat._build_request_body(_request(), reasoning=policy)
wire = await capture_openai_chat_wire_body(body)
@@ -405,11 +411,11 @@ async def test_initial_reasoning_policy_reaches_sdk_wire(
async def test_exact_issue_retries_with_default_and_learns_model() -> None:
provider = _provider()
policy = ReasoningPolicy.on(effort=ReasoningEffort.HIGH)
- body = provider._build_request_body(_request(), reasoning=policy)
+ body = provider._chat._build_request_body(_request(), reasoning=policy)
create = AsyncMock(side_effect=[_vocabulary_error(), object()])
with patch.object(provider._client.chat.completions, "create", create):
- _stream, used_body, attempt, _sent_body = await provider._create_stream(
+ _stream, used_body, attempt, _sent_body = await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -420,11 +426,9 @@ async def test_exact_issue_retries_with_default_and_learns_model() -> None:
assert create.await_args_list[0].kwargs["reasoning_effort"] == "high"
assert create.await_args_list[1].kwargs["reasoning_effort"] == "default"
assert used_body["reasoning_effort"] == "default"
- assert provider._model_reasoning_vocabularies == {
- _MODEL: frozenset({"none", "default"})
- }
+ assert _reasoning_vocabularies(provider) == {_MODEL: frozenset({"none", "default"})}
- next_body = provider._build_request_body(_request(), reasoning=policy)
+ next_body = provider._chat._build_request_body(_request(), reasoning=policy)
assert next_body["reasoning_effort"] == "default"
next_create = AsyncMock(return_value=object())
with patch.object(provider._client.chat.completions, "create", next_create):
@@ -433,7 +437,7 @@ async def test_exact_issue_retries_with_default_and_learns_model() -> None:
next_used_body,
next_attempt,
_sent_body,
- ) = await provider._create_stream(
+ ) = await provider._chat._create_stream(
next_body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -445,9 +449,11 @@ async def test_exact_issue_retries_with_default_and_learns_model() -> None:
def test_cached_none_default_preserves_off() -> None:
provider = _provider()
- provider._model_reasoning_vocabularies[_MODEL] = frozenset({"none", "default"})
+ _reasoning_vocabularies(provider)[_MODEL] = frozenset({"none", "default"})
- body = provider._build_request_body(_request(), reasoning=ReasoningPolicy.off())
+ body = provider._chat._build_request_body(
+ _request(), reasoning=ReasoningPolicy.off()
+ )
assert body["reasoning_effort"] == "none"
@@ -465,11 +471,9 @@ def test_cached_named_vocabulary_preserves_enabled_efforts(
expected: str,
) -> None:
provider = _provider()
- provider._model_reasoning_vocabularies[_MODEL] = frozenset(
- {"low", "medium", "high"}
- )
+ _reasoning_vocabularies(provider)[_MODEL] = frozenset({"low", "medium", "high"})
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.on(effort=effort),
)
@@ -479,11 +483,11 @@ def test_cached_named_vocabulary_preserves_enabled_efforts(
def test_cached_named_vocabulary_omits_unrepresentable_off() -> None:
provider = _provider()
- provider._model_reasoning_vocabularies[_MODEL] = frozenset(
- {"low", "medium", "high"}
- )
+ _reasoning_vocabularies(provider)[_MODEL] = frozenset({"low", "medium", "high"})
- body = provider._build_request_body(_request(), reasoning=ReasoningPolicy.off())
+ body = provider._chat._build_request_body(
+ _request(), reasoning=ReasoningPolicy.off()
+ )
assert "reasoning_effort" not in body
@@ -491,7 +495,7 @@ def test_cached_named_vocabulary_omits_unrepresentable_off() -> None:
@pytest.mark.asyncio
async def test_unknown_vocabulary_retries_without_effort_and_negative_caches() -> None:
provider = _provider()
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -503,7 +507,7 @@ async def test_unknown_vocabulary_retries_without_effort_and_negative_caches() -
)
with patch.object(provider._client.chat.completions, "create", create):
- _stream, used_body, attempt, _sent_body = await provider._create_stream(
+ _stream, used_body, attempt, _sent_body = await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -512,8 +516,8 @@ async def test_unknown_vocabulary_retries_without_effort_and_negative_caches() -
assert "reasoning_effort" not in create.await_args_list[1].kwargs
assert "reasoning_effort" not in used_body
- assert provider._model_reasoning_vocabularies[_MODEL] == frozenset()
- assert "reasoning_effort" not in provider._build_request_body(
+ assert _reasoning_vocabularies(provider)[_MODEL] == frozenset()
+ assert "reasoning_effort" not in provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -522,10 +526,10 @@ async def test_unknown_vocabulary_retries_without_effort_and_negative_caches() -
def test_reasoning_cache_isolated_by_opaque_model_id() -> None:
provider = _provider()
policy = ReasoningPolicy.on(effort=ReasoningEffort.HIGH)
- provider._model_reasoning_vocabularies[_MODEL] = frozenset({"none", "default"})
+ _reasoning_vocabularies(provider)[_MODEL] = frozenset({"none", "default"})
- learned = provider._build_request_body(_request(_MODEL), reasoning=policy)
- unlearned = provider._build_request_body(
+ learned = provider._chat._build_request_body(_request(_MODEL), reasoning=policy)
+ unlearned = provider._chat._build_request_body(
_request("opaque-model-b"), reasoning=policy
)
@@ -538,8 +542,8 @@ async def test_concurrent_first_requests_can_learn_without_state_corruption() ->
provider = _provider()
policy = ReasoningPolicy.on(effort=ReasoningEffort.HIGH)
bodies = [
- provider._build_request_body(_request(), reasoning=policy),
- provider._build_request_body(_request(), reasoning=policy),
+ provider._chat._build_request_body(_request(), reasoning=policy),
+ provider._chat._build_request_body(_request(), reasoning=policy),
]
initial_calls = 0
release_initial_errors = asyncio.Event()
@@ -558,7 +562,7 @@ async def test_concurrent_first_requests_can_learn_without_state_corruption() ->
return object()
async def execute(body: dict):
- _stream, used_body, attempt, _sent_body = await provider._create_stream(
+ _stream, used_body, attempt, _sent_body = await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -574,17 +578,15 @@ async def test_concurrent_first_requests_can_learn_without_state_corruption() ->
assert sent_efforts.count("high") == 2
assert sent_efforts.count("default") == 2
assert all(body["reasoning_effort"] == "default" for body in used_bodies)
- assert provider._model_reasoning_vocabularies == {
- _MODEL: frozenset({"none", "default"})
- }
+ assert _reasoning_vocabularies(provider) == {_MODEL: frozenset({"none", "default"})}
@pytest.mark.asyncio
async def test_stale_cache_self_heals_without_guessing_original_effort() -> None:
provider = _provider()
policy = ReasoningPolicy.on(effort=ReasoningEffort.HIGH)
- provider._model_reasoning_vocabularies[_MODEL] = frozenset({"none", "default"})
- cached_body = provider._build_request_body(_request(), reasoning=policy)
+ _reasoning_vocabularies(provider)[_MODEL] = frozenset({"none", "default"})
+ cached_body = provider._chat._build_request_body(_request(), reasoning=policy)
assert cached_body["reasoning_effort"] == "default"
create = AsyncMock(
side_effect=[
@@ -594,7 +596,12 @@ async def test_stale_cache_self_heals_without_guessing_original_effort() -> None
)
with patch.object(provider._client.chat.completions, "create", create):
- _stream, corrected_body, attempt, _sent_body = await provider._create_stream(
+ (
+ _stream,
+ corrected_body,
+ attempt,
+ _sent_body,
+ ) = await provider._chat._create_stream(
cached_body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -602,17 +609,17 @@ async def test_stale_cache_self_heals_without_guessing_original_effort() -> None
await attempt.aclose()
assert "reasoning_effort" not in corrected_body
- assert provider._model_reasoning_vocabularies[_MODEL] == frozenset(
+ assert _reasoning_vocabularies(provider)[_MODEL] == frozenset(
{"low", "medium", "high"}
)
- rebuilt = provider._build_request_body(_request(), reasoning=policy)
+ rebuilt = provider._chat._build_request_body(_request(), reasoning=policy)
assert rebuilt["reasoning_effort"] == "high"
@pytest.mark.asyncio
async def test_unrelated_400_propagates_without_cache_poisoning() -> None:
provider = _provider()
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -622,20 +629,20 @@ async def test_unrelated_400_propagates_without_cache_poisoning() -> None:
patch.object(provider._client.chat.completions, "create", create),
pytest.raises(_BadRequest, match="wizard"),
):
- await provider._create_stream(
+ await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
)
assert create.await_count == 1
- assert provider._model_reasoning_vocabularies == {}
+ assert _reasoning_vocabularies(provider) == {}
@pytest.mark.asyncio
async def test_nested_unrelated_allow_list_cannot_retry_or_poison_cache() -> None:
provider = _provider()
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.off(),
)
@@ -652,7 +659,7 @@ async def test_nested_unrelated_allow_list_cannot_retry_or_poison_cache() -> Non
patch.object(provider._client.chat.completions, "create", create),
pytest.raises(_BadRequest),
):
- await provider._create_stream(
+ await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -660,13 +667,13 @@ async def test_nested_unrelated_allow_list_cannot_retry_or_poison_cache() -> Non
assert create.await_count == 1
assert create.await_args_list[0].kwargs["reasoning_effort"] == "none"
- assert provider._model_reasoning_vocabularies == {}
+ assert _reasoning_vocabularies(provider) == {}
@pytest.mark.asyncio
async def test_advertised_current_value_does_not_retry_or_cache() -> None:
provider = _provider()
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -676,39 +683,39 @@ async def test_advertised_current_value_does_not_retry_or_cache() -> None:
patch.object(provider._client.chat.completions, "create", create),
pytest.raises(_BadRequest),
):
- await provider._create_stream(
+ await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
)
assert create.await_count == 1
- assert provider._model_reasoning_vocabularies == {}
+ assert _reasoning_vocabularies(provider) == {}
@pytest.mark.asyncio
async def test_last_attempt_learns_but_does_not_exceed_budget() -> None:
provider = _provider(max_attempts=1)
policy = ReasoningPolicy.on(effort=ReasoningEffort.HIGH)
- body = provider._build_request_body(_request(), reasoning=policy)
+ body = provider._chat._build_request_body(_request(), reasoning=policy)
create = AsyncMock(side_effect=_vocabulary_error())
with (
patch.object(provider._client.chat.completions, "create", create),
pytest.raises(_BadRequest),
):
- await provider._create_stream(
+ await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
)
assert create.await_count == 1
- assert provider._model_reasoning_vocabularies[_MODEL] == frozenset(
- {"none", "default"}
- )
+ assert _reasoning_vocabularies(provider)[_MODEL] == frozenset({"none", "default"})
assert (
- provider._build_request_body(_request(), reasoning=policy)["reasoning_effort"]
+ provider._chat._build_request_body(_request(), reasoning=policy)[
+ "reasoning_effort"
+ ]
== "default"
)
@@ -716,7 +723,7 @@ async def test_last_attempt_learns_but_does_not_exceed_budget() -> None:
@pytest.mark.asyncio
async def test_output_cap_and_reasoning_corrections_share_one_session() -> None:
provider = _provider()
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
make_messages_request(_MODEL, max_tokens=64_000),
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -725,7 +732,7 @@ async def test_output_cap_and_reasoning_corrections_share_one_session() -> None:
execution = provider._admission.start_execution()
with patch.object(provider._client.chat.completions, "create", create):
- _stream, used_body, attempt, _sent_body = await provider._create_stream(
+ _stream, used_body, attempt, _sent_body = await provider._chat._create_stream(
body,
execution,
ProviderOperationKind.GENERATION,
@@ -745,7 +752,7 @@ async def test_output_cap_and_reasoning_corrections_share_one_session() -> None:
@pytest.mark.asyncio
async def test_corrected_request_cannot_enter_vocabulary_retry_loop() -> None:
provider = _provider()
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -755,7 +762,7 @@ async def test_corrected_request_cannot_enter_vocabulary_retry_loop() -> None:
patch.object(provider._client.chat.completions, "create", create),
pytest.raises(_BadRequest),
):
- await provider._create_stream(
+ await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
diff --git a/tests/providers/test_groq_tpm.py b/tests/providers/test_groq_tpm.py
index 465a8b03..857011da 100644
--- a/tests/providers/test_groq_tpm.py
+++ b/tests/providers/test_groq_tpm.py
@@ -254,7 +254,7 @@ async def test_tpm_correction_is_one_shot_per_stream_creation() -> None:
patch.object(provider._client.chat.completions, "create", create),
pytest.raises(openai.APIStatusError),
):
- await provider._create_stream(
+ await provider._chat._create_stream(
_body(),
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -272,7 +272,7 @@ async def test_tpm_correction_respects_physical_attempt_ceiling() -> None:
patch.object(provider._client.chat.completions, "create", create),
pytest.raises(openai.APIStatusError),
):
- await provider._create_stream(
+ await provider._chat._create_stream(
_body(),
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -296,7 +296,7 @@ async def test_tpm_and_reasoning_corrections_compose(
) -> None:
provider = _provider()
request = make_messages_request(_MODEL, max_tokens=_ORIGINAL_MAX)
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -308,7 +308,12 @@ async def test_tpm_and_reasoning_corrections_compose(
execution = provider._admission.start_execution()
with patch.object(provider._client.chat.completions, "create", create):
- _stream, accepted_body, attempt, _sent_body = await provider._create_stream(
+ (
+ _stream,
+ accepted_body,
+ attempt,
+ _sent_body,
+ ) = await provider._chat._create_stream(
body,
execution,
ProviderOperationKind.GENERATION,
@@ -331,7 +336,12 @@ async def test_distinct_bodies_get_independent_tpm_corrections() -> None:
create = AsyncMock(side_effect=[_status_error(), object(), second_error, object()])
with patch.object(provider._client.chat.completions, "create", create):
- _stream, first_body, first_attempt, _sent_body = await provider._create_stream(
+ (
+ _stream,
+ first_body,
+ first_attempt,
+ _sent_body,
+ ) = await provider._chat._create_stream(
_body(),
execution,
ProviderOperationKind.CONTINUATION,
@@ -343,7 +353,7 @@ async def test_distinct_bodies_get_independent_tpm_corrections() -> None:
second_body,
second_attempt,
_sent_body,
- ) = await provider._create_stream(
+ ) = await provider._chat._create_stream(
_body(20_000),
execution,
ProviderOperationKind.TOOL_REPAIR,
diff --git a/tests/providers/test_history_transports.py b/tests/providers/test_history_transports.py
index 5af26e00..775df111 100644
--- a/tests/providers/test_history_transports.py
+++ b/tests/providers/test_history_transports.py
@@ -4,6 +4,7 @@ import json
from contextlib import asynccontextmanager
from copy import deepcopy
from typing import Any
+from unittest.mock import patch
import httpx
import httpx2
@@ -130,7 +131,7 @@ def _events_for(protocol):
@asynccontextmanager
-async def _harness(protocol, responder=None, *, key="a", chat_provider=None):
+async def _harness(protocol, responder=None, *, key="a", chat_provider_factory=None):
bodies: list[dict[str, Any]] = []
def reply(request):
@@ -157,19 +158,24 @@ async def _harness(protocol, responder=None, *, key="a", chat_provider=None):
endpoint.token = key
extras = {"endpoint_context": endpoint}
else:
- client = _client(reply)
- client.api_key = key
+ client = _client(reply, api_key=key)
if protocol == "responses":
provider = responses_transport(client)
else:
- provider = chat_provider or OpenRouterProvider(
- make_provider_config(
- api_key=key, base_url="https://provider.invalid/v1"
- ),
- admission=immediate_admission(max_attempts=5),
- )
- await provider._client.close()
- provider._client = client
+ with patch(
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
+ return_value=client,
+ ):
+ provider = (
+ chat_provider_factory()
+ if chat_provider_factory is not None
+ else OpenRouterProvider(
+ make_provider_config(
+ api_key=key, base_url="https://provider.invalid/v1"
+ ),
+ admission=immediate_admission(max_attempts=5),
+ )
+ )
extras = {}
def stream(wire, history):
@@ -196,7 +202,7 @@ async def _harness(protocol, responder=None, *, key="a", chat_provider=None):
)
try:
- yield stream, bodies
+ yield stream, bodies, provider
finally:
if isinstance(client, httpx.AsyncClient):
await client.aclose()
@@ -231,7 +237,7 @@ def _carrier(history, wire):
@pytest.mark.parametrize("protocol", ["responses", "messages", "chat"])
@pytest.mark.parametrize("wire", ["responses", "messages"])
async def test_provider_a_b_a_preserves_exact_native_history(protocol, wire):
- async with _harness(protocol) as (send, bodies):
+ async with _harness(protocol) as (send, bodies, _):
saved = await _saved_reply(
send(wire, [{"role": "user", "content": "hello"}]), wire
)
@@ -245,7 +251,7 @@ async def test_provider_a_b_a_preserves_exact_native_history(protocol, wire):
json.dumps([*saved, {"role": "user", "content": "continue"}])
)
original = deepcopy(history)
- async with _harness(protocol, key="b") as (foreign, foreign_bodies):
+ async with _harness(protocol, key="b") as (foreign, foreign_bodies, _):
await _saved_reply(foreign(wire, history), wire)
foreign_wire = json.dumps(foreign_bodies[-1])
assert (
@@ -291,7 +297,7 @@ async def test_legacy_responses_id_then_cipher_rejection_recovers_without_changi
{"role": "user", "content": "continue"},
]
original = deepcopy(history)
- async with _harness("responses", responder) as (send, bodies):
+ async with _harness("responses", responder) as (send, bodies, _):
await _saved_reply(send(wire, history), wire)
assert len(bodies) == 3
assert ":" not in bodies[1]["input"][0]["id"]
@@ -327,7 +333,7 @@ async def test_explicit_legacy_rejection_corrects_only_history_before_commit(pro
{"role": "user", "content": "continue"},
]
original = deepcopy(history)
- async with _harness(protocol, responder) as (send, bodies):
+ async with _harness(protocol, responder) as (send, bodies, _):
await _saved_reply(send("messages", history), "messages")
assert len(bodies) == 2
assert "opaque-original" in json.dumps(bodies[0])
@@ -392,7 +398,7 @@ async def test_stream_history_rejection_respects_the_public_commit_boundary(
{"role": "assistant", "content": [block, {"type": "text", "text": "17"}]},
{"role": "user", "content": "continue"},
]
- async with _harness(protocol, responder) as (send, bodies):
+ async with _harness(protocol, responder) as (send, bodies, _):
if committed:
output = ""
with pytest.raises(ExecutionFailure):
@@ -429,14 +435,16 @@ async def test_successful_fallback_stamps_its_own_origin_and_gets_unmodified_inp
),
)
- provider = OpenRouterProvider(
- make_provider_config(
- api_key="fallback-key", base_url="https://provider.invalid/v1"
- ),
- admission=immediate_admission(),
- )
- await provider._client.close()
- provider._client = _client(reply)
+ with patch(
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
+ return_value=_client(reply),
+ ):
+ provider = OpenRouterProvider(
+ make_provider_config(
+ api_key="fallback-key", base_url="https://provider.invalid/v1"
+ ),
+ admission=immediate_admission(),
+ )
routed = _routed_request(_target("open_router", "fallback-model"))
original = routed.request.model_dump()
executor = ProviderExecutor(
@@ -480,7 +488,7 @@ async def test_history_corrections_exhaust_the_shared_attempt_budget():
"message": "The encrypted content could not be verified.",
}
- async with _harness("responses", responder) as (send, bodies):
+ async with _harness("responses", responder) as (send, bodies, _):
with pytest.raises(ExecutionFailure):
await _saved_reply(send("responses", history), "responses")
assert len(bodies) == 5
@@ -564,10 +572,6 @@ async def test_chat_buffered_content_preserves_reasoning_through_next_request(
"properties": {"query": {"type": "string"}},
"required": ["query"],
}
- provider = OpenRouterProvider(
- make_provider_config(api_key="a", base_url="https://provider.invalid/v1"),
- admission=immediate_admission(),
- )
def send(history):
if wire == "messages":
@@ -594,9 +598,7 @@ async def test_chat_buffered_content_preserves_reasoning_through_next_request(
reasoning=ReasoningPolicy.on(),
)
- async with _harness(
- "chat", lambda bodies: (200, events), chat_provider=provider
- ) as (_, bodies):
+ async with _harness("chat", lambda bodies: (200, events)) as (_, bodies, provider):
saved = await _saved_reply(send([{"role": "user", "content": "hello"}]), wire)
assert decode_replay(_carrier(saved, wire)).native == {
"reasoning_content": "Plan.",
@@ -651,7 +653,7 @@ async def test_chat_encrypted_only_completion_does_not_add_blank_text(wire):
details = [{"type": "reasoning.encrypted", "data": "opaque-only", "index": 0}]
events = _chat_reasoning_events([{"reasoning_details": details}])
events[-1]["choices"][0]["delta"] = {}
- async with _harness("chat", lambda bodies: (200, events)) as (send, _):
+ async with _harness("chat", lambda bodies: (200, events)) as (send, _, _):
saved = await _saved_reply(
send(wire, [{"role": "user", "content": "hello"}]), wire
)
@@ -687,7 +689,7 @@ async def test_chat_pending_reasoning_is_finalized_on_failure_or_discarded_on_re
def responder(bodies):
return 200, events if len(bodies) == 1 else _events_for("chat")
- async with _harness("chat", responder) as (send, bodies):
+ async with _harness("chat", responder) as (send, bodies, _):
stream = send(wire, [{"role": "user", "content": "hello"}])
if not committed:
saved = await _saved_reply(stream, wire)
@@ -732,7 +734,7 @@ async def test_chat_plaintext_beside_encrypted_details_survives_switching(
events = _chat_reasoning_events(
[{"reasoning_content": text, "reasoning_details": details}]
)
- async with _harness("chat", lambda bodies: (200, events)) as (source, sent):
+ async with _harness("chat", lambda bodies: (200, events)) as (source, sent, _):
saved = await _saved_reply(
source(wire, [{"role": "user", "content": "hello"}]), wire
)
@@ -748,7 +750,7 @@ async def test_chat_plaintext_beside_encrypted_details_survives_switching(
assert record.native["reasoning_content"] == text
history = json.loads(json.dumps([*saved, {"role": "user", "content": "next"}]))
original = deepcopy(history)
- async with _harness(destination, key="b") as (foreign, bodies):
+ async with _harness(destination, key="b") as (foreign, bodies, _):
await _saved_reply(foreign(wire, history), wire)
outgoing = json.dumps(bodies[-1])
assert outgoing.count(text) == 1
@@ -775,7 +777,7 @@ async def test_chat_summary_fragments_remain_readable_and_restore_exactly(
{"reasoning_details": [second, *([opaque] if encrypted else [])]},
]
)
- async with _harness("chat", lambda bodies: (200, events)) as (source, sent):
+ async with _harness("chat", lambda bodies: (200, events)) as (source, sent, _):
saved = await _saved_reply(
source(wire, [{"role": "user", "content": "hello"}]), wire
)
@@ -783,7 +785,7 @@ async def test_chat_summary_fragments_remain_readable_and_restore_exactly(
record = decode_replay(_carrier(saved, wire))
assert record.native["reasoning_details"] == details
history = [*saved, {"role": "user", "content": "next"}]
- async with _harness("responses", key="b") as (foreign, bodies):
+ async with _harness("responses", key="b") as (foreign, bodies, _):
await _saved_reply(foreign(wire, history), wire)
assert bodies[-1]["input"][0] == {
"role": "assistant",
@@ -809,13 +811,13 @@ async def test_chat_alternate_readable_fields_replay_once(native_first):
events = _chat_reasoning_events(
[native, typed] if native_first else [typed, native]
)
- async with _harness("chat", lambda bodies: (200, events)) as (source, sent):
+ async with _harness("chat", lambda bodies: (200, events)) as (source, sent, _):
saved = await _saved_reply(
source("messages", [{"role": "user", "content": "hi"}]), "messages"
)
assert json.dumps(saved).count("One readable thought.") == 1
history = [*saved, {"role": "user", "content": "next"}]
- async with _harness("responses", key="b") as (foreign, bodies):
+ async with _harness("responses", key="b") as (foreign, bodies, _):
await _saved_reply(foreign("messages", history), "messages")
assert json.dumps(bodies[-1]).count("One readable thought.") == 1
await _saved_reply(source("messages", history), "messages")
@@ -846,7 +848,7 @@ async def test_chat_reasoning_groups_do_not_inherit_previous_plaintext():
},
]
)
- async with _harness("chat", lambda bodies: (200, events)) as (source, _):
+ async with _harness("chat", lambda bodies: (200, events)) as (source, _, _):
saved = await _saved_reply(
source("messages", [{"role": "user", "content": "hi"}]), "messages"
)
@@ -884,11 +886,11 @@ async def test_chat_plaintext_matching_multiple_detail_parts_is_not_repeated():
}
]
)
- async with _harness("chat", lambda bodies: (200, events)) as (source, _):
+ async with _harness("chat", lambda bodies: (200, events)) as (source, _, _):
saved = await _saved_reply(
source("messages", [{"role": "user", "content": "hi"}]), "messages"
)
- async with _harness("responses", key="b") as (foreign, bodies):
+ async with _harness("responses", key="b") as (foreign, bodies, _):
await _saved_reply(
foreign("messages", [*saved, {"role": "user", "content": "next"}]),
"messages",
diff --git a/tests/providers/test_huggingface.py b/tests/providers/test_huggingface.py
index 9abf51b9..2aee9e8d 100644
--- a/tests/providers/test_huggingface.py
+++ b/tests/providers/test_huggingface.py
@@ -46,7 +46,7 @@ def test_default_base_url_constant():
def test_init_uses_default_base_url_and_api_key(huggingface_config):
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = profiled_provider(
"huggingface", huggingface_config, admission=immediate_admission()
@@ -60,7 +60,7 @@ def test_init_uses_default_base_url_and_api_key(huggingface_config):
def test_init_strips_trailing_slash(huggingface_config):
config = replace(huggingface_config, base_url=f"{HUGGINGFACE_DEFAULT_BASE}/")
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = profiled_provider(
"huggingface", config, admission=immediate_admission()
)
@@ -143,7 +143,7 @@ def test_build_request_body_keeps_max_tokens(huggingface_provider):
"max_tokens": 42,
}
- body = huggingface_provider._build_request_body(make_request())
+ body = huggingface_provider._chat._build_request_body(make_request())
mock_convert.assert_called_once()
assert (
@@ -159,7 +159,7 @@ def test_build_request_body_preserves_caller_extra_body(huggingface_provider):
extra_body = {"provider": "auto", "routing": {"bill_to": "my-org"}}
req = make_request(extra_body=extra_body)
- body = huggingface_provider._build_request_body(req)
+ body = huggingface_provider._chat._build_request_body(req)
assert body["extra_body"] == extra_body
assert body["extra_body"] is not extra_body
@@ -177,7 +177,7 @@ def test_build_request_body_preserves_caller_extra_body(huggingface_provider):
def test_build_request_body_leaves_reasoning_control_to_selected_upstream(
huggingface_provider, reasoning
):
- body = huggingface_provider._build_request_body(
+ body = huggingface_provider._chat._build_request_body(
make_request(),
reasoning=reasoning,
)
@@ -204,7 +204,7 @@ def test_build_request_body_does_not_replay_prior_thinking_blocks(
],
)
- body = huggingface_provider._build_request_body(req)
+ body = huggingface_provider._chat._build_request_body(req)
assert body["messages"] == [
{
@@ -230,7 +230,7 @@ def test_build_request_body_does_not_replay_top_level_reasoning_content(
],
)
- body = huggingface_provider._build_request_body(req)
+ body = huggingface_provider._chat._build_request_body(req)
assert body["messages"] == [
{
diff --git a/tests/providers/test_kilo.py b/tests/providers/test_kilo.py
index 87542093..9d179c0a 100644
--- a/tests/providers/test_kilo.py
+++ b/tests/providers/test_kilo.py
@@ -101,7 +101,9 @@ def test_build_request_body_openai_shape(kilo_provider):
}
)
- body = kilo_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = kilo_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["model"] == "anthropic/claude-sonnet-4.5"
assert body["messages"][0] == {"role": "user", "content": "Hello"}
@@ -117,7 +119,9 @@ def test_build_request_body_forwards_caller_extra_body(kilo_provider):
}
)
- body = kilo_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = kilo_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body.get("extra_body", {}).get("custom_field") == "value"
@@ -143,7 +147,9 @@ def test_extra_body_cannot_override_canonical_request_fields(kilo_provider, fiel
)
with pytest.raises(InvalidRequestError, match=field):
- kilo_provider._build_request_body(request, reasoning=reasoning_for(request))
+ kilo_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
def test_build_request_body_sends_reasoning_object(kilo_provider):
@@ -155,7 +161,9 @@ def test_build_request_body_sends_reasoning_object(kilo_provider):
}
)
- body = kilo_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = kilo_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body.get("extra_body", {}).get("reasoning") is not None
@@ -168,7 +176,7 @@ def test_build_request_body_sends_reasoning_disabled(kilo_provider):
}
)
- body = kilo_provider._build_request_body(
+ body = kilo_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.off(),
)
@@ -216,7 +224,7 @@ def test_build_request_body_replays_opaque_reasoning_details_on_tool_turn(
}
)
- body = kilo_provider._build_request_body(
+ body = kilo_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_kimi.py b/tests/providers/test_kimi.py
index 878c3443..66cb8dde 100644
--- a/tests/providers/test_kimi.py
+++ b/tests/providers/test_kimi.py
@@ -46,7 +46,9 @@ def test_build_request_body_openai_chat(kimi_provider):
messages=[Message(role="user", content="hi")],
)
- body = kimi_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = kimi_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["model"] == "kimi-k2.5"
assert body["max_tokens"] == 50
@@ -60,7 +62,9 @@ def test_build_request_body_default_max_tokens(kimi_provider):
messages=[Message(role="user", content="x")],
)
- body = kimi_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = kimi_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
@@ -75,7 +79,9 @@ def test_build_request_body_rejects_caller_extra_body(kimi_provider):
)
with pytest.raises(InvalidRequestError, match="Kimi Chat Completions"):
- kimi_provider._build_request_body(request, reasoning=reasoning_for(request))
+ kimi_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
def test_build_request_body_disables_kimi_thinking(kimi_provider):
@@ -87,7 +93,9 @@ def test_build_request_body_disables_kimi_thinking(kimi_provider):
}
)
- body = kimi_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = kimi_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["extra_body"]["thinking"] == {"type": "disabled"}
diff --git a/tests/providers/test_kimi_code.py b/tests/providers/test_kimi_code.py
index fd881961..80e7aa22 100644
--- a/tests/providers/test_kimi_code.py
+++ b/tests/providers/test_kimi_code.py
@@ -53,7 +53,7 @@ def test_init_uses_subscription_endpoint_and_identifies_fcc(kimi_code_provider):
def test_explicit_output_limit_uses_max_completion_tokens(kimi_code_provider):
request = _request(max_tokens=32_768)
- body = kimi_code_provider._build_request_body(
+ body = kimi_code_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -64,7 +64,7 @@ def test_explicit_output_limit_uses_max_completion_tokens(kimi_code_provider):
def test_omitted_output_limit_preserves_kimi_default(kimi_code_provider):
request = _request()
- body = kimi_code_provider._build_request_body(
+ body = kimi_code_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -91,7 +91,7 @@ def test_named_reasoning_effort_uses_kimi_vocabulary(
) -> None:
request = _request(output_config={"effort": client_effort})
- body = kimi_code_provider._build_request_body(
+ body = kimi_code_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -101,7 +101,7 @@ def test_named_reasoning_effort_uses_kimi_vocabulary(
def test_enabled_reasoning_without_named_effort_uses_max(kimi_code_provider):
request = _request(thinking={"type": "enabled", "budget_tokens": 4_096})
- body = kimi_code_provider._build_request_body(
+ body = kimi_code_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -111,7 +111,7 @@ def test_enabled_reasoning_without_named_effort_uses_max(kimi_code_provider):
def test_disabled_reasoning_uses_none(kimi_code_provider):
request = _request(thinking={"type": "disabled"})
- body = kimi_code_provider._build_request_body(
+ body = kimi_code_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -132,7 +132,7 @@ def test_reasoning_history_uses_reasoning_content(kimi_code_provider):
]
)
- body = kimi_code_provider._build_request_body(
+ body = kimi_code_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
assistant = body["messages"][0]
@@ -145,7 +145,7 @@ def test_caller_extra_body_is_rejected(kimi_code_provider):
request = _request(extra_body={"thinking": {"type": "enabled"}})
with pytest.raises(InvalidRequestError, match="Kimi Code Chat Completions"):
- kimi_code_provider._build_request_body(
+ kimi_code_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
diff --git a/tests/providers/test_llamacpp.py b/tests/providers/test_llamacpp.py
index 7b9e8041..fa2174ce 100644
--- a/tests/providers/test_llamacpp.py
+++ b/tests/providers/test_llamacpp.py
@@ -39,7 +39,7 @@ def provider() -> OpenAIChatProvider:
)
def test_init_normalizes_openai_base_url(configured: str, expected: str) -> None:
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as openai_client:
provider = profiled_provider(
"llamacpp",
@@ -60,7 +60,7 @@ def test_init_uses_openai_chat_client() -> None:
http_connect_timeout=5.0,
)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as openai_client:
provider = profiled_provider(
"llamacpp", config, admission=immediate_admission()
@@ -78,7 +78,7 @@ def test_build_request_body_uses_openai_chat_shape(
) -> None:
request = make_messages_request(LLAMACPP_MODEL, max_tokens=None)
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
assert body["model"] == LLAMACPP_MODEL
assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
@@ -104,7 +104,7 @@ def test_replay_is_independent_of_current_turn_reasoning_control(
],
)
- body = provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["messages"][1]["content"] == ("<think>\nprivate\n</think>\n\nvisible")
assert body["extra_body"]["thinking_budget_tokens"] == 0
diff --git a/tests/providers/test_llm7.py b/tests/providers/test_llm7.py
index 8c73eed8..ba871968 100644
--- a/tests/providers/test_llm7.py
+++ b/tests/providers/test_llm7.py
@@ -107,7 +107,7 @@ def test_preserves_provider_reasoning_default_and_standard_request_fields(
llm7_provider: OpenAIChatProvider,
reasoning: ReasoningPolicy,
) -> None:
- body = llm7_provider._build_request_body(_request(), reasoning=reasoning)
+ body = llm7_provider._chat._build_request_body(_request(), reasoning=reasoning)
assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
assert body["model"] == _MODEL
@@ -150,7 +150,7 @@ def test_replays_reasoning_content_with_tool_history(
]
)
- body = llm7_provider._build_request_body(
+ body = llm7_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_lmstudio.py b/tests/providers/test_lmstudio.py
index bf7d11b2..53b16e80 100644
--- a/tests/providers/test_lmstudio.py
+++ b/tests/providers/test_lmstudio.py
@@ -42,7 +42,7 @@ def lmstudio_provider(lmstudio_config):
def test_init(lmstudio_config):
"""Test provider initialization."""
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = LMStudioProvider(lmstudio_config, admission=immediate_admission())
assert provider._api_key == "lm-studio"
@@ -57,7 +57,7 @@ def test_default_base_url_constant():
def test_build_request_body_basic(lmstudio_provider):
req = make_request()
- body = lmstudio_provider._build_request_body(req)
+ body = lmstudio_provider._chat._build_request_body(req)
assert body["model"] == "lmstudio-community/qwen2.5-7b-instruct"
assert body["messages"][0]["role"] == "system"
@@ -66,7 +66,7 @@ def test_build_request_body_basic(lmstudio_provider):
def test_adaptive_client_reasoning_uses_documented_named_effort(lmstudio_provider):
req = make_request()
- body = lmstudio_provider._build_request_body(req, reasoning=REASONING_ON)
+ body = lmstudio_provider._chat._build_request_body(req, reasoning=REASONING_ON)
assert body["extra_body"]["reasoning_effort"] == "high"
assert "reasoning_effort" not in body
@@ -75,7 +75,7 @@ def test_adaptive_client_reasoning_uses_documented_named_effort(lmstudio_provide
def test_exact_client_budget_is_not_derived_from_output_tokens(lmstudio_provider):
req = make_request(max_tokens=8192)
- body = lmstudio_provider._build_request_body(
+ body = lmstudio_provider._chat._build_request_body(
req,
reasoning=ReasoningPolicy.on(
effort=ReasoningEffort.HIGH,
@@ -105,7 +105,7 @@ def test_build_request_body_never_replays_prior_thinking(lmstudio_provider):
},
]
)
- body = lmstudio_provider._build_request_body(req)
+ body = lmstudio_provider._chat._build_request_body(req)
roles = [m.get("role") for m in body.get("messages", [])]
assert "assistant_reasoning_content" not in roles
@@ -129,7 +129,7 @@ def test_preflight_builds_before_context_budget_and_preserves_policy(
calls.append(("context", estimate))
with (
- patch.object(lmstudio_provider, "_build_request_body", side_effect=build),
+ patch.object(lmstudio_provider._chat, "_build_request_body", side_effect=build),
patch.object(
lmstudio_provider,
"_preflight_context_budget",
@@ -150,7 +150,7 @@ def test_preflight_conversion_failure_skips_context_budget(lmstudio_provider):
with (
patch.object(
- lmstudio_provider,
+ lmstudio_provider._chat,
"_build_request_body",
side_effect=conversion_error,
),
diff --git a/tests/providers/test_minimax.py b/tests/providers/test_minimax.py
index ab5759bc..d98e4d19 100644
--- a/tests/providers/test_minimax.py
+++ b/tests/providers/test_minimax.py
@@ -100,7 +100,7 @@ def test_build_request_body_requests_split_output_and_max_completion_tokens(
}
)
- body = minimax_provider._build_request_body(
+ body = minimax_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -119,7 +119,7 @@ def test_build_request_body_does_not_invent_unsupported_compute_control(
messages=[Message(role="user", content="Hello")],
)
- body = minimax_provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = minimax_provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["extra_body"] == {"reasoning_split": True}
diff --git a/tests/providers/test_mistral.py b/tests/providers/test_mistral.py
index f8e7cc32..d84d70a1 100644
--- a/tests/providers/test_mistral.py
+++ b/tests/providers/test_mistral.py
@@ -43,7 +43,7 @@ def mistral_provider(mistral_config):
def test_init(mistral_config):
"""Test provider initialization."""
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = MistralProvider(mistral_config, admission=immediate_admission())
assert provider._api_key == "test_mistral_key"
@@ -123,7 +123,7 @@ async def test_model_catalog_degrades_incomplete_capabilities_to_unknown(
def test_build_request_body_basic(mistral_provider):
"""Basic request body conversion works for Mistral."""
req = make_request()
- body = mistral_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = mistral_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assert body["model"] == "devstral-small-latest"
assert body["messages"][0]["role"] == "system"
@@ -162,7 +162,7 @@ def test_build_request_body_replays_prior_thinking_as_mistral_chunks(
],
)
- body = mistral_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = mistral_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assistant = body["messages"][0]
assert "reasoning_content" not in assistant
@@ -193,7 +193,7 @@ def test_build_request_body_preserves_tools_tool_choice_and_params(mistral_provi
stop_sequences=["STOP"],
)
- body = mistral_provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = mistral_provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assert body["max_tokens"] == 100
assert body["temperature"] == 0.5
@@ -214,7 +214,7 @@ def test_build_request_body_reasoning_off_uses_native_none():
admission=immediate_admission(),
)
req = make_request()
- body = provider._build_request_body(req, reasoning=REASONING_OFF)
+ body = provider._chat._build_request_body(req, reasoning=REASONING_OFF)
assert body["reasoning_effort"] == "none"
assert all("reasoning_content" not in m for m in body.get("messages", []))
@@ -243,7 +243,7 @@ def test_reasoning_off_keeps_replay_separate_from_new_turn_compute():
],
)
- body = provider._build_request_body(req, reasoning=REASONING_OFF)
+ body = provider._chat._build_request_body(req, reasoning=REASONING_OFF)
assert body["reasoning_effort"] == "none"
assert body["messages"][0]["content"] == [
@@ -858,7 +858,7 @@ def test_retry_body_without_reasoning_returns_none(mistral_provider):
body = {"model": "x", "messages": [{"role": "user", "content": "hi"}]}
assert (
- mistral_provider._get_retry_request_body(
+ mistral_provider._behavior.retry_request_body(
_make_bad_request_error("Unsupported field: reasoning_effort"), body
)
is None
diff --git a/tests/providers/test_model_discovery.py b/tests/providers/test_model_discovery.py
index 0727a632..7d2b9028 100644
--- a/tests/providers/test_model_discovery.py
+++ b/tests/providers/test_model_discovery.py
@@ -89,7 +89,7 @@ def test_provider_catalog_contract_is_metadata_only() -> None:
@pytest.mark.asyncio
async def test_nim_lists_openai_compatible_model_infos() -> None:
config = make_provider_config(api_key="test-key", base_url=NVIDIA_NIM_DEFAULT_BASE)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = NvidiaNimProvider(
config, nim_settings=NimSettings(), admission=immediate_admission()
)
diff --git a/tests/providers/test_nebius.py b/tests/providers/test_nebius.py
index dcc708b2..d50e0196 100644
--- a/tests/providers/test_nebius.py
+++ b/tests/providers/test_nebius.py
@@ -65,7 +65,7 @@ def test_encodes_documented_reasoning_effort(
}
)
- body = nebius_provider._build_request_body(request, reasoning=reasoning)
+ body = nebius_provider._chat._build_request_body(request, reasoning=reasoning)
assert body["reasoning_effort"] == expected
assert "extra_body" not in body
@@ -89,7 +89,7 @@ def test_replays_reasoning_content(nebius_provider: OpenAIChatProvider) -> None:
}
)
- body = nebius_provider._build_request_body(
+ body = nebius_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_novita.py b/tests/providers/test_novita.py
index 3909fc32..8b204366 100644
--- a/tests/providers/test_novita.py
+++ b/tests/providers/test_novita.py
@@ -52,7 +52,7 @@ def test_build_request_body_openai_chat_shape(novita_provider):
system="System prompt",
)
- body = novita_provider._build_request_body(
+ body = novita_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -70,7 +70,7 @@ def test_build_request_body_default_max_tokens(novita_provider):
messages=[Message(role="user", content="x")],
)
- body = novita_provider._build_request_body(
+ body = novita_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -86,7 +86,7 @@ def test_build_request_body_preserves_validated_extra_body(novita_provider):
}
)
- body = novita_provider._build_request_body(
+ body = novita_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -105,7 +105,9 @@ def test_build_request_body_rejects_reserved_reasoning_extra_body_keys(
)
with pytest.raises(InvalidRequestError, match="extra_body must not override"):
- novita_provider._build_request_body(request, reasoning=reasoning_for(request))
+ novita_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
def test_build_request_body_disables_thinking_when_reasoning_off(novita_provider):
@@ -114,7 +116,7 @@ def test_build_request_body_disables_thinking_when_reasoning_off(novita_provider
messages=[Message(role="user", content="x")],
)
- body = novita_provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = novita_provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["extra_body"]["enable_thinking"] is False
@@ -125,7 +127,7 @@ def test_build_request_body_enables_thinking_when_reasoning_on(novita_provider):
messages=[Message(role="user", content="x")],
)
- body = novita_provider._build_request_body(request, reasoning=REASONING_ON)
+ body = novita_provider._chat._build_request_body(request, reasoning=REASONING_ON)
assert body["extra_body"]["enable_thinking"] is True
@@ -136,7 +138,7 @@ def test_build_request_body_omits_thinking_field_by_default(novita_provider):
messages=[Message(role="user", content="x")],
)
- body = novita_provider._build_request_body(
+ body = novita_provider._chat._build_request_body(
request, reasoning=ReasoningPolicy.provider_default()
)
diff --git a/tests/providers/test_nvidia_nim.py b/tests/providers/test_nvidia_nim.py
index 5084ce2d..caa8b6b3 100644
--- a/tests/providers/test_nvidia_nim.py
+++ b/tests/providers/test_nvidia_nim.py
@@ -19,6 +19,7 @@ from free_claude_code.core.openai_responses.models import OpenAIResponsesRequest
from free_claude_code.core.reasoning import ReasoningEffort, ReasoningPolicy
from free_claude_code.providers.admission import UPSTREAM_TRANSIENT_TOTAL_ATTEMPTS
from free_claude_code.providers.nvidia_nim import NvidiaNimProvider
+from free_claude_code.providers.nvidia_nim.client import _PROFILE as NIM_PROFILE
from free_claude_code.providers.nvidia_nim.tool_schema import (
NIM_TOOL_ARGUMENT_ALIASES_KEY,
)
@@ -168,7 +169,6 @@ def _alias_events():
],
)
async def test_argument_aliases_survive_request_corrections(wire, correction):
- provider = _alias_provider()
request = _alias_request(wire, reasoning_history=correction == "reasoning_content")
original = deepcopy(request.model_dump())
@@ -177,7 +177,11 @@ async def test_argument_aliases_survive_request_corrections(wire, correction):
return 400, {"message": f"Unsupported field: {correction}"}
return 200, _alias_events()
- async with _harness("chat", responder, chat_provider=provider) as (_, bodies):
+ async with _harness("chat", responder, chat_provider_factory=_alias_provider) as (
+ _,
+ bodies,
+ provider,
+ ):
stream = (
provider.stream_messages
if wire == "messages"
@@ -207,9 +211,14 @@ async def test_argument_aliases_survive_request_corrections(wire, correction):
@pytest.mark.asyncio
@pytest.mark.parametrize("early_sse", [False, True])
async def test_argument_aliases_survive_shared_history_correction(early_sse):
- provider = _alias_provider()
# Test adapter exercises the shared history path; native NIM disables details.
- provider._profile = replace(provider._profile, structured_reasoning_details=True)
+ def provider_factory():
+ with patch(
+ "free_claude_code.providers.nvidia_nim.client._PROFILE",
+ replace(NIM_PROFILE, structured_reasoning_details=True),
+ ):
+ return _alias_provider()
+
request = _alias_request()
request.messages.insert(
0,
@@ -232,7 +241,11 @@ async def test_argument_aliases_survive_shared_history_correction(early_sse):
return (200, [{"error": error}]) if early_sse else (400, error)
return 200, _alias_events()
- async with _harness("chat", responder, chat_provider=provider) as (_, bodies):
+ async with _harness("chat", responder, chat_provider_factory=provider_factory) as (
+ _,
+ bodies,
+ provider,
+ ):
saved = await _saved_reply(provider.stream_messages(request), "messages")
call = next(block for block in saved[0]["content"] if block["type"] == "tool_use")
assert call["input"] == {"pattern": "needle", "type": "py"}
@@ -330,7 +343,7 @@ def _make_internal_server_error(message: str) -> openai.InternalServerError:
async def test_init(provider_config):
"""Test provider initialization."""
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = NvidiaNimProvider(
provider_config,
@@ -354,7 +367,7 @@ async def test_init_uses_configurable_timeouts():
http_connect_timeout=5.0,
)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
NvidiaNimProvider(
config, nim_settings=NimSettings(), admission=immediate_admission()
@@ -375,7 +388,7 @@ async def test_build_request_body(provider_config):
admission=immediate_admission(),
)
req = make_request()
- body = provider._build_request_body(req, reasoning=reasoning_for(req))
+ body = provider._chat._build_request_body(req, reasoning=reasoning_for(req))
assert body["model"] == "test-model"
assert body["temperature"] == 0.5
@@ -417,7 +430,9 @@ def test_responses_request_uses_nim_chat_policy(provider_config):
}
)
- translated = provider._build_responses_request_body(request, reasoning=REASONING_ON)
+ translated = provider._chat._build_responses_request_body(
+ request, reasoning=REASONING_ON
+ )
body = translated.body
tools = body["tools"]
@@ -454,7 +469,7 @@ async def test_build_request_body_encodes_explicit_reasoning_off(
admission=immediate_admission(),
)
req = make_request()
- body = provider._build_request_body(req, reasoning=REASONING_OFF)
+ body = provider._chat._build_request_body(req, reasoning=REASONING_OFF)
extra = body.get("extra_body", {})
assert extra["chat_template_kwargs"] == {
@@ -475,7 +490,7 @@ async def test_build_request_body_omits_reasoning_when_request_disables_thinking
)
req = make_request()
req.thinking.enabled = False
- body = provider._build_request_body(req)
+ body = provider._chat._build_request_body(req)
extra = body.get("extra_body", {})
assert "chat_template_kwargs" not in extra
@@ -513,7 +528,7 @@ def test_preflight_and_build_request_issue_206_post_tool_text(nim_provider):
],
)
nim_provider.preflight_messages(req, reasoning=REASONING_OFF)
- body = nim_provider._build_request_body(req, reasoning=REASONING_OFF)
+ body = nim_provider._chat._build_request_body(req, reasoning=REASONING_OFF)
assert "messages" in body
assert any(m.get("role") == "tool" for m in body["messages"])
diff --git a/tests/providers/test_nvidia_nim_degraded_retry.py b/tests/providers/test_nvidia_nim_degraded_retry.py
index c1912b92..13d0db90 100644
--- a/tests/providers/test_nvidia_nim_degraded_retry.py
+++ b/tests/providers/test_nvidia_nim_degraded_retry.py
@@ -169,7 +169,7 @@ async def test_degraded_function_exhaustion_is_detailed_redacted_overload() -> N
new_callable=AsyncMock,
side_effect=error,
) as create,
- patch("free_claude_code.providers.openai_chat.provider.trace_event") as trace,
+ patch("free_claude_code.providers.openai_chat.transport.trace_event") as trace,
pytest.raises(ExecutionFailure) as exc_info,
):
[
diff --git a/tests/providers/test_ollama.py b/tests/providers/test_ollama.py
index 789910de..c2c1a15e 100644
--- a/tests/providers/test_ollama.py
+++ b/tests/providers/test_ollama.py
@@ -55,7 +55,7 @@ def _cloud_provider() -> OpenAIChatProvider:
)
def test_init_normalizes_openai_base_url(configured: str, expected: str) -> None:
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as openai_client:
provider = _provider(configured)
@@ -67,7 +67,7 @@ def test_init_normalizes_openai_base_url(configured: str, expected: str) -> None
def test_cloud_init_uses_fixed_openai_endpoint_and_api_key() -> None:
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as openai_client:
provider = _cloud_provider()
@@ -79,7 +79,7 @@ def test_cloud_init_uses_fixed_openai_endpoint_and_api_key() -> None:
def test_build_request_body_uses_openai_chat_shape() -> None:
- body = _provider()._build_request_body(make_messages_request(OLLAMA_MODEL))
+ body = _provider()._chat._build_request_body(make_messages_request(OLLAMA_MODEL))
assert body["model"] == OLLAMA_MODEL
assert body["messages"][0]["role"] == "system"
@@ -92,7 +92,7 @@ def test_cloud_build_request_body_forwards_client_reasoning_effort() -> None:
request = make_messages_request(
OLLAMA_CLOUD_MODEL, output_config={"effort": "high"}
)
- body = _cloud_provider()._build_request_body(
+ body = _cloud_provider()._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -129,7 +129,7 @@ def test_cloud_build_request_body_replays_thinking_in_ollama_reasoning_field() -
],
)
- body = _cloud_provider()._build_request_body(
+ body = _cloud_provider()._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -156,7 +156,7 @@ def test_replay_is_independent_of_disabled_current_turn_reasoning(provider) -> N
],
)
- body = provider()._build_request_body(request, reasoning=REASONING_OFF)
+ body = provider()._chat._build_request_body(request, reasoning=REASONING_OFF)
assistant = next(
message for message in body["messages"] if message["role"] == "assistant"
)
diff --git a/tests/providers/test_open_router.py b/tests/providers/test_open_router.py
index 76339b46..a82d290b 100644
--- a/tests/providers/test_open_router.py
+++ b/tests/providers/test_open_router.py
@@ -86,7 +86,7 @@ def test_init_uses_openai_chat_provider(open_router_provider):
def test_build_request_body_uses_openai_chat_shape(open_router_provider):
- body = open_router_provider._build_request_body(make_request())
+ body = open_router_provider._chat._build_request_body(make_request())
assert body["model"] == "moonshotai/kimi-k2.6:free"
assert body["temperature"] == 0.5
@@ -99,7 +99,7 @@ def test_build_request_body_uses_openai_chat_shape(open_router_provider):
def test_build_request_body_default_max_tokens(open_router_provider):
- body = open_router_provider._build_request_body(make_request(max_tokens=None))
+ body = open_router_provider._chat._build_request_body(make_request(max_tokens=None))
assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
@@ -108,13 +108,13 @@ def test_openrouter_extra_body_rejects_overriding_reserved_fields(
open_router_provider,
):
with pytest.raises(InvalidRequestError, match="model"):
- open_router_provider._build_request_body(
+ open_router_provider._chat._build_request_body(
make_request(extra_body={"model": "hijack"})
)
def test_openrouter_extra_body_allows_provider_keys(open_router_provider):
- body = open_router_provider._build_request_body(
+ body = open_router_provider._chat._build_request_body(
make_request(extra_body={"transforms": ["no-web"], "plugins": []}),
reasoning=REASONING_OFF,
)
@@ -130,7 +130,7 @@ def test_build_request_body_disables_reasoning_when_client_disables_it(
open_router_provider,
):
request = make_request(thinking={"type": "disabled"})
- body = open_router_provider._build_request_body(
+ body = open_router_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -141,7 +141,7 @@ def test_build_request_body_maps_thinking_budget_to_reasoning_max_tokens(
open_router_provider,
):
request = make_request(thinking={"type": "enabled", "budget_tokens": 4096})
- body = open_router_provider._build_request_body(
+ body = open_router_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -171,7 +171,7 @@ def test_build_request_body_replays_openrouter_reasoning_details(
}
)
- body = open_router_provider._build_request_body(
+ body = open_router_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -226,7 +226,7 @@ def test_reasoning_details_skip_neutral_tool_turn_boundary(open_router_provider)
}
)
- body = open_router_provider._build_request_body(
+ body = open_router_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
@@ -287,7 +287,7 @@ def test_reasoning_details_preserve_redacted_only_assistant_after_tool(
}
)
- body = open_router_provider._build_request_body(
+ body = open_router_provider._chat._build_request_body(
request, reasoning=reasoning_for(request)
)
diff --git a/tests/providers/test_openai_chat_output_cap.py b/tests/providers/test_openai_chat_output_cap.py
index 684152b3..3e044842 100644
--- a/tests/providers/test_openai_chat_output_cap.py
+++ b/tests/providers/test_openai_chat_output_cap.py
@@ -240,7 +240,7 @@ def groq_provider():
@pytest.mark.asyncio
async def test_create_stream_clamps_and_learns_on_cap_rejection(groq_provider):
- body = groq_provider._build_request_body(
+ body = groq_provider._chat._build_request_body(
make_messages_request(
"llama-3.3-70b-versatile",
max_tokens=64000,
@@ -265,7 +265,12 @@ async def test_create_stream_clamps_and_learns_on_cap_rejection(groq_provider):
create = AsyncMock(side_effect=[error, object()])
with patch.object(groq_provider._client.chat.completions, "create", create):
- _stream, used_body, attempt, _sent_body = await groq_provider._create_stream(
+ (
+ _stream,
+ used_body,
+ attempt,
+ _sent_body,
+ ) = await groq_provider._chat._create_stream(
body,
groq_provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -275,12 +280,12 @@ async def test_create_stream_clamps_and_learns_on_cap_rejection(groq_provider):
assert create.call_count == 2
assert create.call_args_list[1].kwargs["max_completion_tokens"] == 16384
assert used_body["max_completion_tokens"] == 16384
- assert groq_provider._model_output_caps[model] == 16384
+ assert groq_provider._chat._model_output_caps[model] == 16384
@pytest.mark.asyncio
async def test_learned_cap_clamps_next_request_without_a_400(groq_provider):
- body = groq_provider._build_request_body(
+ body = groq_provider._chat._build_request_body(
make_messages_request(
"llama-3.3-70b-versatile",
max_tokens=64000,
@@ -288,11 +293,16 @@ async def test_learned_cap_clamps_next_request_without_a_400(groq_provider):
)
)
model = body["model"]
- groq_provider._model_output_caps[model] = 40960
+ groq_provider._chat._model_output_caps[model] = 40960
create = AsyncMock(return_value=object())
with patch.object(groq_provider._client.chat.completions, "create", create):
- _stream, used_body, attempt, _sent_body = await groq_provider._create_stream(
+ (
+ _stream,
+ used_body,
+ attempt,
+ _sent_body,
+ ) = await groq_provider._chat._create_stream(
body,
groq_provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
@@ -306,7 +316,7 @@ async def test_learned_cap_clamps_next_request_without_a_400(groq_provider):
@pytest.mark.asyncio
async def test_unrelated_400_is_not_clamped_and_propagates(groq_provider):
- body = groq_provider._build_request_body(
+ body = groq_provider._chat._build_request_body(
make_messages_request(
"llama-3.3-70b-versatile",
max_tokens=100,
@@ -319,19 +329,19 @@ async def test_unrelated_400_is_not_clamped_and_propagates(groq_provider):
patch.object(groq_provider._client.chat.completions, "create", create),
pytest.raises(Exception, match="wizard"),
):
- await groq_provider._create_stream(
+ await groq_provider._chat._create_stream(
body,
groq_provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
)
assert create.call_count == 1
- assert groq_provider._model_output_caps == {}
+ assert groq_provider._chat._model_output_caps == {}
@pytest.mark.asyncio
async def test_mixed_field_400_does_not_retry_or_poison_learned_cap(groq_provider):
- body = groq_provider._build_request_body(
+ body = groq_provider._chat._build_request_body(
make_messages_request(
"llama-3.3-70b-versatile",
max_tokens=64000,
@@ -353,11 +363,11 @@ async def test_mixed_field_400_does_not_retry_or_poison_learned_cap(groq_provide
patch.object(groq_provider._client.chat.completions, "create", create),
pytest.raises(Exception, match="temperature"),
):
- await groq_provider._create_stream(
+ await groq_provider._chat._create_stream(
body,
groq_provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
)
assert create.call_count == 1
- assert groq_provider._model_output_caps == {}
+ assert groq_provider._chat._model_output_caps == {}
diff --git a/tests/providers/test_openai_chat_transport.py b/tests/providers/test_openai_chat_transport.py
new file mode 100644
index 00000000..d8f8bfba
--- /dev/null
+++ b/tests/providers/test_openai_chat_transport.py
@@ -0,0 +1,154 @@
+"""Chat execution borrows HTTP resources and releases shared admission."""
+
+import asyncio
+import json
+from collections.abc import AsyncIterator
+
+import httpx2
+import pytest
+from openai import AsyncOpenAI
+
+from free_claude_code.core.anthropic import ReasoningReplayMode
+from free_claude_code.core.failures import ExecutionFailure
+from free_claude_code.core.openai_responses import OpenAIResponsesRequest
+from free_claude_code.providers.admission import ProviderAdmissionController
+from free_claude_code.providers.openai_chat import (
+ NO_REASONING,
+ OpenAIChatBehavior,
+ OpenAIChatProfile,
+ OpenAIChatRequestPolicy,
+ OpenAIChatTransport,
+)
+from tests.providers.request_factory import make_messages_request
+
+pytestmark = pytest.mark.asyncio
+
+
+def _transport(client: AsyncOpenAI) -> OpenAIChatTransport:
+ return OpenAIChatTransport(
+ client=client,
+ admission=ProviderAdmissionController(
+ provider_name="TEST",
+ rate_limit=100,
+ rate_window=1,
+ max_concurrency=1,
+ max_attempts=1,
+ ),
+ behavior=OpenAIChatBehavior(
+ OpenAIChatProfile(
+ OpenAIChatRequestPolicy("TEST", ReasoningReplayMode.DISABLED),
+ NO_REASONING,
+ )
+ ),
+ read_timeout_s=2,
+ log_raw_sse_events=False,
+ log_api_error_tracebacks=False,
+ )
+
+
+def _success() -> httpx2.Response:
+ chunk = {
+ "id": "chat_test",
+ "object": "chat.completion.chunk",
+ "created": 0,
+ "model": "model",
+ "choices": [
+ {"index": 0, "delta": {"content": "hello"}, "finish_reason": "stop"}
+ ],
+ }
+ return httpx2.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ text=f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n",
+ )
+
+
+async def _consume(transport: OpenAIChatTransport, wire: str) -> str:
+ stream = (
+ transport.stream_messages(make_messages_request("model"))
+ if wire == "messages"
+ else transport.stream_responses(
+ OpenAIResponsesRequest(model="model", input="hello")
+ )
+ )
+ return "".join([event async for event in stream])
+
+
[email protected]("wire", ["messages", "responses"])
+async def test_borrowed_client_remains_usable_after_failed_and_successful_turns(wire):
+ calls = 0
+
+ def reply(request: httpx2.Request) -> httpx2.Response:
+ nonlocal calls
+ if request.url.path.endswith("/models"):
+ return httpx2.Response(200, json={"data": [{"id": "model"}]})
+ calls += 1
+ if calls == 1:
+ return httpx2.Response(401, json={"error": {"message": "expired"}})
+ return _success()
+
+ async with AsyncOpenAI(
+ api_key="test",
+ base_url="https://provider.invalid/v1",
+ max_retries=0,
+ http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(reply)),
+ ) as client:
+ transport = _transport(client)
+ with pytest.raises(ExecutionFailure):
+ await _consume(transport, wire)
+ async with asyncio.timeout(2):
+ assert "hello" in await _consume(transport, wire)
+ assert not client.is_closed()
+ assert (await client.models.list()).data[0].id == "model"
+ assert calls == 2
+
+
[email protected]("wire", ["messages", "responses"])
+async def test_cancelled_turn_closes_its_stream_and_releases_admission(wire):
+ reading = asyncio.Event()
+ closed = asyncio.Event()
+
+ class BlockedStream(httpx2.AsyncByteStream):
+ async def __aiter__(self) -> AsyncIterator[bytes]:
+ reading.set()
+ await asyncio.Event().wait()
+ yield b""
+
+ async def aclose(self) -> None:
+ closed.set()
+
+ calls = 0
+
+ def reply(request: httpx2.Request) -> httpx2.Response:
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ return httpx2.Response(
+ 200,
+ headers={"content-type": "text/event-stream"},
+ stream=BlockedStream(),
+ )
+ return _success()
+
+ async with AsyncOpenAI(
+ api_key="test",
+ base_url="https://provider.invalid/v1",
+ max_retries=0,
+ http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(reply)),
+ ) as client:
+ transport = _transport(client)
+ task = asyncio.create_task(_consume(transport, wire))
+ try:
+ async with asyncio.timeout(2):
+ await reading.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert closed.is_set()
+ assert not client.is_closed()
+ # One concurrency slot: this hangs if the cancelled attempt retains it.
+ async with asyncio.timeout(2):
+ assert "hello" in await _consume(transport, wire)
+ finally:
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
diff --git a/tests/providers/test_openai_chat_usage.py b/tests/providers/test_openai_chat_usage.py
index f94a20c5..7c3471b1 100644
--- a/tests/providers/test_openai_chat_usage.py
+++ b/tests/providers/test_openai_chat_usage.py
@@ -9,7 +9,6 @@ import pytest
from httpx2 import Request, Response
from openai.types.completion_usage import CompletionUsage, PromptTokensDetails
-from free_claude_code.application.model_metadata import ProviderModelInfo
from free_claude_code.core.anthropic import ReasoningReplayMode
from free_claude_code.core.anthropic.models import MessagesRequest
from free_claude_code.core.anthropic.sse_aggregation import (
@@ -20,6 +19,7 @@ from free_claude_code.core.openai_responses import OpenAIResponsesRequest
from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy
from free_claude_code.providers.admission import ProviderOperationKind
from free_claude_code.providers.openai_chat import (
+ OpenAIChatBehavior,
OpenAIChatProfile,
OpenAIChatProvider,
OpenAIChatRequestPolicy,
@@ -38,6 +38,16 @@ from tests.providers.support import (
)
+class _UsageTestBehavior(OpenAIChatBehavior):
+ def build_messages_body(
+ self,
+ request: MessagesRequest,
+ *,
+ reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
+ ) -> dict:
+ return {"model": request.model, "messages": [{"role": "user", "content": "x"}]}
+
+
class _UsageTestProvider(OpenAIChatProvider):
def __init__(self):
super().__init__(
@@ -47,25 +57,18 @@ class _UsageTestProvider(OpenAIChatProvider):
rate_limit=100,
rate_window=60,
),
- profile=OpenAIChatProfile(
- OpenAIChatRequestPolicy(
- provider_name="USAGE_TEST",
- reasoning_replay=ReasoningReplayMode.DISABLED,
- ),
- NO_REASONING,
+ behavior=_UsageTestBehavior(
+ OpenAIChatProfile(
+ OpenAIChatRequestPolicy(
+ provider_name="USAGE_TEST",
+ reasoning_replay=ReasoningReplayMode.DISABLED,
+ ),
+ NO_REASONING,
+ )
),
admission=immediate_admission(),
)
- def _build_request_body(
- self,
- request: MessagesRequest,
- *,
- reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
- model_info: ProviderModelInfo | None = None,
- ) -> dict:
- return {"model": request.model, "messages": [{"role": "user", "content": "x"}]}
-
def _bad_request(message: str, body: object | None = None) -> openai.BadRequestError:
response = Response(
@@ -190,7 +193,7 @@ def test_usage_int_reads_dict_object_and_model_extra():
def test_extracts_standard_chat_cache_write_tokens(usage, expected) -> None:
provider = _UsageTestProvider()
- assert provider._cache_write_input_tokens(usage) == expected
+ assert provider._behavior.cache_write_input_tokens(usage) == expected
@pytest.mark.parametrize(
@@ -279,7 +282,7 @@ def test_extracts_standard_chat_cache_write_tokens(usage, expected) -> None:
def test_maps_standard_chat_cache_usage_to_anthropic_fields(usage, expected):
provider = _UsageTestProvider()
- assert provider._anthropic_usage_fields(usage) == expected
+ assert provider._behavior.anthropic_usage_fields(usage) == expected
@pytest.mark.parametrize(
@@ -332,7 +335,7 @@ def test_maps_standard_chat_cache_usage_to_anthropic_fields(usage, expected):
def test_ignores_incomplete_or_inconsistent_standard_cache_usage(usage):
provider = _UsageTestProvider()
- assert provider._anthropic_usage_fields(usage) == {}
+ assert provider._behavior.anthropic_usage_fields(usage) == {}
def test_stream_usage_rejection_matches_usage_option_400():
@@ -535,7 +538,12 @@ async def test_openai_chat_stream_retries_without_usage_when_option_is_rejected(
)
with patch.object(provider._client.chat.completions, "create", create):
- _stream_obj, used_body, attempt, _sent_body = await provider._create_stream(
+ (
+ _stream_obj,
+ used_body,
+ attempt,
+ _sent_body,
+ ) = await provider._chat._create_stream(
body,
provider._admission.start_execution(),
ProviderOperationKind.GENERATION,
diff --git a/tests/providers/test_openai_compat_5xx_retry.py b/tests/providers/test_openai_compat_5xx_retry.py
index 81a7e8f1..86cc0894 100644
--- a/tests/providers/test_openai_compat_5xx_retry.py
+++ b/tests/providers/test_openai_compat_5xx_retry.py
@@ -148,7 +148,7 @@ async def test_nim_stream_connection_error_exhausted_emits_cause_chain():
new_callable=AsyncMock,
side_effect=error,
) as mock_create,
- patch("free_claude_code.providers.openai_chat.provider.trace_event") as trace,
+ patch("free_claude_code.providers.openai_chat.transport.trace_event") as trace,
pytest.raises(ExecutionFailure) as exc_info,
):
[e async for e in provider.stream_messages(req, request_id="req_conn")]
diff --git a/tests/providers/test_openai_responses_transport.py b/tests/providers/test_openai_responses_transport.py
index 2247c4ef..103adbe9 100644
--- a/tests/providers/test_openai_responses_transport.py
+++ b/tests/providers/test_openai_responses_transport.py
@@ -170,9 +170,11 @@ def _sse(*events: Mapping[str, object]) -> str:
def _client(
handler: Callable[[httpx2.Request], httpx2.Response],
+ *,
+ api_key: str = "test-key",
) -> AsyncOpenAI:
return AsyncOpenAI(
- api_key="test-key",
+ api_key=api_key,
base_url="https://provider.invalid/v1",
max_retries=0,
http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(handler)),
diff --git a/tests/providers/test_opencode.py b/tests/providers/test_opencode.py
index 6fc37026..12951dd9 100644
--- a/tests/providers/test_opencode.py
+++ b/tests/providers/test_opencode.py
@@ -262,7 +262,7 @@ def _provider_with_wire_transports(
),
)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
return_value=generation_client,
):
provider = create_opencode_provider(
@@ -313,7 +313,7 @@ def test_client_identifies_as_first_party_opencode_user_agent(
) -> None:
with (
patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai,
patch("httpx.AsyncClient"),
):
@@ -1258,7 +1258,7 @@ def test_build_request_body_replays_tool_reasoning_natively(
provider_id: str,
) -> None:
with (
- patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"),
+ patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"),
patch("httpx.AsyncClient"),
):
provider = create_opencode_provider(
@@ -1301,7 +1301,7 @@ def test_build_request_body_replays_tool_reasoning_natively(
}
)
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
assistant = body["messages"][0]
assert assistant["content"] == ""
@@ -1321,7 +1321,7 @@ async def test_tool_only_history_sends_empty_reasoning_content_on_wire(
provider_id: str,
) -> None:
with (
- patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"),
+ patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"),
patch("httpx.AsyncClient"),
):
provider = create_opencode_provider(
@@ -1358,7 +1358,7 @@ async def test_tool_only_history_sends_empty_reasoning_content_on_wire(
}
)
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
wire = await capture_openai_chat_wire_body(body)
assistant = wire["messages"][0]
diff --git a/tests/providers/test_poolside.py b/tests/providers/test_poolside.py
index 4c81fa4c..49eadc81 100644
--- a/tests/providers/test_poolside.py
+++ b/tests/providers/test_poolside.py
@@ -59,7 +59,7 @@ def test_encodes_documented_chat_template_thinking_control(
reasoning: ReasoningPolicy,
enabled: bool,
) -> None:
- body = poolside_provider._build_request_body(
+ body = poolside_provider._chat._build_request_body(
_request(extra_body={"top_k": 20}),
reasoning=reasoning,
)
@@ -74,7 +74,7 @@ def test_encodes_documented_chat_template_thinking_control(
def test_omits_thinking_control_for_poolside_default(
poolside_provider: OpenAIChatProvider,
) -> None:
- body = poolside_provider._build_request_body(
+ body = poolside_provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.provider_default(),
)
@@ -93,7 +93,7 @@ def test_rejects_caller_reasoning_override(
request = _request(extra_body={field: "caller-owned"})
with pytest.raises(InvalidRequestError, match="must not override reasoning"):
- poolside_provider._build_request_body(request, reasoning=REASONING_ON)
+ poolside_provider._chat._build_request_body(request, reasoning=REASONING_ON)
def test_replays_reasoning_content_with_tool_history(
@@ -128,7 +128,7 @@ def test_replays_reasoning_content_with_tool_history(
]
)
- body = poolside_provider._build_request_body(
+ body = poolside_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -165,7 +165,7 @@ def test_replays_reasoning_content_with_tool_history(
async def test_thinking_control_reaches_wire_as_top_level_extension(
poolside_provider: OpenAIChatProvider,
) -> None:
- body = poolside_provider._build_request_body(
+ body = poolside_provider._chat._build_request_body(
_request(),
reasoning=REASONING_OFF,
)
diff --git a/tests/providers/test_preflight_contract.py b/tests/providers/test_preflight_contract.py
index 0caa66b1..561903a5 100644
--- a/tests/providers/test_preflight_contract.py
+++ b/tests/providers/test_preflight_contract.py
@@ -1,27 +1,40 @@
"""The shared OpenAI-chat provider owns explicit request preflight."""
from collections.abc import AsyncIterator, Mapping
+from unittest.mock import MagicMock
import pytest
from free_claude_code.application.model_metadata import ProviderModelInfo
+from free_claude_code.core.anthropic import ReasoningReplayMode
from free_claude_code.core.anthropic.models import Message, MessagesRequest
from free_claude_code.core.reasoning import DEFAULT_REASONING_POLICY, ReasoningPolicy
from free_claude_code.providers.base import BaseProvider
-from free_claude_code.providers.openai_chat import OpenAIChatProvider
-from tests.providers.support import make_provider_config
+from free_claude_code.providers.openai_chat import (
+ NO_REASONING,
+ OpenAIChatBehavior,
+ OpenAIChatProfile,
+ OpenAIChatProvider,
+ OpenAIChatRequestPolicy,
+)
+from tests.providers.support import immediate_admission, make_provider_config
-class RecordingOpenAIProvider(OpenAIChatProvider):
+class RecordingChatBehavior(OpenAIChatBehavior):
def __init__(self) -> None:
+ super().__init__(
+ OpenAIChatProfile(
+ OpenAIChatRequestPolicy("TEST", ReasoningReplayMode.DISABLED),
+ NO_REASONING,
+ )
+ )
self.build_calls: list[tuple[MessagesRequest, ReasoningPolicy]] = []
- def _build_request_body(
+ def build_messages_body(
self,
request: MessagesRequest,
*,
reasoning: ReasoningPolicy = DEFAULT_REASONING_POLICY,
- model_info: ProviderModelInfo | None = None,
) -> dict:
self.build_calls.append((request, reasoning))
return {}
@@ -61,7 +74,13 @@ def test_openai_provider_owns_preflight() -> None:
def test_provider_preflight_calls_builder_and_preserves_policy() -> None:
- provider = RecordingOpenAIProvider()
+ behavior = RecordingChatBehavior()
+ provider = OpenAIChatProvider(
+ make_provider_config(api_key="test", base_url="https://test.invalid"),
+ behavior=behavior,
+ admission=immediate_admission(),
+ client=MagicMock(),
+ )
request = MessagesRequest(
model="test-model",
messages=[Message(role="user", content="hello")],
@@ -69,4 +88,4 @@ def test_provider_preflight_calls_builder_and_preserves_policy() -> None:
provider.preflight_messages(request, reasoning=ReasoningPolicy.off())
- assert provider.build_calls == [(request, ReasoningPolicy.off())]
+ assert behavior.build_calls == [(request, ReasoningPolicy.off())]
diff --git a/tests/providers/test_provider_client_tool_discovery.py b/tests/providers/test_provider_client_tool_discovery.py
index ad6dede6..33d01ff2 100644
--- a/tests/providers/test_provider_client_tool_discovery.py
+++ b/tests/providers/test_provider_client_tool_discovery.py
@@ -1,5 +1,6 @@
import json
from typing import Any, cast
+from unittest.mock import patch
import httpx2
import pytest
@@ -229,26 +230,34 @@ async def test_provider_discovery_call_and_result_round_trip(
_catalog_payload(), generation_response=upstream
)
else:
- provider = cast(
- OpenAIChatProvider,
- create_provider(
- provider_id,
- Settings(
- open_router_api_key="test",
- nvidia_nim_api_key="test",
- groq_api_key="test",
- mistral_api_key="test",
- ),
- ),
- )
- provider._admission = immediate_admission(provider_name=provider_id)
- await provider._client.close()
- provider._client = AsyncOpenAI(
+ client = AsyncOpenAI(
api_key="test",
base_url="https://provider.test/v1",
http_client=httpx2.AsyncClient(transport=httpx2.MockTransport(upstream)),
max_retries=0,
)
+ with (
+ patch(
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
+ return_value=client,
+ ),
+ patch(
+ "free_claude_code.providers.runtime.factory.ProviderAdmissionController",
+ return_value=immediate_admission(provider_name=provider_id),
+ ),
+ ):
+ provider = cast(
+ OpenAIChatProvider,
+ create_provider(
+ provider_id,
+ Settings(
+ open_router_api_key="test",
+ nvidia_nim_api_key="test",
+ groq_api_key="test",
+ mistral_api_key="test",
+ ),
+ ),
+ )
history: list[dict[str, Any]] = [
{"role": "user", "content": "Find a tool and use it"}
]
diff --git a/tests/providers/test_provider_runtime.py b/tests/providers/test_provider_runtime.py
index 7e654bd6..fe149e6a 100644
--- a/tests/providers/test_provider_runtime.py
+++ b/tests/providers/test_provider_runtime.py
@@ -245,7 +245,7 @@ def test_poolside_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("poolside", settings)
assert descriptor.display_name == "Poolside AI"
@@ -269,7 +269,7 @@ def test_llm7_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("llm7", settings)
assert descriptor.display_name == "LLM7.io"
@@ -293,7 +293,7 @@ def test_xai_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("xai", settings)
assert descriptor.display_name == "xAI (Grok)"
@@ -312,7 +312,7 @@ def test_qwencloud_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("qwencloud", settings)
assert descriptor.display_name == "QwenCloud Token Plan"
@@ -331,7 +331,7 @@ def test_cline_pass_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("cline_pass", settings)
assert descriptor.display_name == "ClinePass"
@@ -354,7 +354,7 @@ def test_qwencloud_coding_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("qwencloud_coding", settings)
assert descriptor.display_name == "QwenCloud Coding Plan"
@@ -373,7 +373,7 @@ def test_together_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("together", settings)
assert descriptor.display_name == "Together AI"
@@ -392,7 +392,7 @@ def test_deepinfra_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("deepinfra", settings)
assert descriptor.display_name == "DeepInfra"
@@ -411,7 +411,7 @@ def test_siliconflow_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("siliconflow", settings)
assert descriptor.display_name == "SiliconFlow"
@@ -431,7 +431,7 @@ def test_nebius_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("nebius", settings)
assert descriptor.display_name == "Nebius Token Factory"
@@ -454,7 +454,7 @@ def test_chutes_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("chutes", settings)
assert descriptor.display_name == "Chutes"
@@ -477,7 +477,7 @@ def test_featherless_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("featherless", settings)
assert descriptor.display_name == "Featherless AI"
@@ -498,7 +498,7 @@ def test_agnes_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("agnes", settings)
assert descriptor.display_name == "Agnes AI"
@@ -518,7 +518,7 @@ def test_zenmux_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("zenmux", settings)
assert descriptor.display_name == "ZenMux"
@@ -538,7 +538,7 @@ def test_wandb_provider_config_uses_key_base_and_proxy() -> None:
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("wandb", settings)
assert descriptor.display_name == "W&B Inference"
@@ -620,7 +620,7 @@ def test_local_provider_factory_resolves_catalog_static_credential(
settings = _make_settings()
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider(provider_id, settings)
assert config.api_key == expected_api_key
@@ -655,7 +655,7 @@ def test_zai_api_provider_config_uses_shared_key_general_base_and_own_proxy():
)
config = build_provider_config(descriptor, settings)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("zai_api", settings)
assert descriptor.display_name == "Z.ai API"
@@ -706,7 +706,7 @@ def test_create_cloudflare_provider_uses_account_scoped_base_url():
cloudflare_account_id="test-account",
)
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("cloudflare", settings)
assert isinstance(provider, CloudflareProvider)
@@ -720,10 +720,10 @@ def test_opencode_zen_provider_config_uses_explicit_id_and_name():
provider = create_provider("opencode_zen", _make_settings())
assert isinstance(provider, OpenCodeProvider)
- assert provider._base_url == "https://opencode.ai/zen/v1"
- assert provider._provider_name == "OPENCODE_ZEN"
- assert provider._api_key == "test_opencode_key"
- assert provider._responses._admission is provider._admission
+ assert str(provider._client.base_url).rstrip("/") == "https://opencode.ai/zen/v1"
+ assert provider._opencode_profile.provider_name == "OPENCODE_ZEN"
+ assert provider._client.api_key == "test_opencode_key"
+ assert provider._responses._admission is provider._chat._admission
def test_opencode_go_provider_config_uses_correct_base_url_and_name():
@@ -731,10 +731,10 @@ def test_opencode_go_provider_config_uses_correct_base_url_and_name():
provider = create_provider("opencode_go", _make_settings())
assert isinstance(provider, OpenCodeProvider)
- assert provider._base_url == "https://opencode.ai/zen/go/v1"
- assert provider._provider_name == "OPENCODE_GO"
- assert provider._api_key == "test_opencode_key"
- assert provider._responses._admission is provider._admission
+ assert str(provider._client.base_url).rstrip("/") == "https://opencode.ai/zen/go/v1"
+ assert provider._opencode_profile.provider_name == "OPENCODE_GO"
+ assert provider._client.api_key == "test_opencode_key"
+ assert provider._responses._admission is provider._chat._admission
def test_opencode_go_catalog_uses_opencode_api_key() -> None:
@@ -817,7 +817,7 @@ def test_build_provider_config_cohere_uses_api_key_and_proxy() -> None:
def test_create_provider_uses_openai_chat_openrouter_by_default():
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = create_provider("open_router", _make_settings())
assert isinstance(provider, OpenRouterProvider)
@@ -913,7 +913,7 @@ def test_create_provider_instantiates_each_builtin():
}
with (
- patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"),
+ patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"),
patch("free_claude_code.providers.github_copilot.provider.AsyncOpenAI"),
patch("free_claude_code.providers.openai_codex.provider.AsyncOpenAI"),
patch("httpx.AsyncClient"),
@@ -930,7 +930,11 @@ def test_create_provider_instantiates_each_builtin():
)
assert isinstance(provider, provider_cls)
- assert provider._admission is sentinel_admission
+ if isinstance(provider, OpenCodeProvider):
+ assert provider._chat._admission is sentinel_admission
+ assert provider._responses._admission is sentinel_admission
+ else:
+ assert provider._admission is sentinel_admission
admission_factory.assert_called_once_with(
provider_name=provider_id,
rate_limit=7,
@@ -945,7 +949,7 @@ def test_create_provider_instantiates_each_builtin():
def test_provider_runtime_caches_by_provider_id():
runtime = ProviderRuntime(_make_settings())
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
first = runtime.resolve_provider("nvidia_nim")
second = runtime.resolve_provider("nvidia_nim")
@@ -955,7 +959,7 @@ def test_provider_runtime_caches_by_provider_id():
def test_provider_runtime_provider_owns_one_admission_controller() -> None:
runtime = ProviderRuntime(_make_settings())
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
first = runtime.resolve_provider("nvidia_nim")
second = runtime.resolve_provider("nvidia_nim")
@@ -968,7 +972,7 @@ def test_separate_provider_runtimes_never_share_admission_controllers() -> None:
first_runtime = ProviderRuntime(_make_settings())
second_runtime = ProviderRuntime(_make_settings())
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
first = first_runtime.resolve_provider("nvidia_nim")
second = second_runtime.resolve_provider("nvidia_nim")
@@ -981,7 +985,7 @@ def test_separate_provider_runtimes_never_share_admission_controllers() -> None:
def test_different_providers_have_independent_admission_controllers() -> None:
runtime = ProviderRuntime(_make_settings())
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
nim = runtime.resolve_provider("nvidia_nim")
open_router = runtime.resolve_provider("open_router")
diff --git a/tests/providers/test_provider_transport_logging.py b/tests/providers/test_provider_transport_logging.py
index 674e02f3..355f9952 100644
--- a/tests/providers/test_provider_transport_logging.py
+++ b/tests/providers/test_provider_transport_logging.py
@@ -34,7 +34,7 @@ async def test_stream_failure_default_logs_exclude_exception_text(caplog) -> Non
provider = _provider()
with (
patch.object(
- provider,
+ provider._chat,
"_create_stream",
new_callable=AsyncMock,
side_effect=RuntimeError("SECRET_OPENAI_COMPAT"),
@@ -58,7 +58,7 @@ async def test_stream_failure_default_logs_cause_types_only(caplog) -> None:
error.__cause__ = httpx2.ConnectError("SECRET_CAUSE_DETAIL")
with (
patch.object(
- provider,
+ provider._chat,
"_create_stream",
new_callable=AsyncMock,
side_effect=error,
@@ -79,7 +79,7 @@ async def test_stream_failure_verbose_traceback_redacts_credentials(caplog) -> N
provider = _provider(verbose=True)
with (
patch.object(
- provider,
+ provider._chat,
"_create_stream",
new_callable=AsyncMock,
side_effect=RuntimeError(
diff --git a/tests/providers/test_qwencloud.py b/tests/providers/test_qwencloud.py
index e6852b37..03738553 100644
--- a/tests/providers/test_qwencloud.py
+++ b/tests/providers/test_qwencloud.py
@@ -81,7 +81,7 @@ def test_build_request_body_preserves_common_chat_tools_and_images(
}
)
- body = qwencloud_provider._build_request_body(
+ body = qwencloud_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -111,7 +111,7 @@ def test_build_request_body_does_not_invent_catalog_wide_reasoning_control(
}
)
- body = qwencloud_provider._build_request_body(request, reasoning=reasoning)
+ body = qwencloud_provider._chat._build_request_body(request, reasoning=reasoning)
extra_body = body.get("extra_body", {})
for field in (
@@ -144,7 +144,7 @@ def test_build_request_body_replays_prior_reasoning_content(
}
)
- body = qwencloud_provider._build_request_body(
+ body = qwencloud_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_qwencloud_coding.py b/tests/providers/test_qwencloud_coding.py
index 167e358f..7a3be809 100644
--- a/tests/providers/test_qwencloud_coding.py
+++ b/tests/providers/test_qwencloud_coding.py
@@ -79,7 +79,7 @@ def test_build_request_body_preserves_tools_and_images_without_inventing_a_cap(
}
)
- body = qwencloud_coding_provider._build_request_body(
+ body = qwencloud_coding_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -109,7 +109,7 @@ def test_build_request_body_preserves_explicit_client_cap(
}
)
- body = qwencloud_coding_provider._build_request_body(
+ body = qwencloud_coding_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -136,7 +136,9 @@ def test_build_request_body_does_not_invent_catalog_wide_reasoning_control(
}
)
- body = qwencloud_coding_provider._build_request_body(request, reasoning=reasoning)
+ body = qwencloud_coding_provider._chat._build_request_body(
+ request, reasoning=reasoning
+ )
extra_body = body.get("extra_body", {})
for field in (
@@ -172,7 +174,7 @@ def test_build_request_body_replays_prior_reasoning_content(
}
)
- body = qwencloud_coding_provider._build_request_body(
+ body = qwencloud_coding_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_sambanova.py b/tests/providers/test_sambanova.py
index f7fdbd8b..aa84e760 100644
--- a/tests/providers/test_sambanova.py
+++ b/tests/providers/test_sambanova.py
@@ -42,7 +42,7 @@ def test_default_base_url_constant():
def test_init_uses_default_base_url_and_api_key(sambanova_config):
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = profiled_provider(
"sambanova", sambanova_config, admission=immediate_admission()
@@ -56,7 +56,7 @@ def test_init_uses_default_base_url_and_api_key(sambanova_config):
def test_init_strips_trailing_slash(sambanova_config):
config = replace(sambanova_config, base_url=f"{SAMBANOVA_DEFAULT_BASE}/")
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = profiled_provider(
"sambanova", config, admission=immediate_admission()
)
@@ -66,7 +66,7 @@ def test_init_strips_trailing_slash(sambanova_config):
def test_build_request_body_basic(sambanova_provider):
"""Basic request body conversion attaches system message and keeps max_tokens."""
- body = sambanova_provider._build_request_body(make_request())
+ body = sambanova_provider._chat._build_request_body(make_request())
assert body["model"] == "Meta-Llama-3.3-70B-Instruct"
assert body["messages"][0]["role"] == "system"
@@ -77,7 +77,7 @@ def test_build_request_body_basic(sambanova_provider):
def test_build_request_body_preserves_caller_extra_body(sambanova_provider):
req = make_request(extra_body={"metadata": {"user": "u1"}})
- body = sambanova_provider._build_request_body(req)
+ body = sambanova_provider._chat._build_request_body(req)
eb = body.get("extra_body")
assert isinstance(eb, dict)
@@ -97,7 +97,7 @@ def test_build_request_body_preserves_caller_extra_body(sambanova_provider):
def test_build_request_body_uses_only_documented_reasoning_efforts(
sambanova_provider, reasoning, expected
):
- body = sambanova_provider._build_request_body(
+ body = sambanova_provider._chat._build_request_body(
make_request(),
reasoning=reasoning,
)
diff --git a/tests/providers/test_siliconflow.py b/tests/providers/test_siliconflow.py
index 7ae76f90..ee1ec0d9 100644
--- a/tests/providers/test_siliconflow.py
+++ b/tests/providers/test_siliconflow.py
@@ -93,7 +93,7 @@ def test_build_request_body_preserves_common_chat_tools_and_images(
],
)
- body = siliconflow_provider._build_request_body(
+ body = siliconflow_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.provider_default(),
)
@@ -126,7 +126,9 @@ def test_build_request_body_omits_model_specific_thinking_controls(
siliconflow_provider: OpenAIChatProvider,
reasoning: ReasoningPolicy,
) -> None:
- body = siliconflow_provider._build_request_body(_request(), reasoning=reasoning)
+ body = siliconflow_provider._chat._build_request_body(
+ _request(), reasoning=reasoning
+ )
assert "extra_body" not in body
@@ -136,7 +138,7 @@ def test_build_request_body_preserves_unrelated_extra_body(
) -> None:
request = _request(extra_body={"min_p": 0.05})
- body = siliconflow_provider._build_request_body(
+ body = siliconflow_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
@@ -154,7 +156,7 @@ def test_build_request_body_rejects_caller_thinking_override(
request = _request(extra_body={field: "caller-owned"})
with pytest.raises(InvalidRequestError, match="must not override reasoning"):
- siliconflow_provider._build_request_body(request, reasoning=REASONING_ON)
+ siliconflow_provider._chat._build_request_body(request, reasoning=REASONING_ON)
def test_build_request_body_replays_reasoning_content_verbatim(
@@ -174,7 +176,7 @@ def test_build_request_body_replays_reasoning_content_verbatim(
]
)
- body = siliconflow_provider._build_request_body(
+ body = siliconflow_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -225,7 +227,7 @@ async def test_model_catalog_uses_documented_endpoint_query_and_auth() -> None:
return AsyncOpenAI(*args, **kwargs)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
side_effect=build_client,
):
provider = profiled_provider(
diff --git a/tests/providers/test_streaming_errors.py b/tests/providers/test_streaming_errors.py
index 4a36d640..18c614a5 100644
--- a/tests/providers/test_streaming_errors.py
+++ b/tests/providers/test_streaming_errors.py
@@ -29,10 +29,6 @@ from free_claude_code.providers.admission import (
ProviderOperationKind,
)
from free_claude_code.providers.nvidia_nim import NvidiaNimProvider
-from free_claude_code.providers.openai_chat.provider import (
- _OpenAIChatStreamRunner,
- _reserved_anthropic_tool_ids,
-)
from free_claude_code.providers.openai_chat.stream_output import (
AnthropicChatStreamOutput,
)
@@ -41,6 +37,10 @@ from free_claude_code.providers.openai_chat.tool_calls import (
OpenAIToolCallCollector,
iter_heuristic_tool_use_events,
)
+from free_claude_code.providers.openai_chat.transport import (
+ _OpenAIChatStreamRunner,
+ _reserved_anthropic_tool_ids,
+)
from free_claude_code.providers.stream_recovery import TruncatedProviderStreamError
from tests.providers.request_factory import make_messages_request
from tests.providers.support import (
@@ -141,7 +141,7 @@ def _make_tool_assembler(
concrete_request = request or _make_request()
return OpenAIToolCallAssembler(
reserved_tool_ids=_reserved_anthropic_tool_ids(concrete_request),
- record_extra_content=provider._record_tool_call_extra_content,
+ record_extra_content=provider._behavior.record_tool_call_extra_content,
)
@@ -178,8 +178,8 @@ def _make_stream_runner(
) -> _OpenAIChatStreamRunner:
concrete_request = request or _make_request()
return _OpenAIChatStreamRunner(
- provider,
- body=provider._build_request_body(concrete_request),
+ provider._chat,
+ body=provider._chat._build_request_body(concrete_request),
tool_names=OpenAIToolNameCodec.from_request(concrete_request),
tool_schemas=tool_schemas_by_name(concrete_request),
reserved_tool_ids=_reserved_anthropic_tool_ids(concrete_request),
@@ -338,13 +338,13 @@ class TestStreamingExceptionHandling:
return_value=stream,
),
patch.object(
- provider,
- "_normalize_stream",
+ provider._behavior,
+ "normalize_stream",
side_effect=ValueError("invalid stream wrapper"),
),
pytest.raises(ValueError, match="invalid stream wrapper"),
):
- await provider._create_stream(
+ await provider._chat._create_stream(
{"model": "test-model", "messages": []},
execution,
ProviderOperationKind.GENERATION,
@@ -1311,7 +1311,7 @@ class TestStreamingExceptionHandling:
},
]
)
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
replay,
reasoning=DEFAULT_REASONING_POLICY,
)
@@ -1823,10 +1823,10 @@ class TestStreamingExceptionHandling:
with (
patch.object(
- provider,
+ provider._chat,
"_create_stream",
new_callable=AsyncMock,
- wraps=provider._create_stream,
+ wraps=provider._chat._create_stream,
) as create_stream,
patch.object(
provider._client.chat.completions,
@@ -1887,7 +1887,7 @@ class TestStreamingExceptionHandling:
)
)
)
- body = provider._build_request_body(request)
+ body = provider._chat._build_request_body(request)
body["stream_options"] = {"include_usage": True}
response = httpx2.Response(
status_code=400,
@@ -1908,10 +1908,10 @@ class TestStreamingExceptionHandling:
with (
patch.object(
- provider,
+ provider._chat,
"_create_stream",
new_callable=AsyncMock,
- wraps=provider._create_stream,
+ wraps=provider._chat._create_stream,
) as create_stream,
patch.object(
provider._client.chat.completions,
@@ -2064,10 +2064,10 @@ class TestStreamingExceptionHandling:
with (
patch.object(
- provider,
+ provider._chat,
"_create_stream",
new_callable=AsyncMock,
- wraps=provider._create_stream,
+ wraps=provider._chat._create_stream,
) as create_stream,
patch.object(
provider._client.chat.completions,
@@ -2334,7 +2334,7 @@ class TestStreamingExceptionHandling:
thinking="hidden reasoning more",
),
) as mock_collect:
- execution = runner._provider._admission.start_execution()
+ execution = runner._transport._admission.start_execution()
events = await runner._recovery_events(
body={"messages": [{"role": "user", "content": "hello"}]},
assembler=assembler,
@@ -3190,7 +3190,6 @@ async def test_openai_compat_stream_ends_with_contract_when_tool_name_never_arri
@pytest.mark.asyncio
@pytest.mark.parametrize("collector", [False, True])
async def test_tool_argument_mapping_survives_correction_then_stream_reopen(collector):
- provider = _alias_provider()
request = _alias_request()
def responder(bodies):
@@ -3212,7 +3211,11 @@ async def test_tool_argument_mapping_survives_correction_then_stream_reopen(coll
]
return 200, _alias_events()
- async with _harness("chat", responder, chat_provider=provider) as (_, bodies):
+ async with _harness("chat", responder, chat_provider_factory=_alias_provider) as (
+ _,
+ bodies,
+ provider,
+ ):
if collector:
runner = _make_stream_runner(provider, request=request)
execution = provider._admission.start_execution()
diff --git a/tests/providers/test_together.py b/tests/providers/test_together.py
index e5012b76..7bd1bc47 100644
--- a/tests/providers/test_together.py
+++ b/tests/providers/test_together.py
@@ -82,7 +82,7 @@ def test_build_request_body_preserves_common_chat_tools_and_images(
}
)
- body = together_provider._build_request_body(
+ body = together_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -112,7 +112,7 @@ def test_build_request_body_does_not_invent_catalog_wide_reasoning_control(
}
)
- body = together_provider._build_request_body(request, reasoning=reasoning)
+ body = together_provider._chat._build_request_body(request, reasoning=reasoning)
extra_body = body.get("extra_body", {})
for field in ("reasoning", "reasoning_effort", "chat_template_kwargs"):
@@ -140,7 +140,7 @@ def test_build_request_body_replays_documented_reasoning_field(
}
)
- body = together_provider._build_request_body(
+ body = together_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_vercel.py b/tests/providers/test_vercel.py
index 8dfba9f1..91843eaf 100644
--- a/tests/providers/test_vercel.py
+++ b/tests/providers/test_vercel.py
@@ -46,7 +46,7 @@ def test_default_base_url_constant():
def test_init_uses_default_base_url_and_api_key(vercel_config):
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as mock_openai:
provider = profiled_provider(
"vercel",
@@ -62,7 +62,7 @@ def test_init_uses_default_base_url_and_api_key(vercel_config):
def test_init_strips_trailing_slash(vercel_config):
config = replace(vercel_config, base_url=f"{VERCEL_AI_GATEWAY_DEFAULT_BASE}/")
- with patch("free_claude_code.providers.openai_chat.provider.AsyncOpenAI"):
+ with patch("free_claude_code.providers.openai_chat.client.AsyncOpenAI"):
provider = profiled_provider(
"vercel",
config,
@@ -127,7 +127,7 @@ def test_build_request_body_keeps_max_tokens(vercel_provider):
"max_tokens": 42,
}
- body = vercel_provider._build_request_body(make_request())
+ body = vercel_provider._chat._build_request_body(make_request())
assert body["messages"][0].get("name") == "alice"
assert body["max_tokens"] == 42
@@ -137,7 +137,7 @@ def test_build_request_body_keeps_max_tokens(vercel_provider):
def test_build_request_body_preserves_caller_extra_body(vercel_provider):
req = make_request(extra_body={"providerOptions": {"openai": {"reasoning": "low"}}})
- body = vercel_provider._build_request_body(req)
+ body = vercel_provider._chat._build_request_body(req)
assert body["extra_body"] == {"providerOptions": {"openai": {"reasoning": "low"}}}
diff --git a/tests/providers/test_vertex.py b/tests/providers/test_vertex.py
index 60a30d07..e8cedcfc 100644
--- a/tests/providers/test_vertex.py
+++ b/tests/providers/test_vertex.py
@@ -226,7 +226,7 @@ def test_vertex_provider_supplies_renewable_token_callback_to_openai() -> None:
token_provider = _token_provider()
with (
patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI"
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI"
) as openai_client,
patch("free_claude_code.providers.vertex.client.httpx.AsyncClient"),
):
@@ -247,7 +247,7 @@ def test_vertex_request_uses_google_thinking_budget_without_named_effort() -> No
thinking={"type": "enabled", "budget_tokens": 2048},
)
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
assert body["model"] == "google/gemini-3.5-flash"
assert "reasoning_effort" not in body
@@ -264,7 +264,7 @@ def test_vertex_request_maps_reasoning_off_to_zero_budget() -> None:
thinking={"type": "disabled"},
)
- body = provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = provider._chat._build_request_body(request, reasoning=reasoning_for(request))
assert body["extra_body"]["extra_body"]["google"]["thinking_config"] == {
"thinking_budget": 0,
@@ -301,7 +301,7 @@ def test_vertex_reasoning_has_one_google_wire_owner(
) -> None:
provider = _provider()
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
make_messages_request("google/gemini", thinking=None),
reasoning=reasoning,
)
@@ -328,7 +328,7 @@ def test_vertex_preserves_caller_thinking_config_only_for_provider_default() ->
},
)
- body = provider._build_request_body(
+ body = provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.provider_default(),
)
@@ -351,7 +351,7 @@ def test_vertex_rejects_caller_thinking_config_with_fcc_reasoning_control() -> N
)
with pytest.raises(InvalidRequestError, match="thinking_config"):
- provider._build_request_body(
+ provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.on(effort=ReasoningEffort.HIGH),
)
diff --git a/tests/providers/test_wafer.py b/tests/providers/test_wafer.py
index afe7fd98..1172c726 100644
--- a/tests/providers/test_wafer.py
+++ b/tests/providers/test_wafer.py
@@ -66,7 +66,9 @@ def test_build_request_body_openai_shape_and_defaults(wafer_provider):
}
)
- body = wafer_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = wafer_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["model"] == "DeepSeek-V4-Pro"
assert body["messages"][0] == {"role": "user", "content": "Hello"}
@@ -83,7 +85,7 @@ def test_build_request_body_honors_effective_no_thinking(wafer_provider):
}
)
- body = wafer_provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = wafer_provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["reasoning_effort"] == "none"
@@ -97,7 +99,9 @@ def test_build_request_body_preserves_request_disabled_thinking(wafer_provider):
}
)
- body = wafer_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = wafer_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["reasoning_effort"] == "none"
@@ -112,7 +116,7 @@ def test_build_request_body_uses_resolved_policy_without_inspecting_model(
}
)
- body = wafer_provider._build_request_body(request, reasoning=REASONING_OFF)
+ body = wafer_provider._chat._build_request_body(request, reasoning=REASONING_OFF)
assert body["reasoning_effort"] == "none"
diff --git a/tests/providers/test_wandb.py b/tests/providers/test_wandb.py
index f3b929be..0184f68e 100644
--- a/tests/providers/test_wandb.py
+++ b/tests/providers/test_wandb.py
@@ -64,7 +64,7 @@ def test_build_request_body_encodes_documented_thinking_control(
reasoning: ReasoningPolicy,
enabled: bool,
) -> None:
- body = wandb_provider._build_request_body(_request(), reasoning=reasoning)
+ body = wandb_provider._chat._build_request_body(_request(), reasoning=reasoning)
assert body["extra_body"] == {"chat_template_kwargs": {"enable_thinking": enabled}}
@@ -72,7 +72,7 @@ def test_build_request_body_encodes_documented_thinking_control(
def test_build_request_body_uses_provider_defaults_when_reasoning_is_inherited(
wandb_provider: OpenAIChatProvider,
) -> None:
- body = wandb_provider._build_request_body(
+ body = wandb_provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.provider_default(),
)
@@ -112,7 +112,7 @@ def test_build_request_body_drops_undocumented_reasoning_replay_but_keeps_tools(
]
)
- body = wandb_provider._build_request_body(
+ body = wandb_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -155,14 +155,14 @@ def test_build_request_body_rejects_caller_reasoning_override(
request = _request(extra_body={field: "caller-owned"})
with pytest.raises(InvalidRequestError, match="must not override reasoning"):
- wandb_provider._build_request_body(request, reasoning=REASONING_ON)
+ wandb_provider._chat._build_request_body(request, reasoning=REASONING_ON)
@pytest.mark.asyncio
async def test_wire_body_uses_current_output_limit_and_thinking_fields(
wandb_provider: OpenAIChatProvider,
) -> None:
- body = wandb_provider._build_request_body(_request(), reasoning=REASONING_ON)
+ body = wandb_provider._chat._build_request_body(_request(), reasoning=REASONING_ON)
wire_body = await capture_openai_chat_wire_body(body)
@@ -201,7 +201,7 @@ async def test_model_catalog_uses_documented_endpoint_and_bearer_auth() -> None:
return AsyncOpenAI(*args, **kwargs)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
side_effect=build_client,
):
provider = profiled_provider(
diff --git a/tests/providers/test_xai.py b/tests/providers/test_xai.py
index 8c156250..f023d49c 100644
--- a/tests/providers/test_xai.py
+++ b/tests/providers/test_xai.py
@@ -81,7 +81,7 @@ def test_build_request_body_preserves_common_chat_tools_and_images(
}
)
- body = xai_provider._build_request_body(
+ body = xai_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -110,7 +110,7 @@ def test_build_request_body_does_not_invent_catalog_wide_reasoning_control(
}
)
- body = xai_provider._build_request_body(request, reasoning=reasoning)
+ body = xai_provider._chat._build_request_body(request, reasoning=reasoning)
assert "reasoning_effort" not in body
assert "reasoning" not in body.get("extra_body", {})
@@ -136,7 +136,7 @@ def test_build_request_body_replays_prior_reasoning_content(
}
)
- body = xai_provider._build_request_body(
+ body = xai_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
diff --git a/tests/providers/test_zai.py b/tests/providers/test_zai.py
index 8cc4d0ea..f9f3f7e3 100644
--- a/tests/providers/test_zai.py
+++ b/tests/providers/test_zai.py
@@ -60,7 +60,9 @@ def test_build_request_body_openai_chat(zai_provider):
}
)
- body = zai_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = zai_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["model"] == "glm-5.2"
assert body["max_tokens"] == 100
@@ -77,7 +79,9 @@ def test_build_request_body_default_max_tokens(zai_provider):
messages=[Message(role="user", content="x")],
)
- body = zai_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = zai_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["max_tokens"] == ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS
@@ -92,7 +96,9 @@ def test_build_request_body_rejects_caller_extra_body(zai_provider):
)
with pytest.raises(InvalidRequestError, match=r"Z\.ai Chat Completions"):
- zai_provider._build_request_body(request, reasoning=reasoning_for(request))
+ zai_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
def test_build_request_body_disables_zai_thinking(zai_provider):
@@ -104,7 +110,9 @@ def test_build_request_body_disables_zai_thinking(zai_provider):
}
)
- body = zai_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = zai_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["extra_body"]["thinking"] == {"type": "disabled"}
@@ -123,7 +131,9 @@ def test_build_request_body_replays_prior_reasoning_content(zai_provider):
}
)
- body = zai_provider._build_request_body(request, reasoning=reasoning_for(request))
+ body = zai_provider._chat._build_request_body(
+ request, reasoning=reasoning_for(request)
+ )
assert body["messages"][0]["reasoning_content"] == "prior"
assert "extra_body" not in body
diff --git a/tests/providers/test_zenmux.py b/tests/providers/test_zenmux.py
index 3f02a380..5eaed095 100644
--- a/tests/providers/test_zenmux.py
+++ b/tests/providers/test_zenmux.py
@@ -135,7 +135,7 @@ def test_build_request_body_uses_supported_output_field_tools_and_images(
],
)
- body = zenmux_provider._build_request_body(
+ body = zenmux_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -167,7 +167,7 @@ def test_build_request_body_maps_reasoning_effort_to_documented_vocabulary(
effort: ReasoningEffort,
expected: str,
) -> None:
- body = zenmux_provider._build_request_body(
+ body = zenmux_provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.on(effort=effort),
)
@@ -188,7 +188,7 @@ def test_build_request_body_maps_reasoning_control_and_budget(
reasoning: ReasoningPolicy,
expected: dict[str, Any],
) -> None:
- body = zenmux_provider._build_request_body(_request(), reasoning=reasoning)
+ body = zenmux_provider._chat._build_request_body(_request(), reasoning=reasoning)
assert body["extra_body"]["reasoning"] == expected
@@ -196,7 +196,7 @@ def test_build_request_body_maps_reasoning_control_and_budget(
def test_build_request_body_leaves_reasoning_to_provider_by_default(
zenmux_provider: OpenAIChatProvider,
) -> None:
- body = zenmux_provider._build_request_body(
+ body = zenmux_provider._chat._build_request_body(
_request(),
reasoning=ReasoningPolicy.provider_default(),
)
@@ -209,7 +209,7 @@ def test_build_request_body_preserves_unrelated_gateway_options(
) -> None:
request = _request(extra_body={"provider": {"fallback": "true"}})
- body = zenmux_provider._build_request_body(
+ body = zenmux_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.provider_default(),
)
@@ -228,7 +228,7 @@ def test_build_request_body_rejects_caller_canonical_override(
request = _request(extra_body={field: "caller-owned"})
with pytest.raises(InvalidRequestError, match="must not override canonical"):
- zenmux_provider._build_request_body(
+ zenmux_provider._chat._build_request_body(
request,
reasoning=ReasoningPolicy.on(),
)
@@ -273,7 +273,7 @@ def test_build_request_body_replays_reasoning_and_signed_details_unchanged(
]
)
- body = zenmux_provider._build_request_body(
+ body = zenmux_provider._chat._build_request_body(
request,
reasoning=reasoning_for(request),
)
@@ -449,7 +449,7 @@ async def test_model_catalog_uses_documented_endpoint_and_auth() -> None:
return AsyncOpenAI(*args, **kwargs)
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
side_effect=build_client,
):
provider = profiled_provider(
diff --git a/tests/runtime/test_provider_manager.py b/tests/runtime/test_provider_manager.py
index b6e40a1c..ed74026a 100644
--- a/tests/runtime/test_provider_manager.py
+++ b/tests/runtime/test_provider_manager.py
@@ -313,7 +313,7 @@ async def test_hot_replacement_owns_admission_per_provider_generation() -> None:
return client
with patch(
- "free_claude_code.providers.openai_chat.provider.AsyncOpenAI",
+ "free_claude_code.providers.openai_chat.client.AsyncOpenAI",
side_effect=create_client,
):
manager = ProviderRuntimeManager(first_settings)
diff --git a/uv.lock b/uv.lock
index a42eb09f..497ab6e2 100644
--- a/uv.lock
+++ b/uv.lock
@@ -598,7 +598,7 @@ wheels = [
[[package]]
name = "free-claude-code"
-version = "6.2.19"
+version = "6.2.20"
source = { editable = "." }
dependencies = [
{ name = "aiohttp" },