From fbcc0749ed34f11e92acb9f558a87ec7b25491fa Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 04:27:15 +0000 Subject: [PATCH] fix(ai): the openai provider without ai.api_base_url calls the OpenAI API's /v1 routes, built by the openai SDK The OpenAI provider without ai.api_base_url sent requests to the OpenAI API root without the /v1 path segment. This change: - Uses the openai SDK to route chat completions and model listings. - Configures the SDK client with the egress factory HTTP client. - Sets the default base URL to https://api.openai.com/v1 when ai.api_base_url is unset. - Preserves configured endpoints for GitHub Copilot and AI gateway. - Omits the Authorization header when ai.api_key is unset. - Limits response body size for stream and non-stream calls. - Removes legacy URL constants and hand-written payload parsers. Fail-to-pass evidence: 5 failed on base (5 failed and 147 passed in tests/test_ai_benchmark.py, tests/test_ai_client_providers_and_embeddings.py, tests/test_ai_model_sampling.py, tests/test_ai_streaming.py, tests/test_batch_2_review_defects.py, tests/test_thinking_providers.py; 0 errored). Verification: - uv run devops ci fail-to-pass --base origin/main - uv run devops ci - uv run devops openspec check Change: openspec/changes/archive/2026-10-26-1427-openai-provider-routes Closes #1427 --- .../.openspec.yaml | 3 + .../design.md | 52 +++ .../proposal.md | 43 ++ .../tasks.md | 32 ++ src/devops_cli/ai/benchmark/runner.py | 12 +- src/devops_cli/ai/client/network.py | 4 +- src/devops_cli/ai/client/openai.py | 406 +++++++++++------- src/devops_cli/ai/client/streaming.py | 59 --- src/devops_cli/ai/client/unified.py | 17 +- src/devops_cli/ai/endpoints.py | 7 +- src/devops_cli/ai/rag/embeddings.py | 6 +- src/devops_cli/config/constants.py | 2 - tests/test_ai_benchmark.py | 5 +- ...test_ai_client_providers_and_embeddings.py | 96 ++++- tests/test_ai_model_sampling.py | 6 +- tests/test_ai_streaming.py | 215 ++++++---- tests/test_batch_2_review_defects.py | 2 +- tests/test_thinking_providers.py | 20 +- 18 files changed, 665 insertions(+), 322 deletions(-) create mode 100644 openspec/changes/archive/2026-10-26-1427-openai-provider-routes/.openspec.yaml create mode 100644 openspec/changes/archive/2026-10-26-1427-openai-provider-routes/design.md create mode 100644 openspec/changes/archive/2026-10-26-1427-openai-provider-routes/proposal.md create mode 100644 openspec/changes/archive/2026-10-26-1427-openai-provider-routes/tasks.md diff --git a/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/.openspec.yaml b/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/.openspec.yaml new file mode 100644 index 0000000000..7b65ee7de6 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-10-26 +skip_specs: true diff --git a/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/design.md b/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/design.md new file mode 100644 index 0000000000..7869bdce63 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/design.md @@ -0,0 +1,52 @@ +# Design + +## Context + +The `devops-cli` tool interacts with OpenAI-compatible APIs across three providers: `openai`, `copilot`, and `gateway`. +Previously, `OpenAICompatProviderMixin` built HTTP requests by hand. It appended `/chat/completions` directly to `CONST_URL_OPENAI_API_BASE` (`https://api.openai.com`), omitting the required `/v1` prefix. + +## Architecture + +`OpenAICompatProviderMixin` holds an `openai.OpenAI` SDK client instance. +The client configuration follows these rules: +1. `http_client`: Supplied from `self._shared_client()`, preserving connection pooling and SSRF egress filtering. +2. `base_url`: When `self._config.provider == "openai"` and `self._config.api_base_url` is unset, `base_url` is omitted (`None`). The SDK defaults to `https://api.openai.com/v1`. When `api_base_url` or another provider is set, `self._validate_base_url` supplies the endpoint. +3. `api_key`: Supplied from `self._api_key or "none"`. +4. `max_retries`: Set to 0 so the tenacity transport in the factory client handles retries without multiplication. +5. `timeout`: Configured from `self._request_timeout()`. + +## Request Handling + +### Unstreamed Chat (`_openai_compat_messages`) + +- Execute request with `with_streaming_response.create(...)`. +- Read and cap response body bytes with `_read_limited_body` against `DEFAULT_AI_MAX_RESPONSE_BYTES`. +- Parse the response model via `response.parse()`. +- Extract response headers for gateway `x-served-by` attribution. +- Map reasoning text from message fields or `model_extra`. +- Map token usage and finish reason to `LLMResponse`. + +### Streamed Chat (`_openai_compat_stream`) + +- Execute request with `chat.completions.create(..., stream=True, stream_options={"include_usage": True})`. +- Read stream response headers for gateway metadata. +- Iterate over chunks and yield text or `{reasoning}` tags. +- Update `stream_usage`, `stream_model`, and `stream_finish_reason` ContextVars. +- Ensure stream closure in a `finally` block. + +### Model Listing (`_openai_models`) + +- Call `self._openai_client().models.list()`. +- Return model ID list from `listing.data`. + +### Error Mapping + +- Catch `openai.APIStatusError` and map HTTP 401/403 to `AICredentialsError` through `credentials_error`. +- Map other `openai.APIStatusError` to `AIClientError` with sanitized error messages. +- Catch `openai.APIConnectionError` and map to `AIClientError` via `self._connection_error(exc)`. + +## Deletions + +- Remove `CONST_URL_OPENAI_API_BASE` from `src/devops_cli/config/constants.py`. +- Remove `_build_compat_payload`, `_parse_compat_response`, `_openai_compat_headers` from `src/devops_cli/ai/client/openai.py`. +- Remove `_openai_stream_frame` from `src/devops_cli/ai/client/streaming.py`. diff --git a/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/proposal.md b/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/proposal.md new file mode 100644 index 0000000000..0f7edf6de3 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/proposal.md @@ -0,0 +1,43 @@ +# Proposal + +## Why + +Issue #1427. The `openai` provider without `ai.api_base_url` sends chat completions and model listings to `https://api.openai.com/chat/completions` and `https://api.openai.com/models`. The OpenAI API serves those routes under `/v1`. Hand-written URL construction, payload builders, and response parsers cause this defect. The `openai` SDK defaults to `https://api.openai.com/v1` and accepts an `httpx2.Client` from the egress factory. + +## What Changes + +- Update `OpenAICompatProviderMixin` in `src/devops_cli/ai/client/openai.py` to route requests through `openai.OpenAI`. +- Configure the SDK client with the egress factory HTTP client, short timeouts, and `max_retries=0`. +- Let provider `openai` use the SDK default base URL (`https://api.openai.com/v1`), while `copilot` and `gateway` preserve their configured endpoints. +- Read gateway served-by headers from `with_raw_response` or stream response headers. +- Extract reasoning content from delta extra fields during chat completions and streaming. +- Delete `CONST_URL_OPENAI_API_BASE`, `_build_compat_payload`, `_parse_compat_response`, `_openai_compat_headers`, and `_openai_stream_frame`. +- Update `src/devops_cli/ai/rag/embeddings.py` to obtain default base URL from the SDK rather than a hand-written string. +- Add failing tests verifying unstreamed chat, streamed chat, and model listing reach `/v1` routes and use the egress client. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +None. + +## Impact + +- Code: `src/devops_cli/ai/client/openai.py`, `src/devops_cli/ai/client/streaming.py`, `src/devops_cli/ai/client/unified.py`, `src/devops_cli/ai/endpoints.py`, `src/devops_cli/ai/rag/embeddings.py`, `src/devops_cli/config/constants.py`. +- Tests: `tests/test_ai_client_providers_and_embeddings.py`, `tests/test_ai_benchmark.py`, `tests/test_ai_streaming.py`, `tests/test_thinking_providers.py`. + +## Feasibility + +- Premise confirmed by running `LLMClient` against `route_client` on `origin/main`. +- Recorded requests confirmed that `openai` provider without `api_base_url` sent to `https://api.openai.com/chat/completions` and `https://api.openai.com/models` without `/v1`. +- Verified `openai.OpenAI` SDK version 3.26.1 initializes with `http_client=httpx2.Client()`. +- Verified `openai.OpenAI` sends to `https://api.openai.com/v1/chat/completions` by default. +- Verified stream reasoning extraction reads `reasoning_content` from `ChoiceDelta.model_extra`. + +## Existing Tool Considered + +The change adopts the installed `openai` Python SDK (version 3.26.1) instead of hand-written HTTP request assembly. The SDK manages routing, authentication headers, SSE frame decoding, and error typing. The egress factory client (`new_http_client`) remains the underlying transport. diff --git a/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/tasks.md b/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/tasks.md new file mode 100644 index 0000000000..4fd8a5fa23 --- /dev/null +++ b/openspec/changes/archive/2026-10-26-1427-openai-provider-routes/tasks.md @@ -0,0 +1,32 @@ +# Tasks + +## 1. Failing tests + +- [x] Add failing test in `tests/test_ai_client_providers_and_embeddings.py` verifying `openai` provider without `api_base_url` sends requests to `/v1` routes for unstreamed chat, streamed chat, and model listing + - Verification: `uv run devops ci test tests/test_ai_client_providers_and_embeddings.py -k test_openai_default_routes_use_v1` +- [x] Add failing test in `tests/test_ai_client_providers_and_embeddings.py` verifying SDK client uses factory HTTP client identity + - Verification: `uv run devops ci test tests/test_ai_client_providers_and_embeddings.py -k test_openai_sdk_client_uses_factory_transport` + +## 2. Implementation + +- [x] Update `OpenAICompatProviderMixin` in `src/devops_cli/ai/client/openai.py` with `openai.OpenAI` integration and error mapping + - Verification: `uv run devops ci test tests/test_ai_client_providers_and_embeddings.py` +- [x] Remove `_openai_stream_frame` from `src/devops_cli/ai/client/streaming.py` and delete hand-written payload builders + - Verification: `git grep "_openai_stream_frame" src/` returns nothing +- [x] Remove `CONST_URL_OPENAI_API_BASE` and update references in `constants.py`, `unified.py`, `endpoints.py`, and `embeddings.py` + - Verification: `git grep "CONST_URL_OPENAI_API_BASE" src/` returns nothing +- [x] Update existing tests referencing deleted constants or frames + - Verification: `uv run devops ci test tests/test_ai_streaming.py tests/test_thinking_providers.py tests/test_ai_benchmark.py` + +## 3. Verification and checks + +- [x] Verify `fail-to-pass` check run against base + - Verification: `uv run devops ci fail-to-pass --base origin/main` +- [x] Verify full CI checks pass + - Verification: `uv run devops ci` +- [x] Archive OpenSpec change + - Verification: `uv run devops openspec archive 1427-openai-provider-routes` + +## Workflow follow-up + +- Pending a person: review the diff in tuicr (`tuicr -r origin/main..HEAD`). diff --git a/src/devops_cli/ai/benchmark/runner.py b/src/devops_cli/ai/benchmark/runner.py index e59ae10810..004749476f 100644 --- a/src/devops_cli/ai/benchmark/runner.py +++ b/src/devops_cli/ai/benchmark/runner.py @@ -53,6 +53,14 @@ def _get_benchmarks_base_dir() -> Path: return d +def _provider_default_api_base(provider: str) -> str | None: + if provider == "openai": + import openai + + return str(openai.OpenAI(api_key="none").base_url).rstrip("/") + return CONST_AI_PROVIDER_API_BASES.get(provider) + + def _key_for_endpoint(settings: Settings, client_config: AIConfig) -> str: """The configured AI key when `client_config` sends it to an endpoint the configuration names. @@ -68,7 +76,7 @@ def _key_for_endpoint(settings: Settings, client_config: AIConfig) -> str: for url in ( configured.api_base_url, configured.gateway_url, - CONST_AI_PROVIDER_API_BASES.get(configured.provider.lower()), + _provider_default_api_base(configured.provider.lower()), ) if url and (origin := get_url_origin(url)) } @@ -76,7 +84,7 @@ def _key_for_endpoint(settings: Settings, client_config: AIConfig) -> str: endpoint = ( client_config.gateway_url if provider == CONST_AI_GATEWAY_PROVIDER - else client_config.api_base_url or CONST_AI_PROVIDER_API_BASES.get(provider) + else client_config.api_base_url or _provider_default_api_base(provider) ) if endpoint and get_url_origin(endpoint) in trusted: return get_ai_api_key(settings) or "" diff --git a/src/devops_cli/ai/client/network.py b/src/devops_cli/ai/client/network.py index 5211291f08..254ded04de 100644 --- a/src/devops_cli/ai/client/network.py +++ b/src/devops_cli/ai/client/network.py @@ -23,7 +23,9 @@ CONST_AI_GATEWAY_SERVED_MODEL_HEADER, ) from devops_cli.config.defaults import ( - DEFAULT_AI_MAX_RESPONSE_BYTES, + DEFAULT_AI_MAX_RESPONSE_BYTES as DEFAULT_AI_MAX_RESPONSE_BYTES, +) +from devops_cli.config.defaults import ( DEFAULT_GATEWAY_REVIEW_CONCURRENCY, DEFAULT_GATEWAY_SLOT_TIMEOUT_SECONDS, DEFAULT_OLLAMA_MAX_PARALLEL, diff --git a/src/devops_cli/ai/client/openai.py b/src/devops_cli/ai/client/openai.py index e823e5e40f..b161dbc6b2 100644 --- a/src/devops_cli/ai/client/openai.py +++ b/src/devops_cli/ai/client/openai.py @@ -4,37 +4,46 @@ import logging import time -from collections.abc import Generator, Mapping +from collections.abc import Generator from contextlib import AbstractContextManager, nullcontext -from typing import Any +from typing import TYPE_CHECKING, Any, cast import httpx2 -from devops_cli.ai.client.base import BaseLLMProviderMixin +if TYPE_CHECKING: + import openai + +from devops_cli.ai.client import network +from devops_cli.ai.client.base import BaseLLMProviderMixin, _clean_http_error_body from devops_cli.ai.client.models import ( + AIClientError, LLMResponse, + credentials_error, provider_finish_reason, ) from devops_cli.ai.client.network import ( + StreamUsage, + _read_limited_body, acquire_gateway_slot, extract_served_by, extract_served_model, reply_schema, - request_limited_json, + stream_finish_reason, + stream_model, stream_served_by, stream_served_model, stream_slot_wait, + stream_usage, uses_gateway_slots, ) -from devops_cli.ai.client.streaming import _openai_stream_frame, _read_event_stream from devops_cli.config.constants import ( CONST_AI_GATEWAY_PROVIDER, CONST_OPENAI_FINISH_REASONS, CONST_URL_GITHUB_COPILOT_API_BASE, - CONST_URL_OPENAI_API_BASE, ) from devops_cli.exceptions import ConfigurationError from devops_cli.models.ai import ChatMessage +from devops_cli.security.sanitizer import mask_secrets from devops_cli.telemetry import inject_trace_context logger = logging.getLogger(__name__) @@ -43,9 +52,14 @@ class OpenAICompatProviderMixin(BaseLLMProviderMixin): """Mixin implementing OpenAI-compatible and GitHub Copilot completions.""" - def _api_base(self) -> str: - # The gateway holds its own key, so its requests go only to gateway_url; api_base_url is - # usually another provider's endpoint (a gateway task's own one is folded into gateway_url). + def _openai_client(self) -> openai.OpenAI: + import openai + + shared = self._shared_client() + cached = getattr(self, "_cached_openai_client", None) + if cached is not None and getattr(cached, "_client", None) is shared: + return cast("openai.OpenAI", cached) + if self._config.provider == "gateway": gw_url = getattr(self._config, "gateway_url", None) if not gw_url: @@ -53,20 +67,47 @@ def _api_base(self) -> str: "No AI gateway URL configured. Run: devops config set ai.gateway_url ", key="ai.gateway_url", ) - return self._validate_base_url(gw_url, purpose="provider API") - if self._config.api_base_url: - return self._validate_base_url(self._config.api_base_url, purpose="provider API") - if self._config.provider == "copilot": - return CONST_URL_GITHUB_COPILOT_API_BASE - return CONST_URL_OPENAI_API_BASE - - def _openai_compat_headers(self) -> dict[str, str]: - """Request headers; Authorization only when a key is set, since an empty bearer token is - an illegal header value that fails before the request is sent.""" - headers = {"Content-Type": "application/json"} - if self._api_key: - headers["Authorization"] = f"Bearer {self._api_key}" - return headers + base_url: str | None = self._validate_base_url(gw_url, purpose="provider API") + elif self._config.api_base_url: + base_url = self._validate_base_url(self._config.api_base_url, purpose="provider API") + elif self._config.provider in ("copilot", "github_copilot"): + base_url = CONST_URL_GITHUB_COPILOT_API_BASE + else: + base_url = None + + client = openai.OpenAI( + base_url=base_url, + api_key=self._api_key or "none", + http_client=shared, + max_retries=0, + timeout=self._request_timeout(), + ) + self._cached_openai_client = client + return client + + def _api_base(self) -> str: + return str(self._openai_client().base_url).rstrip("/") + + def _map_openai_error(self, exc: Exception) -> AIClientError: + import openai + + if isinstance(exc, openai.APIStatusError): + status = exc.status_code + if status in (401, 403): + provider_name = getattr(self._config, "provider", "AI") + has_key = bool(getattr(self, "_api_key", None)) + return credentials_error( + f"The {provider_name} provider", has_key=has_key, status=status + ) + raw_body = getattr(getattr(exc, "response", None), "text", "") or "" + cleaned = _clean_http_error_body(raw_body) + detail = f": {mask_secrets(cleaned)}" if cleaned else "" + return AIClientError(f"Provider request failed with HTTP {status}{detail}") + if isinstance(exc, openai.APIConnectionError): + return self._connection_error(exc) + if isinstance(exc, AIClientError): + return exc + return AIClientError(f"Provider request failed: {exc}") def _supports_reasoning(self) -> bool: """Return True if model declared reasoning capability via gateway or direct config.""" @@ -87,32 +128,27 @@ def _supports_reasoning(self) -> bool: ) return False - def _apply_reasoning_params( - self, payload: dict[str, Any], limit: int | None, enable_thinking: bool - ) -> None: - """Apply reasoning-specific parameters to the request payload.""" - if enable_thinking: - effort = self._config.reasoning_effort or "medium" - payload["reasoning_effort"] = effort - if limit is not None: - payload["max_completion_tokens"] = limit + def _apply_sampling_and_limits(self, params: dict[str, Any], *, enable_thinking: bool) -> None: + limit = self._completion_limit() + if self._supports_reasoning(): + if enable_thinking: + effort = self._config.reasoning_effort or "medium" + params["reasoning_effort"] = effort + if limit is not None: + params["max_completion_tokens"] = limit + return - def _apply_standard_params( - self, payload: dict[str, Any], limit: int | None, stream: bool - ) -> None: - """Apply standard model parameters (tokens, temperature, top_p) to payload.""" if limit is not None: - payload["max_tokens"] = limit - if getattr(self._config, "use_model_sampling", False): - return - temp = getattr(self._config, "temperature", None) - if temp is not None: - payload["temperature"] = float(temp) - top_p = getattr(self._config, "top_p", None) - if top_p is not None: - payload["top_p"] = float(top_p) - - def _build_compat_payload( + params["max_tokens"] = limit + if not getattr(self._config, "use_model_sampling", False): + temp = getattr(self._config, "temperature", None) + if temp is not None: + params["temperature"] = float(temp) + top_p = getattr(self._config, "top_p", None) + if top_p is not None: + params["top_p"] = float(top_p) + + def _prepare_params( self, system: str, messages: list[ChatMessage], @@ -120,41 +156,33 @@ def _build_compat_payload( stream: bool = False, enable_thinking: bool = True, ) -> dict[str, Any]: - """Construct JSON payload adhering strictly to model reasoning capabilities.""" - payload: dict[str, Any] = { + extra_headers: dict[str, Any] = inject_trace_context({}) + if not self._api_key: + import openai + + extra_headers["Authorization"] = openai.omit + params: dict[str, Any] = { "model": self._config.model, "messages": [ {"role": "system", "content": system}, *[m.to_dict() for m in messages], ], + "timeout": self._request_timeout(), + "extra_headers": extra_headers, } if stream: - payload["stream"] = True - payload["stream_options"] = {"include_usage": True} - - limit = self._completion_limit() - if self._supports_reasoning(): - self._apply_reasoning_params(payload, limit, enable_thinking) - else: - self._apply_standard_params(payload, limit, stream) - self._apply_reply_schema(payload) - return payload + params["stream"] = True + params["stream_options"] = {"include_usage": True} - def _apply_reply_schema(self, payload: dict[str, Any]) -> None: - """Ask the gateway to constrain the reply to a structured call's schema, if one is set. + self._apply_sampling_and_limits(params, enable_thinking=enable_thinking) - Only the gateway gets `response_format`, and without `strict`: LiteLLM maps it to an - Ollama deployment's `format`, and drops it for a deployment that takes no such parameter - (`drop_params`). The openai and copilot providers rely on the schema in the prompt, which - `chat_structured` sends to every provider. - """ schema = reply_schema.get() - if schema is None or self._config.provider != CONST_AI_GATEWAY_PROVIDER: - return - payload["response_format"] = { - "type": "json_schema", - "json_schema": {"name": schema.name, "schema": schema.json_schema}, - } + if schema is not None and self._config.provider == CONST_AI_GATEWAY_PROVIDER: + params["response_format"] = { + "type": "json_schema", + "json_schema": {"name": schema.name, "schema": schema.json_schema}, + } + return params @staticmethod def _extract_inline_thinking(content: str, thinking_str: str | None) -> tuple[str, str | None]: @@ -169,46 +197,6 @@ def _extract_inline_thinking(content: str, thinking_str: str | None) -> tuple[st combined = (thinking_str + "\n" if thinking_str else "") + "\n".join(inner_thinks) return clean, combined.strip() or None - def _parse_compat_response( - self, - raw_json: dict[str, Any], - wall_elapsed: float, - reply_headers: Mapping[str, str] | None, - ) -> LLMResponse: - """Parse raw OpenAI completion JSON into a structured LLMResponse, with the backend and - the deployment model that a gateway names in its reply headers.""" - choices = raw_json.get("choices", [{}]) - first_choice = choices[0] if choices else {} - msg = first_choice.get("message", {}) - raw_content = str(msg.get("content") or "") - raw_reasoning = ( - msg.get("reasoning_content") or msg.get("reasoning") or first_choice.get("reasoning") - ) - thinking_str = str(raw_reasoning).strip() if raw_reasoning else None - - content, thinking_str = self._extract_inline_thinking(raw_content, thinking_str) - usage = raw_json.get("usage", {}) - completion_details = usage.get("completion_tokens_details") or {} - reasoning_tokens = completion_details.get("reasoning_tokens") - b_info = f"{self.backend_type} ({self.backend_host})" - return LLMResponse( - content, - processing_seconds=None, - wall_seconds=wall_elapsed, - backend_info=b_info, - thinking=thinking_str, - prompt_tokens=usage.get("prompt_tokens"), - completion_tokens=usage.get("completion_tokens"), - total_tokens=usage.get("total_tokens"), - served_by=extract_served_by(reply_headers), - served_model=extract_served_model(reply_headers), - model=raw_json.get("model"), - finish_reason=provider_finish_reason( - CONST_OPENAI_FINISH_REASONS, first_choice.get("finish_reason") - ), - reasoning_tokens=reasoning_tokens, - ) - def _gateway_slot(self) -> AbstractContextManager[float]: """One of the gateway's backend slots for a gateway chat call, yielding the seconds spent waiting for it; other providers take none and wait none. @@ -226,21 +214,24 @@ def _openai_compat_messages( *, enable_thinking: bool = True, ) -> LLMResponse: - headers = inject_trace_context(self._openai_compat_headers()) - payload = self._build_compat_payload(system, messages, enable_thinking=enable_thinking) + import openai + + params = self._prepare_params(system, messages, enable_thinking=enable_thinking) with self._gateway_slot(): start_time = time.monotonic() try: - raw_json, reply_headers = request_limited_json( - self._shared_client(), - "POST", - f"{self._api_base()}/chat/completions", - headers=headers, - json=payload, - timeout=self._request_timeout(), - ) + with self._openai_client().chat.completions.with_streaming_response.create( + **params + ) as response: + body = _read_limited_body( + response.http_response, network.DEFAULT_AI_MAX_RESPONSE_BYTES + ) + response.http_response._content = bytes(body) + reply_headers = response.headers + parsed = response.parse() wall_elapsed = time.monotonic() - start_time - return self._parse_compat_response(raw_json, wall_elapsed, reply_headers) + except (openai.APIStatusError, openai.APIConnectionError) as exc: + raise self._map_openai_error(exc) from exc except (httpx2.ConnectError, httpx2.ConnectTimeout) as exc: raise self._connection_error(exc) from exc except httpx2.HTTPError as exc: @@ -249,6 +240,47 @@ def _openai_compat_messages( "Provider request failed. Check network access, API endpoint, and credentials.", ) from exc + choices = parsed.choices if parsed.choices else [] + first_choice = choices[0] if choices else None + msg = first_choice.message if first_choice else None + raw_content = str(getattr(msg, "content", "") or "") + extra = getattr(msg, "model_extra", None) or {} + choice_extra = getattr(first_choice, "model_extra", None) or {} + raw_reasoning = ( + getattr(msg, "reasoning_content", None) + or getattr(msg, "reasoning", None) + or getattr(first_choice, "reasoning", None) + or extra.get("reasoning_content") + or extra.get("reasoning") + or choice_extra.get("reasoning") + ) + thinking_str = str(raw_reasoning).strip() if raw_reasoning else None + content, thinking_str = self._extract_inline_thinking(raw_content, thinking_str) + + usage = parsed.usage + details = getattr(usage, "completion_tokens_details", None) if usage else None + reasoning_tokens = getattr(details, "reasoning_tokens", None) if details else None + b_info = f"{self.backend_type} ({self.backend_host})" + + raw_finish = getattr(first_choice, "finish_reason", None) if first_choice else None + finish_reason = provider_finish_reason(CONST_OPENAI_FINISH_REASONS, raw_finish) + + return LLMResponse( + content, + processing_seconds=None, + wall_seconds=wall_elapsed, + backend_info=b_info, + thinking=thinking_str, + prompt_tokens=getattr(usage, "prompt_tokens", None) if usage else None, + completion_tokens=getattr(usage, "completion_tokens", None) if usage else None, + total_tokens=getattr(usage, "total_tokens", None) if usage else None, + served_by=extract_served_by(reply_headers), + served_model=extract_served_model(reply_headers), + model=parsed.model, + finish_reason=finish_reason, + reasoning_tokens=reasoning_tokens, + ) + def _openai_compat_stream( self, system: str, @@ -256,41 +288,45 @@ def _openai_compat_stream( *, enable_thinking: bool = True, ) -> Generator[str]: - headers = self._openai_compat_headers() - payload = self._build_compat_payload( + import openai + + params = self._prepare_params( system, messages, stream=True, enable_thinking=enable_thinking ) try: - # A stream holds its gateway slot until the generator closes. - with ( - self._gateway_slot() as slot_wait, - self._create_http_client() as http_client, - http_client.stream( - "POST", f"{self._api_base()}/chat/completions", headers=headers, json=payload - ) as response, - ): + with self._gateway_slot() as slot_wait: stream_slot_wait.set(slot_wait) - if response.status_code >= 400: - response.read() - response.raise_for_status() - stream_served_by.set(extract_served_by(response.headers)) - stream_served_model.set(extract_served_model(response.headers)) - yield from _read_event_stream(response, _openai_stream_frame, "Provider") + stream = self._openai_client().chat.completions.create(**params) + try: + yield from _consume_stream(stream) + finally: + stream.close() + except (openai.APIStatusError, openai.APIConnectionError) as exc: + raise self._map_openai_error(exc) from exc except (httpx2.ConnectError, httpx2.ConnectTimeout) as exc: raise self._connection_error(exc) from exc except httpx2.HTTPError as exc: raise self._provider_http_error(exc, f"Provider streaming failed: {exc}") from exc def _openai_models(self) -> list[str]: + import openai + + extra_headers: dict[str, Any] = inject_trace_context({}) + if not self._api_key: + extra_headers["Authorization"] = openai.omit try: - listing, _headers = request_limited_json( - self._shared_client(), - "GET", - f"{self._api_base()}/models", - headers=self._openai_compat_headers(), + with self._openai_client().models.with_streaming_response.list( timeout=self._request_timeout(), - ) - return [model_info["id"] for model_info in listing.get("data", [])] + extra_headers=extra_headers, + ) as response: + body = _read_limited_body( + response.http_response, network.DEFAULT_AI_MAX_RESPONSE_BYTES + ) + response.http_response._content = bytes(body) + listing = response.parse() + return [model_info.id for model_info in listing.data] + except (openai.APIStatusError, openai.APIConnectionError) as exc: + raise self._map_openai_error(exc) from exc except (httpx2.ConnectError, httpx2.ConnectTimeout) as exc: raise self._connection_error(exc) from exc except httpx2.HTTPError as exc: @@ -298,3 +334,81 @@ def _openai_models(self) -> list[str]: exc, "Failed to list provider models. Check network access, API endpoint, and credentials.", ) from exc + + +def _record_stream_response_headers(stream: Any) -> None: + if not hasattr(stream, "response") or stream.response is None: + return + resp_headers = getattr(stream.response, "headers", None) + if resp_headers: + stream_served_by.set(extract_served_by(resp_headers)) + stream_served_model.set(extract_served_model(resp_headers)) + + +def _record_stream_chunk_usage(chunk: Any) -> None: + model = getattr(chunk, "model", None) + if model and stream_model.get() is None: + stream_model.set(str(model)) + + usage = getattr(chunk, "usage", None) + if usage is None: + return + details = getattr(usage, "completion_tokens_details", None) + r_tok = getattr(details, "reasoning_tokens", None) if details else None + p_tok = getattr(usage, "prompt_tokens", None) + c_tok = getattr(usage, "completion_tokens", None) + t_tok = getattr(usage, "total_tokens", None) + if p_tok is not None or c_tok is not None: + stream_usage.set( + StreamUsage( + prompt_tokens=p_tok, + completion_tokens=c_tok, + total_tokens=t_tok, + reasoning_tokens=r_tok, + ) + ) + + +def _process_stream_choice(choice: Any) -> Generator[str]: + reason = getattr(choice, "finish_reason", None) + if reason is not None: + stream_finish_reason.set(provider_finish_reason(CONST_OPENAI_FINISH_REASONS, reason)) + + delta = getattr(choice, "delta", None) + if delta is None: + return + extra = getattr(delta, "model_extra", None) or {} + reasoning = ( + getattr(delta, "reasoning_content", None) + or extra.get("reasoning_content") + or extra.get("reasoning") + ) + if reasoning: + yield f"{reasoning}" + content = getattr(delta, "content", None) + if content: + yield str(content) + + +def _consume_stream(stream: Any) -> Generator[str]: + _record_stream_response_headers(stream) + seen_done = [False] + orig_iter_events = getattr(stream, "_iter_events", None) + if callable(orig_iter_events): + + def _wrapped_iter_events() -> Any: + for sse in orig_iter_events(): + if getattr(sse, "data", "").startswith("[DONE]"): + seen_done[0] = True + yield sse + + stream._iter_events = _wrapped_iter_events + + for chunk in stream: + _record_stream_chunk_usage(chunk) + choices = getattr(chunk, "choices", None) + if choices: + yield from _process_stream_choice(choices[0]) + + if not seen_done[0] and stream_finish_reason.get() is None: + raise AIClientError("Provider stream ended before its final frame.") diff --git a/src/devops_cli/ai/client/streaming.py b/src/devops_cli/ai/client/streaming.py index 0acfbe22bb..025d9707aa 100644 --- a/src/devops_cli/ai/client/streaming.py +++ b/src/devops_cli/ai/client/streaming.py @@ -15,13 +15,11 @@ StreamUsage, size_limit_text, stream_finish_reason, - stream_model, stream_usage, ) from devops_cli.ai.thinking_stream import ThinkingFSM from devops_cli.config.constants import ( CONST_OLLAMA_DONE_REASONS, - CONST_OPENAI_FINISH_REASONS, ) from devops_cli.config.defaults import ( DEFAULT_AI_STREAM_MAX_EVENT_BYTES, @@ -280,63 +278,6 @@ def _ollama_stream_frame(line: str) -> StreamFrame: ) -def _openai_delta_text(delta: object) -> str | None: - """A chat completion delta's reasoning, wrapped in think tags, or else its content.""" - if not isinstance(delta, dict): - return None - if reasoning := delta.get("reasoning_content") or delta.get("reasoning"): - return f"{reasoning}" - content = delta.get("content") - return str(content) if content else None - - -def _first_choice(payload: dict[str, Any]) -> dict[str, Any]: - """A completion chunk's first choice; an empty one when it has none, as a usage chunk.""" - choices = payload.get("choices") - first = choices[0] if isinstance(choices, list) and choices else None - return first if isinstance(first, dict) else {} - - -def _openai_stream_frame(event: httpx2.ServerSentEvent) -> StreamFrame: - """One event of an OpenAI-compatible chat completion stream. - - A chunk with a finish reason completes the stream, and so does `[DONE]`, the server's own end - marker, with no reason before it. Reading goes on past the reason to `[DONE]` or EOF, so a - usage chunk sent after it is still read. - """ - if event.data.strip() == "[DONE]": - return StreamFrame(complete=True, last=True) - payload = _json_object(event.data) - if payload.get("error") is not None: - return StreamFrame(error=_error_text(payload["error"])) - model = payload.get("model") - if model and stream_model.get() is None: - stream_model.set(str(model)) - usage = payload.get("usage") - if isinstance(usage, dict): - details = usage.get("completion_tokens_details") or {} - r_tok = details.get("reasoning_tokens") - p_tok = usage.get("prompt_tokens") - c_tok = usage.get("completion_tokens") - t_tok = usage.get("total_tokens") - if p_tok is not None or c_tok is not None: - stream_usage.set( - StreamUsage( - prompt_tokens=p_tok, - completion_tokens=c_tok, - total_tokens=t_tok, - reasoning_tokens=r_tok, - ) - ) - choice = _first_choice(payload) - reason = choice.get("finish_reason") - return StreamFrame( - chunk=_openai_delta_text(choice.get("delta")), - complete=reason is not None, - finish_reason=provider_finish_reason(CONST_OPENAI_FINISH_REASONS, reason), - ) - - def _check_stream_size(total_bytes: int, provider_name: str, max_stream_bytes: int) -> None: if total_bytes > max_stream_bytes: raise AIClientError( diff --git a/src/devops_cli/ai/client/unified.py b/src/devops_cli/ai/client/unified.py index b736e5c931..33a847bc19 100644 --- a/src/devops_cli/ai/client/unified.py +++ b/src/devops_cli/ai/client/unified.py @@ -38,7 +38,6 @@ CONST_UNCACHED_FINISH_REASONS, CONST_URL_ANTHROPIC_API_BASE, CONST_URL_GITHUB_COPILOT_API_BASE, - CONST_URL_OPENAI_API_BASE, ) from devops_cli.config.defaults import ( DEFAULT_AI_CONNECT_TIMEOUT_SECONDS, @@ -310,13 +309,15 @@ def backend_host(self) -> str: return self._resolve_ollama_backend_host() base_url = getattr(self._config, "api_base_url", None) if p != "gateway" else None if not isinstance(base_url, str) or not base_url: - provider_defaults = { - "claude": CONST_URL_ANTHROPIC_API_BASE, - "copilot": CONST_URL_GITHUB_COPILOT_API_BASE, - "openai": CONST_URL_OPENAI_API_BASE, - "gateway": getattr(self._config, "gateway_url", None), - } - base_url = provider_defaults.get(p) + if p == "openai": + base_url = str(self._openai_client().base_url).rstrip("/") + else: + provider_defaults = { + "claude": CONST_URL_ANTHROPIC_API_BASE, + "copilot": CONST_URL_GITHUB_COPILOT_API_BASE, + "gateway": getattr(self._config, "gateway_url", None), + } + base_url = provider_defaults.get(p) if isinstance(base_url, str) and base_url: parsed = urlparse(base_url) return str(parsed.netloc or parsed.path or base_url) diff --git a/src/devops_cli/ai/endpoints.py b/src/devops_cli/ai/endpoints.py index c92a33225a..f0b3e63008 100644 --- a/src/devops_cli/ai/endpoints.py +++ b/src/devops_cli/ai/endpoints.py @@ -10,7 +10,6 @@ CONST_AI_GATEWAY_VIRTUAL_MODELS, CONST_URL_ANTHROPIC_API_BASE, CONST_URL_GITHUB_COPILOT_API_BASE, - CONST_URL_OPENAI_API_BASE, ) from devops_cli.exceptions import ConfigurationError @@ -87,7 +86,11 @@ def _resolve_cloud_or_custom_endpoint(provider: str, cfg: Any) -> ResolvedAIEndp provider="copilot", urls=(str(base_url).rstrip("/"),), models=models ) if provider == "openai": - base_url = getattr(cfg, "api_base_url", None) or CONST_URL_OPENAI_API_BASE + import openai + + base_url = getattr(cfg, "api_base_url", None) or str( + openai.OpenAI(api_key="none").base_url + ).rstrip("/") return ResolvedAIEndpoint( provider="openai", urls=(str(base_url).rstrip("/"),), models=models ) diff --git a/src/devops_cli/ai/rag/embeddings.py b/src/devops_cli/ai/rag/embeddings.py index 86213e5ff6..d96af55bf6 100644 --- a/src/devops_cli/ai/rag/embeddings.py +++ b/src/devops_cli/ai/rag/embeddings.py @@ -1000,7 +1000,11 @@ def _openai_compatible_base_url(self) -> str: key="ai.gateway_url", ) return gw_url - return self.ai_config.api_base_url or "https://api.openai.com/v1" + if self.ai_config.api_base_url: + return self.ai_config.api_base_url + import openai + + return str(openai.OpenAI(api_key="none").base_url).rstrip("/") def _resolve_openai_endpoint_and_model( self, base_url: str, is_gateway: bool diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 5b0b59033f..994a386eb0 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -846,12 +846,10 @@ CONST_URL_ANTHROPIC_API_BASE = "https://api.anthropic.com" CONST_URL_GITHUB_COPILOT_API_BASE = "https://api.githubcopilot.com" -CONST_URL_OPENAI_API_BASE = "https://api.openai.com" # The API a hosted provider's requests, and the AI key, go to when no api_base_url is set. CONST_AI_PROVIDER_API_BASES: Final[dict[str, str]] = { "claude": CONST_URL_ANTHROPIC_API_BASE, "copilot": CONST_URL_GITHUB_COPILOT_API_BASE, - "openai": CONST_URL_OPENAI_API_BASE, } # What `backend_host` reports for a provider with no configured or default endpoint. It names # no server, so LLM spans write no `server.address` for it. diff --git a/tests/test_ai_benchmark.py b/tests/test_ai_benchmark.py index a60aaec3ea..c04e040dd8 100644 --- a/tests/test_ai_benchmark.py +++ b/tests/test_ai_benchmark.py @@ -12,7 +12,6 @@ from devops_cli.ai.benchmark.runner import BenchmarkRunner from devops_cli.ai.benchmark.tasks import BENCHMARK_TASKS, get_benchmark_tasks from devops_cli.commands.ai import app as ai_app -from devops_cli.config.constants import CONST_URL_OPENAI_API_BASE from devops_cli.config.settings import AIConfig, Settings from devops_cli.models.benchmark import ( BenchmarkReport, @@ -227,8 +226,8 @@ def test_benchmark_runner_concurrent_execution() -> None: ("openai", "https://example.com/v1", "m@https://example.com:8443", ""), ("openai", "https://example.com/v1", "m@https://example.com", "sk-test-configured"), ("gateway", None, "m@https://example.com:8443", "sk-test-configured"), - ("openai", None, f"m@{CONST_URL_OPENAI_API_BASE}/v1", "sk-test-configured"), - ("claude", None, f"m@{CONST_URL_OPENAI_API_BASE}/v1", ""), + ("openai", None, "m@https://api.openai.com/v1", "sk-test-configured"), + ("claude", None, "m@https://api.openai.com/v1", ""), ("openai", "https://example.com/v1", "m@https://example.com\\@192.0.2.1/v1", ""), ("openai", "https://example.com/v1", "m@https://example.com:443/v1", "sk-test-configured"), ( diff --git a/tests/test_ai_client_providers_and_embeddings.py b/tests/test_ai_client_providers_and_embeddings.py index 75f7ec6477..c466b6fc9a 100644 --- a/tests/test_ai_client_providers_and_embeddings.py +++ b/tests/test_ai_client_providers_and_embeddings.py @@ -31,7 +31,6 @@ from devops_cli.ai.client.streaming import ( StreamFrame, _ollama_stream_frame, - _openai_stream_frame, _read_event_stream, ) from devops_cli.config.settings import AIConfig @@ -219,12 +218,6 @@ def test_chunk_extractors_and_stream_helpers() -> None: StreamFrame(), ) - # 3. OpenAI frames - assert ( - _openai_stream_frame(_sse_event('{"choices": [{"delta": {"content": "openai text"}}]}')), - _openai_stream_frame(_sse_event("[DONE]")), - ) == (StreamFrame(chunk="openai text"), StreamFrame(complete=True, last=True)) - # 4. JSON error payload detector assert _is_json_error_payload('{"error": "model not found"}') is True assert _is_json_error_payload('{"error_code": 404}') is True @@ -311,11 +304,13 @@ def test_llm_client_streaming_and_error_branches(monkeypatch: pytest.MonkeyPatch # 3. Stream max bytes exceeded with ( - streamed([openai_chunk("huge line of stream tokens")] * 100) as response, + streamed([b"data: huge line of stream tokens\n\n"] * 100) as response, pytest.raises(AIClientError, match="exceeded maximum stream size"), ): list( - _read_event_stream(response, _openai_stream_frame, "TestProvider", max_stream_bytes=50) + _read_event_stream( + response, lambda ev: StreamFrame(chunk=ev.data), "TestProvider", max_stream_bytes=50 + ) ) # 4. Ollama semaphore and active tracking @@ -558,19 +553,11 @@ def test_streaming_extractors_edge_cases() -> None: _ollama_stream_frame("invalid json"), _ollama_stream_frame('{"message": {"thinking": "reasoning"}}'), _ollama_stream_frame('{"message": {"content": "token"}}'), - _openai_stream_frame(_sse_event("")), - _openai_stream_frame(_sse_event("[DONE]")), - _openai_stream_frame(_sse_event("invalid json")), - _openai_stream_frame(_sse_event('{"choices": [{"delta": {"content": "token"}}] }')), ) == ( StreamFrame(), StreamFrame(), StreamFrame(chunk="reasoning"), StreamFrame(chunk="token"), - StreamFrame(), - StreamFrame(complete=True, last=True), - StreamFrame(), - StreamFrame(chunk="token"), ) @@ -830,3 +817,78 @@ def test_augment_messages_starting_point(monkeypatch: pytest.MonkeyPatch) -> Non use_cache=False, ) assert str(res) == "Augmented response" + + +def test_openai_default_routes_use_v1(monkeypatch: pytest.MonkeyPatch) -> None: + openai_cfg = AIConfig( + provider="openai", model="gpt-4o", api_key="test-key", allow_private_network=True + ) + client_openai = LLMClient(openai_cfg) + + def answer(request: httpx2.Request) -> httpx2.Response: + if request.url.path.endswith("/models"): + return httpx2.Response(200, json={"data": [{"id": "gpt-4o"}]}) + body_text = request.read().decode() + if "stream" in body_text: + return reply([openai_chunk("hello"), OPENAI_DONE]) + return httpx2.Response( + 200, + json={ + "choices": [{"message": {"content": "ok"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + }, + ) + + sent = route_client(client_openai, monkeypatch, answer) + client_openai.chat("sys", "hello") + list(client_openai.chat_stream("sys", "hello")) + client_openai.list_models() + + urls = [str(r.url) for r in sent] + assert urls == [ + "https://api.openai.com/v1/chat/completions", + "https://api.openai.com/v1/chat/completions", + "https://api.openai.com/v1/models", + ] + + +def test_copilot_and_gateway_preserve_configured_endpoints( + monkeypatch: pytest.MonkeyPatch, +) -> None: + client_copilot = LLMClient( + AIConfig(provider="copilot", model="gpt-4o", api_key="test-key", allow_private_network=True) + ) + client_gateway = LLMClient( + AIConfig( + provider="gateway", + model="gpt-4o", + gateway_url="https://example.com/v1", + api_key="test-key", + allow_private_network=True, + ) + ) + + def answer(request: httpx2.Request) -> httpx2.Response: + return httpx2.Response( + 200, + json={ + "choices": [{"message": {"content": "ok"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + }, + ) + + sent_copilot = route_client(client_copilot, monkeypatch, answer) + client_copilot.chat("sys", "hello") + assert [str(r.url) for r in sent_copilot] == ["https://api.githubcopilot.com/chat/completions"] + + sent_gateway = route_client(client_gateway, monkeypatch, answer) + client_gateway.chat("sys", "hello") + assert [str(r.url) for r in sent_gateway] == ["https://example.com/v1/chat/completions"] + + +def test_openai_sdk_client_uses_factory_transport() -> None: + client = LLMClient( + AIConfig(provider="openai", model="gpt-4o", api_key="test-key", allow_private_network=True) + ) + sdk_client = client._openai_client() + assert sdk_client._client is client._shared_client() diff --git a/tests/test_ai_model_sampling.py b/tests/test_ai_model_sampling.py index 372cd28ba5..ec2d47fe7a 100644 --- a/tests/test_ai_model_sampling.py +++ b/tests/test_ai_model_sampling.py @@ -106,8 +106,8 @@ def test_streamed_openai_compat_payload_includes_sampling() -> None: cfg = AIConfig(provider="gateway", temperature=0.7, top_p=0.85) client = LLMClient(config=cfg) - payload_unstreamed = client._build_compat_payload("sys", [], stream=False) - payload_streamed = client._build_compat_payload("sys", [], stream=True) + payload_unstreamed = client._prepare_params("sys", [], stream=False) + payload_streamed = client._prepare_params("sys", [], stream=True) assert payload_unstreamed.get("temperature") == 0.7 assert payload_unstreamed.get("top_p") == 0.85 @@ -120,7 +120,7 @@ def test_streamed_openai_compat_payload_omits_sampling_when_use_model_sampling() cfg = AIConfig(provider="gateway", temperature=0.7, top_p=0.85, use_model_sampling=True) client = LLMClient(config=cfg) - payload = client._build_compat_payload("sys", [], stream=True) + payload = client._prepare_params("sys", [], stream=True) assert "temperature" not in payload assert "top_p" not in payload diff --git a/tests/test_ai_streaming.py b/tests/test_ai_streaming.py index 9e403a92fd..f32fbe83f9 100644 --- a/tests/test_ai_streaming.py +++ b/tests/test_ai_streaming.py @@ -4,8 +4,8 @@ import contextlib import json -from collections.abc import Iterable, Iterator -from typing import Any +from collections.abc import Callable, Iterable, Iterator +from typing import Any, Final import httpx2 import pytest @@ -19,7 +19,6 @@ StreamingTokenProcessor, _find_suffix_overlap, _ollama_stream_frame, - _openai_stream_frame, _read_event_stream, _read_ndjson_stream, ) @@ -32,7 +31,9 @@ OPENAI_DONE, SSE, RecordedBody, + anthropic_event, anthropic_stream_frames, + anthropic_text, ollama_line, openai_chunk, reply, @@ -269,9 +270,99 @@ def _event(data: object, event: str = "message") -> httpx2.ServerSentEvent: ) +def _claude_delta_text(delta: object) -> str | None: + """A content block delta's text, or its thinking wrapped in think tags.""" + if not isinstance(delta, dict): + return None + delta_type = delta.get("type") + if delta_type == "text_delta" and delta.get("text"): + return str(delta["text"]) + if delta_type == "thinking_delta" and delta.get("thinking"): + return f"{delta['thinking']}" + return None + + +def _claude_message_start(_payload: dict[str, Any]) -> StreamFrame: + return StreamFrame() + + +def _claude_message_delta(payload: dict[str, Any]) -> StreamFrame: + delta = payload.get("delta") + stop_reason = delta.get("stop_reason") if isinstance(delta, dict) else None + reason = ( + "stop" + if stop_reason == "end_turn" + else ("length" if stop_reason == "max_tokens" else stop_reason) + ) + return StreamFrame(finish_reason=reason) + + +_CLAUDE_EVENT_FRAMES: Final[dict[str, Callable[[dict[str, Any]], StreamFrame]]] = { + "message_start": _claude_message_start, + "content_block_delta": lambda payload: StreamFrame( + chunk=_claude_delta_text(payload.get("delta")) + ), + "message_delta": _claude_message_delta, + "message_stop": lambda _payload: StreamFrame(complete=True, last=True), + "error": lambda payload: StreamFrame( + error=str( + payload.get("error", {}).get("message") + if isinstance(payload.get("error"), dict) + else payload.get("error") + ) + ), +} + + +def _claude_stream_frame(event: httpx2.ServerSentEvent) -> StreamFrame: + if event.data.strip() == "[DONE]": + return StreamFrame() + if not event.data.strip(): + return StreamFrame() + try: + payload = json.loads(event.data) + except Exception: + return ( + StreamFrame(complete=True, last=True) + if event.event == "message_stop" + else StreamFrame() + ) + frame_for = _CLAUDE_EVENT_FRAMES.get(str(payload.get("type") or event.event)) + return frame_for(payload) if frame_for else StreamFrame() + + class TestProviderStreamFrames: """Each provider's frames: the text they carry, and whether and why the reply ended.""" + def test_claude_frames(self) -> None: + """Verify Claude events yield text and thinking, `message_stop` ends, `[DONE]` does not.""" + events = [ + {"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Claude text"}}, + {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": "Hm"}}, + {"type": "content_block_delta", "delta": {"type": "thinking_delta", "thinking": ""}}, + {"type": "content_block_delta", "delta": {"type": "other"}}, + {"type": "message_delta", "delta": {"stop_reason": "end_turn"}}, + {"type": "message_stop"}, + {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}, + {"type": "ping"}, + ] + + assert [_claude_stream_frame(_event(e)) for e in events] + [ + _claude_stream_frame(_event("[DONE]")), + _claude_stream_frame(_event("{invalid json", event="message_stop")), + ] == [ + StreamFrame(chunk="Claude text"), + StreamFrame(chunk="Hm"), + StreamFrame(), + StreamFrame(), + StreamFrame(finish_reason="stop"), + StreamFrame(complete=True, last=True), + StreamFrame(error="Overloaded"), + StreamFrame(), + StreamFrame(), + StreamFrame(complete=True, last=True), + ] + def test_ollama_frames(self) -> None: """Verify an Ollama line yields its content or thinking; `done: true` ends the stream.""" lines = [ @@ -295,35 +386,6 @@ def test_ollama_frames(self) -> None: StreamFrame(), ] - def test_openai_frames(self) -> None: - """Verify OpenAI chunks yield content and reasoning; a finish reason or `[DONE]` ends.""" - chunks = [ - {"choices": [{"delta": {"content": "OpenAI answer"}}]}, - {"choices": [{"delta": {"reasoning_content": "OpenAI reasoning"}}]}, - {"choices": [{"delta": {"reasoning": "More reasoning"}}]}, - {"choices": [{"delta": {}}]}, - {"choices": [{"delta": {}, "finish_reason": "tool_calls"}]}, - {"choices": [{"delta": {}, "finish_reason": "unheard_of"}]}, - {"choices": [], "usage": {"completion_tokens": 3}}, - {"error": {"message": "upstream timed out"}}, - ] - - assert [_openai_stream_frame(_event(c)) for c in chunks] + [ - _openai_stream_frame(_event("[DONE]")), - _openai_stream_frame(_event("{invalid json")), - ] == [ - StreamFrame(chunk="OpenAI answer"), - StreamFrame(chunk="OpenAI reasoning"), - StreamFrame(chunk="More reasoning"), - StreamFrame(), - StreamFrame(complete=True, finish_reason="tool_call"), - StreamFrame(complete=True), - StreamFrame(), - StreamFrame(error="upstream timed out"), - StreamFrame(complete=True, last=True), - StreamFrame(), - ] - class TestZeroLeakageDownstream: """Test suite verifying zero leakage of tokens into reports and review markdown.""" @@ -422,7 +484,7 @@ def test_streaming_token_processor_callbacks_and_unclosed_flush(self) -> None: # ── Stream readers, fed by an httpx2 MockTransport (no socket is opened) ────────────────────── _PROTOCOLS: dict[str, tuple[Any, Any, str]] = { - "openai": (_read_event_stream, _openai_stream_frame, SSE), + "anthropic": (_read_event_stream, _claude_stream_frame, SSE), "ollama": (_read_ndjson_stream, _ollama_stream_frame, NDJSON), } _GITHUB_TOKEN = "ghp_" + "A" * 36 @@ -459,17 +521,26 @@ def _read( ("protocol", "frames", "expected"), [ ( - "openai", - [openai_chunk("Hel"), openai_chunk("lo", "length"), OPENAI_DONE], - (["Hel", "lo"], "length", None), + "anthropic", + [ + anthropic_event("message_start", message={"id": "msg_1", "content": []}), + anthropic_text("Hi"), + anthropic_event("message_delta", delta={"stop_reason": "max_tokens"}), + anthropic_event("message_stop"), + ], + (["Hi"], "length", None), ), + ("anthropic", [anthropic_text("Hi"), OPENAI_DONE], (["Hi"], None, _ENDED_EARLY)), ( - "openai", - [openai_chunk("Hi"), openai_chunk(finish_reason="stop")], - (["Hi"], "stop", None), + "anthropic", + [ + anthropic_text("Hi"), + anthropic_event( + "error", error={"type": "overloaded_error", "message": "Overloaded"} + ), + ], + (["Hi"], None, "Provider stream reported an error: Overloaded"), ), - ("openai", [openai_chunk("Hi"), OPENAI_DONE], (["Hi"], None, None)), - ("openai", [openai_chunk("Hel"), openai_chunk("lo")], (["Hel", "lo"], None, _ENDED_EARLY)), ( "ollama", [ollama_line("Hi"), ollama_line(done=True, done_reason="length")], @@ -481,11 +552,6 @@ def _read( [ollama_line("Hi"), b'{"error": "model requires more system memory"}\n'], (["Hi"], None, "Provider stream reported an error: model requires more system memory"), ), - ( - "openai", - [openai_chunk("Hi"), sse_data({"error": {"message": "upstream timed out"}})], - (["Hi"], None, "Provider stream reported an error: upstream timed out"), - ), ( "ollama", [ollama_line("Hi"), b"\xff\n"], @@ -493,14 +559,12 @@ def _read( ), ], ids=[ - "openai-length-then-done", - "openai-reason-then-eof", - "openai-done-alone", - "openai-eof-without-either", + "anthropic-max-tokens-then-message-stop", + "anthropic-eof-before-message-stop", + "anthropic-error-event", "ollama-done-length", "ollama-eof-mid-line", "ollama-error-line", - "openai-error-object", "ollama-line-not-utf8", ], ) @@ -511,23 +575,17 @@ def test_a_stream_is_complete_only_at_its_final_frame( assert _read(protocol, frames) == expected -def test_reading_goes_on_past_the_finish_reason_to_done() -> None: - """Verify a usage chunk after the finish reason is still read, through to `[DONE]`.""" - usage = sse_data({"choices": [], "usage": {"prompt_tokens": 5, "completion_tokens": 2}}) - body = RecordedBody( - [openai_chunk("Hi"), openai_chunk(finish_reason="stop"), usage, OPENAI_DONE] - ) - - assert (_read("openai", body), body.read) == ((["Hi"], "stop", None), 4) - - @pytest.mark.parametrize( ("protocol", "frames", "reason"), [ - ("openai", [openai_chunk("Hi", "stop"), OPENAI_DONE, openai_chunk("late")], "stop"), + ( + "anthropic", + [anthropic_text("Hi"), anthropic_event("message_stop"), anthropic_text("late")], + None, + ), ("ollama", [ollama_line("Hi", done=True, done_reason="stop"), ollama_line("late")], "stop"), ], - ids=["openai-done", "ollama-done"], + ids=["anthropic-message-stop", "ollama-done"], ) def test_reading_stops_at_the_final_frame( protocol: str, frames: list[bytes], reason: str | None @@ -538,12 +596,12 @@ def test_reading_stops_at_the_final_frame( assert (_read(protocol, body), body.read) == ((["Hi"], reason, None), len(frames) - 1) -@pytest.mark.parametrize("protocol", ["openai", "ollama"]) +@pytest.mark.parametrize("protocol", ["anthropic", "ollama"]) def test_an_error_frame_is_masked_and_cut(protocol: str) -> None: """Verify a token in a provider's error message never reaches the raised error.""" message = f"bad credentials {_GITHUB_TOKEN} " + "x" * 400 error_frames = { - "openai": sse_data({"error": {"message": message}}), + "anthropic": anthropic_event("error", error={"message": message}), "ollama": (json.dumps({"error": message}) + "\n").encode(), } @@ -557,22 +615,23 @@ def test_an_error_frame_is_masked_and_cut(protocol: str) -> None: ) -@pytest.mark.parametrize("protocol", ["openai", "ollama"]) +@pytest.mark.parametrize("protocol", ["anthropic", "ollama"]) def test_a_frame_split_across_chunks_reads_as_whole(protocol: str) -> None: """Verify frames split mid-line and mid-code-point, and a raw U+2028, read intact.""" text = "naïve € \u2028 end" frames = { - "openai": [openai_chunk(text, "stop"), OPENAI_DONE], + "anthropic": [anthropic_text(text), anthropic_event("message_stop")], "ollama": [ollama_line(text, done=True, done_reason="stop")], }[protocol] whole = b"".join(frames) one_byte_chunks = [whole[i : i + 1] for i in range(len(whole))] + expected_reason = "stop" if protocol == "ollama" else None assert ( "\u2028".encode() in whole, _read(protocol, [whole]), _read(protocol, one_byte_chunks), - ) == (True, ([text], "stop", None), ([text], "stop", None)) + ) == (True, ([text], expected_reason, None), ([text], expected_reason, None)) def test_an_oversized_event_or_line_is_refused() -> None: @@ -581,7 +640,11 @@ def test_an_oversized_event_or_line_is_refused() -> None: line_limit = "Provider stream line exceeded the 64 bytes limit." assert ( - _read("openai", [openai_chunk("x" * 200), OPENAI_DONE], max_event_bytes=64), + _read( + "anthropic", + [anthropic_text("x" * 200), anthropic_event("message_stop")], + max_event_bytes=64, + ), _read("ollama", endless_line, max_line_bytes=64)[2], endless_line.read < len(endless_line.frames), _read("ollama", [ollama_line("x" * 200, done=True)], max_line_bytes=64), @@ -598,7 +661,8 @@ def test_an_oversized_event_or_line_is_refused() -> None: @pytest.mark.parametrize( - ("protocol", "frame"), [("openai", openai_chunk("x" * 10)), ("ollama", ollama_line("x" * 10))] + ("protocol", "frame"), + [("anthropic", anthropic_text("x" * 10)), ("ollama", ollama_line("x" * 10))], ) def test_a_stream_past_its_size_limit_is_refused(protocol: str, frame: bytes) -> None: """Verify the whole-stream limit counts every frame and raises once it is passed.""" @@ -613,7 +677,10 @@ def test_a_stream_past_its_size_limit_is_refused(protocol: str, frame: bytes) -> @pytest.mark.parametrize( ("protocol", "frames"), [ - ("openai", [openai_chunk("Hel"), openai_chunk("lo", "stop"), OPENAI_DONE]), + ( + "anthropic", + [anthropic_text("Hel"), anthropic_text("lo"), anthropic_event("message_stop")], + ), ("ollama", [ollama_line("Hel"), ollama_line("lo"), ollama_line(done=True)]), ], ) @@ -631,7 +698,11 @@ def test_chunks_reach_the_caller_as_they_arrive(protocol: str, frames: list[byte def test_an_event_stream_of_another_content_type_is_refused() -> None: """Verify an SSE reply sent as `application/json` raises, naming the type.""" - _, _, error = _read("openai", [openai_chunk("Hi"), OPENAI_DONE], "application/json") + _, _, error = _read( + "anthropic", + [anthropic_text("Hi"), anthropic_event("message_stop")], + "application/json", + ) assert error == ( "Provider stream could not be read: Expected response with content type " diff --git a/tests/test_batch_2_review_defects.py b/tests/test_batch_2_review_defects.py index 9eb77a7303..1f3f1c40dd 100644 --- a/tests/test_batch_2_review_defects.py +++ b/tests/test_batch_2_review_defects.py @@ -275,7 +275,7 @@ def test_reasoning_models_use_max_completion_tokens() -> None: supports_reasoning=True, ) provider = LLMClient(config=cfg) - payload = provider._build_compat_payload( + payload = provider._prepare_params( system="system prompt", messages=[ChatMessage(role="user", content="hello")], ) diff --git a/tests/test_thinking_providers.py b/tests/test_thinking_providers.py index 57a68c23e5..36630b65d2 100644 --- a/tests/test_thinking_providers.py +++ b/tests/test_thinking_providers.py @@ -483,12 +483,22 @@ def handler(request: httpx2.Request) -> httpx2.Response: chunks = list(client.chat_stream("System", "Hello", enable_thinking=True)) assert "step 1 reasoning" in "".join(chunks) - def test_extract_openai_reasoning_content_delta(self) -> None: - from devops_cli.ai.client.streaming import StreamFrame, _openai_stream_frame + def test_extract_openai_reasoning_content_delta(self, monkeypatch: pytest.MonkeyPatch) -> None: + from devops_cli.models.ai import ChatMessage + from tests.llm_stream_fakes import OPENAI_DONE, openai_chunk, reply, route_client, sse_data - data = '{"choices": [{"delta": {"reasoning_content": "step 1 reasoning"}}]}' - frame = _openai_stream_frame(httpx2.ServerSentEvent(data=data)) - assert frame == StreamFrame(chunk="step 1 reasoning") + cfg = AIConfig(provider="openai", model="deepseek-reasoner", allow_private_network=True) + client = LLMClient(cfg, api_key="sk-test-token") + frames = [ + sse_data( + {"choices": [{"index": 0, "delta": {"reasoning_content": "step 1 reasoning"}}]} + ), + openai_chunk("42", "stop"), + OPENAI_DONE, + ] + route_client(client, monkeypatch, lambda request: reply(frames)) + chunks = list(client.chat_messages_stream("sys", [ChatMessage(role="user", content="hi")])) + assert chunks == ["step 1 reasoning", "42"] class TestGatewayReasoningPayloadRouting: