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 1: Extract shared provider utils into providers/common/

Cursor Agentd3f5f8877f2e
diff --git a/providers/common/__init__.py b/providers/common/__init__.py
new file mode 100644
index 00000000..eb4adfcd
--- /dev/null
+++ b/providers/common/__init__.py
@@ -0,0 +1,25 @@
+"""Shared provider utilities used by NIM, OpenRouter, and LM Studio."""
+
+from .sse_builder import SSEBuilder, ContentBlockManager, map_stop_reason
+from .think_parser import ThinkTagParser, ContentType, ContentChunk
+from .heuristic_tool_parser import HeuristicToolParser
+from .message_converter import (
+ AnthropicToOpenAIConverter,
+ get_block_attr,
+ get_block_type,
+)
+from .error_mapping import map_error
+
+__all__ = [
+ "SSEBuilder",
+ "ContentBlockManager",
+ "map_stop_reason",
+ "ThinkTagParser",
+ "ContentType",
+ "ContentChunk",
+ "HeuristicToolParser",
+ "AnthropicToOpenAIConverter",
+ "get_block_attr",
+ "get_block_type",
+ "map_error",
+]
diff --git a/providers/common/error_mapping.py b/providers/common/error_mapping.py
new file mode 100644
index 00000000..9fc1a89a
--- /dev/null
+++ b/providers/common/error_mapping.py
@@ -0,0 +1,35 @@
+"""Error mapping for OpenAI-compatible providers (NIM, OpenRouter, LM Studio)."""
+
+import openai
+
+from providers.exceptions import (
+ AuthenticationError,
+ InvalidRequestError,
+ RateLimitError,
+ OverloadedError,
+ APIError,
+)
+from providers.rate_limit import GlobalRateLimiter
+
+
+def map_error(e: Exception) -> Exception:
+ """Map OpenAI exception to specific ProviderError."""
+ if isinstance(e, openai.AuthenticationError):
+ return AuthenticationError(str(e), raw_error=str(e))
+ if isinstance(e, openai.RateLimitError):
+ # Trigger global rate limit block
+ GlobalRateLimiter.get_instance().set_blocked(60) # Default 60s cooldown
+ return RateLimitError(str(e), raw_error=str(e))
+ if isinstance(e, openai.BadRequestError):
+ return InvalidRequestError(str(e), raw_error=str(e))
+ if isinstance(e, openai.InternalServerError):
+ message = str(e)
+ if "overloaded" in message.lower() or "capacity" in message.lower():
+ return OverloadedError(message, raw_error=str(e))
+ return APIError(message, status_code=500, raw_error=str(e))
+ if isinstance(e, openai.APIError):
+ return APIError(
+ str(e), status_code=getattr(e, "status_code", 500), raw_error=str(e)
+ )
+
+ return e
diff --git a/providers/nvidia_nim/utils/heuristic_tool_parser.py b/providers/common/heuristic_tool_parser.py
similarity index 99%
rename from providers/nvidia_nim/utils/heuristic_tool_parser.py
rename to providers/common/heuristic_tool_parser.py
index bdc78f5e..1028e44b 100644
--- a/providers/nvidia_nim/utils/heuristic_tool_parser.py
+++ b/providers/common/heuristic_tool_parser.py
@@ -70,7 +70,7 @@ class HeuristicToolParser:
Returns a tuple of (filtered_text, detected_tool_calls).
filtered_text: Text that should be passed through as normal message content.
- detected_tool_calls: List of Anthropic-format tool_use blocks.
+ detected_tools: List of Anthropic-format tool_use blocks.
"""
self.buffer += text
self.buffer = self._strip_control_tokens(self.buffer)
diff --git a/providers/nvidia_nim/utils/message_converter.py b/providers/common/message_converter.py
similarity index 100%
rename from providers/nvidia_nim/utils/message_converter.py
rename to providers/common/message_converter.py
diff --git a/providers/nvidia_nim/utils/sse_builder.py b/providers/common/sse_builder.py
similarity index 100%
rename from providers/nvidia_nim/utils/sse_builder.py
rename to providers/common/sse_builder.py
diff --git a/providers/nvidia_nim/utils/think_parser.py b/providers/common/think_parser.py
similarity index 100%
rename from providers/nvidia_nim/utils/think_parser.py
rename to providers/common/think_parser.py
diff --git a/providers/lmstudio/client.py b/providers/lmstudio/client.py
index 0625cd38..e79f5403 100644
--- a/providers/lmstudio/client.py
+++ b/providers/lmstudio/client.py
@@ -10,13 +10,13 @@ from openai import AsyncOpenAI
from providers.base import BaseProvider, ProviderConfig
from providers.rate_limit import GlobalRateLimiter
-from providers.nvidia_nim.errors import map_error
-from providers.nvidia_nim.utils import (
+from providers.common import (
SSEBuilder,
map_stop_reason,
ThinkTagParser,
HeuristicToolParser,
ContentType,
+ map_error,
)
from .request import build_request_body
diff --git a/providers/lmstudio/request.py b/providers/lmstudio/request.py
index aac8cec6..dd87e3a8 100644
--- a/providers/lmstudio/request.py
+++ b/providers/lmstudio/request.py
@@ -2,7 +2,7 @@
from typing import Any, Dict
-from providers.nvidia_nim.utils.message_converter import AnthropicToOpenAIConverter
+from providers.common.message_converter import AnthropicToOpenAIConverter
from loguru import logger
diff --git a/providers/nvidia_nim/client.py b/providers/nvidia_nim/client.py
index 3898c70b..5e87a89e 100644
--- a/providers/nvidia_nim/client.py
+++ b/providers/nvidia_nim/client.py
@@ -10,15 +10,15 @@ from openai import AsyncOpenAI
from providers.base import BaseProvider, ProviderConfig
from providers.rate_limit import GlobalRateLimiter
-from .request import build_request_body
-from .errors import map_error
-from .utils import (
+from providers.common import (
SSEBuilder,
map_stop_reason,
ThinkTagParser,
HeuristicToolParser,
ContentType,
+ map_error,
)
+from .request import build_request_body
class NvidiaNimProvider(BaseProvider):
diff --git a/providers/nvidia_nim/errors.py b/providers/nvidia_nim/errors.py
index d6b1fa2a..4c70b57a 100644
--- a/providers/nvidia_nim/errors.py
+++ b/providers/nvidia_nim/errors.py
@@ -1,35 +1,5 @@
-"""Error mapping for NVIDIA NIM provider."""
+"""Error mapping for NVIDIA NIM provider (re-exports from providers.common)."""
-import openai
+from providers.common.error_mapping import map_error
-from providers.exceptions import (
- AuthenticationError,
- InvalidRequestError,
- RateLimitError,
- OverloadedError,
- APIError,
-)
-from providers.rate_limit import GlobalRateLimiter
-
-
-def map_error(e: Exception) -> Exception:
- """Map OpenAI exception to specific ProviderError."""
- if isinstance(e, openai.AuthenticationError):
- return AuthenticationError(str(e), raw_error=str(e))
- if isinstance(e, openai.RateLimitError):
- # Trigger global rate limit block
- GlobalRateLimiter.get_instance().set_blocked(60) # Default 60s cooldown
- return RateLimitError(str(e), raw_error=str(e))
- if isinstance(e, openai.BadRequestError):
- return InvalidRequestError(str(e), raw_error=str(e))
- if isinstance(e, openai.InternalServerError):
- message = str(e)
- if "overloaded" in message.lower() or "capacity" in message.lower():
- return OverloadedError(message, raw_error=str(e))
- return APIError(message, status_code=500, raw_error=str(e))
- if isinstance(e, openai.APIError):
- return APIError(
- str(e), status_code=getattr(e, "status_code", 500), raw_error=str(e)
- )
-
- return e
+__all__ = ["map_error"]
diff --git a/providers/nvidia_nim/request.py b/providers/nvidia_nim/request.py
index 140f19dd..dac44a1c 100644
--- a/providers/nvidia_nim/request.py
+++ b/providers/nvidia_nim/request.py
@@ -3,7 +3,7 @@
from typing import Any, Dict
from config.nim import NimSettings
-from .utils.message_converter import AnthropicToOpenAIConverter
+from providers.common.message_converter import AnthropicToOpenAIConverter
from loguru import logger
diff --git a/providers/nvidia_nim/utils/__init__.py b/providers/nvidia_nim/utils/__init__.py
index 634b6e51..295c90c9 100644
--- a/providers/nvidia_nim/utils/__init__.py
+++ b/providers/nvidia_nim/utils/__init__.py
@@ -1,13 +1,13 @@
-"""Utility modules for providers."""
+"""Utility modules for providers (re-exports from providers.common)."""
-from .sse_builder import SSEBuilder, ContentBlockManager, map_stop_reason
-from .think_parser import (
+from providers.common import (
+ SSEBuilder,
+ ContentBlockManager,
+ map_stop_reason,
ThinkTagParser,
ContentType,
ContentChunk,
-)
-from .heuristic_tool_parser import HeuristicToolParser
-from .message_converter import (
+ HeuristicToolParser,
AnthropicToOpenAIConverter,
get_block_attr,
get_block_type,
diff --git a/providers/open_router/client.py b/providers/open_router/client.py
index 53969ff5..53b5742d 100644
--- a/providers/open_router/client.py
+++ b/providers/open_router/client.py
@@ -10,13 +10,13 @@ from openai import AsyncOpenAI
from providers.base import BaseProvider, ProviderConfig
from providers.rate_limit import GlobalRateLimiter
-from providers.nvidia_nim.errors import map_error
-from providers.nvidia_nim.utils import (
+from providers.common import (
SSEBuilder,
map_stop_reason,
ThinkTagParser,
HeuristicToolParser,
ContentType,
+ map_error,
)
from .request import build_request_body
diff --git a/providers/open_router/request.py b/providers/open_router/request.py
index 984b3163..3af8763a 100644
--- a/providers/open_router/request.py
+++ b/providers/open_router/request.py
@@ -2,7 +2,7 @@
from typing import Any, Dict
-from providers.nvidia_nim.utils.message_converter import AnthropicToOpenAIConverter
+from providers.common.message_converter import AnthropicToOpenAIConverter
from loguru import logger
diff --git a/tests/test_converter.py b/tests/test_converter.py
index a6dec58c..424dea31 100644
--- a/tests/test_converter.py
+++ b/tests/test_converter.py
@@ -1,6 +1,6 @@
import json
import pytest
-from providers.nvidia_nim.utils.message_converter import AnthropicToOpenAIConverter
+from providers.common.message_converter import AnthropicToOpenAIConverter
# --- Mock Classes ---
@@ -273,7 +273,7 @@ def test_convert_mixed_blocks_and_types_and_roles():
def test_get_block_attr_defaults():
# Test helper directly
- from providers.nvidia_nim.utils.message_converter import get_block_attr
+ from providers.common.message_converter import get_block_attr
assert get_block_attr({}, "missing", "default") == "default"
assert get_block_attr(object(), "missing", "default") == "default"
diff --git a/tests/test_error_mapping.py b/tests/test_error_mapping.py
index c57b1198..8b5ab318 100644
--- a/tests/test_error_mapping.py
+++ b/tests/test_error_mapping.py
@@ -6,7 +6,7 @@ from unittest.mock import patch, MagicMock
import openai
from httpx import Response, Request
-from providers.nvidia_nim.errors import map_error
+from providers.common import map_error
from providers.exceptions import (
AuthenticationError,
InvalidRequestError,
@@ -41,7 +41,7 @@ class TestMapError:
def test_rate_limit_error(self):
"""openai.RateLimitError -> RateLimitError and triggers global block."""
exc = _make_openai_error(openai.RateLimitError, status_code=429)
- with patch("providers.nvidia_nim.errors.GlobalRateLimiter") as mock_rl:
+ with patch("providers.common.error_mapping.GlobalRateLimiter") as mock_rl:
mock_instance = MagicMock()
mock_rl.get_instance.return_value = mock_instance
result = map_error(exc)
@@ -117,6 +117,6 @@ class TestMapError:
openai.BadRequestError: 400,
}
exc = _make_openai_error(exc_cls, status_code=status_map[exc_cls])
- with patch("providers.nvidia_nim.errors.GlobalRateLimiter"):
+ with patch("providers.common.error_mapping.GlobalRateLimiter"):
result = map_error(exc)
assert isinstance(result, expected_cls)
diff --git a/tests/test_lmstudio.py b/tests/test_lmstudio.py
index 8b56a83c..d3005e8b 100644
--- a/tests/test_lmstudio.py
+++ b/tests/test_lmstudio.py
@@ -471,7 +471,7 @@ class TestLMStudioProcessToolCall:
def test_tool_call_with_id(self, lmstudio_provider):
"""Tool call with id starts a tool block."""
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -487,7 +487,7 @@ class TestLMStudioProcessToolCall:
def test_tool_call_without_id_generates_uuid(self, lmstudio_provider):
"""Tool call without id generates a uuid-based id."""
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -501,7 +501,7 @@ class TestLMStudioProcessToolCall:
def test_task_tool_forces_background_false(self, lmstudio_provider):
"""Task tool with run_in_background=true is forced to false."""
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
args = json.dumps({"run_in_background": True, "prompt": "test"})
@@ -516,7 +516,7 @@ class TestLMStudioProcessToolCall:
def test_task_tool_chunked_args_forces_background_false(self, lmstudio_provider):
"""Chunked Task args are buffered until valid JSON, then forced to false."""
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc1 = {
@@ -542,7 +542,7 @@ class TestLMStudioProcessToolCall:
self, lmstudio_provider, caplog
):
"""Invalid JSON args for Task tool emits {} on flush and logs a warning."""
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -561,7 +561,7 @@ class TestLMStudioProcessToolCall:
def test_negative_tool_index_fallback(self, lmstudio_provider):
"""tc_index < 0 uses len(tool_indices) as fallback."""
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -574,7 +574,7 @@ class TestLMStudioProcessToolCall:
def test_tool_args_emitted_as_delta(self, lmstudio_provider):
"""Arguments are emitted as input_json_delta events."""
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -588,7 +588,7 @@ class TestLMStudioProcessToolCall:
def test_stream_malformed_tool_args_chunked(self, lmstudio_provider):
"""Chunked tool args that never form valid JSON are flushed with {}."""
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc1 = {
diff --git a/tests/test_parsers.py b/tests/test_parsers.py
index 89e3c537..4a2ea19d 100644
--- a/tests/test_parsers.py
+++ b/tests/test_parsers.py
@@ -1,7 +1,6 @@
import pytest
-from providers.nvidia_nim.utils.think_parser import ThinkTagParser, ContentType
-from providers.nvidia_nim.utils.heuristic_tool_parser import HeuristicToolParser
+from providers.common import ThinkTagParser, ContentType, HeuristicToolParser
def test_think_tag_parser_basic():
diff --git a/tests/test_sse_builder.py b/tests/test_sse_builder.py
index 1ed58f92..0e8ca1e3 100644
--- a/tests/test_sse_builder.py
+++ b/tests/test_sse_builder.py
@@ -4,7 +4,7 @@ import json
import pytest
from unittest.mock import patch
-from providers.nvidia_nim.utils.sse_builder import (
+from providers.common.sse_builder import (
SSEBuilder,
ContentBlockManager,
map_stop_reason,
@@ -369,7 +369,7 @@ class TestSSEBuilderTokenEstimation:
builder.start_text_block()
builder.emit_text_delta("a" * 100) # 100 chars -> ~25 tokens
- with patch("providers.nvidia_nim.utils.sse_builder.ENCODER", None):
+ with patch("providers.common.sse_builder.ENCODER", None):
tokens = builder.estimate_output_tokens()
assert tokens == 25 # 100 // 4
@@ -379,7 +379,7 @@ class TestSSEBuilderTokenEstimation:
builder.start_tool_block(0, "t1", "Read")
builder.emit_tool_delta(0, '{"path":"test.py"}')
- with patch("providers.nvidia_nim.utils.sse_builder.ENCODER", None):
+ with patch("providers.common.sse_builder.ENCODER", None):
tokens = builder.estimate_output_tokens()
# 1 tool * 50 = 50
assert tokens == 50
diff --git a/tests/test_streaming_errors.py b/tests/test_streaming_errors.py
index 50bb017e..9513bf30 100644
--- a/tests/test_streaming_errors.py
+++ b/tests/test_streaming_errors.py
@@ -270,7 +270,7 @@ class TestProcessToolCall:
def test_tool_call_with_id(self):
"""Tool call with id starts a tool block."""
provider = _make_provider()
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -287,7 +287,7 @@ class TestProcessToolCall:
def test_tool_call_without_id_generates_uuid(self):
"""Tool call without id generates a uuid-based id."""
provider = _make_provider()
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -302,7 +302,7 @@ class TestProcessToolCall:
def test_task_tool_forces_background_false(self):
"""Task tool with run_in_background=true is forced to false."""
provider = _make_provider()
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
args = json.dumps({"run_in_background": True, "prompt": "test"})
@@ -319,7 +319,7 @@ class TestProcessToolCall:
def test_task_tool_chunked_args_forces_background_false(self):
"""Chunked Task args are buffered until valid JSON, then forced to false."""
provider = _make_provider()
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc1 = {
@@ -344,7 +344,7 @@ class TestProcessToolCall:
def test_task_tool_invalid_json_logs_warning_on_flush(self, caplog):
"""Invalid JSON args for Task tool emits {} on flush and logs a warning."""
provider = _make_provider()
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -364,7 +364,7 @@ class TestProcessToolCall:
def test_negative_tool_index_fallback(self):
"""tc_index < 0 uses len(tool_indices) as fallback."""
provider = _make_provider()
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -379,7 +379,7 @@ class TestProcessToolCall:
def test_tool_args_emitted_as_delta(self):
"""Arguments are emitted as input_json_delta events."""
provider = _make_provider()
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc = {
@@ -496,7 +496,7 @@ class TestStreamChunkEdgeCases:
def test_stream_malformed_tool_args_chunked(self):
"""Chunked tool args that never form valid JSON are flushed with {}."""
provider = _make_provider()
- from providers.nvidia_nim.utils import SSEBuilder
+ from providers.common import SSEBuilder
sse = SSEBuilder("msg_test", "test-model")
tc1 = {
diff --git a/tests/test_subagent_interception.py b/tests/test_subagent_interception.py
index d2fef13b..f0b009bd 100644
--- a/tests/test_subagent_interception.py
+++ b/tests/test_subagent_interception.py
@@ -2,7 +2,7 @@ import json
import pytest
from unittest.mock import MagicMock
from providers.nvidia_nim import NvidiaNimProvider
-from providers.nvidia_nim.utils.sse_builder import ContentBlockManager
+from providers.common import ContentBlockManager
from providers.base import ProviderConfig