swarmauri_provider_openrouter 0.1.0.dev1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ Copyright 2024 Jacob Stewart
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: swarmauri_provider_openrouter
3
+ Version: 0.1.0.dev1
4
+ Summary: OpenRouter provider configuration, routing, catalogs, errors, and tool schemas for Swarmauri.
5
+ License: Copyright 2024 Jacob Stewart
6
+
7
+ Licensed under the Apache License, Version 2.0 (the "License");
8
+ you may not use this file except in compliance with the License.
9
+ You may obtain a copy of the License at
10
+
11
+ http://www.apache.org/licenses/LICENSE-2.0
12
+
13
+ Unless required by applicable law or agreed to in writing, software
14
+ distributed under the License is distributed on an "AS IS" BASIS,
15
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ See the License for the specific language governing permissions and
17
+ limitations under the License.
18
+ License-File: LICENSE
19
+ Keywords: swarmauri,provider,openrouter,model routing,model catalog,tool calling
20
+ Author: Jacob Stewart
21
+ Author-email: jacob@swarmauri.com
22
+ Requires-Python: >=3.10,<3.13
23
+ Classifier: Development Status :: 1 - Planning
24
+ Classifier: License :: OSI Approved :: Apache Software License
25
+ Classifier: Programming Language :: Python :: 3.10
26
+ Classifier: Programming Language :: Python :: 3.11
27
+ Classifier: Programming Language :: Python :: 3.12
28
+ Requires-Dist: swarmauri_base (>=0.11.0.dev5)
29
+ Requires-Dist: swarmauri_core (>=0.11.0.dev5)
30
+ Description-Content-Type: text/markdown
31
+
32
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
33
+
34
+ [![PyPI version](https://img.shields.io/pypi/v/swarmauri_provider_openrouter.svg)](https://pypi.org/project/swarmauri_provider_openrouter/) [![Python versions](https://img.shields.io/pypi/pyversions/swarmauri_provider_openrouter.svg)](https://pypi.org/project/swarmauri_provider_openrouter/) [![Downloads](https://static.pepy.tech/badge/swarmauri_provider_openrouter/month)](https://pepy.tech/project/swarmauri_provider_openrouter) [![Hits](https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_provider_openrouter.svg)](https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_provider_openrouter/) [![License](https://img.shields.io/pypi/l/swarmauri_provider_openrouter.svg)](https://pypi.org/project/swarmauri_provider_openrouter/)
35
+
36
+ # swarmauri_provider_openrouter
37
+
38
+ `swarmauri_provider_openrouter` describes OpenRouter authentication, endpoints,
39
+ model metadata, routing preferences, provider errors, and tool schemas without
40
+ owning an HTTP implementation.
41
+
42
+ ## Features
43
+
44
+ - Bearer authentication with optional application attribution headers.
45
+ - Capability-based resolution for chat, catalog, and image-generation APIs.
46
+ - Provider routing, fallback, data-collection, and ZDR preferences.
47
+ - Mutable provider catalog populated by an injected model client.
48
+ - OpenRouter-compatible function-tool schema conversion.
49
+ - Serializable connection configurations that exclude credentials.
50
+
51
+ ## Installation
52
+
53
+ ```bash
54
+ uv add swarmauri_provider_openrouter
55
+ ```
56
+
57
+ ```bash
58
+ pip install swarmauri_provider_openrouter
59
+ ```
60
+
61
+ ## Usage
62
+
63
+ ```python
64
+ from swarmauri_provider_openrouter import (
65
+ OpenRouterProvider,
66
+ OpenRouterProviderPreferences,
67
+ )
68
+
69
+ provider = OpenRouterProvider(
70
+ api_key="...",
71
+ site_url="https://example.com",
72
+ app_name="My application",
73
+ )
74
+ config = provider.connection_config(
75
+ "chat.completions",
76
+ model="openai/gpt-4o-mini",
77
+ )
78
+ headers = provider.authorize(config)
79
+ routing = OpenRouterProviderPreferences(order=["OpenAI"])
80
+ ```
81
+
82
+ Pass the provider and routing preferences to a compatible model package. The
83
+ provider returns connection configuration; a Swarmauri transport such as
84
+ `swarmauri_transport_httpx` performs the request.
85
+
86
+ ## Project links
87
+
88
+ - [Swarmauri SDK](https://github.com/swarmauri/swarmauri-sdk)
89
+ - [OpenRouter documentation](https://openrouter.ai/docs)
90
+
@@ -0,0 +1,58 @@
1
+ ![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/swarmauri_provider_openrouter.svg)](https://pypi.org/project/swarmauri_provider_openrouter/) [![Python versions](https://img.shields.io/pypi/pyversions/swarmauri_provider_openrouter.svg)](https://pypi.org/project/swarmauri_provider_openrouter/) [![Downloads](https://static.pepy.tech/badge/swarmauri_provider_openrouter/month)](https://pepy.tech/project/swarmauri_provider_openrouter) [![Hits](https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_provider_openrouter.svg)](https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_provider_openrouter/) [![License](https://img.shields.io/pypi/l/swarmauri_provider_openrouter.svg)](https://pypi.org/project/swarmauri_provider_openrouter/)
4
+
5
+ # swarmauri_provider_openrouter
6
+
7
+ `swarmauri_provider_openrouter` describes OpenRouter authentication, endpoints,
8
+ model metadata, routing preferences, provider errors, and tool schemas without
9
+ owning an HTTP implementation.
10
+
11
+ ## Features
12
+
13
+ - Bearer authentication with optional application attribution headers.
14
+ - Capability-based resolution for chat, catalog, and image-generation APIs.
15
+ - Provider routing, fallback, data-collection, and ZDR preferences.
16
+ - Mutable provider catalog populated by an injected model client.
17
+ - OpenRouter-compatible function-tool schema conversion.
18
+ - Serializable connection configurations that exclude credentials.
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ uv add swarmauri_provider_openrouter
24
+ ```
25
+
26
+ ```bash
27
+ pip install swarmauri_provider_openrouter
28
+ ```
29
+
30
+ ## Usage
31
+
32
+ ```python
33
+ from swarmauri_provider_openrouter import (
34
+ OpenRouterProvider,
35
+ OpenRouterProviderPreferences,
36
+ )
37
+
38
+ provider = OpenRouterProvider(
39
+ api_key="...",
40
+ site_url="https://example.com",
41
+ app_name="My application",
42
+ )
43
+ config = provider.connection_config(
44
+ "chat.completions",
45
+ model="openai/gpt-4o-mini",
46
+ )
47
+ headers = provider.authorize(config)
48
+ routing = OpenRouterProviderPreferences(order=["OpenAI"])
49
+ ```
50
+
51
+ Pass the provider and routing preferences to a compatible model package. The
52
+ provider returns connection configuration; a Swarmauri transport such as
53
+ `swarmauri_transport_httpx` performs the request.
54
+
55
+ ## Project links
56
+
57
+ - [Swarmauri SDK](https://github.com/swarmauri/swarmauri-sdk)
58
+ - [OpenRouter documentation](https://openrouter.ai/docs)
@@ -0,0 +1,47 @@
1
+ [project]
2
+ name = "swarmauri_provider_openrouter"
3
+ version = "0.1.0.dev1"
4
+ description = "OpenRouter provider configuration, routing, catalogs, errors, and tool schemas for Swarmauri."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10,<3.13"
7
+ authors = [{ name = "Jacob Stewart", email = "jacob@swarmauri.com" }]
8
+ license = { file = "LICENSE" }
9
+ dependencies = ["swarmauri_core>=0.11.0.dev5", "swarmauri_base>=0.11.0.dev5"]
10
+ classifiers = [
11
+ "Development Status :: 1 - Planning",
12
+ "License :: OSI Approved :: Apache Software License",
13
+ "Programming Language :: Python :: 3.10",
14
+ "Programming Language :: Python :: 3.11",
15
+ "Programming Language :: Python :: 3.12",
16
+ ]
17
+ keywords = [
18
+ "swarmauri",
19
+ "provider",
20
+ "openrouter",
21
+ "model routing",
22
+ "model catalog",
23
+ "tool calling",
24
+ ]
25
+
26
+ [tool.uv.sources]
27
+ swarmauri_core = { workspace = true }
28
+ swarmauri_base = { workspace = true }
29
+
30
+ [project.entry-points."swarmauri.model_providers"]
31
+ OpenRouterProvider = "swarmauri_provider_openrouter:OpenRouterProvider"
32
+
33
+ [build-system]
34
+ requires = ["poetry-core>=1.8.0"]
35
+ build-backend = "poetry.core.masonry.api"
36
+
37
+ [dependency-groups]
38
+ dev = ["pytest>=8.0", "ruff>=0.9.9"]
39
+
40
+ [tool.pytest.ini_options]
41
+ markers = ["unit: Unit tests"]
42
+
43
+ [tool.ruff]
44
+ extend = "../../pyproject.toml"
45
+
46
+ [tool.ruff.lint]
47
+ ignore = ["N999", "RUF012"]
@@ -0,0 +1,24 @@
1
+ from collections.abc import Mapping
2
+ from typing import Literal
3
+
4
+ from pydantic import SecretStr
5
+ from swarmauri_base.model_providers.ProviderAuthBase import ProviderAuthBase
6
+
7
+
8
+ class OpenRouterAuthConfig(ProviderAuthBase):
9
+ api_key: SecretStr | None = None
10
+ site_url: str | None = None
11
+ app_name: str | None = None
12
+ type: Literal["OpenRouterAuthConfig"] = "OpenRouterAuthConfig"
13
+
14
+ def apply(self, headers: Mapping[str, str]) -> dict[str, str]:
15
+ authorized = dict(headers)
16
+ if self.api_key is not None:
17
+ authorized["Authorization"] = (
18
+ f"Bearer {self.api_key.get_secret_value()}"
19
+ )
20
+ if self.site_url:
21
+ authorized["HTTP-Referer"] = self.site_url
22
+ if self.app_name:
23
+ authorized["X-OpenRouter-Title"] = self.app_name
24
+ return authorized
@@ -0,0 +1,27 @@
1
+ from typing import Literal
2
+
3
+ from swarmauri_base.model_providers.ProviderEndpointBase import (
4
+ ProviderEndpointBase,
5
+ )
6
+
7
+
8
+ class OpenRouterEndpoints(ProviderEndpointBase):
9
+ base_url: str = "https://openrouter.ai/api/v1"
10
+ chat_completions_path: str = "/chat/completions"
11
+ models_path: str = "/models"
12
+ image_generations_path: str = "/images/generations"
13
+ type: Literal["OpenRouterEndpoints"] = "OpenRouterEndpoints"
14
+
15
+ def resolve(self, capability: str) -> str:
16
+ paths = {
17
+ "chat.completions": self.chat_completions_path,
18
+ "models.list": self.models_path,
19
+ "images.generate": self.image_generations_path,
20
+ }
21
+ try:
22
+ path = paths[capability]
23
+ except KeyError as error:
24
+ raise ValueError(
25
+ f"OpenRouter does not support capability {capability!r}"
26
+ ) from error
27
+ return f"{self.base_url.rstrip('/')}/{path.lstrip('/')}"
@@ -0,0 +1,12 @@
1
+ from typing import Any, Literal
2
+
3
+ from swarmauri_base.model_providers.ProviderErrorMapperBase import (
4
+ ProviderErrorMapperBase,
5
+ )
6
+
7
+
8
+ class OpenRouterErrorMapper(ProviderErrorMapperBase):
9
+ type: Literal["OpenRouterErrorMapper"] = "OpenRouterErrorMapper"
10
+
11
+ def map_error(self, error: BaseException | Any) -> BaseException:
12
+ return RuntimeError(f"OpenRouter provider error: {error}")
@@ -0,0 +1,41 @@
1
+ from collections.abc import Iterable
2
+ from typing import Any, Literal
3
+
4
+ from swarmauri_base.model_providers.ModelCatalogBase import ModelCatalogBase
5
+
6
+
7
+ class OpenRouterModelCatalog(ModelCatalogBase):
8
+ models: dict[str, Any] = {
9
+ "openrouter/auto": {
10
+ "id": "openrouter/auto",
11
+ "name": "openrouter/auto",
12
+ "capabilities": ["chat_completions", "streaming", "tools"],
13
+ }
14
+ }
15
+ type: Literal["OpenRouterModelCatalog"] = "OpenRouterModelCatalog"
16
+
17
+ def load_response(self, payload: dict[str, Any]) -> list[dict[str, Any]]:
18
+ models = [item for item in payload.get("data", []) if item.get("id")]
19
+ self.models = {item["id"]: dict(item) for item in models}
20
+ return models
21
+
22
+ def list_models(
23
+ self, *, output_modalities: str | None = None
24
+ ) -> Iterable[Any]:
25
+ models = list(self.models.values())
26
+ if output_modalities is None:
27
+ return models
28
+ return [
29
+ model
30
+ for model in models
31
+ if output_modalities
32
+ in (model.get("architecture", {}).get("output_modalities") or [])
33
+ ]
34
+
35
+ def list_model_ids(
36
+ self, *, output_modalities: str | None = None
37
+ ) -> list[str]:
38
+ return [
39
+ model.get("id") or model["name"]
40
+ for model in self.list_models(output_modalities=output_modalities)
41
+ ]
@@ -0,0 +1,76 @@
1
+ from typing import Any, Literal
2
+
3
+ from pydantic import Field, model_validator
4
+ from swarmauri_base.model_providers.ModelProviderBase import ModelProviderBase
5
+ from swarmauri_base.model_providers.ProviderConnectionConfig import (
6
+ ProviderConnectionConfig,
7
+ )
8
+
9
+ from .OpenRouterAuthConfig import OpenRouterAuthConfig
10
+ from .OpenRouterEndpoints import OpenRouterEndpoints
11
+ from .OpenRouterErrorMapper import OpenRouterErrorMapper
12
+ from .OpenRouterModelCatalog import OpenRouterModelCatalog
13
+
14
+
15
+ class OpenRouterProvider(ModelProviderBase):
16
+ provider_name: Literal["openrouter"] = "openrouter"
17
+ endpoints: OpenRouterEndpoints = Field(default_factory=OpenRouterEndpoints)
18
+ catalog: OpenRouterModelCatalog = Field(
19
+ default_factory=OpenRouterModelCatalog
20
+ )
21
+ error_mapper: OpenRouterErrorMapper = Field(
22
+ default_factory=OpenRouterErrorMapper
23
+ )
24
+ auth: OpenRouterAuthConfig = Field(
25
+ default_factory=OpenRouterAuthConfig, exclude=True
26
+ )
27
+ site_url: str | None = None
28
+ app_name: str | None = None
29
+ type: Literal["OpenRouterProvider"] = "OpenRouterProvider"
30
+
31
+ @model_validator(mode="after")
32
+ def configure(self) -> "OpenRouterProvider":
33
+ self.base_url = self.base_url or self.endpoints.base_url
34
+ self.endpoints.base_url = self.base_url
35
+ if self.api_key is not None:
36
+ self.auth.api_key = self.api_key
37
+ elif self.auth.api_key is not None:
38
+ self.api_key = self.auth.api_key
39
+ if self.site_url is not None:
40
+ self.auth.site_url = self.site_url
41
+ elif self.auth.site_url is not None:
42
+ self.site_url = self.auth.site_url
43
+ if self.app_name is not None:
44
+ self.auth.app_name = self.app_name
45
+ elif self.auth.app_name is not None:
46
+ self.app_name = self.auth.app_name
47
+ return self
48
+
49
+ def connection_config(
50
+ self,
51
+ capability: str,
52
+ model: str | None = None,
53
+ ) -> ProviderConnectionConfig:
54
+ endpoint = self.endpoints.resolve(capability)
55
+ options: dict[str, Any] = super().connection_options()
56
+ if model is not None:
57
+ options["model"] = model
58
+ return ProviderConnectionConfig(
59
+ endpoint=endpoint,
60
+ headers={
61
+ **self.default_headers,
62
+ "Accept": "application/json",
63
+ "Content-Type": "application/json",
64
+ },
65
+ transport_options=options,
66
+ auth_context=self.auth,
67
+ )
68
+
69
+ @staticmethod
70
+ def authorize(config: ProviderConnectionConfig) -> dict[str, str]:
71
+ auth = config.auth_context
72
+ if not isinstance(auth, OpenRouterAuthConfig):
73
+ raise TypeError(
74
+ "OpenRouter connection configuration has no auth context"
75
+ )
76
+ return auth.apply(config.headers)
@@ -0,0 +1,15 @@
1
+ from typing import Any, Literal
2
+
3
+ from pydantic import BaseModel, ConfigDict
4
+
5
+
6
+ class OpenRouterProviderPreferences(BaseModel):
7
+ """Configure OpenRouter upstream-provider selection and data handling."""
8
+
9
+ order: list[str] | None = None
10
+ allow_fallbacks: bool = True
11
+ require_parameters: bool = False
12
+ data_collection: Literal["allow", "deny"] | None = None
13
+ zdr: bool | None = None
14
+ options: dict[str, Any] | None = None
15
+ model_config = ConfigDict(extra="forbid")
@@ -0,0 +1,31 @@
1
+ from typing import Any
2
+
3
+
4
+ class OpenRouterToolSchemaConverter:
5
+ def convert(self, tool: Any) -> dict[str, Any]:
6
+ properties: dict[str, Any] = {}
7
+ required: list[str] = []
8
+ for parameter in getattr(tool, "parameters", []):
9
+ schema: dict[str, Any] = {
10
+ "type": getattr(parameter, "input_type", "string"),
11
+ "description": getattr(parameter, "description", None),
12
+ }
13
+ enum = getattr(parameter, "enum", None)
14
+ if enum:
15
+ schema["enum"] = enum
16
+ properties[parameter.name] = schema
17
+ if getattr(parameter, "required", False):
18
+ required.append(parameter.name)
19
+ return {
20
+ "type": "function",
21
+ "function": {
22
+ "name": tool.name,
23
+ "description": getattr(tool, "description", None),
24
+ "parameters": {
25
+ "type": "object",
26
+ "properties": properties,
27
+ "required": required,
28
+ "additionalProperties": False,
29
+ },
30
+ },
31
+ }
@@ -0,0 +1,24 @@
1
+ from importlib.metadata import PackageNotFoundError, version
2
+
3
+ from .OpenRouterAuthConfig import OpenRouterAuthConfig
4
+ from .OpenRouterEndpoints import OpenRouterEndpoints
5
+ from .OpenRouterErrorMapper import OpenRouterErrorMapper
6
+ from .OpenRouterModelCatalog import OpenRouterModelCatalog
7
+ from .OpenRouterProvider import OpenRouterProvider
8
+ from .OpenRouterProviderPreferences import OpenRouterProviderPreferences
9
+ from .OpenRouterToolSchemaConverter import OpenRouterToolSchemaConverter
10
+
11
+ __all__ = [
12
+ "OpenRouterAuthConfig",
13
+ "OpenRouterEndpoints",
14
+ "OpenRouterErrorMapper",
15
+ "OpenRouterModelCatalog",
16
+ "OpenRouterProvider",
17
+ "OpenRouterProviderPreferences",
18
+ "OpenRouterToolSchemaConverter",
19
+ ]
20
+
21
+ try:
22
+ __version__ = version("swarmauri_provider_openrouter")
23
+ except PackageNotFoundError:
24
+ __version__ = "0.0.0"