Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
schema: spec-driven
created: 2026-10-26
skip_specs: true
Original file line number Diff line number Diff line change
@@ -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 `<think>{reasoning}</think>` 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`.
Original file line number Diff line number Diff line change
@@ -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.
Original file line number Diff line number Diff line change
@@ -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 <!-- id: 0 -->
- 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 <!-- id: 1 -->
- 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 <!-- id: 2 -->
- 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 <!-- id: 3 -->
- 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` <!-- id: 4 -->
- Verification: `git grep "CONST_URL_OPENAI_API_BASE" src/` returns nothing
- [x] Update existing tests referencing deleted constants or frames <!-- id: 5 -->
- 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 <!-- id: 6 -->
- Verification: `uv run devops ci fail-to-pass --base origin/main`
- [x] Verify full CI checks pass <!-- id: 7 -->
- Verification: `uv run devops ci`
- [x] Archive OpenSpec change <!-- id: 8 -->
- 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`).
12 changes: 10 additions & 2 deletions src/devops_cli/ai/benchmark/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -68,15 +76,15 @@ 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))
}
provider = client_config.provider.lower()
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 ""
Expand Down
4 changes: 3 additions & 1 deletion src/devops_cli/ai/client/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading