Skip to content

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

Python

Phase 2: Extract OpenAICompatibleProvider base class

Cursor Agentbab86a268716
diff --git a/providers/lmstudio/client.py b/providers/lmstudio/client.py
index e79f5403..67ee31ce 100644
--- a/providers/lmstudio/client.py
+++ b/providers/lmstudio/client.py
@@ -1,23 +1,9 @@
"""LM Studio provider implementation."""
-import json
-import uuid
-from typing import Any, AsyncIterator
+from typing import Any
-import httpx
-from loguru import logger
-from openai import AsyncOpenAI
-
-from providers.base import BaseProvider, ProviderConfig
-from providers.rate_limit import GlobalRateLimiter
-from providers.common import (
- SSEBuilder,
- map_stop_reason,
- ThinkTagParser,
- HeuristicToolParser,
- ContentType,
- map_error,
-)
+from providers.openai_compat import OpenAICompatibleProvider
+from providers.base import ProviderConfig
from .request import build_request_body
@@ -25,285 +11,17 @@ from .request import build_request_body
LMSTUDIO_DEFAULT_BASE_URL = "http://localhost:1234/v1"
-class LMStudioProvider(BaseProvider):
+class LMStudioProvider(OpenAICompatibleProvider):
"""LM Studio provider using OpenAI-compatible local API."""
def __init__(self, config: ProviderConfig):
- super().__init__(config)
- self._api_key = config.api_key or "lm-studio"
- self._base_url = (config.base_url or LMSTUDIO_DEFAULT_BASE_URL).rstrip("/")
- self._global_rate_limiter = GlobalRateLimiter.get_instance(
- rate_limit=config.rate_limit,
- rate_window=config.rate_window,
- )
- self._client = AsyncOpenAI(
- api_key=self._api_key,
- base_url=self._base_url,
- max_retries=0,
- timeout=httpx.Timeout(
- config.http_read_timeout,
- connect=config.http_connect_timeout,
- read=config.http_read_timeout,
- write=config.http_write_timeout,
- ),
+ super().__init__(
+ config,
+ provider_name="LMSTUDIO",
+ base_url=config.base_url or LMSTUDIO_DEFAULT_BASE_URL,
+ api_key=config.api_key or "lm-studio",
)
def _build_request_body(self, request: Any) -> dict:
"""Internal helper for tests and shared building."""
return build_request_body(request)
-
- async def stream_response(
- self,
- request: Any,
- input_tokens: int = 0,
- *,
- request_id: str | None = None,
- ) -> AsyncIterator[str]:
- """Stream response in Anthropic SSE format."""
- with logger.contextualize(request_id=request_id):
- async for event in self._stream_response_impl(
- request, input_tokens, request_id
- ):
- yield event
-
- async def _stream_response_impl(
- self,
- request: Any,
- input_tokens: int,
- request_id: str | None,
- ) -> AsyncIterator[str]:
- """Internal streaming implementation with context bound."""
- message_id = f"msg_{uuid.uuid4()}"
- sse = SSEBuilder(message_id, request.model, input_tokens)
-
- body = self._build_request_body(request)
- req_tag = f" request_id={request_id}" if request_id else ""
- logger.info(
- "LMSTUDIO_STREAM:%s model=%s msgs=%d tools=%d",
- req_tag,
- body.get("model"),
- len(body.get("messages", [])),
- len(body.get("tools", [])),
- )
-
- yield sse.message_start()
-
- think_parser = ThinkTagParser()
- heuristic_parser = HeuristicToolParser()
-
- finish_reason = None
- usage_info = None
- error_occurred = False
- error_message = ""
-
- try:
- stream = await self._global_rate_limiter.execute_with_retry(
- self._client.chat.completions.create, **body, stream=True
- )
- async for chunk in stream:
- if getattr(chunk, "usage", None):
- usage_info = chunk.usage
-
- if not chunk.choices:
- continue
-
- choice = chunk.choices[0]
- delta = choice.delta
- if delta is None:
- continue
-
- if choice.finish_reason:
- finish_reason = choice.finish_reason
- logger.debug("LMSTUDIO finish_reason: %s", finish_reason)
-
- # Handle reasoning_content (if LM Studio adds it in future)
- reasoning = getattr(delta, "reasoning_content", None)
- if reasoning:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(reasoning)
-
- # Handle text content
- if delta.content:
- for part in think_parser.feed(delta.content):
- if part.type == ContentType.THINKING:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(part.content)
- else:
- filtered_text, detected_tools = heuristic_parser.feed(
- part.content
- )
-
- if filtered_text:
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(filtered_text)
-
- for tool_use in detected_tools:
- for event in sse.close_content_blocks():
- yield event
-
- block_idx = sse.blocks.allocate_index()
- if tool_use.get("name") == "Task" and isinstance(
- tool_use.get("input"), dict
- ):
- tool_use["input"]["run_in_background"] = False
- yield sse.content_block_start(
- block_idx,
- "tool_use",
- id=tool_use["id"],
- name=tool_use["name"],
- )
- yield sse.content_block_delta(
- block_idx,
- "input_json_delta",
- json.dumps(tool_use["input"]),
- )
- yield sse.content_block_stop(block_idx)
-
- # Handle native tool calls
- if delta.tool_calls:
- for event in sse.close_content_blocks():
- yield event
- for tc in delta.tool_calls:
- tc_info = {
- "index": tc.index,
- "id": tc.id,
- "function": {
- "name": tc.function.name,
- "arguments": tc.function.arguments,
- },
- }
- for event in self._process_tool_call(tc_info, sse):
- yield event
-
- except Exception as e:
- req_tag = f" request_id={request_id}" if request_id else ""
- logger.error("LMSTUDIO_ERROR:%s %s: %s", req_tag, type(e).__name__, e)
- mapped_e = map_error(e)
- error_occurred = True
- error_message = str(mapped_e)
- logger.info(
- "LMSTUDIO_STREAM: Emitting SSE error event for %s%s",
- type(e).__name__,
- req_tag,
- )
- for event in sse.close_content_blocks():
- yield event
- for event in sse.emit_error(error_message):
- yield event
-
- # Flush remaining content
- remaining = think_parser.flush()
- if remaining:
- if remaining.type == ContentType.THINKING:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(remaining.content)
- else:
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(remaining.content)
-
- for tool_use in heuristic_parser.flush():
- for event in sse.close_content_blocks():
- yield event
-
- block_idx = sse.blocks.allocate_index()
- yield sse.content_block_start(
- block_idx,
- "tool_use",
- id=tool_use["id"],
- name=tool_use["name"],
- )
- if tool_use.get("name") == "Task" and isinstance(
- tool_use.get("input"), dict
- ):
- tool_use["input"]["run_in_background"] = False
- yield sse.content_block_delta(
- block_idx,
- "input_json_delta",
- json.dumps(tool_use["input"]),
- )
- yield sse.content_block_stop(block_idx)
-
- if (
- not error_occurred
- and sse.blocks.text_index == -1
- and not sse.blocks.tool_indices
- ):
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(" ")
-
- for event in self._flush_task_arg_buffers(sse):
- yield event
-
- for event in sse.close_all_blocks():
- yield event
-
- output_tokens = (
- usage_info.completion_tokens
- if usage_info and hasattr(usage_info, "completion_tokens")
- else sse.estimate_output_tokens()
- )
- if usage_info and hasattr(usage_info, "prompt_tokens"):
- provider_input = usage_info.prompt_tokens
- if isinstance(provider_input, int):
- logger.debug(
- "TOKEN_ESTIMATE: our=%d provider=%d diff=%+d",
- input_tokens,
- provider_input,
- provider_input - input_tokens,
- )
- yield sse.message_delta(map_stop_reason(finish_reason), output_tokens)
- yield sse.message_stop()
- yield sse.done()
-
- def _process_tool_call(self, tc: dict, sse: Any):
- """Process a single tool call delta and yield SSE events."""
- tc_index = tc.get("index", 0)
- if tc_index < 0:
- tc_index = len(sse.blocks.tool_indices)
-
- fn_delta = tc.get("function", {})
- incoming_name = fn_delta.get("name")
- if incoming_name is not None:
- sse.blocks.register_tool_name(tc_index, incoming_name)
-
- if tc_index not in sse.blocks.tool_indices:
- name = sse.blocks.tool_names.get(tc_index, "")
- if name or tc.get("id"):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
- elif not sse.blocks.tool_started.get(tc_index) and sse.blocks.tool_names.get(
- tc_index
- ):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- name = sse.blocks.tool_names[tc_index]
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
-
- args = fn_delta.get("arguments", "")
- if args:
- if not sse.blocks.tool_started.get(tc_index):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- name = sse.blocks.tool_names.get(tc_index, "tool_call") or "tool_call"
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
-
- current_name = sse.blocks.tool_names.get(tc_index, "")
- if current_name == "Task":
- parsed = sse.blocks.buffer_task_args(tc_index, args)
- if parsed is not None:
- yield sse.emit_tool_delta(tc_index, json.dumps(parsed))
- return
-
- yield sse.emit_tool_delta(tc_index, args)
-
- def _flush_task_arg_buffers(self, sse: Any):
- """Emit buffered Task args as a single JSON delta (best-effort)."""
- for tool_index, out in sse.blocks.flush_task_arg_buffers():
- yield sse.emit_tool_delta(tool_index, out)
diff --git a/providers/nvidia_nim/client.py b/providers/nvidia_nim/client.py
index 5e87a89e..41f57e72 100644
--- a/providers/nvidia_nim/client.py
+++ b/providers/nvidia_nim/client.py
@@ -1,310 +1,26 @@
"""NVIDIA NIM provider implementation."""
-import json
-import uuid
-from typing import Any, AsyncIterator
+from typing import Any
-import httpx
-from loguru import logger
-from openai import AsyncOpenAI
+from providers.openai_compat import OpenAICompatibleProvider
+from providers.base import ProviderConfig
-from providers.base import BaseProvider, ProviderConfig
-from providers.rate_limit import GlobalRateLimiter
-from providers.common import (
- SSEBuilder,
- map_stop_reason,
- ThinkTagParser,
- HeuristicToolParser,
- ContentType,
- map_error,
-)
from .request import build_request_body
-class NvidiaNimProvider(BaseProvider):
+class NvidiaNimProvider(OpenAICompatibleProvider):
"""NVIDIA NIM provider using official OpenAI client."""
def __init__(self, config: ProviderConfig):
- super().__init__(config)
- self._api_key = config.api_key
- self._base_url = (
- config.base_url or "https://integrate.api.nvidia.com/v1"
- ).rstrip("/")
- self._nim_settings = config.nim_settings
- self._global_rate_limiter = GlobalRateLimiter.get_instance(
- rate_limit=config.rate_limit,
- rate_window=config.rate_window,
- )
- self._client = AsyncOpenAI(
- api_key=self._api_key,
- base_url=self._base_url,
- max_retries=0,
- timeout=httpx.Timeout(
- config.http_read_timeout,
- connect=config.http_connect_timeout,
- read=config.http_read_timeout,
- write=config.http_write_timeout,
- ),
+ super().__init__(
+ config,
+ provider_name="NIM",
+ base_url=config.base_url or "https://integrate.api.nvidia.com/v1",
+ api_key=config.api_key,
+ nim_settings=config.nim_settings,
)
def _build_request_body(self, request: Any) -> dict:
"""Internal helper for tests and shared building."""
+ assert self._nim_settings is not None
return build_request_body(request, self._nim_settings)
-
- async def stream_response(
- self,
- request: Any,
- input_tokens: int = 0,
- *,
- request_id: str | None = None,
- ) -> AsyncIterator[str]:
- """Stream response in Anthropic SSE format."""
- with logger.contextualize(request_id=request_id):
- async for event in self._stream_response_impl(
- request, input_tokens, request_id
- ):
- yield event
-
- async def _stream_response_impl(
- self,
- request: Any,
- input_tokens: int,
- request_id: str | None,
- ) -> AsyncIterator[str]:
- """Internal streaming implementation with context bound."""
- message_id = f"msg_{uuid.uuid4()}"
- sse = SSEBuilder(message_id, request.model, input_tokens)
-
- body = self._build_request_body(request)
- req_tag = f" request_id={request_id}" if request_id else ""
- logger.info(
- "NIM_STREAM:%s model=%s msgs=%d tools=%d",
- req_tag,
- body.get("model"),
- len(body.get("messages", [])),
- len(body.get("tools", [])),
- )
-
- yield sse.message_start()
-
- think_parser = ThinkTagParser()
- heuristic_parser = HeuristicToolParser()
-
- finish_reason = None
- usage_info = None
- error_occurred = False
- error_message = ""
-
- try:
- stream = await self._global_rate_limiter.execute_with_retry(
- self._client.chat.completions.create, **body, stream=True
- )
- async for chunk in stream:
- # OpenAI client returns objects, not JSON
- if getattr(chunk, "usage", None):
- usage_info = chunk.usage
-
- if not chunk.choices:
- continue
-
- choice = chunk.choices[0]
- delta = choice.delta
- if delta is None:
- continue
-
- if choice.finish_reason:
- finish_reason = choice.finish_reason
- logger.debug(f"NIM finish_reason: {finish_reason}")
-
- # Handle reasoning content from delta
- reasoning = getattr(delta, "reasoning_content", None)
- if reasoning:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(reasoning)
-
- # Handle text content
- if delta.content:
- for part in think_parser.feed(delta.content):
- if part.type == ContentType.THINKING:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(part.content)
- else:
- filtered_text, detected_tools = heuristic_parser.feed(
- part.content
- )
-
- if filtered_text:
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(filtered_text)
-
- for tool_use in detected_tools:
- for event in sse.close_content_blocks():
- yield event
-
- block_idx = sse.blocks.allocate_index()
- if tool_use.get("name") == "Task" and isinstance(
- tool_use.get("input"), dict
- ):
- tool_use["input"]["run_in_background"] = False
- yield sse.content_block_start(
- block_idx,
- "tool_use",
- id=tool_use["id"],
- name=tool_use["name"],
- )
- yield sse.content_block_delta(
- block_idx,
- "input_json_delta",
- json.dumps(tool_use["input"]),
- )
- yield sse.content_block_stop(block_idx)
-
- # Handle native tool calls
- if delta.tool_calls:
- for event in sse.close_content_blocks():
- yield event
- for tc in delta.tool_calls:
- # Convert OpenAI tool call object to dict for existing logic
- tc_info = {
- "index": tc.index,
- "id": tc.id,
- "function": {
- "name": tc.function.name,
- "arguments": tc.function.arguments,
- },
- }
- for event in self._process_tool_call(tc_info, sse):
- yield event
-
- except Exception as e:
- req_tag = f" request_id={request_id}" if request_id else ""
- logger.error("NIM_ERROR:%s %s: %s", req_tag, type(e).__name__, e)
- mapped_e = map_error(e)
- error_occurred = True
- error_message = str(mapped_e)
- logger.info(
- "NIM_STREAM: Emitting SSE error event for %s%s",
- type(e).__name__,
- req_tag,
- )
- # Ensure open blocks are closed before emitting error to follow Anthropic protocol
- for event in sse.close_content_blocks():
- yield event
- for event in sse.emit_error(error_message):
- yield event
-
- # Flush remaining content
- remaining = think_parser.flush()
- if remaining:
- if remaining.type == ContentType.THINKING:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(remaining.content)
- else:
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(remaining.content)
-
- for tool_use in heuristic_parser.flush():
- for event in sse.close_content_blocks():
- yield event
-
- block_idx = sse.blocks.allocate_index()
- yield sse.content_block_start(
- block_idx,
- "tool_use",
- id=tool_use["id"],
- name=tool_use["name"],
- )
- if tool_use.get("name") == "Task" and isinstance(
- tool_use.get("input"), dict
- ):
- tool_use["input"]["run_in_background"] = False
- yield sse.content_block_delta(
- block_idx,
- "input_json_delta",
- json.dumps(tool_use["input"]),
- )
- yield sse.content_block_stop(block_idx)
-
- if (
- not error_occurred
- and sse.blocks.text_index == -1
- and not sse.blocks.tool_indices
- ):
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(" ")
-
- # Flush buffered Task args before closing tool blocks.
- for event in self._flush_task_arg_buffers(sse):
- yield event
-
- for event in sse.close_all_blocks():
- yield event
-
- output_tokens = (
- usage_info.completion_tokens
- if usage_info and hasattr(usage_info, "completion_tokens")
- else sse.estimate_output_tokens()
- )
- if usage_info and hasattr(usage_info, "prompt_tokens"):
- provider_input = usage_info.prompt_tokens
- if isinstance(provider_input, int):
- diff = provider_input - input_tokens
- logger.debug(
- f"TOKEN_ESTIMATE: our={input_tokens} provider={provider_input} diff={diff:+d}"
- )
- yield sse.message_delta(map_stop_reason(finish_reason), output_tokens)
- yield sse.message_stop()
- yield sse.done()
-
- def _process_tool_call(self, tc: dict, sse: Any):
- """Process a single tool call delta and yield SSE events."""
- tc_index = tc.get("index", 0)
- if tc_index < 0:
- tc_index = len(sse.blocks.tool_indices)
-
- fn_delta = tc.get("function", {})
- incoming_name = fn_delta.get("name")
- if incoming_name is not None:
- sse.blocks.register_tool_name(tc_index, incoming_name)
-
- if tc_index not in sse.blocks.tool_indices:
- name = sse.blocks.tool_names.get(tc_index, "")
- if name or tc.get("id"):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
- elif not sse.blocks.tool_started.get(tc_index) and sse.blocks.tool_names.get(
- tc_index
- ):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- name = sse.blocks.tool_names[tc_index]
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
-
- args = fn_delta.get("arguments", "")
- if args:
- if not sse.blocks.tool_started.get(tc_index):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- name = sse.blocks.tool_names.get(tc_index, "tool_call") or "tool_call"
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
-
- current_name = sse.blocks.tool_names.get(tc_index, "")
- if current_name == "Task":
- parsed = sse.blocks.buffer_task_args(tc_index, args)
- if parsed is not None:
- yield sse.emit_tool_delta(tc_index, json.dumps(parsed))
- return
-
- yield sse.emit_tool_delta(tc_index, args)
-
- def _flush_task_arg_buffers(self, sse: Any):
- """Emit buffered Task args as a single JSON delta (best-effort)."""
- for tool_index, out in sse.blocks.flush_task_arg_buffers():
- yield sse.emit_tool_delta(tool_index, out)
diff --git a/providers/open_router/client.py b/providers/open_router/client.py
index 53b5742d..79a126b6 100644
--- a/providers/open_router/client.py
+++ b/providers/open_router/client.py
@@ -1,23 +1,10 @@
"""OpenRouter provider implementation."""
-import json
-import uuid
-from typing import Any, AsyncIterator
+from typing import Any, Iterator
-import httpx
-from loguru import logger
-from openai import AsyncOpenAI
-
-from providers.base import BaseProvider, ProviderConfig
-from providers.rate_limit import GlobalRateLimiter
-from providers.common import (
- SSEBuilder,
- map_stop_reason,
- ThinkTagParser,
- HeuristicToolParser,
- ContentType,
- map_error,
-)
+from providers.openai_compat import OpenAICompatibleProvider
+from providers.base import ProviderConfig
+from providers.common import SSEBuilder
from .request import build_request_body
@@ -25,296 +12,28 @@ from .request import build_request_body
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
-class OpenRouterProvider(BaseProvider):
+class OpenRouterProvider(OpenAICompatibleProvider):
"""OpenRouter provider using OpenAI-compatible API."""
def __init__(self, config: ProviderConfig):
- super().__init__(config)
- self._api_key = config.api_key
- self._base_url = (config.base_url or OPENROUTER_BASE_URL).rstrip("/")
- self._global_rate_limiter = GlobalRateLimiter.get_instance(
- rate_limit=config.rate_limit,
- rate_window=config.rate_window,
- )
- self._client = AsyncOpenAI(
- api_key=self._api_key,
- base_url=self._base_url,
- max_retries=0,
- timeout=httpx.Timeout(
- config.http_read_timeout,
- connect=config.http_connect_timeout,
- read=config.http_read_timeout,
- write=config.http_write_timeout,
- ),
+ super().__init__(
+ config,
+ provider_name="OPENROUTER",
+ base_url=config.base_url or OPENROUTER_BASE_URL,
+ api_key=config.api_key,
)
def _build_request_body(self, request: Any) -> dict:
"""Internal helper for tests and shared building."""
return build_request_body(request)
- async def stream_response(
- self,
- request: Any,
- input_tokens: int = 0,
- *,
- request_id: str | None = None,
- ) -> AsyncIterator[str]:
- """Stream response in Anthropic SSE format."""
- with logger.contextualize(request_id=request_id):
- async for event in self._stream_response_impl(
- request, input_tokens, request_id
- ):
- yield event
-
- async def _stream_response_impl(
- self,
- request: Any,
- input_tokens: int,
- request_id: str | None,
- ) -> AsyncIterator[str]:
- """Internal streaming implementation with context bound."""
- message_id = f"msg_{uuid.uuid4()}"
- sse = SSEBuilder(message_id, request.model, input_tokens)
-
- body = self._build_request_body(request)
- req_tag = f" request_id={request_id}" if request_id else ""
- logger.info(
- "OPENROUTER_STREAM:%s model=%s msgs=%d tools=%d",
- req_tag,
- body.get("model"),
- len(body.get("messages", [])),
- len(body.get("tools", [])),
- )
-
- yield sse.message_start()
-
- think_parser = ThinkTagParser()
- heuristic_parser = HeuristicToolParser()
-
- finish_reason = None
- usage_info = None
- error_occurred = False
- error_message = ""
-
- try:
- stream = await self._global_rate_limiter.execute_with_retry(
- self._client.chat.completions.create, **body, stream=True
- )
- async for chunk in stream:
- if getattr(chunk, "usage", None):
- usage_info = chunk.usage
-
- if not chunk.choices:
- continue
-
- choice = chunk.choices[0]
- delta = choice.delta
- if delta is None:
- continue
-
- if choice.finish_reason:
- finish_reason = choice.finish_reason
- logger.debug("OPENROUTER finish_reason: %s", finish_reason)
-
- # Handle reasoning_content (OpenRouter/OpenAI extended format)
- reasoning = getattr(delta, "reasoning_content", None)
- if reasoning:
+ def _handle_extra_reasoning(self, delta: Any, sse: SSEBuilder) -> Iterator[str]:
+ """Handle reasoning_details for StepFun models."""
+ reasoning_details = getattr(delta, "reasoning_details", None)
+ if reasoning_details and isinstance(reasoning_details, list):
+ for item in reasoning_details:
+ text = item.get("text", "") if isinstance(item, dict) else ""
+ if text:
for event in sse.ensure_thinking_block():
yield event
- yield sse.emit_thinking_delta(reasoning)
-
- # Handle reasoning_details (e.g. stepfun models)
- reasoning_details = getattr(delta, "reasoning_details", None)
- if reasoning_details and isinstance(reasoning_details, list):
- for item in reasoning_details:
- text = item.get("text", "") if isinstance(item, dict) else ""
- if text:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(text)
-
- # Handle text content
- if delta.content:
- for part in think_parser.feed(delta.content):
- if part.type == ContentType.THINKING:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(part.content)
- else:
- filtered_text, detected_tools = heuristic_parser.feed(
- part.content
- )
-
- if filtered_text:
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(filtered_text)
-
- for tool_use in detected_tools:
- for event in sse.close_content_blocks():
- yield event
-
- block_idx = sse.blocks.allocate_index()
- if tool_use.get("name") == "Task" and isinstance(
- tool_use.get("input"), dict
- ):
- tool_use["input"]["run_in_background"] = False
- yield sse.content_block_start(
- block_idx,
- "tool_use",
- id=tool_use["id"],
- name=tool_use["name"],
- )
- yield sse.content_block_delta(
- block_idx,
- "input_json_delta",
- json.dumps(tool_use["input"]),
- )
- yield sse.content_block_stop(block_idx)
-
- # Handle native tool calls
- if delta.tool_calls:
- for event in sse.close_content_blocks():
- yield event
- for tc in delta.tool_calls:
- tc_info = {
- "index": tc.index,
- "id": tc.id,
- "function": {
- "name": tc.function.name,
- "arguments": tc.function.arguments,
- },
- }
- for event in self._process_tool_call(tc_info, sse):
- yield event
-
- except Exception as e:
- req_tag = f" request_id={request_id}" if request_id else ""
- logger.error("OPENROUTER_ERROR:%s %s: %s", req_tag, type(e).__name__, e)
- mapped_e = map_error(e)
- error_occurred = True
- error_message = str(mapped_e)
- logger.info(
- "OPENROUTER_STREAM: Emitting SSE error event for %s%s",
- type(e).__name__,
- req_tag,
- )
- for event in sse.close_content_blocks():
- yield event
- for event in sse.emit_error(error_message):
- yield event
-
- # Flush remaining content
- remaining = think_parser.flush()
- if remaining:
- if remaining.type == ContentType.THINKING:
- for event in sse.ensure_thinking_block():
- yield event
- yield sse.emit_thinking_delta(remaining.content)
- else:
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(remaining.content)
-
- for tool_use in heuristic_parser.flush():
- for event in sse.close_content_blocks():
- yield event
-
- block_idx = sse.blocks.allocate_index()
- yield sse.content_block_start(
- block_idx,
- "tool_use",
- id=tool_use["id"],
- name=tool_use["name"],
- )
- if tool_use.get("name") == "Task" and isinstance(
- tool_use.get("input"), dict
- ):
- tool_use["input"]["run_in_background"] = False
- yield sse.content_block_delta(
- block_idx,
- "input_json_delta",
- json.dumps(tool_use["input"]),
- )
- yield sse.content_block_stop(block_idx)
-
- if (
- not error_occurred
- and sse.blocks.text_index == -1
- and not sse.blocks.tool_indices
- ):
- for event in sse.ensure_text_block():
- yield event
- yield sse.emit_text_delta(" ")
-
- for event in self._flush_task_arg_buffers(sse):
- yield event
-
- for event in sse.close_all_blocks():
- yield event
-
- output_tokens = (
- usage_info.completion_tokens
- if usage_info and hasattr(usage_info, "completion_tokens")
- else sse.estimate_output_tokens()
- )
- if usage_info and hasattr(usage_info, "prompt_tokens"):
- provider_input = usage_info.prompt_tokens
- if isinstance(provider_input, int):
- diff = provider_input - input_tokens
- logger.debug(
- "TOKEN_ESTIMATE: our=%d provider=%d diff=%+d",
- input_tokens,
- provider_input,
- diff,
- )
- yield sse.message_delta(map_stop_reason(finish_reason), output_tokens)
- yield sse.message_stop()
- yield sse.done()
-
- def _process_tool_call(self, tc: dict, sse: Any):
- """Process a single tool call delta and yield SSE events."""
- tc_index = tc.get("index", 0)
- if tc_index < 0:
- tc_index = len(sse.blocks.tool_indices)
-
- fn_delta = tc.get("function", {})
- incoming_name = fn_delta.get("name")
- if incoming_name is not None:
- sse.blocks.register_tool_name(tc_index, incoming_name)
-
- if tc_index not in sse.blocks.tool_indices:
- name = sse.blocks.tool_names.get(tc_index, "")
- if name or tc.get("id"):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
- elif not sse.blocks.tool_started.get(tc_index) and sse.blocks.tool_names.get(
- tc_index
- ):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- name = sse.blocks.tool_names[tc_index]
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
-
- args = fn_delta.get("arguments", "")
- if args:
- if not sse.blocks.tool_started.get(tc_index):
- tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
- name = sse.blocks.tool_names.get(tc_index, "tool_call") or "tool_call"
- yield sse.start_tool_block(tc_index, tool_id, name)
- sse.blocks.tool_started[tc_index] = True
-
- current_name = sse.blocks.tool_names.get(tc_index, "")
- if current_name == "Task":
- parsed = sse.blocks.buffer_task_args(tc_index, args)
- if parsed is not None:
- yield sse.emit_tool_delta(tc_index, json.dumps(parsed))
- return
-
- yield sse.emit_tool_delta(tc_index, args)
-
- def _flush_task_arg_buffers(self, sse: Any):
- """Emit buffered Task args as a single JSON delta (best-effort)."""
- for tool_index, out in sse.blocks.flush_task_arg_buffers():
- yield sse.emit_tool_delta(tool_index, out)
+ yield sse.emit_thinking_delta(text)
diff --git a/providers/openai_compat.py b/providers/openai_compat.py
new file mode 100644
index 00000000..ccc465d6
--- /dev/null
+++ b/providers/openai_compat.py
@@ -0,0 +1,325 @@
+"""Shared base class for OpenAI-compatible providers (NIM, OpenRouter, LM Studio)."""
+
+import json
+import uuid
+from typing import Any, AsyncIterator, Iterator, Optional
+
+import httpx
+from loguru import logger
+from openai import AsyncOpenAI
+
+from providers.base import BaseProvider, ProviderConfig
+from providers.rate_limit import GlobalRateLimiter
+from providers.common import (
+ SSEBuilder,
+ map_stop_reason,
+ ThinkTagParser,
+ HeuristicToolParser,
+ ContentType,
+ map_error,
+)
+
+
+class OpenAICompatibleProvider(BaseProvider):
+ """Base class for providers using OpenAI-compatible chat completions API."""
+
+ def __init__(
+ self,
+ config: ProviderConfig,
+ *,
+ provider_name: str,
+ base_url: str,
+ api_key: str,
+ nim_settings: Optional[Any] = None,
+ ):
+ super().__init__(config)
+ self._provider_name = provider_name
+ self._api_key = api_key
+ self._base_url = base_url.rstrip("/")
+ self._nim_settings = nim_settings
+ self._global_rate_limiter = GlobalRateLimiter.get_instance(
+ rate_limit=config.rate_limit,
+ rate_window=config.rate_window,
+ )
+ self._client = AsyncOpenAI(
+ api_key=self._api_key,
+ base_url=self._base_url,
+ max_retries=0,
+ timeout=httpx.Timeout(
+ config.http_read_timeout,
+ connect=config.http_connect_timeout,
+ read=config.http_read_timeout,
+ write=config.http_write_timeout,
+ ),
+ )
+
+ def _build_request_body(self, request: Any) -> dict:
+ """Build request body. Override in subclasses."""
+ raise NotImplementedError
+
+ def _handle_extra_reasoning(self, delta: Any, sse: SSEBuilder) -> Iterator[str]:
+ """Hook for provider-specific reasoning (e.g. OpenRouter reasoning_details)."""
+ return iter(())
+
+ def _process_tool_call(self, tc: dict, sse: Any) -> Iterator[str]:
+ """Process a single tool call delta and yield SSE events."""
+ tc_index = tc.get("index", 0)
+ if tc_index < 0:
+ tc_index = len(sse.blocks.tool_indices)
+
+ fn_delta = tc.get("function", {})
+ incoming_name = fn_delta.get("name")
+ if incoming_name is not None:
+ sse.blocks.register_tool_name(tc_index, incoming_name)
+
+ if tc_index not in sse.blocks.tool_indices:
+ name = sse.blocks.tool_names.get(tc_index, "")
+ if name or tc.get("id"):
+ tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
+ yield sse.start_tool_block(tc_index, tool_id, name)
+ sse.blocks.tool_started[tc_index] = True
+ elif not sse.blocks.tool_started.get(tc_index) and sse.blocks.tool_names.get(
+ tc_index
+ ):
+ tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
+ name = sse.blocks.tool_names[tc_index]
+ yield sse.start_tool_block(tc_index, tool_id, name)
+ sse.blocks.tool_started[tc_index] = True
+
+ args = fn_delta.get("arguments", "")
+ if args:
+ if not sse.blocks.tool_started.get(tc_index):
+ tool_id = tc.get("id") or f"tool_{uuid.uuid4()}"
+ name = sse.blocks.tool_names.get(tc_index, "tool_call") or "tool_call"
+ yield sse.start_tool_block(tc_index, tool_id, name)
+ sse.blocks.tool_started[tc_index] = True
+
+ current_name = sse.blocks.tool_names.get(tc_index, "")
+ if current_name == "Task":
+ parsed = sse.blocks.buffer_task_args(tc_index, args)
+ if parsed is not None:
+ yield sse.emit_tool_delta(tc_index, json.dumps(parsed))
+ return
+
+ yield sse.emit_tool_delta(tc_index, args)
+
+ def _flush_task_arg_buffers(self, sse: Any) -> Iterator[str]:
+ """Emit buffered Task args as a single JSON delta (best-effort)."""
+ for tool_index, out in sse.blocks.flush_task_arg_buffers():
+ yield sse.emit_tool_delta(tool_index, out)
+
+ async def stream_response(
+ self,
+ request: Any,
+ input_tokens: int = 0,
+ *,
+ request_id: str | None = None,
+ ) -> AsyncIterator[str]:
+ """Stream response in Anthropic SSE format."""
+ with logger.contextualize(request_id=request_id):
+ async for event in self._stream_response_impl(
+ request, input_tokens, request_id
+ ):
+ yield event
+
+ async def _stream_response_impl(
+ self,
+ request: Any,
+ input_tokens: int,
+ request_id: str | None,
+ ) -> AsyncIterator[str]:
+ """Shared streaming implementation."""
+ tag = self._provider_name
+ message_id = f"msg_{uuid.uuid4()}"
+ sse = SSEBuilder(message_id, request.model, input_tokens)
+
+ body = self._build_request_body(request)
+ req_tag = f" request_id={request_id}" if request_id else ""
+ logger.info(
+ "%s_STREAM:%s model=%s msgs=%d tools=%d",
+ tag,
+ req_tag,
+ body.get("model"),
+ len(body.get("messages", [])),
+ len(body.get("tools", [])),
+ )
+
+ yield sse.message_start()
+
+ think_parser = ThinkTagParser()
+ heuristic_parser = HeuristicToolParser()
+
+ finish_reason = None
+ usage_info = None
+ error_occurred = False
+ error_message = ""
+
+ try:
+ stream = await self._global_rate_limiter.execute_with_retry(
+ self._client.chat.completions.create, **body, stream=True
+ )
+ async for chunk in stream:
+ if getattr(chunk, "usage", None):
+ usage_info = chunk.usage
+
+ if not chunk.choices:
+ continue
+
+ choice = chunk.choices[0]
+ delta = choice.delta
+ if delta is None:
+ continue
+
+ if choice.finish_reason:
+ finish_reason = choice.finish_reason
+ logger.debug("%s finish_reason: %s", tag, finish_reason)
+
+ # Handle reasoning_content (OpenAI extended format)
+ reasoning = getattr(delta, "reasoning_content", None)
+ if reasoning:
+ for event in sse.ensure_thinking_block():
+ yield event
+ yield sse.emit_thinking_delta(reasoning)
+
+ # Provider-specific extra reasoning (e.g. OpenRouter reasoning_details)
+ for event in self._handle_extra_reasoning(delta, sse):
+ yield event
+
+ # Handle text content
+ if delta.content:
+ for part in think_parser.feed(delta.content):
+ if part.type == ContentType.THINKING:
+ for event in sse.ensure_thinking_block():
+ yield event
+ yield sse.emit_thinking_delta(part.content)
+ else:
+ filtered_text, detected_tools = heuristic_parser.feed(
+ part.content
+ )
+
+ if filtered_text:
+ for event in sse.ensure_text_block():
+ yield event
+ yield sse.emit_text_delta(filtered_text)
+
+ for tool_use in detected_tools:
+ for event in sse.close_content_blocks():
+ yield event
+
+ block_idx = sse.blocks.allocate_index()
+ if tool_use.get("name") == "Task" and isinstance(
+ tool_use.get("input"), dict
+ ):
+ tool_use["input"]["run_in_background"] = False
+ yield sse.content_block_start(
+ block_idx,
+ "tool_use",
+ id=tool_use["id"],
+ name=tool_use["name"],
+ )
+ yield sse.content_block_delta(
+ block_idx,
+ "input_json_delta",
+ json.dumps(tool_use["input"]),
+ )
+ yield sse.content_block_stop(block_idx)
+
+ # Handle native tool calls
+ if delta.tool_calls:
+ for event in sse.close_content_blocks():
+ yield event
+ for tc in delta.tool_calls:
+ tc_info = {
+ "index": tc.index,
+ "id": tc.id,
+ "function": {
+ "name": tc.function.name,
+ "arguments": tc.function.arguments,
+ },
+ }
+ for event in self._process_tool_call(tc_info, sse):
+ yield event
+
+ except Exception as e:
+ req_tag = f" request_id={request_id}" if request_id else ""
+ logger.error("%s_ERROR:%s %s: %s", tag, req_tag, type(e).__name__, e)
+ mapped_e = map_error(e)
+ error_occurred = True
+ error_message = str(mapped_e)
+ logger.info(
+ "%s_STREAM: Emitting SSE error event for %s%s",
+ tag,
+ type(e).__name__,
+ req_tag,
+ )
+ for event in sse.close_content_blocks():
+ yield event
+ for event in sse.emit_error(error_message):
+ yield event
+
+ # Flush remaining content
+ remaining = think_parser.flush()
+ if remaining:
+ if remaining.type == ContentType.THINKING:
+ for event in sse.ensure_thinking_block():
+ yield event
+ yield sse.emit_thinking_delta(remaining.content)
+ else:
+ for event in sse.ensure_text_block():
+ yield event
+ yield sse.emit_text_delta(remaining.content)
+
+ for tool_use in heuristic_parser.flush():
+ for event in sse.close_content_blocks():
+ yield event
+
+ block_idx = sse.blocks.allocate_index()
+ yield sse.content_block_start(
+ block_idx,
+ "tool_use",
+ id=tool_use["id"],
+ name=tool_use["name"],
+ )
+ if tool_use.get("name") == "Task" and isinstance(
+ tool_use.get("input"), dict
+ ):
+ tool_use["input"]["run_in_background"] = False
+ yield sse.content_block_delta(
+ block_idx,
+ "input_json_delta",
+ json.dumps(tool_use["input"]),
+ )
+ yield sse.content_block_stop(block_idx)
+
+ if (
+ not error_occurred
+ and sse.blocks.text_index == -1
+ and not sse.blocks.tool_indices
+ ):
+ for event in sse.ensure_text_block():
+ yield event
+ yield sse.emit_text_delta(" ")
+
+ for event in self._flush_task_arg_buffers(sse):
+ yield event
+
+ for event in sse.close_all_blocks():
+ yield event
+
+ output_tokens = (
+ usage_info.completion_tokens
+ if usage_info and hasattr(usage_info, "completion_tokens")
+ else sse.estimate_output_tokens()
+ )
+ if usage_info and hasattr(usage_info, "prompt_tokens"):
+ provider_input = usage_info.prompt_tokens
+ if isinstance(provider_input, int):
+ logger.debug(
+ "TOKEN_ESTIMATE: our=%d provider=%d diff=%+d",
+ input_tokens,
+ provider_input,
+ provider_input - input_tokens,
+ )
+ yield sse.message_delta(map_stop_reason(finish_reason), output_tokens)
+ yield sse.message_stop()
+ yield sse.done()
diff --git a/tests/test_dependencies.py b/tests/test_dependencies.py
index eeef8155..2aafdb7e 100644
--- a/tests/test_dependencies.py
+++ b/tests/test_dependencies.py
@@ -127,7 +127,7 @@ async def test_get_provider_passes_http_timeouts_from_settings():
"""Provider receives http timeouts from settings when creating client."""
with (
patch("api.dependencies.get_settings") as mock_settings,
- patch("providers.nvidia_nim.client.AsyncOpenAI") as mock_openai,
+ patch("providers.openai_compat.AsyncOpenAI") as mock_openai,
):
mock_settings.return_value = _make_mock_settings(
http_read_timeout=600.0,
diff --git a/tests/test_lmstudio.py b/tests/test_lmstudio.py
index d3005e8b..2c99bd4f 100644
--- a/tests/test_lmstudio.py
+++ b/tests/test_lmstudio.py
@@ -109,7 +109,7 @@ def lmstudio_config():
@pytest.fixture(autouse=True)
def mock_rate_limiter():
"""Mock the global rate limiter to prevent waiting."""
- with patch("providers.lmstudio.client.GlobalRateLimiter") as mock:
+ with patch("providers.openai_compat.GlobalRateLimiter") as mock:
instance = mock.get_instance.return_value
instance.wait_if_blocked = AsyncMock(return_value=False)
@@ -127,7 +127,7 @@ def lmstudio_provider(lmstudio_config):
def test_init(lmstudio_config):
"""Test provider initialization."""
- with patch("providers.lmstudio.client.AsyncOpenAI") as mock_openai:
+ with patch("providers.openai_compat.AsyncOpenAI") as mock_openai:
provider = LMStudioProvider(lmstudio_config)
assert provider._api_key == "lm-studio"
assert provider._base_url == "http://localhost:1234/v1"
@@ -143,7 +143,7 @@ def test_init_with_empty_api_key():
rate_window=60,
nim_settings=NimSettings(),
)
- with patch("providers.lmstudio.client.AsyncOpenAI"):
+ with patch("providers.openai_compat.AsyncOpenAI"):
provider = LMStudioProvider(config)
assert provider._api_key == "lm-studio"
@@ -157,7 +157,7 @@ def test_init_uses_configurable_timeouts():
http_write_timeout=15.0,
http_connect_timeout=5.0,
)
- with patch("providers.lmstudio.client.AsyncOpenAI") as mock_openai:
+ with patch("providers.openai_compat.AsyncOpenAI") as mock_openai:
LMStudioProvider(config)
call_kwargs = mock_openai.call_args[1]
timeout = call_kwargs["timeout"]
@@ -657,6 +657,6 @@ def test_init_base_url_strips_trailing_slash():
rate_window=60,
nim_settings=NimSettings(),
)
- with patch("providers.lmstudio.client.AsyncOpenAI"):
+ with patch("providers.openai_compat.AsyncOpenAI"):
provider = LMStudioProvider(config)
assert provider._base_url == "http://localhost:1234/v1"
diff --git a/tests/test_nvidia_nim.py b/tests/test_nvidia_nim.py
index e1c4e2da..d5037760 100644
--- a/tests/test_nvidia_nim.py
+++ b/tests/test_nvidia_nim.py
@@ -38,7 +38,7 @@ class MockRequest:
@pytest.fixture(autouse=True)
def mock_rate_limiter():
"""Mock the global rate limiter to prevent waiting."""
- with patch("providers.nvidia_nim.client.GlobalRateLimiter") as mock:
+ with patch("providers.openai_compat.GlobalRateLimiter") as mock:
instance = mock.get_instance.return_value
instance.wait_if_blocked = AsyncMock(return_value=False)
@@ -53,7 +53,7 @@ def mock_rate_limiter():
@pytest.mark.asyncio
async def test_init(provider_config):
"""Test provider initialization."""
- with patch("providers.nvidia_nim.client.AsyncOpenAI") as mock_openai:
+ with patch("providers.openai_compat.AsyncOpenAI") as mock_openai:
provider = NvidiaNimProvider(provider_config)
assert provider._api_key == "test_key"
assert provider._base_url == "https://test.api.nvidia.com/v1"
@@ -72,7 +72,7 @@ async def test_init_uses_configurable_timeouts():
http_write_timeout=15.0,
http_connect_timeout=5.0,
)
- with patch("providers.nvidia_nim.client.AsyncOpenAI") as mock_openai:
+ with patch("providers.openai_compat.AsyncOpenAI") as mock_openai:
NvidiaNimProvider(config)
call_kwargs = mock_openai.call_args[1]
timeout = call_kwargs["timeout"]
diff --git a/tests/test_open_router.py b/tests/test_open_router.py
index 7f3b58ce..07573281 100644
--- a/tests/test_open_router.py
+++ b/tests/test_open_router.py
@@ -46,7 +46,7 @@ def open_router_config():
@pytest.fixture(autouse=True)
def mock_rate_limiter():
"""Mock the global rate limiter to prevent waiting."""
- with patch("providers.open_router.client.GlobalRateLimiter") as mock:
+ with patch("providers.openai_compat.GlobalRateLimiter") as mock:
instance = mock.get_instance.return_value
instance.wait_if_blocked = AsyncMock(return_value=False)
@@ -64,7 +64,7 @@ def open_router_provider(open_router_config):
def test_init(open_router_config):
"""Test provider initialization."""
- with patch("providers.open_router.client.AsyncOpenAI") as mock_openai:
+ with patch("providers.openai_compat.AsyncOpenAI") as mock_openai:
provider = OpenRouterProvider(open_router_config)
assert provider._api_key == "test_openrouter_key"
assert provider._base_url == "https://openrouter.ai/api/v1"
@@ -80,7 +80,7 @@ def test_init_uses_configurable_timeouts():
http_write_timeout=15.0,
http_connect_timeout=5.0,
)
- with patch("providers.open_router.client.AsyncOpenAI") as mock_openai:
+ with patch("providers.openai_compat.AsyncOpenAI") as mock_openai:
OpenRouterProvider(config)
call_kwargs = mock_openai.call_args[1]
timeout = call_kwargs["timeout"]