irregular6612 commited on
Commit
6491bd0
·
1 Parent(s): 3635b39

feat(cp4): port cloud providers (openai/anthropic/gemini/ollama) into proteus

Browse files
proteus/providers/anthropic_provider.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Anthropic provider for Claude-family models.
2
+
3
+ Uses the official anthropic Python client (sync) to call the messages API.
4
+ Handles the Anthropic-specific system message placement and thinking content
5
+ blocks.
6
+
7
+ Example configuration::
8
+
9
+ provider:
10
+ type: anthropic
11
+ model: claude-sonnet-4-20250514
12
+ # api_key: defaults to ANTHROPIC_API_KEY env var
13
+
14
+ Note: This file is intentionally named ``anthropic_provider.py`` (not
15
+ ``anthropic.py``) to avoid shadowing the ``anthropic`` package.
16
+ """
17
+
18
+ import logging
19
+ import os
20
+ import time
21
+
22
+ from anthropic import Anthropic
23
+ from anthropic import APIError, APITimeoutError, RateLimitError
24
+
25
+ from proteus.providers.base import CompletionResult, LLMProvider
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ _RETRYABLE_EXCEPTIONS = (RateLimitError, APITimeoutError, APIError)
30
+ _MAX_RETRIES = 3
31
+ _BACKOFF_SECONDS = (1, 2, 4)
32
+
33
+
34
+ class AnthropicProvider(LLMProvider):
35
+ """LLM provider backed by the Anthropic messages API.
36
+
37
+ Args:
38
+ model: Model identifier (e.g. ``"claude-sonnet-4-20250514"``).
39
+ api_key: Anthropic API key. Falls back to ``ANTHROPIC_API_KEY`` env var.
40
+ base_url: Custom API base URL for private Anthropic deployments.
41
+ max_retries: Number of retries on transient failures.
42
+ timeout: Request timeout in seconds.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ model: str = "claude-sonnet-4-20250514",
48
+ api_key: str | None = None,
49
+ base_url: str | None = None,
50
+ max_retries: int = 3,
51
+ timeout: float = 120.0,
52
+ top_p: float = 0.0,
53
+ top_k: int = 0,
54
+ enable_thinking: bool | None = None,
55
+ thinking_budget: int | None = None,
56
+ ) -> None:
57
+ self._model = model
58
+ self._max_retries = max_retries
59
+ self._timeout = timeout
60
+ self._top_p = top_p
61
+ self._top_k = top_k
62
+ self._enable_thinking = enable_thinking
63
+ self._thinking_budget = thinking_budget
64
+ resolved_key = api_key or os.environ.get("ANTHROPIC_API_KEY")
65
+ if not resolved_key:
66
+ raise ValueError(
67
+ "Anthropic API key must be provided via api_key param "
68
+ "or ANTHROPIC_API_KEY environment variable."
69
+ )
70
+ client_kwargs: dict = {"api_key": resolved_key}
71
+ if base_url:
72
+ client_kwargs["base_url"] = base_url
73
+ self._client = Anthropic(**client_kwargs)
74
+
75
+ @property
76
+ def model_name(self) -> str:
77
+ return self._model
78
+
79
+ def complete(
80
+ self,
81
+ messages: list[dict[str, str]],
82
+ temperature: float = 0.7,
83
+ max_tokens: int = 4096,
84
+ ) -> CompletionResult:
85
+ """Send a messages request with retry on transient failures.
86
+
87
+ System messages are extracted from ``messages`` and passed via the
88
+ dedicated ``system`` parameter, as required by the Anthropic API.
89
+
90
+ Args:
91
+ messages: Chat messages with ``role`` and ``content`` keys.
92
+ Messages with ``role="system"`` are extracted automatically.
93
+ temperature: Sampling temperature.
94
+ max_tokens: Maximum tokens to generate.
95
+
96
+ Returns:
97
+ CompletionResult containing response text and token usage.
98
+
99
+ Raises:
100
+ anthropic.APIError: After exhausting all retries.
101
+ """
102
+ system_text, non_system = self._split_system_messages(messages)
103
+
104
+ kwargs: dict = {
105
+ "model": self._model,
106
+ "messages": non_system,
107
+ "temperature": temperature,
108
+ "max_tokens": max_tokens,
109
+ }
110
+ if self._top_p > 0.0:
111
+ kwargs["top_p"] = self._top_p
112
+ if self._top_k > 0:
113
+ kwargs["top_k"] = self._top_k
114
+ if system_text:
115
+ kwargs["system"] = system_text
116
+
117
+ # Extended thinking support (Claude 3.5+).
118
+ # Anthropic requires temperature=1.0 when thinking is enabled.
119
+ if self._enable_thinking:
120
+ budget = self._thinking_budget or 10240
121
+ kwargs["thinking"] = {
122
+ "type": "enabled",
123
+ "budget_tokens": budget,
124
+ }
125
+ kwargs["temperature"] = 1.0
126
+
127
+ last_error: Exception | None = None
128
+ for attempt in range(self._max_retries + 1):
129
+ try:
130
+ response = self._client.messages.create(**kwargs)
131
+ break
132
+ except _RETRYABLE_EXCEPTIONS as exc:
133
+ last_error = exc
134
+ if attempt < self._max_retries:
135
+ wait = _BACKOFF_SECONDS[min(attempt, len(_BACKOFF_SECONDS) - 1)]
136
+ logger.warning(
137
+ "Anthropic request failed (attempt %d/%d): %s. "
138
+ "Retrying in %ds...",
139
+ attempt + 1,
140
+ self._max_retries + 1,
141
+ exc,
142
+ wait,
143
+ )
144
+ time.sleep(wait)
145
+ else:
146
+ raise last_error # type: ignore[misc]
147
+
148
+ # Extract text and thinking tokens from content blocks.
149
+ text_parts: list[str] = []
150
+ thinking_text_parts: list[str] = []
151
+ thinking_tokens = 0
152
+ for block in response.content:
153
+ if block.type == "text":
154
+ text_parts.append(block.text)
155
+ elif block.type == "thinking":
156
+ thinking_tokens += getattr(
157
+ block, "input_tokens", len(block.thinking) // 4
158
+ )
159
+ thinking_text_parts.append(block.thinking)
160
+
161
+ text = "\n".join(text_parts)
162
+ thinking_text = "\n".join(thinking_text_parts) if thinking_text_parts else None
163
+
164
+ usage = response.usage
165
+ input_tokens = usage.input_tokens
166
+ output_tokens = usage.output_tokens
167
+ finish_reason = response.stop_reason # "end_turn", "max_tokens", etc.
168
+
169
+ return CompletionResult(
170
+ text=text,
171
+ input_tokens=input_tokens,
172
+ output_tokens=output_tokens,
173
+ thinking_tokens=thinking_tokens,
174
+ thinking_text=thinking_text,
175
+ finish_reason=finish_reason,
176
+ )
177
+
178
+ @staticmethod
179
+ def _split_system_messages(
180
+ messages: list[dict[str, str]],
181
+ ) -> tuple[str, list[dict[str, str]]]:
182
+ """Separate system messages from user/assistant messages.
183
+
184
+ The Anthropic API requires the system prompt to be passed as a
185
+ top-level ``system`` parameter rather than as a message with
186
+ ``role="system"``.
187
+
188
+ Returns:
189
+ A tuple of (concatenated system text, remaining messages).
190
+ """
191
+ system_parts: list[str] = []
192
+ non_system: list[dict[str, str]] = []
193
+ for msg in messages:
194
+ if msg["role"] == "system":
195
+ system_parts.append(msg["content"])
196
+ else:
197
+ non_system.append(msg)
198
+ return "\n\n".join(system_parts), non_system
proteus/providers/gemini.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Google Gemini provider for Gemini-family models.
2
+
3
+ Uses the official google-genai Python SDK (sync) to call generate_content.
4
+ Supports thinking tokens from Gemini 2.5+ models for Reasoning Investment
5
+ tracking.
6
+
7
+ Example configuration::
8
+
9
+ provider:
10
+ type: gemini
11
+ model: gemini-2.0-flash
12
+ # api_key: defaults to GEMINI_API_KEY env var
13
+ """
14
+
15
+ import logging
16
+ import os
17
+ import time
18
+
19
+ from google import genai
20
+ from google.genai import types
21
+ from google.genai.errors import APIError, ClientError, ServerError
22
+
23
+ from proteus.providers.base import CompletionResult, LLMProvider
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ _RETRYABLE_EXCEPTIONS = (ServerError, ClientError, APIError)
28
+ _MAX_RETRIES = 3
29
+ _BACKOFF_SECONDS = (2, 4, 8)
30
+
31
+
32
+ class GeminiProvider(LLMProvider):
33
+ """LLM provider backed by the Google Gemini API.
34
+
35
+ Args:
36
+ model: Model identifier (e.g. ``"gemini-2.0-flash"``).
37
+ api_key: Gemini API key. Falls back to ``GEMINI_API_KEY`` env var.
38
+ max_retries: Number of retries on transient failures.
39
+ timeout: Request timeout in seconds.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ model: str = "gemini-2.0-flash",
45
+ api_key: str | None = None,
46
+ max_retries: int = 3,
47
+ timeout: float = 120.0,
48
+ top_p: float = 0.0,
49
+ top_k: int = 0,
50
+ seed: int | None = None,
51
+ enable_thinking: bool | None = None,
52
+ thinking_budget: int | None = None,
53
+ reasoning_effort: str | None = None,
54
+ ) -> None:
55
+ self._model = model
56
+ self._max_retries = max_retries
57
+ self._timeout = timeout
58
+ self._top_p = top_p
59
+ self._top_k = top_k
60
+ self._seed = seed
61
+ self._enable_thinking = enable_thinking
62
+ self._thinking_budget = thinking_budget
63
+ self._reasoning_effort = reasoning_effort
64
+ resolved_key = api_key or os.environ.get("GEMINI_API_KEY")
65
+ if not resolved_key:
66
+ raise ValueError(
67
+ "Gemini API key must be provided via api_key param "
68
+ "or GEMINI_API_KEY environment variable."
69
+ )
70
+ self._client = genai.Client(
71
+ api_key=resolved_key,
72
+ http_options=types.HttpOptions(timeout=int(timeout * 1000)),
73
+ )
74
+
75
+ @property
76
+ def model_name(self) -> str:
77
+ return self._model
78
+
79
+ def complete(
80
+ self,
81
+ messages: list[dict[str, str]],
82
+ temperature: float = 0.7,
83
+ max_tokens: int = 4096,
84
+ ) -> CompletionResult:
85
+ """Send a generate_content request with retry on transient failures.
86
+
87
+ System messages are extracted and passed via the ``system_instruction``
88
+ parameter, as required by the Gemini API.
89
+
90
+ Args:
91
+ messages: Chat messages with ``role`` and ``content`` keys.
92
+ Messages with ``role="system"`` are extracted automatically.
93
+ temperature: Sampling temperature.
94
+ max_tokens: Maximum tokens to generate.
95
+
96
+ Returns:
97
+ CompletionResult containing response text and token usage.
98
+
99
+ Raises:
100
+ google.genai.errors.APIError: After exhausting all retries.
101
+ """
102
+ system_text, contents = self._convert_messages(messages)
103
+
104
+ config_kwargs: dict = {
105
+ "temperature": temperature,
106
+ "max_output_tokens": max_tokens,
107
+ }
108
+ if self._top_p > 0.0:
109
+ config_kwargs["top_p"] = self._top_p
110
+ if self._top_k > 0:
111
+ config_kwargs["top_k"] = self._top_k
112
+ if self._seed is not None:
113
+ config_kwargs["seed"] = self._seed
114
+
115
+ # Thinking config: always include thoughts for RI tracking.
116
+ thinking_kwargs: dict = {"include_thoughts": True}
117
+ if self._thinking_budget is not None:
118
+ thinking_kwargs["thinking_budget"] = self._thinking_budget
119
+ if self._reasoning_effort:
120
+ thinking_kwargs["thinking_level"] = self._reasoning_effort
121
+ if self._enable_thinking is False:
122
+ thinking_kwargs = {"include_thoughts": False}
123
+
124
+ config_kwargs["thinking_config"] = types.ThinkingConfig(**thinking_kwargs)
125
+ config = types.GenerateContentConfig(**config_kwargs)
126
+ if system_text:
127
+ config.system_instruction = system_text
128
+
129
+ last_error: Exception | None = None
130
+ response = None
131
+ for attempt in range(self._max_retries + 1):
132
+ try:
133
+ response = self._client.models.generate_content(
134
+ model=self._model,
135
+ contents=contents,
136
+ config=config,
137
+ )
138
+ break
139
+ except _RETRYABLE_EXCEPTIONS as exc:
140
+ last_error = exc
141
+ if attempt < self._max_retries:
142
+ wait = _BACKOFF_SECONDS[min(attempt, len(_BACKOFF_SECONDS) - 1)]
143
+ logger.warning(
144
+ "Gemini request failed (attempt %d/%d): %s. "
145
+ "Retrying in %ds...",
146
+ attempt + 1,
147
+ self._max_retries + 1,
148
+ exc,
149
+ wait,
150
+ )
151
+ time.sleep(wait)
152
+ else:
153
+ raise last_error # type: ignore[misc]
154
+
155
+ # Extract text and thinking from response parts.
156
+ text_parts: list[str] = []
157
+ thinking_text_parts: list[str] = []
158
+ finish_reason = None
159
+ if response.candidates:
160
+ candidate = response.candidates[0]
161
+ finish_reason = getattr(candidate, "finish_reason", None)
162
+ # Gemini returns enum; convert to string.
163
+ if finish_reason is not None:
164
+ finish_reason = str(finish_reason).lower()
165
+ for part in candidate.content.parts:
166
+ if part.thought:
167
+ if part.text:
168
+ thinking_text_parts.append(part.text)
169
+ elif part.text:
170
+ text_parts.append(part.text)
171
+
172
+ text = "\n".join(text_parts)
173
+ thinking_text = "\n".join(thinking_text_parts) if thinking_text_parts else None
174
+
175
+ # Token counts from usage metadata.
176
+ usage = response.usage_metadata
177
+ input_tokens = usage.prompt_token_count or 0 if usage else 0
178
+ output_tokens = usage.candidates_token_count or 0 if usage else 0
179
+
180
+ # Prefer API-reported thinking token count; fall back to heuristic.
181
+ thinking_tokens = 0
182
+ if usage and usage.thoughts_token_count:
183
+ thinking_tokens = usage.thoughts_token_count
184
+ elif thinking_text_parts:
185
+ thinking_tokens = len("".join(thinking_text_parts)) // 4
186
+
187
+ return CompletionResult(
188
+ text=text,
189
+ input_tokens=input_tokens,
190
+ output_tokens=output_tokens,
191
+ thinking_tokens=thinking_tokens,
192
+ thinking_text=thinking_text,
193
+ finish_reason=finish_reason,
194
+ )
195
+
196
+ @staticmethod
197
+ def _convert_messages(
198
+ messages: list[dict[str, str]],
199
+ ) -> tuple[str, list[types.Content]]:
200
+ """Convert OpenAI-style messages to Gemini Content objects.
201
+
202
+ Separates system messages and maps ``assistant`` role to ``model``.
203
+
204
+ Returns:
205
+ A tuple of (system instruction text, list of Content objects).
206
+ """
207
+ system_parts: list[str] = []
208
+ contents: list[types.Content] = []
209
+ for msg in messages:
210
+ role = msg["role"]
211
+ if role == "system":
212
+ system_parts.append(msg["content"])
213
+ else:
214
+ # Gemini uses "model" instead of "assistant".
215
+ gemini_role = "model" if role == "assistant" else "user"
216
+ contents.append(
217
+ types.Content(
218
+ role=gemini_role,
219
+ parts=[types.Part(text=msg["content"])],
220
+ )
221
+ )
222
+ return "\n\n".join(system_parts), contents
proteus/providers/ollama_cloud.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Ollama Cloud provider for Qwen3 / GPT-OSS / DeepSeek reasoning models.
2
+
3
+ Unlike :class:`LocalProvider` (which targets the OpenAI-compatible
4
+ ``/v1/chat/completions`` endpoint and therefore strips the native
5
+ ``message.thinking`` field), this provider speaks Ollama's **native**
6
+ ``/api/chat`` protocol so that reasoning content is returned as a
7
+ structured ``message.thinking`` string — the shape the Phase O Unit 15
8
+ split-call analyses expect for `thinking_text_task` /
9
+ `thinking_text_forfeit`.
10
+
11
+ The endpoint, authentication, and payload schema follow the Ollama Cloud
12
+ docs (https://docs.ollama.com/cloud, https://docs.ollama.com/capabilities/thinking):
13
+
14
+ - Base URL default: ``https://ollama.com``
15
+ - Path: ``POST /api/chat``
16
+ - Auth: ``Authorization: Bearer $OLLAMA_API_KEY``
17
+ - Request body: ``{model, messages, stream=false, think, options{...}}``
18
+ - Response body: ``{message:{content, thinking}, prompt_eval_count,
19
+ eval_count, done_reason, ...}``
20
+
21
+ Example configuration::
22
+
23
+ provider:
24
+ provider: ollama_cloud
25
+ model: qwen3.5:cloud
26
+ api_key_env: OLLAMA_API_KEY
27
+ enable_thinking: true
28
+ temperature: 0.7
29
+ top_p: 0.95
30
+ top_k: 20
31
+
32
+ The ``enable_thinking`` toggle is forwarded to Ollama as ``think``
33
+ (boolean). For ``gpt-oss`` models that require a level
34
+ (``"low"``/``"medium"``/``"high"``), pass ``reasoning_effort`` on the
35
+ provider config instead — it is forwarded verbatim to ``think``.
36
+
37
+ Token accounting mirrors :class:`MLXServerProvider`: ``output_tokens``
38
+ is kept as Ollama's ``eval_count`` (total generated tokens, which
39
+ physically includes any thinking output), and ``thinking_tokens`` is a
40
+ whitespace-split estimate of ``message.thinking`` so the Reasoning
41
+ Investment metric is comparable across providers.
42
+ """
43
+
44
+ import logging
45
+ import os
46
+ import time
47
+
48
+ import httpx
49
+
50
+ from proteus.providers.base import CompletionResult, LLMProvider
51
+ from proteus.providers.thinking_utils import parse_thinking_tags
52
+
53
+ logger = logging.getLogger(__name__)
54
+
55
+ # HTTP status codes we retry on. 4xx other than 429 are permanent
56
+ # client errors (auth, malformed payload) and propagate immediately.
57
+ _RETRYABLE_STATUSES: frozenset[int] = frozenset({429, 500, 502, 503, 504})
58
+ _BACKOFF_SECONDS: tuple[int, ...] = (1, 2, 4)
59
+
60
+
61
+ class OllamaCloudProvider(LLMProvider):
62
+ """LLM provider backed by Ollama Cloud's native ``/api/chat`` endpoint.
63
+
64
+ Routes every request through the native protocol (not the
65
+ OpenAI-compatible path) so that Qwen3 / GPT-OSS / DeepSeek
66
+ reasoning models return ``message.thinking`` as a structured field
67
+ rather than inlining ``<think>`` tags. Falls back to
68
+ :func:`parse_thinking_tags` when the server happens to inline tags
69
+ (older deployments, non-cloud tags).
70
+
71
+ Args:
72
+ model: Ollama model tag, e.g. ``"qwen3.5:cloud"`` or
73
+ ``"gpt-oss:120b-cloud"``. For local Ollama usage the
74
+ existing ``LocalProvider`` is the better fit — this class
75
+ targets the hosted cloud path.
76
+ api_key: Ollama Cloud API key. Falls back to the
77
+ ``OLLAMA_API_KEY`` environment variable.
78
+ base_url: Override the cloud host. Defaults to
79
+ ``https://ollama.com``. Any ``/api/chat`` suffix on the
80
+ input is stripped before the request is dispatched.
81
+ max_retries: Retry budget for transient 429/5xx and network
82
+ errors (exponential backoff: 1s, 2s, 4s).
83
+ timeout: Request timeout in seconds.
84
+ top_p: Nucleus sampling parameter (``0.0`` disables).
85
+ top_k: Top-k sampling parameter (``0`` disables).
86
+ seed: Deterministic seed.
87
+ repetition_penalty: Ollama ``repeat_penalty`` option
88
+ (``0.0`` / ``1.0`` disables).
89
+ enable_thinking: Forwarded as the Ollama ``think`` field.
90
+ ``None`` = omit (server default), ``True`` / ``False`` =
91
+ force on/off. For gpt-oss which expects a level string,
92
+ use ``reasoning_effort`` instead.
93
+ reasoning_effort: Level string (``"low"`` / ``"medium"`` /
94
+ ``"high"``) forwarded to ``think`` for gpt-oss-family
95
+ models. Takes precedence over ``enable_thinking`` when set.
96
+ """
97
+
98
+ DEFAULT_BASE_URL = "https://ollama.com"
99
+
100
+ def __init__(
101
+ self,
102
+ model: str = "qwen3.5:cloud",
103
+ api_key: str | None = None,
104
+ base_url: str | None = None,
105
+ max_retries: int = 3,
106
+ timeout: float = 120.0,
107
+ top_p: float = 0.0,
108
+ top_k: int = 0,
109
+ seed: int | None = None,
110
+ repetition_penalty: float = 0.0,
111
+ enable_thinking: bool | None = None,
112
+ reasoning_effort: str | None = None,
113
+ ) -> None:
114
+ self._model = model
115
+ self._max_retries = max_retries
116
+ self._timeout = timeout
117
+ self._top_p = top_p
118
+ self._top_k = top_k
119
+ self._seed = seed
120
+ self._repetition_penalty = repetition_penalty
121
+ self._enable_thinking = enable_thinking
122
+ self._reasoning_effort = reasoning_effort
123
+
124
+ resolved_key = api_key or os.environ.get("OLLAMA_API_KEY")
125
+ if not resolved_key:
126
+ raise ValueError(
127
+ "Ollama Cloud API key must be provided via api_key param "
128
+ "or OLLAMA_API_KEY environment variable."
129
+ )
130
+ self._api_key = resolved_key
131
+
132
+ # Normalise the base URL: accept either ``https://ollama.com``
133
+ # or ``https://ollama.com/api/chat`` — we always POST to /api/chat
134
+ # internally so duplicate suffixes would break silently.
135
+ host = (base_url or self.DEFAULT_BASE_URL).rstrip("/")
136
+ if host.endswith("/api/chat"):
137
+ host = host[: -len("/api/chat")]
138
+ self._base_url = host
139
+
140
+ self._client = httpx.Client(
141
+ base_url=self._base_url,
142
+ timeout=timeout,
143
+ headers={
144
+ "Authorization": f"Bearer {self._api_key}",
145
+ "Content-Type": "application/json",
146
+ "Accept": "application/json",
147
+ },
148
+ )
149
+ logger.info(
150
+ "OllamaCloudProvider targeting %s at %s (thinking=%s, effort=%s)",
151
+ model, self._base_url, enable_thinking, reasoning_effort,
152
+ )
153
+
154
+ @property
155
+ def model_name(self) -> str:
156
+ return self._model
157
+
158
+ # ------------------------------------------------------------------
159
+ # Public entry
160
+ # ------------------------------------------------------------------
161
+
162
+ def complete(
163
+ self,
164
+ messages: list[dict[str, str]],
165
+ temperature: float = 0.7,
166
+ max_tokens: int = 4096,
167
+ ) -> CompletionResult:
168
+ """Send a non-streaming chat request to Ollama Cloud.
169
+
170
+ Args:
171
+ messages: Chat messages with ``role`` and ``content`` keys.
172
+ Forwarded verbatim to ``/api/chat`` — Ollama accepts
173
+ the same role set (``system`` / ``user`` / ``assistant``
174
+ / ``tool``) we already produce.
175
+ temperature: Sampling temperature → ``options.temperature``.
176
+ max_tokens: Max generation tokens → ``options.num_predict``.
177
+
178
+ Returns:
179
+ :class:`CompletionResult` with the answer in ``text`` and the
180
+ reasoning trace in ``thinking_text`` (``None`` if the model
181
+ did not reason). ``thinking_tokens`` is a whitespace-split
182
+ estimate of the thinking text, matching the convention used
183
+ by :class:`MLXServerProvider` so Reasoning Investment values
184
+ are comparable across backends.
185
+ """
186
+ options: dict[str, object] = {
187
+ "temperature": temperature,
188
+ "num_predict": max_tokens,
189
+ }
190
+ if self._top_p > 0.0:
191
+ options["top_p"] = self._top_p
192
+ if self._top_k > 0:
193
+ options["top_k"] = self._top_k
194
+ if self._seed is not None:
195
+ options["seed"] = self._seed
196
+ if self._repetition_penalty > 0.0 and self._repetition_penalty != 1.0:
197
+ options["repeat_penalty"] = self._repetition_penalty
198
+
199
+ payload: dict[str, object] = {
200
+ "model": self._model,
201
+ "messages": messages,
202
+ "stream": False,
203
+ "options": options,
204
+ }
205
+
206
+ # Resolve the ``think`` field. reasoning_effort wins (gpt-oss
207
+ # needs a level string) and falls back to the boolean toggle.
208
+ # Absent both → omit so the server default applies.
209
+ think_value: object | None = None
210
+ if self._reasoning_effort is not None:
211
+ think_value = self._reasoning_effort
212
+ elif self._enable_thinking is not None:
213
+ think_value = self._enable_thinking
214
+ if think_value is not None:
215
+ payload["think"] = think_value
216
+
217
+ response_json = self._call_with_retry(payload)
218
+
219
+ message = response_json.get("message") or {}
220
+ text = message.get("content") or ""
221
+ thinking_text_raw = message.get("thinking") or None
222
+
223
+ input_tokens = int(response_json.get("prompt_eval_count") or 0)
224
+ output_tokens = int(response_json.get("eval_count") or 0)
225
+ done_reason = response_json.get("done_reason") or "stop"
226
+
227
+ # Preferred path: Ollama returned a structured ``thinking``
228
+ # field (cloud Qwen3 with ``think=true``). Count tokens via
229
+ # whitespace split — matches parse_thinking_tags so the RI
230
+ # metric is comparable to MLXServerProvider / CUDAServerProvider.
231
+ if thinking_text_raw:
232
+ thinking_text: str | None = thinking_text_raw
233
+ thinking_tokens = len(thinking_text_raw.split())
234
+ else:
235
+ # Fallback: older deployments or non-cloud tags may still
236
+ # inline <think>...</think> tags in content. Reuse the
237
+ # shared parser so behaviour stays consistent with other
238
+ # server-based providers.
239
+ text, thinking_tokens, thinking_text = parse_thinking_tags(text)
240
+
241
+ return CompletionResult(
242
+ text=text,
243
+ input_tokens=input_tokens,
244
+ output_tokens=output_tokens,
245
+ thinking_tokens=thinking_tokens,
246
+ thinking_text=thinking_text,
247
+ logprobs=None,
248
+ finish_reason=done_reason,
249
+ )
250
+
251
+ # ------------------------------------------------------------------
252
+ # HTTP helpers
253
+ # ------------------------------------------------------------------
254
+
255
+ def _call_with_retry(self, payload: dict) -> dict:
256
+ """POST ``/api/chat`` with exponential-backoff retries.
257
+
258
+ Retries on 429 / 5xx / network errors only. Auth / validation
259
+ errors (4xx other than 429) surface immediately so the caller
260
+ sees actionable failure rather than burning the retry budget.
261
+ """
262
+ last_error: Exception | None = None
263
+ for attempt in range(self._max_retries + 1):
264
+ try:
265
+ response = self._client.post("/api/chat", json=payload)
266
+ if response.status_code in _RETRYABLE_STATUSES:
267
+ snippet = response.text[:200]
268
+ logger.warning(
269
+ "Ollama Cloud %d on attempt %d/%d: %s",
270
+ response.status_code,
271
+ attempt + 1,
272
+ self._max_retries + 1,
273
+ snippet,
274
+ )
275
+ last_error = httpx.HTTPStatusError(
276
+ f"Ollama Cloud transient {response.status_code}: {snippet}",
277
+ request=response.request,
278
+ response=response,
279
+ )
280
+ else:
281
+ response.raise_for_status()
282
+ return response.json()
283
+ except (
284
+ httpx.TimeoutException,
285
+ httpx.ConnectError,
286
+ httpx.ReadError,
287
+ httpx.RemoteProtocolError,
288
+ ) as exc:
289
+ last_error = exc
290
+ logger.warning(
291
+ "Ollama Cloud network error on attempt %d/%d: %s",
292
+ attempt + 1, self._max_retries + 1, exc,
293
+ )
294
+ except httpx.HTTPStatusError:
295
+ # Non-retryable (permanent 4xx). Propagate immediately.
296
+ raise
297
+
298
+ if attempt < self._max_retries:
299
+ wait = _BACKOFF_SECONDS[
300
+ min(attempt, len(_BACKOFF_SECONDS) - 1)
301
+ ]
302
+ time.sleep(wait)
303
+ assert last_error is not None # loop guarantees at least one
304
+ raise last_error
305
+
306
+ def __del__(self) -> None:
307
+ # Best-effort cleanup; httpx clients hold a connection pool.
308
+ client = getattr(self, "_client", None)
309
+ if client is not None:
310
+ try:
311
+ client.close()
312
+ except Exception:
313
+ pass
proteus/providers/openai.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI provider for GPT-family and o-series reasoning models.
2
+
3
+ Dual-path implementation:
4
+
5
+ - **Chat Completions API** (default): used for non-reasoning models
6
+ (``gpt-4o``, ``gpt-4-turbo`` etc.). Thinking-token extraction falls
7
+ back to ``usage.completion_tokens_details.reasoning_tokens`` when the
8
+ model is an o-series model routed through the legacy chat endpoint.
9
+
10
+ - **Responses API** (reasoning models): used automatically for
11
+ ``o1``/``o3``/``o4``/``gpt-5`` models, or when ``use_responses_api=True``
12
+ is set explicitly. The Responses API is the only OpenAI endpoint that
13
+ exposes (a) reasoning summaries (``response.output[*].summary[*].text``)
14
+ and (b) API-reported reasoning tokens
15
+ (``response.usage.output_tokens_details.reasoning_tokens``). Both are
16
+ captured into ``CompletionResult.thinking_text`` and
17
+ ``CompletionResult.thinking_tokens`` respectively.
18
+
19
+ The ``reasoning_effort`` param is forwarded to the Responses API as
20
+ ``reasoning.effort``; requesting a summary is always on (``summary="auto"``)
21
+ so Phase O Unit 15 split-call analyses see thinking_text for the
22
+ linguistic channel (H_thinking_* keyword counts) in the same schema as
23
+ Gemini / Qwen3 providers.
24
+
25
+ Example configuration::
26
+
27
+ provider:
28
+ type: openai
29
+ model: o4-mini
30
+ reasoning_effort: medium # forwarded to Responses API
31
+ # api_key: defaults to OPENAI_API_KEY env var
32
+ """
33
+
34
+ import logging
35
+ import os
36
+ import time
37
+
38
+ from openai import OpenAI
39
+ from openai import APIError, APITimeoutError, BadRequestError, RateLimitError
40
+
41
+ from proteus.providers.base import CompletionResult, LLMProvider
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # Only transient errors are retried. BadRequestError (400 — permanent
46
+ # client-side validation errors such as "org not verified for reasoning
47
+ # summaries") must propagate immediately so the caller's fallback logic
48
+ # can handle it without burning the retry budget.
49
+ _RETRYABLE_EXCEPTIONS = (RateLimitError, APITimeoutError)
50
+ _BACKOFF_SECONDS = (1, 2, 4)
51
+
52
+ # Model-name prefixes that trigger automatic Responses API routing.
53
+ # All o-series and gpt-5 family models are reasoning models that report
54
+ # reasoning tokens + reasoning summaries only through /v1/responses.
55
+ _REASONING_PREFIXES: tuple[str, ...] = ("o1", "o3", "o4", "gpt-5")
56
+
57
+
58
+ def _is_reasoning_model(model: str) -> bool:
59
+ """Whether *model* should be routed through the Responses API."""
60
+ return any(model.startswith(p) for p in _REASONING_PREFIXES)
61
+
62
+
63
+ class OpenAIProvider(LLMProvider):
64
+ """LLM provider backed by the OpenAI API.
65
+
66
+ Dispatches to Chat Completions (``/v1/chat/completions``) or
67
+ Responses (``/v1/responses``) based on model family. The Responses
68
+ path is required for o-series reasoning models to receive the
69
+ reasoning summary and the API-reported reasoning-token count.
70
+
71
+ Args:
72
+ model: Model identifier (e.g. ``"gpt-4o"`` or ``"o4-mini"``).
73
+ api_key: OpenAI API key. Falls back to ``OPENAI_API_KEY`` env var.
74
+ base_url: Optional base URL override for compatible APIs.
75
+ max_retries: Retry budget on transient errors.
76
+ timeout: HTTP timeout in seconds.
77
+ top_p: Nucleus sampling parameter (ignored for reasoning models).
78
+ seed: Deterministic seed (ignored for reasoning models).
79
+ logprobs: Request log probabilities (Chat Completions only).
80
+ reasoning_effort: One of ``"low"``/``"medium"``/``"high"``. When
81
+ set, overrides auto-detection and forces the Responses API.
82
+ use_responses_api: Explicit override. ``None`` = auto-detect by
83
+ model prefix; ``True``/``False`` force one or the other.
84
+ reasoning_summary: Summary verbosity forwarded to the Responses
85
+ API (``"auto"`` / ``"concise"`` / ``"detailed"``). Default
86
+ ``"auto"`` gives the provider best-effort summaries.
87
+ """
88
+
89
+ def __init__(
90
+ self,
91
+ model: str = "gpt-4o",
92
+ api_key: str | None = None,
93
+ base_url: str | None = None,
94
+ max_retries: int = 3,
95
+ timeout: float = 120.0,
96
+ top_p: float = 0.0,
97
+ seed: int | None = None,
98
+ logprobs: bool = False,
99
+ reasoning_effort: str | None = None,
100
+ use_responses_api: bool | None = None,
101
+ reasoning_summary: str = "auto",
102
+ ) -> None:
103
+ self._model = model
104
+ self._max_retries = max_retries
105
+ self._timeout = timeout
106
+ self._top_p = top_p
107
+ self._seed = seed
108
+ self._logprobs = logprobs
109
+ self._reasoning_effort = reasoning_effort
110
+ self._reasoning_summary = reasoning_summary
111
+ # Auto-route reasoning models through the Responses API unless
112
+ # the caller explicitly opts out. Non-reasoning models stay on
113
+ # Chat Completions for backward compatibility (deterministic
114
+ # seeds, logprobs, temperature support).
115
+ if use_responses_api is None:
116
+ self._use_responses = _is_reasoning_model(model) or (
117
+ reasoning_effort is not None
118
+ )
119
+ else:
120
+ self._use_responses = bool(use_responses_api)
121
+
122
+ resolved_key = api_key or os.environ.get("OPENAI_API_KEY")
123
+ if not resolved_key:
124
+ raise ValueError(
125
+ "OpenAI API key must be provided via api_key param "
126
+ "or OPENAI_API_KEY environment variable."
127
+ )
128
+ self._client = OpenAI(
129
+ api_key=resolved_key,
130
+ base_url=base_url,
131
+ timeout=timeout,
132
+ max_retries=0, # Disable SDK-level retries; our provider handles retries
133
+ )
134
+
135
+ @property
136
+ def model_name(self) -> str:
137
+ return self._model
138
+
139
+ # ------------------------------------------------------------------
140
+ # Public entry
141
+ # ------------------------------------------------------------------
142
+
143
+ def complete(
144
+ self,
145
+ messages: list[dict[str, str]],
146
+ temperature: float = 0.7,
147
+ max_tokens: int = 4096,
148
+ ) -> CompletionResult:
149
+ """Send a completion request, dispatching by endpoint family.
150
+
151
+ Args:
152
+ messages: Chat messages with ``role`` and ``content`` keys.
153
+ temperature: Sampling temperature (ignored on Responses API).
154
+ max_tokens: Maximum tokens to generate (forwarded as
155
+ ``max_completion_tokens`` on Chat / ``max_output_tokens``
156
+ on Responses).
157
+
158
+ Returns:
159
+ CompletionResult. For reasoning models routed through the
160
+ Responses API, ``thinking_tokens`` is the API-reported
161
+ ``reasoning_tokens`` count and ``thinking_text`` is the
162
+ concatenated ``summary_text`` blocks.
163
+ """
164
+ if self._use_responses:
165
+ return self._complete_responses(messages, max_tokens)
166
+ return self._complete_chat(messages, temperature, max_tokens)
167
+
168
+ # ------------------------------------------------------------------
169
+ # Responses API path (o-series / gpt-5)
170
+ # ------------------------------------------------------------------
171
+
172
+ def _complete_responses(
173
+ self,
174
+ messages: list[dict[str, str]],
175
+ max_tokens: int,
176
+ ) -> CompletionResult:
177
+ """Call ``/v1/responses`` and extract summary + reasoning tokens."""
178
+ input_items = self._messages_to_input(messages)
179
+
180
+ reasoning_payload: dict = {}
181
+ if self._reasoning_summary:
182
+ reasoning_payload["summary"] = self._reasoning_summary
183
+ if self._reasoning_effort:
184
+ reasoning_payload["effort"] = self._reasoning_effort
185
+
186
+ kwargs: dict = {
187
+ "model": self._model,
188
+ "input": input_items,
189
+ "max_output_tokens": max_tokens,
190
+ }
191
+ if reasoning_payload:
192
+ kwargs["reasoning"] = reasoning_payload
193
+
194
+ try:
195
+ response = self._call_with_retry(
196
+ self._client.responses.create, kwargs, endpoint="responses"
197
+ )
198
+ except BadRequestError as exc:
199
+ # Organization-not-verified orgs can still use o-series for
200
+ # reasoning token accounting, they just cannot receive the
201
+ # human-readable summary. Detect that specific 400 and retry
202
+ # without ``summary``. We remember the downgrade so subsequent
203
+ # calls skip the summary request up-front (cheaper).
204
+ msg = str(exc)
205
+ if (
206
+ "reasoning.summary" in msg
207
+ or "generate reasoning summaries" in msg
208
+ ) and "summary" in reasoning_payload:
209
+ logger.warning(
210
+ "OpenAI org not verified for reasoning summaries — "
211
+ "falling back to token-only accounting. "
212
+ "thinking_text will be None for this model."
213
+ )
214
+ self._reasoning_summary = ""
215
+ reasoning_payload.pop("summary", None)
216
+ if reasoning_payload:
217
+ kwargs["reasoning"] = reasoning_payload
218
+ else:
219
+ kwargs.pop("reasoning", None)
220
+ response = self._call_with_retry(
221
+ self._client.responses.create,
222
+ kwargs,
223
+ endpoint="responses",
224
+ )
225
+ else:
226
+ raise
227
+
228
+ # Usage: prompt / output / reasoning tokens. Shape:
229
+ # usage.input_tokens, usage.output_tokens,
230
+ # usage.output_tokens_details.reasoning_tokens
231
+ usage = getattr(response, "usage", None)
232
+ input_tokens = int(getattr(usage, "input_tokens", 0) or 0) if usage else 0
233
+ output_tokens = int(getattr(usage, "output_tokens", 0) or 0) if usage else 0
234
+ reasoning_tokens = 0
235
+ if usage is not None:
236
+ details = getattr(usage, "output_tokens_details", None)
237
+ if details is not None:
238
+ reasoning_tokens = int(
239
+ getattr(details, "reasoning_tokens", 0) or 0
240
+ )
241
+
242
+ # Walk response.output to split reasoning summaries from the
243
+ # final message content. The Responses API returns a list of
244
+ # output items; reasoning items carry ``type="reasoning"`` with
245
+ # a ``summary`` array, and the final answer arrives as
246
+ # ``type="message"`` with ``content`` list of output_text parts.
247
+ summary_parts: list[str] = []
248
+ answer_parts: list[str] = []
249
+ finish_reason: str | None = None
250
+ output_items = getattr(response, "output", None) or []
251
+ for item in output_items:
252
+ item_type = getattr(item, "type", None)
253
+ if item_type == "reasoning":
254
+ for block in getattr(item, "summary", None) or []:
255
+ btype = getattr(block, "type", None)
256
+ btext = getattr(block, "text", None)
257
+ if btype == "summary_text" and btext:
258
+ summary_parts.append(btext)
259
+ elif item_type == "message":
260
+ for block in getattr(item, "content", None) or []:
261
+ btype = getattr(block, "type", None)
262
+ btext = getattr(block, "text", None)
263
+ if btype in ("output_text", "text") and btext:
264
+ answer_parts.append(btext)
265
+ if finish_reason is None:
266
+ finish_reason = getattr(item, "status", None)
267
+
268
+ # Fallback: older SDK versions expose a flattened ``output_text``.
269
+ if not answer_parts:
270
+ fallback_text = getattr(response, "output_text", None)
271
+ if fallback_text:
272
+ answer_parts.append(fallback_text)
273
+ if finish_reason is None:
274
+ finish_reason = getattr(response, "status", None)
275
+
276
+ text = "\n".join(p for p in answer_parts if p).strip()
277
+ thinking_text = "\n\n".join(summary_parts).strip() or None
278
+
279
+ # If the summary is empty but reasoning tokens were charged, the
280
+ # model reasoned internally without emitting a summary — still
281
+ # report the token count so Reasoning Investment accounting is
282
+ # accurate.
283
+ return CompletionResult(
284
+ text=text,
285
+ input_tokens=input_tokens,
286
+ output_tokens=output_tokens,
287
+ thinking_tokens=reasoning_tokens,
288
+ thinking_text=thinking_text,
289
+ logprobs=None,
290
+ finish_reason=finish_reason,
291
+ )
292
+
293
+ # ------------------------------------------------------------------
294
+ # Chat Completions API path (non-reasoning models)
295
+ # ------------------------------------------------------------------
296
+
297
+ def _complete_chat(
298
+ self,
299
+ messages: list[dict[str, str]],
300
+ temperature: float,
301
+ max_tokens: int,
302
+ ) -> CompletionResult:
303
+ """Call ``/v1/chat/completions`` for non-reasoning models."""
304
+ kwargs: dict = {
305
+ "model": self._model,
306
+ "messages": messages,
307
+ "max_tokens": max_tokens,
308
+ "temperature": temperature,
309
+ }
310
+ if self._top_p > 0.0:
311
+ kwargs["top_p"] = self._top_p
312
+ if self._seed is not None:
313
+ kwargs["seed"] = self._seed
314
+ if self._logprobs:
315
+ kwargs["logprobs"] = True
316
+
317
+ extra_body = getattr(self, "_extra_body", None)
318
+ if extra_body:
319
+ kwargs["extra_body"] = extra_body
320
+
321
+ response = self._call_with_retry(
322
+ self._client.chat.completions.create, kwargs, endpoint="chat"
323
+ )
324
+
325
+ usage = response.usage
326
+ input_tokens = usage.prompt_tokens if usage else 0
327
+ output_tokens = usage.completion_tokens if usage else 0
328
+
329
+ # API-reported reasoning tokens — present for o-series even when
330
+ # routed through chat completions (rare but possible via proxy).
331
+ thinking_tokens = 0
332
+ if usage is not None:
333
+ details = getattr(usage, "completion_tokens_details", None)
334
+ if details is not None:
335
+ thinking_tokens = int(
336
+ getattr(details, "reasoning_tokens", 0) or 0
337
+ )
338
+
339
+ choice = response.choices[0]
340
+ text = choice.message.content or ""
341
+ finish_reason = choice.finish_reason
342
+
343
+ # Some newer SDK builds surface a ``reasoning_content`` field on
344
+ # the message (o-series on chat completions, Qwen on compat
345
+ # proxies). Capture it for the linguistic channel if present.
346
+ thinking_text: str | None = None
347
+ msg_data = (
348
+ choice.message.model_dump()
349
+ if hasattr(choice.message, "model_dump")
350
+ else {}
351
+ )
352
+ reasoning_text = (
353
+ msg_data.get("reasoning_content")
354
+ or msg_data.get("reasoning")
355
+ or ""
356
+ )
357
+ if reasoning_text:
358
+ thinking_text = reasoning_text
359
+ # If API reported 0 reasoning_tokens but text exists, fall
360
+ # back to whitespace split as a last-resort estimate so RI
361
+ # is non-zero.
362
+ if thinking_tokens == 0:
363
+ thinking_tokens = len(reasoning_text.split())
364
+ if not text:
365
+ text = reasoning_text
366
+
367
+ logprobs_list: list[float] | None = None
368
+ if choice.logprobs and choice.logprobs.content:
369
+ logprobs_list = [tok.logprob for tok in choice.logprobs.content]
370
+
371
+ return CompletionResult(
372
+ text=text,
373
+ input_tokens=input_tokens,
374
+ output_tokens=output_tokens,
375
+ thinking_tokens=thinking_tokens,
376
+ thinking_text=thinking_text,
377
+ logprobs=logprobs_list,
378
+ finish_reason=finish_reason,
379
+ )
380
+
381
+ # ------------------------------------------------------------------
382
+ # Shared helpers
383
+ # ------------------------------------------------------------------
384
+
385
+ def _call_with_retry(self, fn, kwargs: dict, *, endpoint: str):
386
+ """Exponential-backoff retry wrapper shared by both endpoints."""
387
+ last_error: Exception | None = None
388
+ for attempt in range(self._max_retries + 1):
389
+ try:
390
+ return fn(**kwargs)
391
+ except _RETRYABLE_EXCEPTIONS as exc:
392
+ last_error = exc
393
+ if attempt < self._max_retries:
394
+ wait = _BACKOFF_SECONDS[
395
+ min(attempt, len(_BACKOFF_SECONDS) - 1)
396
+ ]
397
+ logger.warning(
398
+ "OpenAI %s request failed (attempt %d/%d): %s. "
399
+ "Retrying in %ds...",
400
+ endpoint,
401
+ attempt + 1,
402
+ self._max_retries + 1,
403
+ exc,
404
+ wait,
405
+ )
406
+ time.sleep(wait)
407
+ raise last_error # type: ignore[misc]
408
+
409
+ @staticmethod
410
+ def _messages_to_input(
411
+ messages: list[dict[str, str]],
412
+ ) -> list[dict[str, object]]:
413
+ """Convert Chat-style messages to Responses API ``input`` shape.
414
+
415
+ The Responses API accepts either a bare string or a list of
416
+ message-like items. Each item has ``role`` and ``content`` where
417
+ ``content`` is a list of typed parts — ``input_text`` for user
418
+ / system input, ``output_text`` reserved for model echoes.
419
+ """
420
+ input_items: list[dict[str, object]] = []
421
+ for msg in messages:
422
+ role = msg.get("role", "user")
423
+ content = msg.get("content", "")
424
+ input_items.append(
425
+ {
426
+ "role": role,
427
+ "content": [
428
+ {"type": "input_text", "text": content}
429
+ ],
430
+ }
431
+ )
432
+ return input_items
tests/providers/test_real_providers_ported.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pathlib
2
+
3
+ PORTED = ["openai.py", "anthropic_provider.py", "gemini.py", "ollama_cloud.py"]
4
+
5
+
6
+ def _providers_dir():
7
+ return pathlib.Path(__file__).parent.parent.parent / "proteus" / "providers"
8
+
9
+
10
+ def test_ported_cloud_providers_exist():
11
+ root = _providers_dir()
12
+ missing = [n for n in PORTED if not (root / n).is_file()]
13
+ assert missing == [], f"missing ported providers: {missing}"
14
+
15
+
16
+ def test_ported_providers_have_no_squid_game_references():
17
+ root = _providers_dir()
18
+ offenders = [
19
+ n for n in PORTED
20
+ if "squid_game" in (root / n).read_text(encoding="utf-8")
21
+ ]
22
+ assert offenders == [], f"ported providers still reference squid_game: {offenders}"
23
+
24
+
25
+ def test_ported_providers_import_proteus_base():
26
+ root = _providers_dir()
27
+ missing = [
28
+ n for n in PORTED
29
+ if "from proteus.providers.base import" not in (root / n).read_text(encoding="utf-8")
30
+ ]
31
+ assert missing == [], f"ported providers missing proteus base import: {missing}"