Initial commit: OpenRouter Python SDK

Auto-generated Python SDK for OpenRouter API, providing comprehensive client library with:
- Chat completions and streaming support
- Embeddings API
- Model and provider information
- API key management
- Analytics and usage tracking
- OAuth authentication flows
- Full type hints and error handling
This commit is contained in:
Matt Apperson
2025-11-13 10:56:25 -05:00
commit 5fc522c72f
721 changed files with 45654 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from ._version import (
__title__,
__version__,
__openapi_doc_version__,
__gen_version__,
__user_agent__,
)
from .sdk import *
from .sdkconfiguration import *
VERSION: str = __version__
OPENAPI_DOC_VERSION = __openapi_doc_version__
SPEAKEASY_GENERATOR_VERSION = __gen_version__
USER_AGENT = __user_agent__
+5
View File
@@ -0,0 +1,5 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .sdkhooks import *
from .types import *
from .registration import *
+13
View File
@@ -0,0 +1,13 @@
from .types import Hooks
# This file is only ever generated once on the first generation and then is free to be modified.
# Any hooks you wish to add should be registered in the init_hooks function. Feel free to define them
# in this file or in separate files in the hooks folder.
def init_hooks(hooks: Hooks):
# pylint: disable=unused-argument
"""Add hooks by calling hooks.register{sdk_init/before_request/after_success/after_error}Hook
with an instance of a hook that implements that specific Hook interface
Hooks are registered per SDK instance, and are valid for the lifetime of the SDK instance"""
+76
View File
@@ -0,0 +1,76 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import httpx
from .types import (
SDKInitHook,
BeforeRequestContext,
BeforeRequestHook,
AfterSuccessContext,
AfterSuccessHook,
AfterErrorContext,
AfterErrorHook,
Hooks,
)
from .registration import init_hooks
from typing import List, Optional, Tuple
from openrouter.sdkconfiguration import SDKConfiguration
class SDKHooks(Hooks):
def __init__(self) -> None:
self.sdk_init_hooks: List[SDKInitHook] = []
self.before_request_hooks: List[BeforeRequestHook] = []
self.after_success_hooks: List[AfterSuccessHook] = []
self.after_error_hooks: List[AfterErrorHook] = []
init_hooks(self)
def register_sdk_init_hook(self, hook: SDKInitHook) -> None:
self.sdk_init_hooks.append(hook)
def register_before_request_hook(self, hook: BeforeRequestHook) -> None:
self.before_request_hooks.append(hook)
def register_after_success_hook(self, hook: AfterSuccessHook) -> None:
self.after_success_hooks.append(hook)
def register_after_error_hook(self, hook: AfterErrorHook) -> None:
self.after_error_hooks.append(hook)
def sdk_init(self, config: SDKConfiguration) -> SDKConfiguration:
for hook in self.sdk_init_hooks:
config = hook.sdk_init(config)
return config
def before_request(
self, hook_ctx: BeforeRequestContext, request: httpx.Request
) -> httpx.Request:
for hook in self.before_request_hooks:
out = hook.before_request(hook_ctx, request)
if isinstance(out, Exception):
raise out
request = out
return request
def after_success(
self, hook_ctx: AfterSuccessContext, response: httpx.Response
) -> httpx.Response:
for hook in self.after_success_hooks:
out = hook.after_success(hook_ctx, response)
if isinstance(out, Exception):
raise out
response = out
return response
def after_error(
self,
hook_ctx: AfterErrorContext,
response: Optional[httpx.Response],
error: Optional[Exception],
) -> Tuple[Optional[httpx.Response], Optional[Exception]]:
for hook in self.after_error_hooks:
result = hook.after_error(hook_ctx, response, error)
if isinstance(result, Exception):
raise result
response, error = result
return response, error
+112
View File
@@ -0,0 +1,112 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from abc import ABC, abstractmethod
import httpx
from openrouter.sdkconfiguration import SDKConfiguration
from typing import Any, Callable, List, Optional, Tuple, Union
class HookContext:
config: SDKConfiguration
base_url: str
operation_id: str
oauth2_scopes: Optional[List[str]] = None
security_source: Optional[Union[Any, Callable[[], Any]]] = None
def __init__(
self,
config: SDKConfiguration,
base_url: str,
operation_id: str,
oauth2_scopes: Optional[List[str]],
security_source: Optional[Union[Any, Callable[[], Any]]],
):
self.config = config
self.base_url = base_url
self.operation_id = operation_id
self.oauth2_scopes = oauth2_scopes
self.security_source = security_source
class BeforeRequestContext(HookContext):
def __init__(self, hook_ctx: HookContext):
super().__init__(
hook_ctx.config,
hook_ctx.base_url,
hook_ctx.operation_id,
hook_ctx.oauth2_scopes,
hook_ctx.security_source,
)
class AfterSuccessContext(HookContext):
def __init__(self, hook_ctx: HookContext):
super().__init__(
hook_ctx.config,
hook_ctx.base_url,
hook_ctx.operation_id,
hook_ctx.oauth2_scopes,
hook_ctx.security_source,
)
class AfterErrorContext(HookContext):
def __init__(self, hook_ctx: HookContext):
super().__init__(
hook_ctx.config,
hook_ctx.base_url,
hook_ctx.operation_id,
hook_ctx.oauth2_scopes,
hook_ctx.security_source,
)
class SDKInitHook(ABC):
@abstractmethod
def sdk_init(self, config: SDKConfiguration) -> SDKConfiguration:
pass
class BeforeRequestHook(ABC):
@abstractmethod
def before_request(
self, hook_ctx: BeforeRequestContext, request: httpx.Request
) -> Union[httpx.Request, Exception]:
pass
class AfterSuccessHook(ABC):
@abstractmethod
def after_success(
self, hook_ctx: AfterSuccessContext, response: httpx.Response
) -> Union[httpx.Response, Exception]:
pass
class AfterErrorHook(ABC):
@abstractmethod
def after_error(
self,
hook_ctx: AfterErrorContext,
response: Optional[httpx.Response],
error: Optional[Exception],
) -> Union[Tuple[Optional[httpx.Response], Optional[Exception]], Exception]:
pass
class Hooks(ABC):
@abstractmethod
def register_sdk_init_hook(self, hook: SDKInitHook):
pass
@abstractmethod
def register_before_request_hook(self, hook: BeforeRequestHook):
pass
@abstractmethod
def register_after_success_hook(self, hook: AfterSuccessHook):
pass
@abstractmethod
def register_after_error_hook(self, hook: AfterErrorHook):
pass
+15
View File
@@ -0,0 +1,15 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import importlib.metadata
__title__: str = "openrouter"
__version__: str = "0.0.1"
__openapi_doc_version__: str = "1.0.0"
__gen_version__: str = "2.753.6"
__user_agent__: str = "speakeasy-sdk/python 0.0.1 2.753.6 1.0.0 openrouter"
try:
if __package__ is not None:
__version__ = importlib.metadata.version(__package__)
except importlib.metadata.PackageNotFoundError:
pass
+229
View File
@@ -0,0 +1,229 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from openrouter import errors, models, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Mapping, Optional
class Analytics(BaseSDK):
r"""Analytics and usage endpoints"""
def get_user_activity(
self,
*,
date_: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.GetUserActivityResponse:
r"""Get user activity grouped by endpoint
Returns user activity data grouped by endpoint for the last 30 (completed) UTC days
:param date_: Filter by a single UTC date in the last 30 days (YYYY-MM-DD format).
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.GetUserActivityRequest(
date_=date_,
)
req = self._build_request(
method="GET",
path="/activity",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getUserActivity",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["400", "401", "403", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.GetUserActivityResponse, http_res)
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def get_user_activity_async(
self,
*,
date_: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.GetUserActivityResponse:
r"""Get user activity grouped by endpoint
Returns user activity data grouped by endpoint for the last 30 (completed) UTC days
:param date_: Filter by a single UTC date in the last 30 days (YYYY-MM-DD format).
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.GetUserActivityRequest(
date_=date_,
)
req = self._build_request_async(
method="GET",
path="/activity",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getUserActivity",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["400", "401", "403", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.GetUserActivityResponse, http_res)
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
File diff suppressed because it is too large Load Diff
+368
View File
@@ -0,0 +1,368 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .sdkconfiguration import SDKConfiguration
import httpx
from openrouter import errors, models, utils
from openrouter._hooks import (
AfterErrorContext,
AfterSuccessContext,
BeforeRequestContext,
)
from openrouter.utils import RetryConfig, SerializedRequestBody, get_body_content
from typing import Callable, List, Mapping, Optional, Tuple
from urllib.parse import parse_qs, urlparse
class BaseSDK:
sdk_configuration: SDKConfiguration
parent_ref: Optional[object] = None
"""
Reference to the root SDK instance, if any. This will prevent it from
being garbage collected while there are active streams.
"""
def __init__(
self,
sdk_config: SDKConfiguration,
parent_ref: Optional[object] = None,
) -> None:
self.sdk_configuration = sdk_config
self.parent_ref = parent_ref
def _get_url(self, base_url, url_variables):
sdk_url, sdk_variables = self.sdk_configuration.get_server_details()
if base_url is None:
base_url = sdk_url
if url_variables is None:
url_variables = sdk_variables
return utils.template_url(base_url, url_variables)
def _build_request_async(
self,
method,
path,
base_url,
url_variables,
request,
request_body_required,
request_has_path_params,
request_has_query_params,
user_agent_header,
accept_header_value,
_globals=None,
security=None,
timeout_ms: Optional[int] = None,
get_serialized_body: Optional[
Callable[[], Optional[SerializedRequestBody]]
] = None,
url_override: Optional[str] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> httpx.Request:
client = self.sdk_configuration.async_client
return self._build_request_with_client(
client,
method,
path,
base_url,
url_variables,
request,
request_body_required,
request_has_path_params,
request_has_query_params,
user_agent_header,
accept_header_value,
_globals,
security,
timeout_ms,
get_serialized_body,
url_override,
http_headers,
)
def _build_request(
self,
method,
path,
base_url,
url_variables,
request,
request_body_required,
request_has_path_params,
request_has_query_params,
user_agent_header,
accept_header_value,
_globals=None,
security=None,
timeout_ms: Optional[int] = None,
get_serialized_body: Optional[
Callable[[], Optional[SerializedRequestBody]]
] = None,
url_override: Optional[str] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> httpx.Request:
client = self.sdk_configuration.client
return self._build_request_with_client(
client,
method,
path,
base_url,
url_variables,
request,
request_body_required,
request_has_path_params,
request_has_query_params,
user_agent_header,
accept_header_value,
_globals,
security,
timeout_ms,
get_serialized_body,
url_override,
http_headers,
)
def _build_request_with_client(
self,
client,
method,
path,
base_url,
url_variables,
request,
request_body_required,
request_has_path_params,
request_has_query_params,
user_agent_header,
accept_header_value,
_globals=None,
security=None,
timeout_ms: Optional[int] = None,
get_serialized_body: Optional[
Callable[[], Optional[SerializedRequestBody]]
] = None,
url_override: Optional[str] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> httpx.Request:
query_params = {}
url = url_override
if url is None:
url = utils.generate_url(
self._get_url(base_url, url_variables),
path,
request if request_has_path_params else None,
_globals if request_has_path_params else None,
)
query_params = utils.get_query_params(
request if request_has_query_params else None,
_globals if request_has_query_params else None,
)
else:
# Pick up the query parameter from the override so they can be
# preserved when building the request later on (necessary as of
# httpx 0.28).
parsed_override = urlparse(str(url_override))
query_params = parse_qs(parsed_override.query, keep_blank_values=True)
headers = utils.get_headers(request, _globals)
headers["Accept"] = accept_header_value
headers[user_agent_header] = self.sdk_configuration.user_agent
if security is not None:
if callable(security):
security = security()
security = utils.get_security_from_env(security, models.Security)
if security is not None:
security_headers, security_query_params = utils.get_security(security)
headers = {**headers, **security_headers}
query_params = {**query_params, **security_query_params}
serialized_request_body = SerializedRequestBody()
if get_serialized_body is not None:
rb = get_serialized_body()
if request_body_required and rb is None:
raise ValueError("request body is required")
if rb is not None:
serialized_request_body = rb
if (
serialized_request_body.media_type is not None
and serialized_request_body.media_type
not in (
"multipart/form-data",
"multipart/mixed",
)
):
headers["content-type"] = serialized_request_body.media_type
if http_headers is not None:
for header, value in http_headers.items():
headers[header] = value
timeout = timeout_ms / 1000 if timeout_ms is not None else None
return client.build_request(
method,
url,
params=query_params,
content=serialized_request_body.content,
data=serialized_request_body.data,
files=serialized_request_body.files,
headers=headers,
timeout=timeout,
)
def do_request(
self,
hook_ctx,
request,
error_status_codes,
stream=False,
retry_config: Optional[Tuple[RetryConfig, List[str]]] = None,
) -> httpx.Response:
client = self.sdk_configuration.client
logger = self.sdk_configuration.debug_logger
hooks = self.sdk_configuration.__dict__["_hooks"]
def do():
http_res = None
try:
req = hooks.before_request(BeforeRequestContext(hook_ctx), request)
logger.debug(
"Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s",
req.method,
req.url,
req.headers,
get_body_content(req),
)
if client is None:
raise ValueError("client is required")
http_res = client.send(req, stream=stream)
except Exception as e:
_, e = hooks.after_error(AfterErrorContext(hook_ctx), None, e)
if e is not None:
logger.debug("Request Exception", exc_info=True)
raise e
if http_res is None:
logger.debug("Raising no response SDK error")
raise errors.NoResponseError("No response received")
logger.debug(
"Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s",
http_res.status_code,
http_res.url,
http_res.headers,
"<streaming response>" if stream else http_res.text,
)
if utils.match_status_codes(error_status_codes, http_res.status_code):
result, err = hooks.after_error(
AfterErrorContext(hook_ctx), http_res, None
)
if err is not None:
logger.debug("Request Exception", exc_info=True)
raise err
if result is not None:
http_res = result
else:
logger.debug("Raising unexpected SDK error")
raise errors.OpenRouterDefaultError(
"Unexpected error occurred", http_res
)
return http_res
if retry_config is not None:
http_res = utils.retry(do, utils.Retries(retry_config[0], retry_config[1]))
else:
http_res = do()
if not utils.match_status_codes(error_status_codes, http_res.status_code):
http_res = hooks.after_success(AfterSuccessContext(hook_ctx), http_res)
return http_res
async def do_request_async(
self,
hook_ctx,
request,
error_status_codes,
stream=False,
retry_config: Optional[Tuple[RetryConfig, List[str]]] = None,
) -> httpx.Response:
client = self.sdk_configuration.async_client
logger = self.sdk_configuration.debug_logger
hooks = self.sdk_configuration.__dict__["_hooks"]
async def do():
http_res = None
try:
req = hooks.before_request(BeforeRequestContext(hook_ctx), request)
logger.debug(
"Request:\nMethod: %s\nURL: %s\nHeaders: %s\nBody: %s",
req.method,
req.url,
req.headers,
get_body_content(req),
)
if client is None:
raise ValueError("client is required")
http_res = await client.send(req, stream=stream)
except Exception as e:
_, e = hooks.after_error(AfterErrorContext(hook_ctx), None, e)
if e is not None:
logger.debug("Request Exception", exc_info=True)
raise e
if http_res is None:
logger.debug("Raising no response SDK error")
raise errors.NoResponseError("No response received")
logger.debug(
"Response:\nStatus Code: %s\nURL: %s\nHeaders: %s\nBody: %s",
http_res.status_code,
http_res.url,
http_res.headers,
"<streaming response>" if stream else http_res.text,
)
if utils.match_status_codes(error_status_codes, http_res.status_code):
result, err = hooks.after_error(
AfterErrorContext(hook_ctx), http_res, None
)
if err is not None:
logger.debug("Request Exception", exc_info=True)
raise err
if result is not None:
http_res = result
else:
logger.debug("Raising unexpected SDK error")
raise errors.OpenRouterDefaultError(
"Unexpected error occurred", http_res
)
return http_res
if retry_config is not None:
http_res = await utils.retry_async(
do, utils.Retries(retry_config[0], retry_config[1])
)
else:
http_res = await do()
if not utils.match_status_codes(error_status_codes, http_res.status_code):
http_res = hooks.after_success(AfterSuccessContext(hook_ctx), http_res)
return http_res
+21
View File
@@ -0,0 +1,21 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from .sdkconfiguration import SDKConfiguration
from openrouter.responses import Responses
from typing import Optional
class Beta(BaseSDK):
responses: Responses
r"""beta.responses endpoints"""
def __init__(
self, sdk_config: SDKConfiguration, parent_ref: Optional[object] = None
) -> None:
BaseSDK.__init__(self, sdk_config, parent_ref=parent_ref)
self.sdk_configuration = sdk_config
self._init_sdks()
def _init_sdks(self):
self.responses = Responses(self.sdk_configuration, parent_ref=self.parent_ref)
+751
View File
@@ -0,0 +1,751 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from enum import Enum
from openrouter import errors, models, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import eventstreaming, get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Dict, List, Literal, Mapping, Optional, Union, overload
class SendAcceptEnum(str, Enum):
APPLICATION_JSON = "application/json"
TEXT_EVENT_STREAM = "text/event-stream"
class Chat(BaseSDK):
@overload
def send(
self,
*,
messages: Union[List[models.Message], List[models.MessageTypedDict]],
model: Optional[str] = None,
models: Optional[List[str]] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
top_logprobs: OptionalNullable[float] = UNSET,
max_completion_tokens: OptionalNullable[float] = UNSET,
max_tokens: OptionalNullable[float] = UNSET,
metadata: Optional[Dict[str, str]] = None,
presence_penalty: OptionalNullable[float] = UNSET,
reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None,
response_format: Optional[
Union[
models.ChatGenerationParamsResponseFormatUnion,
models.ChatGenerationParamsResponseFormatUnionTypedDict,
]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
models.ChatGenerationParamsStop,
models.ChatGenerationParamsStopTypedDict,
]
] = UNSET,
stream: Union[Literal[False], None] = None,
stream_options: OptionalNullable[
Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
tool_choice: Optional[Any] = None,
tools: Optional[
Union[
List[models.ToolDefinitionJSON],
List[models.ToolDefinitionJSONTypedDict],
]
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.ChatResponse:
r"""Create a chat completion
Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes.
:param messages:
:param model:
:param models:
:param frequency_penalty:
:param logit_bias:
:param logprobs:
:param top_logprobs:
:param max_completion_tokens:
:param max_tokens:
:param metadata:
:param presence_penalty:
:param reasoning:
:param response_format:
:param seed:
:param stop:
:param stream:
:param stream_options:
:param temperature:
:param tool_choice:
:param tools:
:param top_p:
:param user:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
@overload
def send(
self,
*,
messages: Union[List[models.Message], List[models.MessageTypedDict]],
model: Optional[str] = None,
models: Optional[List[str]] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
top_logprobs: OptionalNullable[float] = UNSET,
max_completion_tokens: OptionalNullable[float] = UNSET,
max_tokens: OptionalNullable[float] = UNSET,
metadata: Optional[Dict[str, str]] = None,
presence_penalty: OptionalNullable[float] = UNSET,
reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None,
response_format: Optional[
Union[
models.ChatGenerationParamsResponseFormatUnion,
models.ChatGenerationParamsResponseFormatUnionTypedDict,
]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
models.ChatGenerationParamsStop,
models.ChatGenerationParamsStopTypedDict,
]
] = UNSET,
stream: Literal[True],
stream_options: OptionalNullable[
Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
tool_choice: Optional[Any] = None,
tools: Optional[
Union[
List[models.ToolDefinitionJSON],
List[models.ToolDefinitionJSONTypedDict],
]
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> eventstreaming.EventStream[models.ChatStreamingResponseChunk]:
r"""Create a chat completion
Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes.
:param messages:
:param model:
:param models:
:param frequency_penalty:
:param logit_bias:
:param logprobs:
:param top_logprobs:
:param max_completion_tokens:
:param max_tokens:
:param metadata:
:param presence_penalty:
:param reasoning:
:param response_format:
:param seed:
:param stop:
:param stream:
:param stream_options:
:param temperature:
:param tool_choice:
:param tools:
:param top_p:
:param user:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
def send(
self,
*,
messages: Union[List[models.Message], List[models.MessageTypedDict]],
model: Optional[str] = None,
models: Optional[List[str]] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
top_logprobs: OptionalNullable[float] = UNSET,
max_completion_tokens: OptionalNullable[float] = UNSET,
max_tokens: OptionalNullable[float] = UNSET,
metadata: Optional[Dict[str, str]] = None,
presence_penalty: OptionalNullable[float] = UNSET,
reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None,
response_format: Optional[
Union[
models.ChatGenerationParamsResponseFormatUnion,
models.ChatGenerationParamsResponseFormatUnionTypedDict,
]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
models.ChatGenerationParamsStop,
models.ChatGenerationParamsStopTypedDict,
]
] = UNSET,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
tool_choice: Optional[Any] = None,
tools: Optional[
Union[
List[models.ToolDefinitionJSON],
List[models.ToolDefinitionJSONTypedDict],
]
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.SendChatCompletionRequestResponse:
r"""Create a chat completion
Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes.
:param messages:
:param model:
:param models:
:param frequency_penalty:
:param logit_bias:
:param logprobs:
:param top_logprobs:
:param max_completion_tokens:
:param max_tokens:
:param metadata:
:param presence_penalty:
:param reasoning:
:param response_format:
:param seed:
:param stop:
:param stream:
:param stream_options:
:param temperature:
:param tool_choice:
:param tools:
:param top_p:
:param user:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.ChatGenerationParams(
messages=utils.get_pydantic_model(messages, List[models.Message]),
model=model,
models=models,
frequency_penalty=frequency_penalty,
logit_bias=logit_bias,
logprobs=logprobs,
top_logprobs=top_logprobs,
max_completion_tokens=max_completion_tokens,
max_tokens=max_tokens,
metadata=metadata,
presence_penalty=presence_penalty,
reasoning=utils.get_pydantic_model(reasoning, Optional[models.Reasoning]),
response_format=utils.get_pydantic_model(
response_format,
Optional[models.ChatGenerationParamsResponseFormatUnion],
),
seed=seed,
stop=stop,
stream=stream,
stream_options=utils.get_pydantic_model(
stream_options, OptionalNullable[models.ChatStreamOptions]
),
temperature=temperature,
tool_choice=tool_choice,
tools=utils.get_pydantic_model(
tools, Optional[List[models.ToolDefinitionJSON]]
),
top_p=top_p,
user=user,
)
req = self._build_request(
method="POST",
path="/chat/completions",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="text/event-stream" if stream else "application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", models.ChatGenerationParams
),
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="sendChatCompletionRequest",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
stream=True,
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
http_res_text = utils.stream_to_text(http_res)
return unmarshal_json_response(models.ChatResponse, http_res, http_res_text)
if utils.match_response(http_res, "200", "text/event-stream"):
return eventstreaming.EventStream(
http_res,
lambda raw: utils.unmarshal_json(
raw, models.ChatStreamingResponseChunk
),
sentinel="[DONE]",
client_ref=self,
)
if utils.match_response(http_res, ["400", "401", "429"], "application/json"):
http_res_text = utils.stream_to_text(http_res)
response_data = unmarshal_json_response(
errors.ChatErrorData, http_res, http_res_text
)
raise errors.ChatError(response_data, http_res, http_res_text)
if utils.match_response(http_res, "500", "application/json"):
http_res_text = utils.stream_to_text(http_res)
response_data = unmarshal_json_response(
errors.ChatErrorData, http_res, http_res_text
)
raise errors.ChatError(response_data, http_res, http_res_text)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"Unexpected response received", http_res, http_res_text
)
@overload
async def send_async(
self,
*,
messages: Union[List[models.Message], List[models.MessageTypedDict]],
model: Optional[str] = None,
models: Optional[List[str]] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
top_logprobs: OptionalNullable[float] = UNSET,
max_completion_tokens: OptionalNullable[float] = UNSET,
max_tokens: OptionalNullable[float] = UNSET,
metadata: Optional[Dict[str, str]] = None,
presence_penalty: OptionalNullable[float] = UNSET,
reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None,
response_format: Optional[
Union[
models.ChatGenerationParamsResponseFormatUnion,
models.ChatGenerationParamsResponseFormatUnionTypedDict,
]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
models.ChatGenerationParamsStop,
models.ChatGenerationParamsStopTypedDict,
]
] = UNSET,
stream: Union[Literal[False], None] = None,
stream_options: OptionalNullable[
Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
tool_choice: Optional[Any] = None,
tools: Optional[
Union[
List[models.ToolDefinitionJSON],
List[models.ToolDefinitionJSONTypedDict],
]
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.ChatResponse:
r"""Create a chat completion
Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes.
:param messages:
:param model:
:param models:
:param frequency_penalty:
:param logit_bias:
:param logprobs:
:param top_logprobs:
:param max_completion_tokens:
:param max_tokens:
:param metadata:
:param presence_penalty:
:param reasoning:
:param response_format:
:param seed:
:param stop:
:param stream:
:param stream_options:
:param temperature:
:param tool_choice:
:param tools:
:param top_p:
:param user:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
@overload
async def send_async(
self,
*,
messages: Union[List[models.Message], List[models.MessageTypedDict]],
model: Optional[str] = None,
models: Optional[List[str]] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
top_logprobs: OptionalNullable[float] = UNSET,
max_completion_tokens: OptionalNullable[float] = UNSET,
max_tokens: OptionalNullable[float] = UNSET,
metadata: Optional[Dict[str, str]] = None,
presence_penalty: OptionalNullable[float] = UNSET,
reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None,
response_format: Optional[
Union[
models.ChatGenerationParamsResponseFormatUnion,
models.ChatGenerationParamsResponseFormatUnionTypedDict,
]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
models.ChatGenerationParamsStop,
models.ChatGenerationParamsStopTypedDict,
]
] = UNSET,
stream: Literal[True],
stream_options: OptionalNullable[
Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
tool_choice: Optional[Any] = None,
tools: Optional[
Union[
List[models.ToolDefinitionJSON],
List[models.ToolDefinitionJSONTypedDict],
]
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> eventstreaming.EventStreamAsync[models.ChatStreamingResponseChunk]:
r"""Create a chat completion
Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes.
:param messages:
:param model:
:param models:
:param frequency_penalty:
:param logit_bias:
:param logprobs:
:param top_logprobs:
:param max_completion_tokens:
:param max_tokens:
:param metadata:
:param presence_penalty:
:param reasoning:
:param response_format:
:param seed:
:param stop:
:param stream:
:param stream_options:
:param temperature:
:param tool_choice:
:param tools:
:param top_p:
:param user:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
async def send_async(
self,
*,
messages: Union[List[models.Message], List[models.MessageTypedDict]],
model: Optional[str] = None,
models: Optional[List[str]] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
top_logprobs: OptionalNullable[float] = UNSET,
max_completion_tokens: OptionalNullable[float] = UNSET,
max_tokens: OptionalNullable[float] = UNSET,
metadata: Optional[Dict[str, str]] = None,
presence_penalty: OptionalNullable[float] = UNSET,
reasoning: Optional[Union[models.Reasoning, models.ReasoningTypedDict]] = None,
response_format: Optional[
Union[
models.ChatGenerationParamsResponseFormatUnion,
models.ChatGenerationParamsResponseFormatUnionTypedDict,
]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
models.ChatGenerationParamsStop,
models.ChatGenerationParamsStopTypedDict,
]
] = UNSET,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
Union[models.ChatStreamOptions, models.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
tool_choice: Optional[Any] = None,
tools: Optional[
Union[
List[models.ToolDefinitionJSON],
List[models.ToolDefinitionJSONTypedDict],
]
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.SendChatCompletionRequestResponse:
r"""Create a chat completion
Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes.
:param messages:
:param model:
:param models:
:param frequency_penalty:
:param logit_bias:
:param logprobs:
:param top_logprobs:
:param max_completion_tokens:
:param max_tokens:
:param metadata:
:param presence_penalty:
:param reasoning:
:param response_format:
:param seed:
:param stop:
:param stream:
:param stream_options:
:param temperature:
:param tool_choice:
:param tools:
:param top_p:
:param user:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.ChatGenerationParams(
messages=utils.get_pydantic_model(messages, List[models.Message]),
model=model,
models=models,
frequency_penalty=frequency_penalty,
logit_bias=logit_bias,
logprobs=logprobs,
top_logprobs=top_logprobs,
max_completion_tokens=max_completion_tokens,
max_tokens=max_tokens,
metadata=metadata,
presence_penalty=presence_penalty,
reasoning=utils.get_pydantic_model(reasoning, Optional[models.Reasoning]),
response_format=utils.get_pydantic_model(
response_format,
Optional[models.ChatGenerationParamsResponseFormatUnion],
),
seed=seed,
stop=stop,
stream=stream,
stream_options=utils.get_pydantic_model(
stream_options, OptionalNullable[models.ChatStreamOptions]
),
temperature=temperature,
tool_choice=tool_choice,
tools=utils.get_pydantic_model(
tools, Optional[List[models.ToolDefinitionJSON]]
),
top_p=top_p,
user=user,
)
req = self._build_request_async(
method="POST",
path="/chat/completions",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="text/event-stream" if stream else "application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", models.ChatGenerationParams
),
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="sendChatCompletionRequest",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
stream=True,
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
http_res_text = await utils.stream_to_text_async(http_res)
return unmarshal_json_response(models.ChatResponse, http_res, http_res_text)
if utils.match_response(http_res, "200", "text/event-stream"):
return eventstreaming.EventStreamAsync(
http_res,
lambda raw: utils.unmarshal_json(
raw, models.ChatStreamingResponseChunk
),
sentinel="[DONE]",
client_ref=self,
)
if utils.match_response(http_res, ["400", "401", "429"], "application/json"):
http_res_text = await utils.stream_to_text_async(http_res)
response_data = unmarshal_json_response(
errors.ChatErrorData, http_res, http_res_text
)
raise errors.ChatError(response_data, http_res, http_res_text)
if utils.match_response(http_res, "500", "application/json"):
http_res_text = await utils.stream_to_text_async(http_res)
response_data = unmarshal_json_response(
errors.ChatErrorData, http_res, http_res_text
)
raise errors.ChatError(response_data, http_res, http_res_text)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"Unexpected response received", http_res, http_res_text
)
+359
View File
@@ -0,0 +1,359 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from openrouter import errors, models, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Dict, List, Mapping, Optional, Union
class Completions(BaseSDK):
def generate(
self,
*,
prompt: Union[models.Prompt, models.PromptTypedDict],
model: Optional[str] = None,
models: Optional[List[str]] = None,
best_of: OptionalNullable[int] = UNSET,
echo: OptionalNullable[bool] = UNSET,
frequency_penalty: OptionalNullable[float] = UNSET,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[int] = UNSET,
max_tokens: OptionalNullable[int] = UNSET,
n: OptionalNullable[int] = UNSET,
presence_penalty: OptionalNullable[float] = UNSET,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
models.CompletionCreateParamsStop,
models.CompletionCreateParamsStopTypedDict,
]
] = UNSET,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
Union[models.StreamOptions, models.StreamOptionsTypedDict]
] = UNSET,
suffix: OptionalNullable[str] = UNSET,
temperature: OptionalNullable[float] = UNSET,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
metadata: OptionalNullable[Dict[str, str]] = UNSET,
response_format: OptionalNullable[
Union[
models.CompletionCreateParamsResponseFormatUnion,
models.CompletionCreateParamsResponseFormatUnionTypedDict,
]
] = UNSET,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.CompletionResponse:
r"""Create a completion
Creates a completion for the provided prompt and parameters. Supports both streaming and non-streaming modes.
:param prompt:
:param model:
:param models:
:param best_of:
:param echo:
:param frequency_penalty:
:param logit_bias:
:param logprobs:
:param max_tokens:
:param n:
:param presence_penalty:
:param seed:
:param stop:
:param stream:
:param stream_options:
:param suffix:
:param temperature:
:param top_p:
:param user:
:param metadata:
:param response_format:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.CompletionCreateParams(
model=model,
models=models,
prompt=prompt,
best_of=best_of,
echo=echo,
frequency_penalty=frequency_penalty,
logit_bias=logit_bias,
logprobs=logprobs,
max_tokens=max_tokens,
n=n,
presence_penalty=presence_penalty,
seed=seed,
stop=stop,
stream=stream,
stream_options=utils.get_pydantic_model(
stream_options, OptionalNullable[models.StreamOptions]
),
suffix=suffix,
temperature=temperature,
top_p=top_p,
user=user,
metadata=metadata,
response_format=utils.get_pydantic_model(
response_format,
OptionalNullable[models.CompletionCreateParamsResponseFormatUnion],
),
)
req = self._build_request(
method="POST",
path="/completions",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", models.CompletionCreateParams
),
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="createCompletions",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.CompletionResponse, http_res)
if utils.match_response(http_res, ["400", "401", "429"], "application/json"):
response_data = unmarshal_json_response(errors.ChatErrorData, http_res)
raise errors.ChatError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(errors.ChatErrorData, http_res)
raise errors.ChatError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def generate_async(
self,
*,
prompt: Union[models.Prompt, models.PromptTypedDict],
model: Optional[str] = None,
models: Optional[List[str]] = None,
best_of: OptionalNullable[int] = UNSET,
echo: OptionalNullable[bool] = UNSET,
frequency_penalty: OptionalNullable[float] = UNSET,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[int] = UNSET,
max_tokens: OptionalNullable[int] = UNSET,
n: OptionalNullable[int] = UNSET,
presence_penalty: OptionalNullable[float] = UNSET,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
models.CompletionCreateParamsStop,
models.CompletionCreateParamsStopTypedDict,
]
] = UNSET,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
Union[models.StreamOptions, models.StreamOptionsTypedDict]
] = UNSET,
suffix: OptionalNullable[str] = UNSET,
temperature: OptionalNullable[float] = UNSET,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
metadata: OptionalNullable[Dict[str, str]] = UNSET,
response_format: OptionalNullable[
Union[
models.CompletionCreateParamsResponseFormatUnion,
models.CompletionCreateParamsResponseFormatUnionTypedDict,
]
] = UNSET,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.CompletionResponse:
r"""Create a completion
Creates a completion for the provided prompt and parameters. Supports both streaming and non-streaming modes.
:param prompt:
:param model:
:param models:
:param best_of:
:param echo:
:param frequency_penalty:
:param logit_bias:
:param logprobs:
:param max_tokens:
:param n:
:param presence_penalty:
:param seed:
:param stop:
:param stream:
:param stream_options:
:param suffix:
:param temperature:
:param top_p:
:param user:
:param metadata:
:param response_format:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.CompletionCreateParams(
model=model,
models=models,
prompt=prompt,
best_of=best_of,
echo=echo,
frequency_penalty=frequency_penalty,
logit_bias=logit_bias,
logprobs=logprobs,
max_tokens=max_tokens,
n=n,
presence_penalty=presence_penalty,
seed=seed,
stop=stop,
stream=stream,
stream_options=utils.get_pydantic_model(
stream_options, OptionalNullable[models.StreamOptions]
),
suffix=suffix,
temperature=temperature,
top_p=top_p,
user=user,
metadata=metadata,
response_format=utils.get_pydantic_model(
response_format,
OptionalNullable[models.CompletionCreateParamsResponseFormatUnion],
),
)
req = self._build_request_async(
method="POST",
path="/completions",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", models.CompletionCreateParams
),
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="createCompletions",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.CompletionResponse, http_res)
if utils.match_response(http_res, ["400", "401", "429"], "application/json"):
response_data = unmarshal_json_response(errors.ChatErrorData, http_res)
raise errors.ChatError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(errors.ChatErrorData, http_res)
raise errors.ChatError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
+453
View File
@@ -0,0 +1,453 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from openrouter import errors, models, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Mapping, Optional, Union
class Credits(BaseSDK):
r"""Credit management endpoints"""
def get_credits(
self,
*,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.GetCreditsResponse:
r"""Get remaining credits
Get total credits purchased and used for the authenticated user
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
req = self._build_request(
method="GET",
path="/credits",
base_url=base_url,
url_variables=url_variables,
request=None,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getCredits",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["401", "403", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.GetCreditsResponse, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def get_credits_async(
self,
*,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.GetCreditsResponse:
r"""Get remaining credits
Get total credits purchased and used for the authenticated user
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
req = self._build_request_async(
method="GET",
path="/credits",
base_url=base_url,
url_variables=url_variables,
request=None,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getCredits",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["401", "403", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.GetCreditsResponse, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
def create_coinbase_charge(
self,
*,
security: Union[
models.CreateCoinbaseChargeSecurity,
models.CreateCoinbaseChargeSecurityTypedDict,
],
amount: float,
sender: str,
chain_id: models.ChainID,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.CreateCoinbaseChargeResponse:
r"""Create a Coinbase charge for crypto payment
Create a Coinbase charge for crypto payment
:param security:
:param amount:
:param sender:
:param chain_id:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.CreateChargeRequest(
amount=amount,
sender=sender,
chain_id=chain_id,
)
req = self._build_request(
method="POST",
path="/credits/coinbase",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=utils.get_pydantic_model(
security, models.CreateCoinbaseChargeSecurity
),
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", models.CreateChargeRequest
),
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="createCoinbaseCharge",
oauth2_scopes=None,
security_source=get_security_from_env(security, models.Security),
),
request=req,
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
models.CreateCoinbaseChargeResponse, http_res
)
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "429", "application/json"):
response_data = unmarshal_json_response(
errors.TooManyRequestsResponseErrorData, http_res
)
raise errors.TooManyRequestsResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def create_coinbase_charge_async(
self,
*,
security: Union[
models.CreateCoinbaseChargeSecurity,
models.CreateCoinbaseChargeSecurityTypedDict,
],
amount: float,
sender: str,
chain_id: models.ChainID,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.CreateCoinbaseChargeResponse:
r"""Create a Coinbase charge for crypto payment
Create a Coinbase charge for crypto payment
:param security:
:param amount:
:param sender:
:param chain_id:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.CreateChargeRequest(
amount=amount,
sender=sender,
chain_id=chain_id,
)
req = self._build_request_async(
method="POST",
path="/credits/coinbase",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=utils.get_pydantic_model(
security, models.CreateCoinbaseChargeSecurity
),
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", models.CreateChargeRequest
),
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="createCoinbaseCharge",
oauth2_scopes=None,
security_source=get_security_from_env(security, models.Security),
),
request=req,
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
models.CreateCoinbaseChargeResponse, http_res
)
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "429", "application/json"):
response_data = unmarshal_json_response(
errors.TooManyRequestsResponseErrorData, http_res
)
raise errors.TooManyRequestsResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
+567
View File
@@ -0,0 +1,567 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from enum import Enum
from openrouter import errors, models, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Mapping, Optional, Union
class GenerateAcceptEnum(str, Enum):
APPLICATION_JSON = "application/json"
TEXT_EVENT_STREAM = "text/event-stream"
class Embeddings(BaseSDK):
r"""Text embedding endpoints"""
def generate(
self,
*,
input: Union[models.Input, models.InputTypedDict],
model: str,
provider: Optional[
Union[
models.CreateEmbeddingsProvider,
models.CreateEmbeddingsProviderTypedDict,
]
] = None,
encoding_format: Optional[
Union[models.EncodingFormat, models.EncodingFormatTypedDict]
] = None,
user: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
accept_header_override: Optional[GenerateAcceptEnum] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.CreateEmbeddingsResponse:
r"""Submit an embedding request
Submits an embedding request to the embeddings router
:param input:
:param model:
:param provider:
:param encoding_format:
:param user:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.CreateEmbeddingsRequest(
input=input,
model=model,
provider=utils.get_pydantic_model(
provider, Optional[models.CreateEmbeddingsProvider]
),
encoding_format=encoding_format,
user=user,
)
req = self._build_request(
method="POST",
path="/embeddings",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value=accept_header_override.value
if accept_header_override is not None
else "application/json;q=1, text/event-stream;q=0",
http_headers=http_headers,
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", models.CreateEmbeddingsRequest
),
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="createEmbeddings",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=[
"400",
"401",
"402",
"404",
"429",
"4XX",
"500",
"502",
"503",
"524",
"529",
"5XX",
],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
models.CreateEmbeddingsResponseBody, http_res
)
if utils.match_response(http_res, "200", "text/event-stream"):
return http_res.text
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "402", "application/json"):
response_data = unmarshal_json_response(
errors.PaymentRequiredResponseErrorData, http_res
)
raise errors.PaymentRequiredResponseError(response_data, http_res)
if utils.match_response(http_res, "404", "application/json"):
response_data = unmarshal_json_response(
errors.NotFoundResponseErrorData, http_res
)
raise errors.NotFoundResponseError(response_data, http_res)
if utils.match_response(http_res, "429", "application/json"):
response_data = unmarshal_json_response(
errors.TooManyRequestsResponseErrorData, http_res
)
raise errors.TooManyRequestsResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "502", "application/json"):
response_data = unmarshal_json_response(
errors.BadGatewayResponseErrorData, http_res
)
raise errors.BadGatewayResponseError(response_data, http_res)
if utils.match_response(http_res, "503", "application/json"):
response_data = unmarshal_json_response(
errors.ServiceUnavailableResponseErrorData, http_res
)
raise errors.ServiceUnavailableResponseError(response_data, http_res)
if utils.match_response(http_res, "524", "application/json"):
response_data = unmarshal_json_response(
errors.EdgeNetworkTimeoutResponseErrorData, http_res
)
raise errors.EdgeNetworkTimeoutResponseError(response_data, http_res)
if utils.match_response(http_res, "529", "application/json"):
response_data = unmarshal_json_response(
errors.ProviderOverloadedResponseErrorData, http_res
)
raise errors.ProviderOverloadedResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def generate_async(
self,
*,
input: Union[models.Input, models.InputTypedDict],
model: str,
provider: Optional[
Union[
models.CreateEmbeddingsProvider,
models.CreateEmbeddingsProviderTypedDict,
]
] = None,
encoding_format: Optional[
Union[models.EncodingFormat, models.EncodingFormatTypedDict]
] = None,
user: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
accept_header_override: Optional[GenerateAcceptEnum] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.CreateEmbeddingsResponse:
r"""Submit an embedding request
Submits an embedding request to the embeddings router
:param input:
:param model:
:param provider:
:param encoding_format:
:param user:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.CreateEmbeddingsRequest(
input=input,
model=model,
provider=utils.get_pydantic_model(
provider, Optional[models.CreateEmbeddingsProvider]
),
encoding_format=encoding_format,
user=user,
)
req = self._build_request_async(
method="POST",
path="/embeddings",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value=accept_header_override.value
if accept_header_override is not None
else "application/json;q=1, text/event-stream;q=0",
http_headers=http_headers,
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", models.CreateEmbeddingsRequest
),
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="createEmbeddings",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=[
"400",
"401",
"402",
"404",
"429",
"4XX",
"500",
"502",
"503",
"524",
"529",
"5XX",
],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
models.CreateEmbeddingsResponseBody, http_res
)
if utils.match_response(http_res, "200", "text/event-stream"):
return http_res.text
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "402", "application/json"):
response_data = unmarshal_json_response(
errors.PaymentRequiredResponseErrorData, http_res
)
raise errors.PaymentRequiredResponseError(response_data, http_res)
if utils.match_response(http_res, "404", "application/json"):
response_data = unmarshal_json_response(
errors.NotFoundResponseErrorData, http_res
)
raise errors.NotFoundResponseError(response_data, http_res)
if utils.match_response(http_res, "429", "application/json"):
response_data = unmarshal_json_response(
errors.TooManyRequestsResponseErrorData, http_res
)
raise errors.TooManyRequestsResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "502", "application/json"):
response_data = unmarshal_json_response(
errors.BadGatewayResponseErrorData, http_res
)
raise errors.BadGatewayResponseError(response_data, http_res)
if utils.match_response(http_res, "503", "application/json"):
response_data = unmarshal_json_response(
errors.ServiceUnavailableResponseErrorData, http_res
)
raise errors.ServiceUnavailableResponseError(response_data, http_res)
if utils.match_response(http_res, "524", "application/json"):
response_data = unmarshal_json_response(
errors.EdgeNetworkTimeoutResponseErrorData, http_res
)
raise errors.EdgeNetworkTimeoutResponseError(response_data, http_res)
if utils.match_response(http_res, "529", "application/json"):
response_data = unmarshal_json_response(
errors.ProviderOverloadedResponseErrorData, http_res
)
raise errors.ProviderOverloadedResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
def list_models(
self,
*,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.ModelsListResponse:
r"""List all embeddings models
Returns a list of all available embeddings models and their properties
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
req = self._build_request(
method="GET",
path="/embeddings/models",
base_url=base_url,
url_variables=url_variables,
request=None,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listEmbeddingsModels",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["400", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.ModelsListResponse, http_res)
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def list_models_async(
self,
*,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.ModelsListResponse:
r"""List all embeddings models
Returns a list of all available embeddings models and their properties
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
req = self._build_request_async(
method="GET",
path="/embeddings/models",
base_url=base_url,
url_variables=url_variables,
request=None,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listEmbeddingsModels",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["400", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.ModelsListResponse, http_res)
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
+383
View File
@@ -0,0 +1,383 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from openrouter import errors, models, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Mapping, Optional
class Endpoints(BaseSDK):
r"""Endpoint information"""
def list(
self,
*,
author: str,
slug: str,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.EndpointsListEndpointsResponse:
r"""List all endpoints for a model
:param author:
:param slug:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.ListEndpointsRequest(
author=author,
slug=slug,
)
req = self._build_request(
method="GET",
path="/models/{author}/{slug}/endpoints",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=False,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listEndpoints",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["404", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
models.EndpointsListEndpointsResponse, http_res
)
if utils.match_response(http_res, "404", "application/json"):
response_data = unmarshal_json_response(
errors.NotFoundResponseErrorData, http_res
)
raise errors.NotFoundResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def list_async(
self,
*,
author: str,
slug: str,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.EndpointsListEndpointsResponse:
r"""List all endpoints for a model
:param author:
:param slug:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.ListEndpointsRequest(
author=author,
slug=slug,
)
req = self._build_request_async(
method="GET",
path="/models/{author}/{slug}/endpoints",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=False,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listEndpoints",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["404", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
models.EndpointsListEndpointsResponse, http_res
)
if utils.match_response(http_res, "404", "application/json"):
response_data = unmarshal_json_response(
errors.NotFoundResponseErrorData, http_res
)
raise errors.NotFoundResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
def list_zdr_endpoints(
self,
*,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.ListEndpointsZdrResponse:
r"""Preview the impact of ZDR on the available endpoints
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
req = self._build_request(
method="GET",
path="/endpoints/zdr",
base_url=base_url,
url_variables=url_variables,
request=None,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listEndpointsZdr",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.ListEndpointsZdrResponse, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def list_zdr_endpoints_async(
self,
*,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.ListEndpointsZdrResponse:
r"""Preview the impact of ZDR on the available endpoints
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
req = self._build_request_async(
method="GET",
path="/endpoints/zdr",
base_url=base_url,
url_variables=url_variables,
request=None,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listEndpointsZdr",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=["4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.ListEndpointsZdrResponse, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
+177
View File
@@ -0,0 +1,177 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .openroutererror import OpenRouterError
from typing import TYPE_CHECKING
from importlib import import_module
import builtins
import sys
if TYPE_CHECKING:
from .badgatewayresponse_error import (
BadGatewayResponseError,
BadGatewayResponseErrorData,
)
from .badrequestresponse_error import (
BadRequestResponseError,
BadRequestResponseErrorData,
)
from .chaterror import ChatError, ChatErrorData
from .edgenetworktimeoutresponse_error import (
EdgeNetworkTimeoutResponseError,
EdgeNetworkTimeoutResponseErrorData,
)
from .forbiddenresponse_error import (
ForbiddenResponseError,
ForbiddenResponseErrorData,
)
from .internalserverresponse_error import (
InternalServerResponseError,
InternalServerResponseErrorData,
)
from .no_response_error import NoResponseError
from .notfoundresponse_error import NotFoundResponseError, NotFoundResponseErrorData
from .openrouterdefaulterror import OpenRouterDefaultError
from .payloadtoolargeresponse_error import (
PayloadTooLargeResponseError,
PayloadTooLargeResponseErrorData,
)
from .paymentrequiredresponse_error import (
PaymentRequiredResponseError,
PaymentRequiredResponseErrorData,
)
from .provideroverloadedresponse_error import (
ProviderOverloadedResponseError,
ProviderOverloadedResponseErrorData,
)
from .requesttimeoutresponse_error import (
RequestTimeoutResponseError,
RequestTimeoutResponseErrorData,
)
from .responsevalidationerror import ResponseValidationError
from .serviceunavailableresponse_error import (
ServiceUnavailableResponseError,
ServiceUnavailableResponseErrorData,
)
from .toomanyrequestsresponse_error import (
TooManyRequestsResponseError,
TooManyRequestsResponseErrorData,
)
from .unauthorizedresponse_error import (
UnauthorizedResponseError,
UnauthorizedResponseErrorData,
)
from .unprocessableentityresponse_error import (
UnprocessableEntityResponseError,
UnprocessableEntityResponseErrorData,
)
__all__ = [
"BadGatewayResponseError",
"BadGatewayResponseErrorData",
"BadRequestResponseError",
"BadRequestResponseErrorData",
"ChatError",
"ChatErrorData",
"EdgeNetworkTimeoutResponseError",
"EdgeNetworkTimeoutResponseErrorData",
"ForbiddenResponseError",
"ForbiddenResponseErrorData",
"InternalServerResponseError",
"InternalServerResponseErrorData",
"NoResponseError",
"NotFoundResponseError",
"NotFoundResponseErrorData",
"OpenRouterDefaultError",
"OpenRouterError",
"PayloadTooLargeResponseError",
"PayloadTooLargeResponseErrorData",
"PaymentRequiredResponseError",
"PaymentRequiredResponseErrorData",
"ProviderOverloadedResponseError",
"ProviderOverloadedResponseErrorData",
"RequestTimeoutResponseError",
"RequestTimeoutResponseErrorData",
"ResponseValidationError",
"ServiceUnavailableResponseError",
"ServiceUnavailableResponseErrorData",
"TooManyRequestsResponseError",
"TooManyRequestsResponseErrorData",
"UnauthorizedResponseError",
"UnauthorizedResponseErrorData",
"UnprocessableEntityResponseError",
"UnprocessableEntityResponseErrorData",
]
_dynamic_imports: dict[str, str] = {
"BadGatewayResponseError": ".badgatewayresponse_error",
"BadGatewayResponseErrorData": ".badgatewayresponse_error",
"BadRequestResponseError": ".badrequestresponse_error",
"BadRequestResponseErrorData": ".badrequestresponse_error",
"ChatError": ".chaterror",
"ChatErrorData": ".chaterror",
"EdgeNetworkTimeoutResponseError": ".edgenetworktimeoutresponse_error",
"EdgeNetworkTimeoutResponseErrorData": ".edgenetworktimeoutresponse_error",
"ForbiddenResponseError": ".forbiddenresponse_error",
"ForbiddenResponseErrorData": ".forbiddenresponse_error",
"InternalServerResponseError": ".internalserverresponse_error",
"InternalServerResponseErrorData": ".internalserverresponse_error",
"NoResponseError": ".no_response_error",
"NotFoundResponseError": ".notfoundresponse_error",
"NotFoundResponseErrorData": ".notfoundresponse_error",
"OpenRouterDefaultError": ".openrouterdefaulterror",
"PayloadTooLargeResponseError": ".payloadtoolargeresponse_error",
"PayloadTooLargeResponseErrorData": ".payloadtoolargeresponse_error",
"PaymentRequiredResponseError": ".paymentrequiredresponse_error",
"PaymentRequiredResponseErrorData": ".paymentrequiredresponse_error",
"ProviderOverloadedResponseError": ".provideroverloadedresponse_error",
"ProviderOverloadedResponseErrorData": ".provideroverloadedresponse_error",
"RequestTimeoutResponseError": ".requesttimeoutresponse_error",
"RequestTimeoutResponseErrorData": ".requesttimeoutresponse_error",
"ResponseValidationError": ".responsevalidationerror",
"ServiceUnavailableResponseError": ".serviceunavailableresponse_error",
"ServiceUnavailableResponseErrorData": ".serviceunavailableresponse_error",
"TooManyRequestsResponseError": ".toomanyrequestsresponse_error",
"TooManyRequestsResponseErrorData": ".toomanyrequestsresponse_error",
"UnauthorizedResponseError": ".unauthorizedresponse_error",
"UnauthorizedResponseErrorData": ".unauthorizedresponse_error",
"UnprocessableEntityResponseError": ".unprocessableentityresponse_error",
"UnprocessableEntityResponseErrorData": ".unprocessableentityresponse_error",
}
def dynamic_import(modname, retries=3):
for attempt in range(retries):
try:
return import_module(modname, __package__)
except KeyError:
# Clear any half-initialized module and retry
sys.modules.pop(modname, None)
if attempt == retries - 1:
break
raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")
def __getattr__(attr_name: str) -> object:
module_name = _dynamic_imports.get(attr_name)
if module_name is None:
raise AttributeError(
f"No {attr_name} found in _dynamic_imports for module name -> {__name__} "
)
try:
module = dynamic_import(module_name)
result = getattr(module, attr_name)
return result
except ImportError as e:
raise ImportError(
f"Failed to import {attr_name} from {module_name}: {e}"
) from e
except AttributeError as e:
raise AttributeError(
f"Failed to get {attr_name} from {module_name}: {e}"
) from e
def __dir__():
lazy_attrs = builtins.list(_dynamic_imports.keys())
return builtins.sorted(lazy_attrs)
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
badgatewayresponseerrordata as models_badgatewayresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class BadGatewayResponseErrorData(BaseModel):
error: models_badgatewayresponseerrordata.BadGatewayResponseErrorData
r"""Error data for BadGatewayResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class BadGatewayResponseError(OpenRouterError):
r"""Bad Gateway - Provider/upstream API failure"""
data: BadGatewayResponseErrorData = field(hash=False)
def __init__(
self,
data: BadGatewayResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
badrequestresponseerrordata as models_badrequestresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class BadRequestResponseErrorData(BaseModel):
error: models_badrequestresponseerrordata.BadRequestResponseErrorData
r"""Error data for BadRequestResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class BadRequestResponseError(OpenRouterError):
r"""Bad Request - Invalid request parameters or malformed input"""
data: BadRequestResponseErrorData = field(hash=False)
def __init__(
self,
data: BadRequestResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
+29
View File
@@ -0,0 +1,29 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import chaterror as models_chaterror
from openrouter.types import BaseModel
from typing import Optional
class ChatErrorData(BaseModel):
error: models_chaterror.ChatErrorError
@dataclass(unsafe_hash=True)
class ChatError(OpenRouterError):
data: ChatErrorData = field(hash=False)
def __init__(
self,
data: ChatErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,38 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
edgenetworktimeoutresponseerrordata as models_edgenetworktimeoutresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class EdgeNetworkTimeoutResponseErrorData(BaseModel):
error: (
models_edgenetworktimeoutresponseerrordata.EdgeNetworkTimeoutResponseErrorData
)
r"""Error data for EdgeNetworkTimeoutResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class EdgeNetworkTimeoutResponseError(OpenRouterError):
r"""Infrastructure Timeout - Provider request timed out at edge network"""
data: EdgeNetworkTimeoutResponseErrorData = field(hash=False)
def __init__(
self,
data: EdgeNetworkTimeoutResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
forbiddenresponseerrordata as models_forbiddenresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class ForbiddenResponseErrorData(BaseModel):
error: models_forbiddenresponseerrordata.ForbiddenResponseErrorData
r"""Error data for ForbiddenResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class ForbiddenResponseError(OpenRouterError):
r"""Forbidden - Authentication successful but insufficient permissions"""
data: ForbiddenResponseErrorData = field(hash=False)
def __init__(
self,
data: ForbiddenResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
internalserverresponseerrordata as models_internalserverresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class InternalServerResponseErrorData(BaseModel):
error: models_internalserverresponseerrordata.InternalServerResponseErrorData
r"""Error data for InternalServerResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class InternalServerResponseError(OpenRouterError):
r"""Internal Server Error - Unexpected server error"""
data: InternalServerResponseErrorData = field(hash=False)
def __init__(
self,
data: InternalServerResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,17 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from dataclasses import dataclass
@dataclass(unsafe_hash=True)
class NoResponseError(Exception):
"""Error raised when no HTTP response is received from the server."""
message: str
def __init__(self, message: str = "No response received"):
object.__setattr__(self, "message", message)
super().__init__(message)
def __str__(self):
return self.message
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
notfoundresponseerrordata as models_notfoundresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class NotFoundResponseErrorData(BaseModel):
error: models_notfoundresponseerrordata.NotFoundResponseErrorData
r"""Error data for NotFoundResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class NotFoundResponseError(OpenRouterError):
r"""Not Found - Resource does not exist"""
data: NotFoundResponseErrorData = field(hash=False)
def __init__(
self,
data: NotFoundResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,40 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import httpx
from typing import Optional
from dataclasses import dataclass
from openrouter.errors import OpenRouterError
MAX_MESSAGE_LEN = 10_000
@dataclass(unsafe_hash=True)
class OpenRouterDefaultError(OpenRouterError):
"""The fallback error class if no more specific error class is matched."""
def __init__(
self, message: str, raw_response: httpx.Response, body: Optional[str] = None
):
body_display = body or raw_response.text or '""'
if message:
message += ": "
message += f"Status {raw_response.status_code}"
headers = raw_response.headers
content_type = headers.get("content-type", '""')
if content_type != "application/json":
if " " in content_type:
content_type = f'"{content_type}"'
message += f" Content-Type {content_type}"
if len(body_display) > MAX_MESSAGE_LEN:
truncated = body_display[:MAX_MESSAGE_LEN]
remaining = len(body_display) - MAX_MESSAGE_LEN
body_display = f"{truncated}...and {remaining} more chars"
message += f". Body: {body_display}"
message = message.strip()
super().__init__(message, raw_response, body)
+30
View File
@@ -0,0 +1,30 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import httpx
from typing import Optional
from dataclasses import dataclass, field
@dataclass(unsafe_hash=True)
class OpenRouterError(Exception):
"""The base class for all HTTP error responses."""
message: str
status_code: int
body: str
headers: httpx.Headers = field(hash=False)
raw_response: httpx.Response = field(hash=False)
def __init__(
self, message: str, raw_response: httpx.Response, body: Optional[str] = None
):
object.__setattr__(self, "message", message)
object.__setattr__(self, "status_code", raw_response.status_code)
object.__setattr__(
self, "body", body if body is not None else raw_response.text
)
object.__setattr__(self, "headers", raw_response.headers)
object.__setattr__(self, "raw_response", raw_response)
def __str__(self):
return self.message
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
payloadtoolargeresponseerrordata as models_payloadtoolargeresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class PayloadTooLargeResponseErrorData(BaseModel):
error: models_payloadtoolargeresponseerrordata.PayloadTooLargeResponseErrorData
r"""Error data for PayloadTooLargeResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class PayloadTooLargeResponseError(OpenRouterError):
r"""Payload Too Large - Request payload exceeds size limits"""
data: PayloadTooLargeResponseErrorData = field(hash=False)
def __init__(
self,
data: PayloadTooLargeResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
paymentrequiredresponseerrordata as models_paymentrequiredresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class PaymentRequiredResponseErrorData(BaseModel):
error: models_paymentrequiredresponseerrordata.PaymentRequiredResponseErrorData
r"""Error data for PaymentRequiredResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class PaymentRequiredResponseError(OpenRouterError):
r"""Payment Required - Insufficient credits or quota to complete request"""
data: PaymentRequiredResponseErrorData = field(hash=False)
def __init__(
self,
data: PaymentRequiredResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,38 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
provideroverloadedresponseerrordata as models_provideroverloadedresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class ProviderOverloadedResponseErrorData(BaseModel):
error: (
models_provideroverloadedresponseerrordata.ProviderOverloadedResponseErrorData
)
r"""Error data for ProviderOverloadedResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class ProviderOverloadedResponseError(OpenRouterError):
r"""Provider Overloaded - Provider is temporarily overloaded"""
data: ProviderOverloadedResponseErrorData = field(hash=False)
def __init__(
self,
data: ProviderOverloadedResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
requesttimeoutresponseerrordata as models_requesttimeoutresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class RequestTimeoutResponseErrorData(BaseModel):
error: models_requesttimeoutresponseerrordata.RequestTimeoutResponseErrorData
r"""Error data for RequestTimeoutResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class RequestTimeoutResponseError(OpenRouterError):
r"""Request Timeout - Operation exceeded time limit"""
data: RequestTimeoutResponseErrorData = field(hash=False)
def __init__(
self,
data: RequestTimeoutResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,27 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
import httpx
from typing import Optional
from dataclasses import dataclass
from openrouter.errors import OpenRouterError
@dataclass(unsafe_hash=True)
class ResponseValidationError(OpenRouterError):
"""Error raised when there is a type mismatch between the response data and the expected Pydantic model."""
def __init__(
self,
message: str,
raw_response: httpx.Response,
cause: Exception,
body: Optional[str] = None,
):
message = f"{message}: {cause}"
super().__init__(message, raw_response, body)
@property
def cause(self):
"""Normally the Pydantic ValidationError"""
return self.__cause__
@@ -0,0 +1,38 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
serviceunavailableresponseerrordata as models_serviceunavailableresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class ServiceUnavailableResponseErrorData(BaseModel):
error: (
models_serviceunavailableresponseerrordata.ServiceUnavailableResponseErrorData
)
r"""Error data for ServiceUnavailableResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class ServiceUnavailableResponseError(OpenRouterError):
r"""Service Unavailable - Service temporarily unavailable"""
data: ServiceUnavailableResponseErrorData = field(hash=False)
def __init__(
self,
data: ServiceUnavailableResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
toomanyrequestsresponseerrordata as models_toomanyrequestsresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class TooManyRequestsResponseErrorData(BaseModel):
error: models_toomanyrequestsresponseerrordata.TooManyRequestsResponseErrorData
r"""Error data for TooManyRequestsResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class TooManyRequestsResponseError(OpenRouterError):
r"""Too Many Requests - Rate limit exceeded"""
data: TooManyRequestsResponseErrorData = field(hash=False)
def __init__(
self,
data: TooManyRequestsResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
unauthorizedresponseerrordata as models_unauthorizedresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class UnauthorizedResponseErrorData(BaseModel):
error: models_unauthorizedresponseerrordata.UnauthorizedResponseErrorData
r"""Error data for UnauthorizedResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class UnauthorizedResponseError(OpenRouterError):
r"""Unauthorized - Authentication required or invalid credentials"""
data: UnauthorizedResponseErrorData = field(hash=False)
def __init__(
self,
data: UnauthorizedResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
@@ -0,0 +1,38 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from dataclasses import dataclass, field
import httpx
from openrouter.errors import OpenRouterError
from openrouter.models import (
unprocessableentityresponseerrordata as models_unprocessableentityresponseerrordata,
)
from openrouter.types import BaseModel, OptionalNullable, UNSET
from typing import Optional
class UnprocessableEntityResponseErrorData(BaseModel):
error: (
models_unprocessableentityresponseerrordata.UnprocessableEntityResponseErrorData
)
r"""Error data for UnprocessableEntityResponse"""
user_id: OptionalNullable[str] = UNSET
@dataclass(unsafe_hash=True)
class UnprocessableEntityResponseError(OpenRouterError):
r"""Unprocessable Entity - Semantic validation failure"""
data: UnprocessableEntityResponseErrorData = field(hash=False)
def __init__(
self,
data: UnprocessableEntityResponseErrorData,
raw_response: httpx.Response,
body: Optional[str] = None,
):
fallback = body or raw_response.text
message = str(data.error.message) or fallback
super().__init__(message, raw_response, body)
object.__setattr__(self, "data", data)
+287
View File
@@ -0,0 +1,287 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from openrouter import errors, models, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Mapping, Optional
class Generations(BaseSDK):
r"""Generation history endpoints"""
def get_generation(
self,
*,
id: str,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.GetGenerationResponse:
r"""Get request & usage metadata for a generation
:param id:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.GetGenerationRequest(
id=id,
)
req = self._build_request(
method="GET",
path="/generation",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getGeneration",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=[
"401",
"402",
"404",
"429",
"4XX",
"500",
"502",
"524",
"529",
"5XX",
],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.GetGenerationResponse, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "402", "application/json"):
response_data = unmarshal_json_response(
errors.PaymentRequiredResponseErrorData, http_res
)
raise errors.PaymentRequiredResponseError(response_data, http_res)
if utils.match_response(http_res, "404", "application/json"):
response_data = unmarshal_json_response(
errors.NotFoundResponseErrorData, http_res
)
raise errors.NotFoundResponseError(response_data, http_res)
if utils.match_response(http_res, "429", "application/json"):
response_data = unmarshal_json_response(
errors.TooManyRequestsResponseErrorData, http_res
)
raise errors.TooManyRequestsResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "502", "application/json"):
response_data = unmarshal_json_response(
errors.BadGatewayResponseErrorData, http_res
)
raise errors.BadGatewayResponseError(response_data, http_res)
if utils.match_response(http_res, "524", "application/json"):
response_data = unmarshal_json_response(
errors.EdgeNetworkTimeoutResponseErrorData, http_res
)
raise errors.EdgeNetworkTimeoutResponseError(response_data, http_res)
if utils.match_response(http_res, "529", "application/json"):
response_data = unmarshal_json_response(
errors.ProviderOverloadedResponseErrorData, http_res
)
raise errors.ProviderOverloadedResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def get_generation_async(
self,
*,
id: str,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.GetGenerationResponse:
r"""Get request & usage metadata for a generation
:param id:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = models.GetGenerationRequest(
id=id,
)
req = self._build_request_async(
method="GET",
path="/generation",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["429", "500", "502", "503", "504"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getGeneration",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, models.Security
),
),
request=req,
error_status_codes=[
"401",
"402",
"404",
"429",
"4XX",
"500",
"502",
"524",
"529",
"5XX",
],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(models.GetGenerationResponse, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "402", "application/json"):
response_data = unmarshal_json_response(
errors.PaymentRequiredResponseErrorData, http_res
)
raise errors.PaymentRequiredResponseError(response_data, http_res)
if utils.match_response(http_res, "404", "application/json"):
response_data = unmarshal_json_response(
errors.NotFoundResponseErrorData, http_res
)
raise errors.NotFoundResponseError(response_data, http_res)
if utils.match_response(http_res, "429", "application/json"):
response_data = unmarshal_json_response(
errors.TooManyRequestsResponseErrorData, http_res
)
raise errors.TooManyRequestsResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "502", "application/json"):
response_data = unmarshal_json_response(
errors.BadGatewayResponseErrorData, http_res
)
raise errors.BadGatewayResponseError(response_data, http_res)
if utils.match_response(http_res, "524", "application/json"):
response_data = unmarshal_json_response(
errors.EdgeNetworkTimeoutResponseErrorData, http_res
)
raise errors.EdgeNetworkTimeoutResponseError(response_data, http_res)
if utils.match_response(http_res, "529", "application/json"):
response_data = unmarshal_json_response(
errors.ProviderOverloadedResponseErrorData, http_res
)
raise errors.ProviderOverloadedResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
+125
View File
@@ -0,0 +1,125 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
# pyright: reportReturnType = false
import asyncio
from typing_extensions import Protocol, runtime_checkable
import httpx
from typing import Any, Optional, Union
@runtime_checkable
class HttpClient(Protocol):
def send(
self,
request: httpx.Request,
*,
stream: bool = False,
auth: Union[
httpx._types.AuthTypes, httpx._client.UseClientDefault, None
] = httpx.USE_CLIENT_DEFAULT,
follow_redirects: Union[
bool, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
) -> httpx.Response:
pass
def build_request(
self,
method: str,
url: httpx._types.URLTypes,
*,
content: Optional[httpx._types.RequestContent] = None,
data: Optional[httpx._types.RequestData] = None,
files: Optional[httpx._types.RequestFiles] = None,
json: Optional[Any] = None,
params: Optional[httpx._types.QueryParamTypes] = None,
headers: Optional[httpx._types.HeaderTypes] = None,
cookies: Optional[httpx._types.CookieTypes] = None,
timeout: Union[
httpx._types.TimeoutTypes, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
extensions: Optional[httpx._types.RequestExtensions] = None,
) -> httpx.Request:
pass
def close(self) -> None:
pass
@runtime_checkable
class AsyncHttpClient(Protocol):
async def send(
self,
request: httpx.Request,
*,
stream: bool = False,
auth: Union[
httpx._types.AuthTypes, httpx._client.UseClientDefault, None
] = httpx.USE_CLIENT_DEFAULT,
follow_redirects: Union[
bool, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
) -> httpx.Response:
pass
def build_request(
self,
method: str,
url: httpx._types.URLTypes,
*,
content: Optional[httpx._types.RequestContent] = None,
data: Optional[httpx._types.RequestData] = None,
files: Optional[httpx._types.RequestFiles] = None,
json: Optional[Any] = None,
params: Optional[httpx._types.QueryParamTypes] = None,
headers: Optional[httpx._types.HeaderTypes] = None,
cookies: Optional[httpx._types.CookieTypes] = None,
timeout: Union[
httpx._types.TimeoutTypes, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
extensions: Optional[httpx._types.RequestExtensions] = None,
) -> httpx.Request:
pass
async def aclose(self) -> None:
pass
class ClientOwner(Protocol):
client: Union[HttpClient, None]
async_client: Union[AsyncHttpClient, None]
def close_clients(
owner: ClientOwner,
sync_client: Union[HttpClient, None],
sync_client_supplied: bool,
async_client: Union[AsyncHttpClient, None],
async_client_supplied: bool,
) -> None:
"""
A finalizer function that is meant to be used with weakref.finalize to close
httpx clients used by an SDK so that underlying resources can be garbage
collected.
"""
# Unset the client/async_client properties so there are no more references
# to them from the owning SDK instance and they can be reaped.
owner.client = None
owner.async_client = None
if sync_client is not None and not sync_client_supplied:
try:
sync_client.close()
except Exception:
pass
if async_client is not None and not async_client_supplied:
try:
loop = asyncio.get_running_loop()
asyncio.run_coroutine_threadsafe(async_client.aclose(), loop)
except RuntimeError:
try:
asyncio.run(async_client.aclose())
except RuntimeError:
# best effort
pass
File diff suppressed because it is too large Load Diff
+66
View File
@@ -0,0 +1,66 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
import pydantic
from typing_extensions import Annotated, TypedDict
class ActivityItemTypedDict(TypedDict):
date_: str
r"""Date of the activity (YYYY-MM-DD format)"""
model: str
r"""Model slug (e.g., \"openai/gpt-4.1\")"""
model_permaslug: str
r"""Model permaslug (e.g., \"openai/gpt-4.1-2025-04-14\")"""
endpoint_id: str
r"""Unique identifier for the endpoint"""
provider_name: str
r"""Name of the provider serving this endpoint"""
usage: float
r"""Total cost in USD (OpenRouter credits spent)"""
byok_usage_inference: float
r"""BYOK inference cost in USD (external credits spent)"""
requests: float
r"""Number of requests made"""
prompt_tokens: float
r"""Total prompt tokens used"""
completion_tokens: float
r"""Total completion tokens generated"""
reasoning_tokens: float
r"""Total reasoning tokens used"""
class ActivityItem(BaseModel):
date_: Annotated[str, pydantic.Field(alias="date")]
r"""Date of the activity (YYYY-MM-DD format)"""
model: str
r"""Model slug (e.g., \"openai/gpt-4.1\")"""
model_permaslug: str
r"""Model permaslug (e.g., \"openai/gpt-4.1-2025-04-14\")"""
endpoint_id: str
r"""Unique identifier for the endpoint"""
provider_name: str
r"""Name of the provider serving this endpoint"""
usage: float
r"""Total cost in USD (OpenRouter credits spent)"""
byok_usage_inference: float
r"""BYOK inference cost in USD (external credits spent)"""
requests: float
r"""Number of requests made"""
prompt_tokens: float
r"""Total prompt tokens used"""
completion_tokens: float
r"""Total completion tokens generated"""
reasoning_tokens: float
r"""Total reasoning tokens used"""
+88
View File
@@ -0,0 +1,88 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatmessagecontentitem import (
ChatMessageContentItem,
ChatMessageContentItemTypedDict,
)
from .chatmessagetoolcall import ChatMessageToolCall, ChatMessageToolCallTypedDict
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_const
import pydantic
from pydantic import model_serializer
from pydantic.functional_validators import AfterValidator
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
AssistantMessageContentTypedDict = TypeAliasType(
"AssistantMessageContentTypedDict",
Union[str, List[ChatMessageContentItemTypedDict]],
)
AssistantMessageContent = TypeAliasType(
"AssistantMessageContent", Union[str, List[ChatMessageContentItem]]
)
class AssistantMessageTypedDict(TypedDict):
role: Literal["assistant"]
content: NotRequired[Nullable[AssistantMessageContentTypedDict]]
name: NotRequired[str]
tool_calls: NotRequired[List[ChatMessageToolCallTypedDict]]
refusal: NotRequired[Nullable[str]]
reasoning: NotRequired[Nullable[str]]
class AssistantMessage(BaseModel):
ROLE: Annotated[
Annotated[Literal["assistant"], AfterValidator(validate_const("assistant"))],
pydantic.Field(alias="role"),
] = "assistant"
content: OptionalNullable[AssistantMessageContent] = UNSET
name: Optional[str] = None
tool_calls: Optional[List[ChatMessageToolCall]] = None
refusal: OptionalNullable[str] = UNSET
reasoning: OptionalNullable[str] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["content", "name", "tool_calls", "refusal", "reasoning"]
nullable_fields = ["content", "refusal", "reasoning"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,61 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import Any, Dict
from typing_extensions import NotRequired, TypedDict
class BadGatewayResponseErrorDataTypedDict(TypedDict):
r"""Error data for BadGatewayResponse"""
code: int
message: str
metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]]
class BadGatewayResponseErrorData(BaseModel):
r"""Error data for BadGatewayResponse"""
code: int
message: str
metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["metadata"]
nullable_fields = ["metadata"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,61 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import Any, Dict
from typing_extensions import NotRequired, TypedDict
class BadRequestResponseErrorDataTypedDict(TypedDict):
r"""Error data for BadRequestResponse"""
code: int
message: str
metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]]
class BadRequestResponseErrorData(BaseModel):
r"""Error data for BadRequestResponse"""
code: int
message: str
metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["metadata"]
nullable_fields = ["metadata"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,17 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import UnrecognizedStr
from typing import Literal, Union
ChatCompletionFinishReason = Union[
Literal[
"tool_calls",
"stop",
"length",
"content_filter",
"error",
],
UnrecognizedStr,
]
+66
View File
@@ -0,0 +1,66 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import Union
from typing_extensions import NotRequired, TypeAliasType, TypedDict
CodeTypedDict = TypeAliasType("CodeTypedDict", Union[str, float])
Code = TypeAliasType("Code", Union[str, float])
class ChatErrorErrorTypedDict(TypedDict):
code: Nullable[CodeTypedDict]
message: str
param: NotRequired[Nullable[str]]
type: NotRequired[Nullable[str]]
class ChatErrorError(BaseModel):
code: Nullable[Code]
message: str
param: OptionalNullable[str] = UNSET
type: OptionalNullable[str] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["param", "type"]
nullable_fields = ["code", "param", "type"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,291 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatstreamoptions import ChatStreamOptions, ChatStreamOptionsTypedDict
from .message import Message, MessageTypedDict
from .reasoningsummaryverbosity import ReasoningSummaryVerbosity
from .responseformatjsonschema import (
ResponseFormatJSONSchema,
ResponseFormatJSONSchemaTypedDict,
)
from .responseformattextgrammar import (
ResponseFormatTextGrammar,
ResponseFormatTextGrammarTypedDict,
)
from .tooldefinitionjson import ToolDefinitionJSON, ToolDefinitionJSONTypedDict
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import validate_const, validate_open_enum
import pydantic
from pydantic import model_serializer
from pydantic.functional_validators import AfterValidator, PlainValidator
from typing import Any, Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
Effort = Union[
Literal[
"minimal",
"low",
"medium",
"high",
],
UnrecognizedStr,
]
class ReasoningTypedDict(TypedDict):
effort: NotRequired[Nullable[Effort]]
summary: NotRequired[Nullable[ReasoningSummaryVerbosity]]
class Reasoning(BaseModel):
effort: Annotated[
OptionalNullable[Effort], PlainValidator(validate_open_enum(False))
] = UNSET
summary: Annotated[
OptionalNullable[ReasoningSummaryVerbosity],
PlainValidator(validate_open_enum(False)),
] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["effort", "summary"]
nullable_fields = ["effort", "summary"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class ChatGenerationParamsResponseFormatPythonTypedDict(TypedDict):
type: Literal["python"]
class ChatGenerationParamsResponseFormatPython(BaseModel):
TYPE: Annotated[
Annotated[Literal["python"], AfterValidator(validate_const("python"))],
pydantic.Field(alias="type"),
] = "python"
class ChatGenerationParamsResponseFormatJSONObjectTypedDict(TypedDict):
type: Literal["json_object"]
class ChatGenerationParamsResponseFormatJSONObject(BaseModel):
TYPE: Annotated[
Annotated[
Literal["json_object"], AfterValidator(validate_const("json_object"))
],
pydantic.Field(alias="type"),
] = "json_object"
class ChatGenerationParamsResponseFormatTextTypedDict(TypedDict):
type: Literal["text"]
class ChatGenerationParamsResponseFormatText(BaseModel):
TYPE: Annotated[
Annotated[Literal["text"], AfterValidator(validate_const("text"))],
pydantic.Field(alias="type"),
] = "text"
ChatGenerationParamsResponseFormatUnionTypedDict = TypeAliasType(
"ChatGenerationParamsResponseFormatUnionTypedDict",
Union[
ChatGenerationParamsResponseFormatTextTypedDict,
ChatGenerationParamsResponseFormatJSONObjectTypedDict,
ChatGenerationParamsResponseFormatPythonTypedDict,
ResponseFormatJSONSchemaTypedDict,
ResponseFormatTextGrammarTypedDict,
],
)
ChatGenerationParamsResponseFormatUnion = TypeAliasType(
"ChatGenerationParamsResponseFormatUnion",
Union[
ChatGenerationParamsResponseFormatText,
ChatGenerationParamsResponseFormatJSONObject,
ChatGenerationParamsResponseFormatPython,
ResponseFormatJSONSchema,
ResponseFormatTextGrammar,
],
)
ChatGenerationParamsStopTypedDict = TypeAliasType(
"ChatGenerationParamsStopTypedDict", Union[str, List[str]]
)
ChatGenerationParamsStop = TypeAliasType(
"ChatGenerationParamsStop", Union[str, List[str]]
)
class ChatGenerationParamsTypedDict(TypedDict):
messages: List[MessageTypedDict]
model: NotRequired[str]
models: NotRequired[List[str]]
frequency_penalty: NotRequired[Nullable[float]]
logit_bias: NotRequired[Nullable[Dict[str, float]]]
logprobs: NotRequired[Nullable[bool]]
top_logprobs: NotRequired[Nullable[float]]
max_completion_tokens: NotRequired[Nullable[float]]
max_tokens: NotRequired[Nullable[float]]
metadata: NotRequired[Dict[str, str]]
presence_penalty: NotRequired[Nullable[float]]
reasoning: NotRequired[ReasoningTypedDict]
response_format: NotRequired[ChatGenerationParamsResponseFormatUnionTypedDict]
seed: NotRequired[Nullable[int]]
stop: NotRequired[Nullable[ChatGenerationParamsStopTypedDict]]
stream: NotRequired[bool]
stream_options: NotRequired[Nullable[ChatStreamOptionsTypedDict]]
temperature: NotRequired[Nullable[float]]
tool_choice: NotRequired[Any]
tools: NotRequired[List[ToolDefinitionJSONTypedDict]]
top_p: NotRequired[Nullable[float]]
user: NotRequired[str]
class ChatGenerationParams(BaseModel):
messages: List[Message]
model: Optional[str] = None
models: Optional[List[str]] = None
frequency_penalty: OptionalNullable[float] = UNSET
logit_bias: OptionalNullable[Dict[str, float]] = UNSET
logprobs: OptionalNullable[bool] = UNSET
top_logprobs: OptionalNullable[float] = UNSET
max_completion_tokens: OptionalNullable[float] = UNSET
max_tokens: OptionalNullable[float] = UNSET
metadata: Optional[Dict[str, str]] = None
presence_penalty: OptionalNullable[float] = UNSET
reasoning: Optional[Reasoning] = None
response_format: Optional[ChatGenerationParamsResponseFormatUnion] = None
seed: OptionalNullable[int] = UNSET
stop: OptionalNullable[ChatGenerationParamsStop] = UNSET
stream: Optional[bool] = False
stream_options: OptionalNullable[ChatStreamOptions] = UNSET
temperature: OptionalNullable[float] = UNSET
tool_choice: Optional[Any] = None
tools: Optional[List[ToolDefinitionJSON]] = None
top_p: OptionalNullable[float] = UNSET
user: Optional[str] = None
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = [
"model",
"models",
"frequency_penalty",
"logit_bias",
"logprobs",
"top_logprobs",
"max_completion_tokens",
"max_tokens",
"metadata",
"presence_penalty",
"reasoning",
"response_format",
"seed",
"stop",
"stream",
"stream_options",
"temperature",
"tool_choice",
"tools",
"top_p",
"user",
]
nullable_fields = [
"frequency_penalty",
"logit_bias",
"logprobs",
"top_logprobs",
"max_completion_tokens",
"max_tokens",
"presence_penalty",
"seed",
"stop",
"stream_options",
"temperature",
"top_p",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,134 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import Optional
from typing_extensions import NotRequired, TypedDict
class CompletionTokensDetailsTypedDict(TypedDict):
reasoning_tokens: NotRequired[Nullable[float]]
audio_tokens: NotRequired[Nullable[float]]
accepted_prediction_tokens: NotRequired[Nullable[float]]
rejected_prediction_tokens: NotRequired[Nullable[float]]
class CompletionTokensDetails(BaseModel):
reasoning_tokens: OptionalNullable[float] = UNSET
audio_tokens: OptionalNullable[float] = UNSET
accepted_prediction_tokens: OptionalNullable[float] = UNSET
rejected_prediction_tokens: OptionalNullable[float] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = [
"reasoning_tokens",
"audio_tokens",
"accepted_prediction_tokens",
"rejected_prediction_tokens",
]
nullable_fields = [
"reasoning_tokens",
"audio_tokens",
"accepted_prediction_tokens",
"rejected_prediction_tokens",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class PromptTokensDetailsTypedDict(TypedDict):
cached_tokens: NotRequired[float]
audio_tokens: NotRequired[float]
video_tokens: NotRequired[float]
class PromptTokensDetails(BaseModel):
cached_tokens: Optional[float] = None
audio_tokens: Optional[float] = None
video_tokens: Optional[float] = None
class ChatGenerationTokenUsageTypedDict(TypedDict):
completion_tokens: float
prompt_tokens: float
total_tokens: float
completion_tokens_details: NotRequired[Nullable[CompletionTokensDetailsTypedDict]]
prompt_tokens_details: NotRequired[Nullable[PromptTokensDetailsTypedDict]]
class ChatGenerationTokenUsage(BaseModel):
completion_tokens: float
prompt_tokens: float
total_tokens: float
completion_tokens_details: OptionalNullable[CompletionTokensDetails] = UNSET
prompt_tokens_details: OptionalNullable[PromptTokensDetails] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["completion_tokens_details", "prompt_tokens_details"]
nullable_fields = ["completion_tokens_details", "prompt_tokens_details"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,45 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatmessagecontentitemaudio import (
ChatMessageContentItemAudio,
ChatMessageContentItemAudioTypedDict,
)
from .chatmessagecontentitemimage import (
ChatMessageContentItemImage,
ChatMessageContentItemImageTypedDict,
)
from .chatmessagecontentitemtext import (
ChatMessageContentItemText,
ChatMessageContentItemTextTypedDict,
)
from .chatmessagecontentitemvideo import (
ChatMessageContentItemVideo,
ChatMessageContentItemVideoTypedDict,
)
from openrouter.utils import get_discriminator
from pydantic import Discriminator, Tag
from typing import Union
from typing_extensions import Annotated, TypeAliasType
ChatMessageContentItemTypedDict = TypeAliasType(
"ChatMessageContentItemTypedDict",
Union[
ChatMessageContentItemTextTypedDict,
ChatMessageContentItemImageTypedDict,
ChatMessageContentItemAudioTypedDict,
ChatMessageContentItemVideoTypedDict,
],
)
ChatMessageContentItem = Annotated[
Union[
Annotated[ChatMessageContentItemText, Tag("text")],
Annotated[ChatMessageContentItemImage, Tag("image_url")],
Annotated[ChatMessageContentItemAudio, Tag("input_audio")],
Annotated[ChatMessageContentItemVideo, Tag("input_video")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
@@ -0,0 +1,55 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, UnrecognizedStr
from openrouter.utils import validate_const, validate_open_enum
import pydantic
from pydantic.functional_validators import AfterValidator, PlainValidator
from typing import Literal, Union
from typing_extensions import Annotated, TypedDict
ChatMessageContentItemAudioFormat = Union[
Literal[
"wav",
"mp3",
"flac",
"m4a",
"ogg",
"pcm16",
"pcm24",
],
UnrecognizedStr,
]
class ChatMessageContentItemAudioInputAudioTypedDict(TypedDict):
data: str
format_: ChatMessageContentItemAudioFormat
class ChatMessageContentItemAudioInputAudio(BaseModel):
data: str
format_: Annotated[
Annotated[
ChatMessageContentItemAudioFormat, PlainValidator(validate_open_enum(False))
],
pydantic.Field(alias="format"),
]
class ChatMessageContentItemAudioTypedDict(TypedDict):
input_audio: ChatMessageContentItemAudioInputAudioTypedDict
type: Literal["input_audio"]
class ChatMessageContentItemAudio(BaseModel):
input_audio: ChatMessageContentItemAudioInputAudio
TYPE: Annotated[
Annotated[
Literal["input_audio"], AfterValidator(validate_const("input_audio"))
],
pydantic.Field(alias="type"),
] = "input_audio"
@@ -0,0 +1,47 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, UnrecognizedStr
from openrouter.utils import validate_const, validate_open_enum
import pydantic
from pydantic.functional_validators import AfterValidator, PlainValidator
from typing import Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
ChatMessageContentItemImageDetail = Union[
Literal[
"auto",
"low",
"high",
],
UnrecognizedStr,
]
class ImageURLTypedDict(TypedDict):
url: str
detail: NotRequired[ChatMessageContentItemImageDetail]
class ImageURL(BaseModel):
url: str
detail: Annotated[
Optional[ChatMessageContentItemImageDetail],
PlainValidator(validate_open_enum(False)),
] = None
class ChatMessageContentItemImageTypedDict(TypedDict):
image_url: ImageURLTypedDict
type: Literal["image_url"]
class ChatMessageContentItemImage(BaseModel):
image_url: ImageURL
TYPE: Annotated[
Annotated[Literal["image_url"], AfterValidator(validate_const("image_url"))],
pydantic.Field(alias="type"),
] = "image_url"
@@ -0,0 +1,23 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal
from typing_extensions import Annotated, TypedDict
class ChatMessageContentItemTextTypedDict(TypedDict):
text: str
type: Literal["text"]
class ChatMessageContentItemText(BaseModel):
text: str
TYPE: Annotated[
Annotated[Literal["text"], AfterValidator(validate_const("text"))],
pydantic.Field(alias="type"),
] = "text"
@@ -0,0 +1,33 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal
from typing_extensions import Annotated, TypedDict
class VideoURLTypedDict(TypedDict):
url: str
class VideoURL(BaseModel):
url: str
class ChatMessageContentItemVideoTypedDict(TypedDict):
video_url: VideoURLTypedDict
type: Literal["input_video"]
class ChatMessageContentItemVideo(BaseModel):
video_url: VideoURL
TYPE: Annotated[
Annotated[
Literal["input_video"], AfterValidator(validate_const("input_video"))
],
pydantic.Field(alias="type"),
] = "input_video"
@@ -0,0 +1,99 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
import pydantic
from pydantic import model_serializer
from typing import List
from typing_extensions import Annotated, TypedDict
class TopLogprobTypedDict(TypedDict):
token: str
logprob: float
bytes_: Nullable[List[float]]
class TopLogprob(BaseModel):
token: str
logprob: float
bytes_: Annotated[Nullable[List[float]], pydantic.Field(alias="bytes")]
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["bytes"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class ChatMessageTokenLogprobTypedDict(TypedDict):
token: str
logprob: float
bytes_: Nullable[List[float]]
top_logprobs: List[TopLogprobTypedDict]
class ChatMessageTokenLogprob(BaseModel):
token: str
logprob: float
bytes_: Annotated[Nullable[List[float]], pydantic.Field(alias="bytes")]
top_logprobs: List[TopLogprob]
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["bytes"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,52 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatmessagetokenlogprob import (
ChatMessageTokenLogprob,
ChatMessageTokenLogprobTypedDict,
)
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
from pydantic import model_serializer
from typing import List
from typing_extensions import TypedDict
class ChatMessageTokenLogprobsTypedDict(TypedDict):
content: Nullable[List[ChatMessageTokenLogprobTypedDict]]
refusal: Nullable[List[ChatMessageTokenLogprobTypedDict]]
class ChatMessageTokenLogprobs(BaseModel):
content: Nullable[List[ChatMessageTokenLogprob]]
refusal: Nullable[List[ChatMessageTokenLogprob]]
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["content", "refusal"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,37 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal
from typing_extensions import Annotated, TypedDict
class ChatMessageToolCallFunctionTypedDict(TypedDict):
name: str
arguments: str
class ChatMessageToolCallFunction(BaseModel):
name: str
arguments: str
class ChatMessageToolCallTypedDict(TypedDict):
id: str
function: ChatMessageToolCallFunctionTypedDict
type: Literal["function"]
class ChatMessageToolCall(BaseModel):
id: str
function: ChatMessageToolCallFunction
TYPE: Annotated[
Annotated[Literal["function"], AfterValidator(validate_const("function"))],
pydantic.Field(alias="type"),
] = "function"
+83
View File
@@ -0,0 +1,83 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatgenerationtokenusage import (
ChatGenerationTokenUsage,
ChatGenerationTokenUsageTypedDict,
)
from .chatresponsechoice import ChatResponseChoice, ChatResponseChoiceTypedDict
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_const
import pydantic
from pydantic import model_serializer
from pydantic.functional_validators import AfterValidator
from typing import List, Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class ChatResponseTypedDict(TypedDict):
id: str
choices: List[ChatResponseChoiceTypedDict]
created: float
model: str
object: Literal["chat.completion"]
system_fingerprint: NotRequired[Nullable[str]]
usage: NotRequired[ChatGenerationTokenUsageTypedDict]
class ChatResponse(BaseModel):
id: str
choices: List[ChatResponseChoice]
created: float
model: str
OBJECT: Annotated[
Annotated[
Literal["chat.completion"],
AfterValidator(validate_const("chat.completion")),
],
pydantic.Field(alias="object"),
] = "chat.completion"
system_fingerprint: OptionalNullable[str] = UNSET
usage: Optional[ChatGenerationTokenUsage] = None
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["system_fingerprint", "usage"]
nullable_fields = ["system_fingerprint"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,69 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .assistantmessage import AssistantMessage, AssistantMessageTypedDict
from .chatcompletionfinishreason import ChatCompletionFinishReason
from .chatmessagetokenlogprobs import (
ChatMessageTokenLogprobs,
ChatMessageTokenLogprobsTypedDict,
)
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing_extensions import Annotated, NotRequired, TypedDict
class ChatResponseChoiceTypedDict(TypedDict):
finish_reason: Nullable[ChatCompletionFinishReason]
index: float
message: AssistantMessageTypedDict
logprobs: NotRequired[Nullable[ChatMessageTokenLogprobsTypedDict]]
class ChatResponseChoice(BaseModel):
finish_reason: Annotated[
Nullable[ChatCompletionFinishReason], PlainValidator(validate_open_enum(False))
]
index: float
message: AssistantMessage
logprobs: OptionalNullable[ChatMessageTokenLogprobs] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["logprobs"]
nullable_fields = ["finish_reason", "logprobs"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,72 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatcompletionfinishreason import ChatCompletionFinishReason
from .chatmessagetokenlogprobs import (
ChatMessageTokenLogprobs,
ChatMessageTokenLogprobsTypedDict,
)
from .chatstreamingmessagechunk import (
ChatStreamingMessageChunk,
ChatStreamingMessageChunkTypedDict,
)
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing_extensions import Annotated, NotRequired, TypedDict
class ChatStreamingChoiceTypedDict(TypedDict):
delta: ChatStreamingMessageChunkTypedDict
finish_reason: Nullable[ChatCompletionFinishReason]
index: float
logprobs: NotRequired[Nullable[ChatMessageTokenLogprobsTypedDict]]
class ChatStreamingChoice(BaseModel):
delta: ChatStreamingMessageChunk
finish_reason: Annotated[
Nullable[ChatCompletionFinishReason], PlainValidator(validate_open_enum(False))
]
index: float
logprobs: OptionalNullable[ChatMessageTokenLogprobs] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["logprobs"]
nullable_fields = ["finish_reason", "logprobs"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,70 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatstreamingmessagetoolcall import (
ChatStreamingMessageToolCall,
ChatStreamingMessageToolCallTypedDict,
)
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import List, Literal, Optional
from typing_extensions import NotRequired, TypedDict
ChatStreamingMessageChunkRole = Literal["assistant",]
class ChatStreamingMessageChunkTypedDict(TypedDict):
role: NotRequired[ChatStreamingMessageChunkRole]
content: NotRequired[Nullable[str]]
reasoning: NotRequired[Nullable[str]]
refusal: NotRequired[Nullable[str]]
tool_calls: NotRequired[List[ChatStreamingMessageToolCallTypedDict]]
class ChatStreamingMessageChunk(BaseModel):
role: Optional[ChatStreamingMessageChunkRole] = None
content: OptionalNullable[str] = UNSET
reasoning: OptionalNullable[str] = UNSET
refusal: OptionalNullable[str] = UNSET
tool_calls: Optional[List[ChatStreamingMessageToolCall]] = None
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["role", "content", "reasoning", "refusal", "tool_calls"]
nullable_fields = ["content", "reasoning", "refusal"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,42 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class ChatStreamingMessageToolCallFunctionTypedDict(TypedDict):
name: NotRequired[str]
arguments: NotRequired[str]
class ChatStreamingMessageToolCallFunction(BaseModel):
name: Optional[str] = None
arguments: Optional[str] = None
class ChatStreamingMessageToolCallTypedDict(TypedDict):
index: float
id: NotRequired[str]
type: Literal["function"]
function: NotRequired[ChatStreamingMessageToolCallFunctionTypedDict]
class ChatStreamingMessageToolCall(BaseModel):
index: float
id: Optional[str] = None
TYPE: Annotated[
Annotated[
Optional[Literal["function"]], AfterValidator(validate_const("function"))
],
pydantic.Field(alias="type"),
] = "function"
function: Optional[ChatStreamingMessageToolCallFunction] = None
@@ -0,0 +1,105 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatgenerationtokenusage import (
ChatGenerationTokenUsage,
ChatGenerationTokenUsageTypedDict,
)
from .chatstreamingchoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_const
import pydantic
from pydantic import model_serializer
from pydantic.functional_validators import AfterValidator
from typing import List, Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class ChatStreamingResponseChunkErrorTypedDict(TypedDict):
message: str
code: float
class ChatStreamingResponseChunkError(BaseModel):
message: str
code: float
class ChatStreamingResponseChunkDataTypedDict(TypedDict):
id: str
choices: List[ChatStreamingChoiceTypedDict]
created: float
model: str
object: Literal["chat.completion.chunk"]
system_fingerprint: NotRequired[Nullable[str]]
error: NotRequired[ChatStreamingResponseChunkErrorTypedDict]
usage: NotRequired[ChatGenerationTokenUsageTypedDict]
class ChatStreamingResponseChunkData(BaseModel):
id: str
choices: List[ChatStreamingChoice]
created: float
model: str
OBJECT: Annotated[
Annotated[
Literal["chat.completion.chunk"],
AfterValidator(validate_const("chat.completion.chunk")),
],
pydantic.Field(alias="object"),
] = "chat.completion.chunk"
system_fingerprint: OptionalNullable[str] = UNSET
error: Optional[ChatStreamingResponseChunkError] = None
usage: Optional[ChatGenerationTokenUsage] = None
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["system_fingerprint", "error", "usage"]
nullable_fields = ["system_fingerprint"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class ChatStreamingResponseChunkTypedDict(TypedDict):
data: ChatStreamingResponseChunkDataTypedDict
class ChatStreamingResponseChunk(BaseModel):
data: ChatStreamingResponseChunkData
@@ -0,0 +1,14 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from typing import Optional
from typing_extensions import NotRequired, TypedDict
class ChatStreamOptionsTypedDict(TypedDict):
include_usage: NotRequired[bool]
class ChatStreamOptions(BaseModel):
include_usage: Optional[bool] = None
+69
View File
@@ -0,0 +1,69 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .completionlogprobs import CompletionLogprobs, CompletionLogprobsTypedDict
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedStr
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Literal, Union
from typing_extensions import Annotated, TypedDict
CompletionFinishReason = Union[
Literal[
"stop",
"length",
"content_filter",
],
UnrecognizedStr,
]
class CompletionChoiceTypedDict(TypedDict):
text: str
index: float
logprobs: Nullable[CompletionLogprobsTypedDict]
finish_reason: Nullable[CompletionFinishReason]
class CompletionChoice(BaseModel):
text: str
index: float
logprobs: Nullable[CompletionLogprobs]
finish_reason: Annotated[
Nullable[CompletionFinishReason], PlainValidator(validate_open_enum(False))
]
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["logprobs", "finish_reason"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,277 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .responseformatjsonschema import (
ResponseFormatJSONSchema,
ResponseFormatJSONSchemaTypedDict,
)
from .responseformattextgrammar import (
ResponseFormatTextGrammar,
ResponseFormatTextGrammarTypedDict,
)
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_const
import pydantic
from pydantic import model_serializer
from pydantic.functional_validators import AfterValidator
from typing import Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
PromptTypedDict = TypeAliasType(
"PromptTypedDict", Union[str, List[str], List[float], List[List[float]]]
)
Prompt = TypeAliasType("Prompt", Union[str, List[str], List[float], List[List[float]]])
CompletionCreateParamsStopTypedDict = TypeAliasType(
"CompletionCreateParamsStopTypedDict", Union[str, List[str]]
)
CompletionCreateParamsStop = TypeAliasType(
"CompletionCreateParamsStop", Union[str, List[str]]
)
class StreamOptionsTypedDict(TypedDict):
include_usage: NotRequired[Nullable[bool]]
class StreamOptions(BaseModel):
include_usage: OptionalNullable[bool] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["include_usage"]
nullable_fields = ["include_usage"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class CompletionCreateParamsResponseFormatPythonTypedDict(TypedDict):
type: Literal["python"]
class CompletionCreateParamsResponseFormatPython(BaseModel):
TYPE: Annotated[
Annotated[Literal["python"], AfterValidator(validate_const("python"))],
pydantic.Field(alias="type"),
] = "python"
class CompletionCreateParamsResponseFormatJSONObjectTypedDict(TypedDict):
type: Literal["json_object"]
class CompletionCreateParamsResponseFormatJSONObject(BaseModel):
TYPE: Annotated[
Annotated[
Literal["json_object"], AfterValidator(validate_const("json_object"))
],
pydantic.Field(alias="type"),
] = "json_object"
class CompletionCreateParamsResponseFormatTextTypedDict(TypedDict):
type: Literal["text"]
class CompletionCreateParamsResponseFormatText(BaseModel):
TYPE: Annotated[
Annotated[Literal["text"], AfterValidator(validate_const("text"))],
pydantic.Field(alias="type"),
] = "text"
CompletionCreateParamsResponseFormatUnionTypedDict = TypeAliasType(
"CompletionCreateParamsResponseFormatUnionTypedDict",
Union[
CompletionCreateParamsResponseFormatTextTypedDict,
CompletionCreateParamsResponseFormatJSONObjectTypedDict,
CompletionCreateParamsResponseFormatPythonTypedDict,
ResponseFormatJSONSchemaTypedDict,
ResponseFormatTextGrammarTypedDict,
],
)
CompletionCreateParamsResponseFormatUnion = TypeAliasType(
"CompletionCreateParamsResponseFormatUnion",
Union[
CompletionCreateParamsResponseFormatText,
CompletionCreateParamsResponseFormatJSONObject,
CompletionCreateParamsResponseFormatPython,
ResponseFormatJSONSchema,
ResponseFormatTextGrammar,
],
)
class CompletionCreateParamsTypedDict(TypedDict):
prompt: PromptTypedDict
model: NotRequired[str]
models: NotRequired[List[str]]
best_of: NotRequired[Nullable[int]]
echo: NotRequired[Nullable[bool]]
frequency_penalty: NotRequired[Nullable[float]]
logit_bias: NotRequired[Nullable[Dict[str, float]]]
logprobs: NotRequired[Nullable[int]]
max_tokens: NotRequired[Nullable[int]]
n: NotRequired[Nullable[int]]
presence_penalty: NotRequired[Nullable[float]]
seed: NotRequired[Nullable[int]]
stop: NotRequired[Nullable[CompletionCreateParamsStopTypedDict]]
stream: NotRequired[bool]
stream_options: NotRequired[Nullable[StreamOptionsTypedDict]]
suffix: NotRequired[Nullable[str]]
temperature: NotRequired[Nullable[float]]
top_p: NotRequired[Nullable[float]]
user: NotRequired[str]
metadata: NotRequired[Nullable[Dict[str, str]]]
response_format: NotRequired[
Nullable[CompletionCreateParamsResponseFormatUnionTypedDict]
]
class CompletionCreateParams(BaseModel):
prompt: Prompt
model: Optional[str] = None
models: Optional[List[str]] = None
best_of: OptionalNullable[int] = UNSET
echo: OptionalNullable[bool] = UNSET
frequency_penalty: OptionalNullable[float] = UNSET
logit_bias: OptionalNullable[Dict[str, float]] = UNSET
logprobs: OptionalNullable[int] = UNSET
max_tokens: OptionalNullable[int] = UNSET
n: OptionalNullable[int] = UNSET
presence_penalty: OptionalNullable[float] = UNSET
seed: OptionalNullable[int] = UNSET
stop: OptionalNullable[CompletionCreateParamsStop] = UNSET
stream: Optional[bool] = False
stream_options: OptionalNullable[StreamOptions] = UNSET
suffix: OptionalNullable[str] = UNSET
temperature: OptionalNullable[float] = UNSET
top_p: OptionalNullable[float] = UNSET
user: Optional[str] = None
metadata: OptionalNullable[Dict[str, str]] = UNSET
response_format: OptionalNullable[CompletionCreateParamsResponseFormatUnion] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = [
"model",
"models",
"best_of",
"echo",
"frequency_penalty",
"logit_bias",
"logprobs",
"max_tokens",
"n",
"presence_penalty",
"seed",
"stop",
"stream",
"stream_options",
"suffix",
"temperature",
"top_p",
"user",
"metadata",
"response_format",
]
nullable_fields = [
"best_of",
"echo",
"frequency_penalty",
"logit_bias",
"logprobs",
"max_tokens",
"n",
"presence_penalty",
"seed",
"stop",
"stream_options",
"suffix",
"temperature",
"top_p",
"metadata",
"response_format",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,54 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
from pydantic import model_serializer
from typing import Dict, List
from typing_extensions import TypedDict
class CompletionLogprobsTypedDict(TypedDict):
tokens: List[str]
token_logprobs: List[float]
top_logprobs: Nullable[List[Dict[str, float]]]
text_offset: List[float]
class CompletionLogprobs(BaseModel):
tokens: List[str]
token_logprobs: List[float]
top_logprobs: Nullable[List[Dict[str, float]]]
text_offset: List[float]
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["top_logprobs"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -0,0 +1,43 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .completionchoice import CompletionChoice, CompletionChoiceTypedDict
from .completionusage import CompletionUsage, CompletionUsageTypedDict
from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import List, Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class CompletionResponseTypedDict(TypedDict):
id: str
created: float
model: str
choices: List[CompletionChoiceTypedDict]
object: Literal["text_completion"]
system_fingerprint: NotRequired[str]
usage: NotRequired[CompletionUsageTypedDict]
class CompletionResponse(BaseModel):
id: str
created: float
model: str
choices: List[CompletionChoice]
OBJECT: Annotated[
Annotated[
Literal["text_completion"],
AfterValidator(validate_const("text_completion")),
],
pydantic.Field(alias="object"),
] = "text_completion"
system_fingerprint: Optional[str] = None
usage: Optional[CompletionUsage] = None
+19
View File
@@ -0,0 +1,19 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from typing_extensions import TypedDict
class CompletionUsageTypedDict(TypedDict):
prompt_tokens: float
completion_tokens: float
total_tokens: float
class CompletionUsage(BaseModel):
prompt_tokens: float
completion_tokens: float
total_tokens: float
@@ -0,0 +1,133 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from datetime import datetime
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
CreateAuthKeysCodeCodeChallengeMethod = Union[
Literal[
"S256",
"plain",
],
UnrecognizedStr,
]
r"""The method used to generate the code challenge"""
class CreateAuthKeysCodeRequestTypedDict(TypedDict):
callback_url: str
r"""The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed."""
code_challenge: NotRequired[str]
r"""PKCE code challenge for enhanced security"""
code_challenge_method: NotRequired[CreateAuthKeysCodeCodeChallengeMethod]
r"""The method used to generate the code challenge"""
limit: NotRequired[float]
r"""Credit limit for the API key to be created"""
expires_at: NotRequired[Nullable[datetime]]
r"""Optional expiration time for the API key to be created"""
class CreateAuthKeysCodeRequest(BaseModel):
callback_url: str
r"""The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed."""
code_challenge: Optional[str] = None
r"""PKCE code challenge for enhanced security"""
code_challenge_method: Annotated[
Optional[CreateAuthKeysCodeCodeChallengeMethod],
PlainValidator(validate_open_enum(False)),
] = None
r"""The method used to generate the code challenge"""
limit: Optional[float] = None
r"""Credit limit for the API key to be created"""
expires_at: OptionalNullable[datetime] = UNSET
r"""Optional expiration time for the API key to be created"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = [
"code_challenge",
"code_challenge_method",
"limit",
"expires_at",
]
nullable_fields = ["expires_at"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class CreateAuthKeysCodeDataTypedDict(TypedDict):
r"""Auth code data"""
id: str
r"""The authorization code ID to use in the exchange request"""
app_id: float
r"""The application ID associated with this auth code"""
created_at: str
r"""ISO 8601 timestamp of when the auth code was created"""
class CreateAuthKeysCodeData(BaseModel):
r"""Auth code data"""
id: str
r"""The authorization code ID to use in the exchange request"""
app_id: float
r"""The application ID associated with this auth code"""
created_at: str
r"""ISO 8601 timestamp of when the auth code was created"""
class CreateAuthKeysCodeResponseTypedDict(TypedDict):
r"""Successfully created authorization code"""
data: CreateAuthKeysCodeDataTypedDict
r"""Auth code data"""
class CreateAuthKeysCodeResponse(BaseModel):
r"""Successfully created authorization code"""
data: CreateAuthKeysCodeData
r"""Auth code data"""
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, UnrecognizedInt
from openrouter.utils import validate_open_enum
from pydantic.functional_validators import PlainValidator
from typing import Literal, Union
from typing_extensions import Annotated, TypedDict
ChainID = Union[
Literal[
1,
137,
8453,
],
UnrecognizedInt,
]
class CreateChargeRequestTypedDict(TypedDict):
r"""Create a Coinbase charge for crypto payment"""
amount: float
sender: str
chain_id: ChainID
class CreateChargeRequest(BaseModel):
r"""Create a Coinbase charge for crypto payment"""
amount: float
sender: str
chain_id: Annotated[ChainID, PlainValidator(validate_open_enum(True))]
@@ -0,0 +1,121 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import FieldMetadata, SecurityMetadata
from typing_extensions import Annotated, TypedDict
class CreateCoinbaseChargeSecurityTypedDict(TypedDict):
bearer: str
class CreateCoinbaseChargeSecurity(BaseModel):
bearer: Annotated[
str,
FieldMetadata(
security=SecurityMetadata(
scheme=True,
scheme_type="http",
sub_type="bearer",
field_name="Authorization",
)
),
]
class CallDataTypedDict(TypedDict):
deadline: str
fee_amount: str
id: str
operator: str
prefix: str
recipient: str
recipient_amount: str
recipient_currency: str
refund_destination: str
signature: str
class CallData(BaseModel):
deadline: str
fee_amount: str
id: str
operator: str
prefix: str
recipient: str
recipient_amount: str
recipient_currency: str
refund_destination: str
signature: str
class MetadataTypedDict(TypedDict):
chain_id: float
contract_address: str
sender: str
class Metadata(BaseModel):
chain_id: float
contract_address: str
sender: str
class TransferIntentTypedDict(TypedDict):
call_data: CallDataTypedDict
metadata: MetadataTypedDict
class TransferIntent(BaseModel):
call_data: CallData
metadata: Metadata
class Web3DataTypedDict(TypedDict):
transfer_intent: TransferIntentTypedDict
class Web3Data(BaseModel):
transfer_intent: TransferIntent
class CreateCoinbaseChargeDataTypedDict(TypedDict):
id: str
created_at: str
expires_at: str
web3_data: Web3DataTypedDict
class CreateCoinbaseChargeData(BaseModel):
id: str
created_at: str
expires_at: str
web3_data: Web3Data
class CreateCoinbaseChargeResponseTypedDict(TypedDict):
r"""Returns the calldata to fulfill the transaction"""
data: CreateCoinbaseChargeDataTypedDict
class CreateCoinbaseChargeResponse(BaseModel):
r"""Returns the calldata to fulfill the transaction"""
data: CreateCoinbaseChargeData
+366
View File
@@ -0,0 +1,366 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .providername import ProviderName
from .quantization import Quantization
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Any, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
InputTypedDict = TypeAliasType(
"InputTypedDict", Union[str, List[str], List[float], List[List[float]]]
)
Input = TypeAliasType("Input", Union[str, List[str], List[float], List[List[float]]])
CreateEmbeddingsDataCollection = Union[
Literal[
"deny",
"allow",
],
UnrecognizedStr,
]
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
"""
CreateEmbeddingsOrderTypedDict = TypeAliasType(
"CreateEmbeddingsOrderTypedDict", Union[ProviderName, str]
)
CreateEmbeddingsOrder = TypeAliasType(
"CreateEmbeddingsOrder",
Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str],
)
CreateEmbeddingsOnlyTypedDict = TypeAliasType(
"CreateEmbeddingsOnlyTypedDict", Union[ProviderName, str]
)
CreateEmbeddingsOnly = TypeAliasType(
"CreateEmbeddingsOnly",
Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str],
)
CreateEmbeddingsIgnoreTypedDict = TypeAliasType(
"CreateEmbeddingsIgnoreTypedDict", Union[ProviderName, str]
)
CreateEmbeddingsIgnore = TypeAliasType(
"CreateEmbeddingsIgnore",
Union[Annotated[ProviderName, PlainValidator(validate_open_enum(False))], str],
)
CreateEmbeddingsSort = Union[
Literal[
"price",
"throughput",
"latency",
],
UnrecognizedStr,
]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
class CreateEmbeddingsMaxPriceTypedDict(TypedDict):
r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
prompt: NotRequired[Any]
r"""A value in string or number format that is a large number"""
completion: NotRequired[Any]
r"""A value in string or number format that is a large number"""
image: NotRequired[Any]
r"""A value in string or number format that is a large number"""
audio: NotRequired[Any]
r"""A value in string or number format that is a large number"""
request: NotRequired[Any]
r"""A value in string or number format that is a large number"""
class CreateEmbeddingsMaxPrice(BaseModel):
r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
prompt: Optional[Any] = None
r"""A value in string or number format that is a large number"""
completion: Optional[Any] = None
r"""A value in string or number format that is a large number"""
image: Optional[Any] = None
r"""A value in string or number format that is a large number"""
audio: Optional[Any] = None
r"""A value in string or number format that is a large number"""
request: Optional[Any] = None
r"""A value in string or number format that is a large number"""
class CreateEmbeddingsProviderTypedDict(TypedDict):
allow_fallbacks: NotRequired[Nullable[bool]]
r"""Whether to allow backup providers to serve requests
- true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider.
- false: use only the primary/custom provider, and return the upstream error if it's unavailable.
"""
require_parameters: NotRequired[Nullable[bool]]
r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest."""
data_collection: NotRequired[Nullable[CreateEmbeddingsDataCollection]]
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
"""
zdr: NotRequired[Nullable[bool]]
r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used."""
enforce_distillable_text: NotRequired[Nullable[bool]]
r"""Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used."""
order: NotRequired[Nullable[List[CreateEmbeddingsOrderTypedDict]]]
r"""An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message."""
only: NotRequired[Nullable[List[CreateEmbeddingsOnlyTypedDict]]]
r"""List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request."""
ignore: NotRequired[Nullable[List[CreateEmbeddingsIgnoreTypedDict]]]
r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request."""
quantizations: NotRequired[Nullable[List[Quantization]]]
r"""A list of quantization levels to filter the provider by."""
sort: NotRequired[Nullable[CreateEmbeddingsSort]]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
max_price: NotRequired[CreateEmbeddingsMaxPriceTypedDict]
r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
class CreateEmbeddingsProvider(BaseModel):
allow_fallbacks: OptionalNullable[bool] = UNSET
r"""Whether to allow backup providers to serve requests
- true: (default) when the primary provider (or your custom providers in \"order\") is unavailable, use the next best provider.
- false: use only the primary/custom provider, and return the upstream error if it's unavailable.
"""
require_parameters: OptionalNullable[bool] = UNSET
r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest."""
data_collection: Annotated[
OptionalNullable[CreateEmbeddingsDataCollection],
PlainValidator(validate_open_enum(False)),
] = UNSET
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
"""
zdr: OptionalNullable[bool] = UNSET
r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used."""
enforce_distillable_text: OptionalNullable[bool] = UNSET
r"""Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used."""
order: OptionalNullable[List[CreateEmbeddingsOrder]] = UNSET
r"""An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message."""
only: OptionalNullable[List[CreateEmbeddingsOnly]] = UNSET
r"""List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request."""
ignore: OptionalNullable[List[CreateEmbeddingsIgnore]] = UNSET
r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request."""
quantizations: OptionalNullable[
List[Annotated[Quantization, PlainValidator(validate_open_enum(False))]]
] = UNSET
r"""A list of quantization levels to filter the provider by."""
sort: Annotated[
OptionalNullable[CreateEmbeddingsSort],
PlainValidator(validate_open_enum(False)),
] = UNSET
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
max_price: Optional[CreateEmbeddingsMaxPrice] = None
r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = [
"allow_fallbacks",
"require_parameters",
"data_collection",
"zdr",
"enforce_distillable_text",
"order",
"only",
"ignore",
"quantizations",
"sort",
"max_price",
]
nullable_fields = [
"allow_fallbacks",
"require_parameters",
"data_collection",
"zdr",
"enforce_distillable_text",
"order",
"only",
"ignore",
"quantizations",
"sort",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
EncodingFormatBase64 = Literal["base64",]
EncodingFormatFloat = Literal["float",]
EncodingFormatTypedDict = TypeAliasType(
"EncodingFormatTypedDict", Union[EncodingFormatFloat, EncodingFormatBase64]
)
EncodingFormat = TypeAliasType(
"EncodingFormat", Union[EncodingFormatFloat, EncodingFormatBase64]
)
class CreateEmbeddingsRequestTypedDict(TypedDict):
input: InputTypedDict
model: str
provider: NotRequired[CreateEmbeddingsProviderTypedDict]
encoding_format: NotRequired[EncodingFormatTypedDict]
user: NotRequired[str]
class CreateEmbeddingsRequest(BaseModel):
input: Input
model: str
provider: Optional[CreateEmbeddingsProvider] = None
encoding_format: Optional[EncodingFormat] = None
user: Optional[str] = None
CreateEmbeddingsObject = Literal["list",]
ObjectEmbedding = Literal["embedding",]
EmbeddingTypedDict = TypeAliasType("EmbeddingTypedDict", Union[List[float], str])
Embedding = TypeAliasType("Embedding", Union[List[float], str])
class CreateEmbeddingsDataTypedDict(TypedDict):
object: ObjectEmbedding
embedding: EmbeddingTypedDict
index: NotRequired[float]
class CreateEmbeddingsData(BaseModel):
object: ObjectEmbedding
embedding: Embedding
index: Optional[float] = None
class UsageTypedDict(TypedDict):
prompt_tokens: float
total_tokens: float
cost: NotRequired[float]
class Usage(BaseModel):
prompt_tokens: float
total_tokens: float
cost: Optional[float] = None
class CreateEmbeddingsResponseBodyTypedDict(TypedDict):
r"""Embedding response"""
object: CreateEmbeddingsObject
data: List[CreateEmbeddingsDataTypedDict]
model: str
id: NotRequired[str]
usage: NotRequired[UsageTypedDict]
class CreateEmbeddingsResponseBody(BaseModel):
r"""Embedding response"""
object: CreateEmbeddingsObject
data: List[CreateEmbeddingsData]
model: str
id: Optional[str] = None
usage: Optional[Usage] = None
CreateEmbeddingsResponseTypedDict = TypeAliasType(
"CreateEmbeddingsResponseTypedDict",
Union[CreateEmbeddingsResponseBodyTypedDict, str],
)
CreateEmbeddingsResponse = TypeAliasType(
"CreateEmbeddingsResponse", Union[CreateEmbeddingsResponseBody, str]
)
+255
View File
@@ -0,0 +1,255 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from datetime import datetime
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
CreateKeysLimitReset = Union[
Literal[
"daily",
"weekly",
"monthly",
],
UnrecognizedStr,
]
r"""Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday."""
class CreateKeysRequestTypedDict(TypedDict):
name: str
r"""Name for the new API key"""
limit: NotRequired[Nullable[float]]
r"""Optional spending limit for the API key in USD"""
limit_reset: NotRequired[Nullable[CreateKeysLimitReset]]
r"""Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday."""
include_byok_in_limit: NotRequired[bool]
r"""Whether to include BYOK usage in the limit"""
expires_at: NotRequired[Nullable[datetime]]
r"""Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected"""
class CreateKeysRequest(BaseModel):
name: str
r"""Name for the new API key"""
limit: OptionalNullable[float] = UNSET
r"""Optional spending limit for the API key in USD"""
limit_reset: Annotated[
OptionalNullable[CreateKeysLimitReset],
PlainValidator(validate_open_enum(False)),
] = UNSET
r"""Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday."""
include_byok_in_limit: Optional[bool] = None
r"""Whether to include BYOK usage in the limit"""
expires_at: OptionalNullable[datetime] = UNSET
r"""Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = [
"limit",
"limit_reset",
"include_byok_in_limit",
"expires_at",
]
nullable_fields = ["limit", "limit_reset", "expires_at"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class CreateKeysDataTypedDict(TypedDict):
r"""The created API key information"""
hash: str
r"""Unique hash identifier for the API key"""
name: str
r"""Name of the API key"""
label: str
r"""Human-readable label for the API key"""
disabled: bool
r"""Whether the API key is disabled"""
limit: Nullable[float]
r"""Spending limit for the API key in USD"""
limit_remaining: Nullable[float]
r"""Remaining spending limit in USD"""
limit_reset: Nullable[str]
r"""Type of limit reset for the API key"""
include_byok_in_limit: bool
r"""Whether to include external BYOK usage in the credit limit"""
usage: float
r"""Total OpenRouter credit usage (in USD) for the API key"""
usage_daily: float
r"""OpenRouter credit usage (in USD) for the current UTC day"""
usage_weekly: float
r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)"""
usage_monthly: float
r"""OpenRouter credit usage (in USD) for the current UTC month"""
byok_usage: float
r"""Total external BYOK usage (in USD) for the API key"""
byok_usage_daily: float
r"""External BYOK usage (in USD) for the current UTC day"""
byok_usage_weekly: float
r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)"""
byok_usage_monthly: float
r"""External BYOK usage (in USD) for current UTC month"""
created_at: str
r"""ISO 8601 timestamp of when the API key was created"""
updated_at: Nullable[str]
r"""ISO 8601 timestamp of when the API key was last updated"""
expires_at: NotRequired[Nullable[datetime]]
r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration"""
class CreateKeysData(BaseModel):
r"""The created API key information"""
hash: str
r"""Unique hash identifier for the API key"""
name: str
r"""Name of the API key"""
label: str
r"""Human-readable label for the API key"""
disabled: bool
r"""Whether the API key is disabled"""
limit: Nullable[float]
r"""Spending limit for the API key in USD"""
limit_remaining: Nullable[float]
r"""Remaining spending limit in USD"""
limit_reset: Nullable[str]
r"""Type of limit reset for the API key"""
include_byok_in_limit: bool
r"""Whether to include external BYOK usage in the credit limit"""
usage: float
r"""Total OpenRouter credit usage (in USD) for the API key"""
usage_daily: float
r"""OpenRouter credit usage (in USD) for the current UTC day"""
usage_weekly: float
r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)"""
usage_monthly: float
r"""OpenRouter credit usage (in USD) for the current UTC month"""
byok_usage: float
r"""Total external BYOK usage (in USD) for the API key"""
byok_usage_daily: float
r"""External BYOK usage (in USD) for the current UTC day"""
byok_usage_weekly: float
r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)"""
byok_usage_monthly: float
r"""External BYOK usage (in USD) for current UTC month"""
created_at: str
r"""ISO 8601 timestamp of when the API key was created"""
updated_at: Nullable[str]
r"""ISO 8601 timestamp of when the API key was last updated"""
expires_at: OptionalNullable[datetime] = UNSET
r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["expires_at"]
nullable_fields = [
"limit",
"limit_remaining",
"limit_reset",
"updated_at",
"expires_at",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class CreateKeysResponseTypedDict(TypedDict):
r"""API key created successfully"""
data: CreateKeysDataTypedDict
r"""The created API key information"""
key: str
r"""The actual API key string (only shown once)"""
class CreateKeysResponse(BaseModel):
r"""API key created successfully"""
data: CreateKeysData
r"""The created API key information"""
key: str
r"""The actual API key string (only shown once)"""
@@ -0,0 +1,53 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .openresponsesnonstreamingresponse import (
OpenResponsesNonStreamingResponse,
OpenResponsesNonStreamingResponseTypedDict,
)
from .openresponsesstreamevent import (
OpenResponsesStreamEvent,
OpenResponsesStreamEventTypedDict,
)
from openrouter.types import BaseModel
from openrouter.utils import eventstreaming
from typing import Union
from typing_extensions import TypeAliasType, TypedDict
class CreateResponsesResponseBodyTypedDict(TypedDict):
r"""Successful response"""
data: OpenResponsesStreamEventTypedDict
r"""Union of all possible event types emitted during response streaming"""
class CreateResponsesResponseBody(BaseModel):
r"""Successful response"""
data: OpenResponsesStreamEvent
r"""Union of all possible event types emitted during response streaming"""
CreateResponsesResponseTypedDict = TypeAliasType(
"CreateResponsesResponseTypedDict",
Union[
OpenResponsesNonStreamingResponseTypedDict,
Union[
eventstreaming.EventStream[CreateResponsesResponseBodyTypedDict],
eventstreaming.EventStreamAsync[CreateResponsesResponseBodyTypedDict],
],
],
)
CreateResponsesResponse = TypeAliasType(
"CreateResponsesResponse",
Union[
OpenResponsesNonStreamingResponse,
Union[
eventstreaming.EventStream[CreateResponsesResponseBody],
eventstreaming.EventStreamAsync[CreateResponsesResponseBody],
],
],
)
@@ -0,0 +1,60 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing_extensions import NotRequired, TypedDict
class DefaultParametersTypedDict(TypedDict):
r"""Default parameters for this model"""
temperature: NotRequired[Nullable[float]]
top_p: NotRequired[Nullable[float]]
frequency_penalty: NotRequired[Nullable[float]]
class DefaultParameters(BaseModel):
r"""Default parameters for this model"""
temperature: OptionalNullable[float] = UNSET
top_p: OptionalNullable[float] = UNSET
frequency_penalty: OptionalNullable[float] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["temperature", "top_p", "frequency_penalty"]
nullable_fields = ["temperature", "top_p", "frequency_penalty"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
+38
View File
@@ -0,0 +1,38 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import FieldMetadata, PathParamMetadata, validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal
from typing_extensions import Annotated, TypedDict
class DeleteKeysRequestTypedDict(TypedDict):
hash: str
r"""The hash identifier of the API key to delete"""
class DeleteKeysRequest(BaseModel):
hash: Annotated[
str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))
]
r"""The hash identifier of the API key to delete"""
class DeleteKeysResponseTypedDict(TypedDict):
r"""API key deleted successfully"""
deleted: Literal[True]
r"""Confirmation that the API key was deleted"""
class DeleteKeysResponse(BaseModel):
r"""API key deleted successfully"""
DELETED: Annotated[
Annotated[Literal[True], AfterValidator(validate_const(True))],
pydantic.Field(alias="deleted"),
] = True
r"""Confirmation that the API key was deleted"""
@@ -0,0 +1,61 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import Any, Dict
from typing_extensions import NotRequired, TypedDict
class EdgeNetworkTimeoutResponseErrorDataTypedDict(TypedDict):
r"""Error data for EdgeNetworkTimeoutResponse"""
code: int
message: str
metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]]
class EdgeNetworkTimeoutResponseErrorData(BaseModel):
r"""Error data for EdgeNetworkTimeoutResponse"""
code: int
message: str
metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["metadata"]
nullable_fields = ["metadata"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
+18
View File
@@ -0,0 +1,18 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import UnrecognizedInt
from typing import Literal, Union
EndpointStatus = Union[
Literal[
0,
-1,
-2,
-3,
-5,
-10,
],
UnrecognizedInt,
]
@@ -0,0 +1,130 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
ExchangeAuthCodeForAPIKeyCodeChallengeMethod = Union[
Literal[
"S256",
"plain",
],
UnrecognizedStr,
]
r"""The method used to generate the code challenge"""
class ExchangeAuthCodeForAPIKeyRequestTypedDict(TypedDict):
code: str
r"""The authorization code received from the OAuth redirect"""
code_verifier: NotRequired[str]
r"""The code verifier if code_challenge was used in the authorization request"""
code_challenge_method: NotRequired[
Nullable[ExchangeAuthCodeForAPIKeyCodeChallengeMethod]
]
r"""The method used to generate the code challenge"""
class ExchangeAuthCodeForAPIKeyRequest(BaseModel):
code: str
r"""The authorization code received from the OAuth redirect"""
code_verifier: Optional[str] = None
r"""The code verifier if code_challenge was used in the authorization request"""
code_challenge_method: Annotated[
OptionalNullable[ExchangeAuthCodeForAPIKeyCodeChallengeMethod],
PlainValidator(validate_open_enum(False)),
] = UNSET
r"""The method used to generate the code challenge"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["code_verifier", "code_challenge_method"]
nullable_fields = ["code_challenge_method"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class ExchangeAuthCodeForAPIKeyResponseTypedDict(TypedDict):
r"""Successfully exchanged code for an API key"""
key: str
r"""The API key to use for OpenRouter requests"""
user_id: Nullable[str]
r"""User ID associated with the API key"""
class ExchangeAuthCodeForAPIKeyResponse(BaseModel):
r"""Successfully exchanged code for an API key"""
key: str
r"""The API key to use for OpenRouter requests"""
user_id: Nullable[str]
r"""User ID associated with the API key"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["user_id"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
+26
View File
@@ -0,0 +1,26 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from typing import Literal
from typing_extensions import TypedDict
FileCitationType = Literal["file_citation",]
class FileCitationTypedDict(TypedDict):
type: FileCitationType
file_id: str
filename: str
index: float
class FileCitation(BaseModel):
type: FileCitationType
file_id: str
filename: str
index: float
+23
View File
@@ -0,0 +1,23 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from typing import Literal
from typing_extensions import TypedDict
FilePathType = Literal["file_path",]
class FilePathTypedDict(TypedDict):
type: FilePathType
file_id: str
index: float
class FilePath(BaseModel):
type: FilePathType
file_id: str
index: float
@@ -0,0 +1,61 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import Any, Dict
from typing_extensions import NotRequired, TypedDict
class ForbiddenResponseErrorDataTypedDict(TypedDict):
r"""Error data for ForbiddenResponse"""
code: int
message: str
metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]]
class ForbiddenResponseErrorData(BaseModel):
r"""Error data for ForbiddenResponse"""
code: int
message: str
metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["metadata"]
nullable_fields = ["metadata"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
+13
View File
@@ -0,0 +1,13 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from typing_extensions import TypedDict
class GetCreditsResponseTypedDict(TypedDict):
r"""Total credits purchased and used"""
class GetCreditsResponse(BaseModel):
r"""Total credits purchased and used"""
+187
View File
@@ -0,0 +1,187 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from datetime import datetime
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
import pydantic
from pydantic import model_serializer
from typing_extensions import Annotated, NotRequired, TypedDict, deprecated
@deprecated(
"warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible."
)
class RateLimitTypedDict(TypedDict):
r"""Legacy rate limit information about a key. Will always return -1."""
requests: float
r"""Number of requests allowed per interval"""
interval: str
r"""Rate limit interval"""
note: str
r"""Note about the rate limit"""
@deprecated(
"warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible."
)
class RateLimit(BaseModel):
r"""Legacy rate limit information about a key. Will always return -1."""
requests: float
r"""Number of requests allowed per interval"""
interval: str
r"""Rate limit interval"""
note: str
r"""Note about the rate limit"""
class GetCurrentKeyDataTypedDict(TypedDict):
r"""Current API key information"""
label: str
r"""Human-readable label for the API key"""
limit: Nullable[float]
r"""Spending limit for the API key in USD"""
usage: float
r"""Total OpenRouter credit usage (in USD) for the API key"""
usage_daily: float
r"""OpenRouter credit usage (in USD) for the current UTC day"""
usage_weekly: float
r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)"""
usage_monthly: float
r"""OpenRouter credit usage (in USD) for the current UTC month"""
byok_usage: float
r"""Total external BYOK usage (in USD) for the API key"""
byok_usage_daily: float
r"""External BYOK usage (in USD) for the current UTC day"""
byok_usage_weekly: float
r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)"""
byok_usage_monthly: float
r"""External BYOK usage (in USD) for current UTC month"""
is_free_tier: bool
r"""Whether this is a free tier API key"""
is_provisioning_key: bool
r"""Whether this is a provisioning key"""
limit_remaining: Nullable[float]
r"""Remaining spending limit in USD"""
limit_reset: Nullable[str]
r"""Type of limit reset for the API key"""
include_byok_in_limit: bool
r"""Whether to include external BYOK usage in the credit limit"""
rate_limit: RateLimitTypedDict
r"""Legacy rate limit information about a key. Will always return -1."""
expires_at: NotRequired[Nullable[datetime]]
r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration"""
class GetCurrentKeyData(BaseModel):
r"""Current API key information"""
label: str
r"""Human-readable label for the API key"""
limit: Nullable[float]
r"""Spending limit for the API key in USD"""
usage: float
r"""Total OpenRouter credit usage (in USD) for the API key"""
usage_daily: float
r"""OpenRouter credit usage (in USD) for the current UTC day"""
usage_weekly: float
r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)"""
usage_monthly: float
r"""OpenRouter credit usage (in USD) for the current UTC month"""
byok_usage: float
r"""Total external BYOK usage (in USD) for the API key"""
byok_usage_daily: float
r"""External BYOK usage (in USD) for the current UTC day"""
byok_usage_weekly: float
r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)"""
byok_usage_monthly: float
r"""External BYOK usage (in USD) for current UTC month"""
is_free_tier: bool
r"""Whether this is a free tier API key"""
is_provisioning_key: bool
r"""Whether this is a provisioning key"""
limit_remaining: Nullable[float]
r"""Remaining spending limit in USD"""
limit_reset: Nullable[str]
r"""Type of limit reset for the API key"""
include_byok_in_limit: bool
r"""Whether to include external BYOK usage in the credit limit"""
rate_limit: Annotated[
RateLimit,
pydantic.Field(
deprecated="warning: ** DEPRECATED ** - This will be removed in a future release, please migrate away from it as soon as possible."
),
]
r"""Legacy rate limit information about a key. Will always return -1."""
expires_at: OptionalNullable[datetime] = UNSET
r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["expires_at"]
nullable_fields = ["limit", "limit_remaining", "limit_reset", "expires_at"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class GetCurrentKeyResponseTypedDict(TypedDict):
r"""API key details"""
data: GetCurrentKeyDataTypedDict
r"""Current API key information"""
class GetCurrentKeyResponse(BaseModel):
r"""API key details"""
data: GetCurrentKeyData
r"""Current API key information"""
+268
View File
@@ -0,0 +1,268 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedStr
from openrouter.utils import FieldMetadata, QueryParamMetadata, validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Literal, Union
from typing_extensions import Annotated, TypedDict
class GetGenerationRequestTypedDict(TypedDict):
id: str
class GetGenerationRequest(BaseModel):
id: Annotated[
str, FieldMetadata(query=QueryParamMetadata(style="form", explode=True))
]
APIType = Union[
Literal[
"completions",
"embeddings",
],
UnrecognizedStr,
]
r"""Type of API used for the generation"""
class GetGenerationDataTypedDict(TypedDict):
r"""Generation data"""
id: str
r"""Unique identifier for the generation"""
upstream_id: Nullable[str]
r"""Upstream provider's identifier for this generation"""
total_cost: float
r"""Total cost of the generation in USD"""
cache_discount: Nullable[float]
r"""Discount applied due to caching"""
upstream_inference_cost: Nullable[float]
r"""Cost charged by the upstream provider"""
created_at: str
r"""ISO 8601 timestamp of when the generation was created"""
model: str
r"""Model used for the generation"""
app_id: Nullable[float]
r"""ID of the app that made the request"""
streamed: Nullable[bool]
r"""Whether the response was streamed"""
cancelled: Nullable[bool]
r"""Whether the generation was cancelled"""
provider_name: Nullable[str]
r"""Name of the provider that served the request"""
latency: Nullable[float]
r"""Total latency in milliseconds"""
moderation_latency: Nullable[float]
r"""Moderation latency in milliseconds"""
generation_time: Nullable[float]
r"""Time taken for generation in milliseconds"""
finish_reason: Nullable[str]
r"""Reason the generation finished"""
tokens_prompt: Nullable[float]
r"""Number of tokens in the prompt"""
tokens_completion: Nullable[float]
r"""Number of tokens in the completion"""
native_tokens_prompt: Nullable[float]
r"""Native prompt tokens as reported by provider"""
native_tokens_completion: Nullable[float]
r"""Native completion tokens as reported by provider"""
native_tokens_completion_images: Nullable[float]
r"""Native completion image tokens as reported by provider"""
native_tokens_reasoning: Nullable[float]
r"""Native reasoning tokens as reported by provider"""
native_tokens_cached: Nullable[float]
r"""Native cached tokens as reported by provider"""
num_media_prompt: Nullable[float]
r"""Number of media items in the prompt"""
num_input_audio_prompt: Nullable[float]
r"""Number of audio inputs in the prompt"""
num_media_completion: Nullable[float]
r"""Number of media items in the completion"""
num_search_results: Nullable[float]
r"""Number of search results included"""
origin: str
r"""Origin URL of the request"""
usage: float
r"""Usage amount in USD"""
is_byok: bool
r"""Whether this used bring-your-own-key"""
native_finish_reason: Nullable[str]
r"""Native finish reason as reported by provider"""
external_user: Nullable[str]
r"""External user identifier"""
api_type: Nullable[APIType]
r"""Type of API used for the generation"""
class GetGenerationData(BaseModel):
r"""Generation data"""
id: str
r"""Unique identifier for the generation"""
upstream_id: Nullable[str]
r"""Upstream provider's identifier for this generation"""
total_cost: float
r"""Total cost of the generation in USD"""
cache_discount: Nullable[float]
r"""Discount applied due to caching"""
upstream_inference_cost: Nullable[float]
r"""Cost charged by the upstream provider"""
created_at: str
r"""ISO 8601 timestamp of when the generation was created"""
model: str
r"""Model used for the generation"""
app_id: Nullable[float]
r"""ID of the app that made the request"""
streamed: Nullable[bool]
r"""Whether the response was streamed"""
cancelled: Nullable[bool]
r"""Whether the generation was cancelled"""
provider_name: Nullable[str]
r"""Name of the provider that served the request"""
latency: Nullable[float]
r"""Total latency in milliseconds"""
moderation_latency: Nullable[float]
r"""Moderation latency in milliseconds"""
generation_time: Nullable[float]
r"""Time taken for generation in milliseconds"""
finish_reason: Nullable[str]
r"""Reason the generation finished"""
tokens_prompt: Nullable[float]
r"""Number of tokens in the prompt"""
tokens_completion: Nullable[float]
r"""Number of tokens in the completion"""
native_tokens_prompt: Nullable[float]
r"""Native prompt tokens as reported by provider"""
native_tokens_completion: Nullable[float]
r"""Native completion tokens as reported by provider"""
native_tokens_completion_images: Nullable[float]
r"""Native completion image tokens as reported by provider"""
native_tokens_reasoning: Nullable[float]
r"""Native reasoning tokens as reported by provider"""
native_tokens_cached: Nullable[float]
r"""Native cached tokens as reported by provider"""
num_media_prompt: Nullable[float]
r"""Number of media items in the prompt"""
num_input_audio_prompt: Nullable[float]
r"""Number of audio inputs in the prompt"""
num_media_completion: Nullable[float]
r"""Number of media items in the completion"""
num_search_results: Nullable[float]
r"""Number of search results included"""
origin: str
r"""Origin URL of the request"""
usage: float
r"""Usage amount in USD"""
is_byok: bool
r"""Whether this used bring-your-own-key"""
native_finish_reason: Nullable[str]
r"""Native finish reason as reported by provider"""
external_user: Nullable[str]
r"""External user identifier"""
api_type: Annotated[Nullable[APIType], PlainValidator(validate_open_enum(False))]
r"""Type of API used for the generation"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = [
"upstream_id",
"cache_discount",
"upstream_inference_cost",
"app_id",
"streamed",
"cancelled",
"provider_name",
"latency",
"moderation_latency",
"generation_time",
"finish_reason",
"tokens_prompt",
"tokens_completion",
"native_tokens_prompt",
"native_tokens_completion",
"native_tokens_completion_images",
"native_tokens_reasoning",
"native_tokens_cached",
"num_media_prompt",
"num_input_audio_prompt",
"num_media_completion",
"num_search_results",
"native_finish_reason",
"external_user",
"api_type",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class GetGenerationResponseTypedDict(TypedDict):
r"""Generation response"""
data: GetGenerationDataTypedDict
r"""Generation data"""
class GetGenerationResponse(BaseModel):
r"""Generation response"""
data: GetGenerationData
r"""Generation data"""
+180
View File
@@ -0,0 +1,180 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from datetime import datetime
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import FieldMetadata, PathParamMetadata
from pydantic import model_serializer
from typing_extensions import Annotated, NotRequired, TypedDict
class GetKeyRequestTypedDict(TypedDict):
hash: str
r"""The hash identifier of the API key to retrieve"""
class GetKeyRequest(BaseModel):
hash: Annotated[
str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))
]
r"""The hash identifier of the API key to retrieve"""
class GetKeyDataTypedDict(TypedDict):
r"""The API key information"""
hash: str
r"""Unique hash identifier for the API key"""
name: str
r"""Name of the API key"""
label: str
r"""Human-readable label for the API key"""
disabled: bool
r"""Whether the API key is disabled"""
limit: Nullable[float]
r"""Spending limit for the API key in USD"""
limit_remaining: Nullable[float]
r"""Remaining spending limit in USD"""
limit_reset: Nullable[str]
r"""Type of limit reset for the API key"""
include_byok_in_limit: bool
r"""Whether to include external BYOK usage in the credit limit"""
usage: float
r"""Total OpenRouter credit usage (in USD) for the API key"""
usage_daily: float
r"""OpenRouter credit usage (in USD) for the current UTC day"""
usage_weekly: float
r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)"""
usage_monthly: float
r"""OpenRouter credit usage (in USD) for the current UTC month"""
byok_usage: float
r"""Total external BYOK usage (in USD) for the API key"""
byok_usage_daily: float
r"""External BYOK usage (in USD) for the current UTC day"""
byok_usage_weekly: float
r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)"""
byok_usage_monthly: float
r"""External BYOK usage (in USD) for current UTC month"""
created_at: str
r"""ISO 8601 timestamp of when the API key was created"""
updated_at: Nullable[str]
r"""ISO 8601 timestamp of when the API key was last updated"""
expires_at: NotRequired[Nullable[datetime]]
r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration"""
class GetKeyData(BaseModel):
r"""The API key information"""
hash: str
r"""Unique hash identifier for the API key"""
name: str
r"""Name of the API key"""
label: str
r"""Human-readable label for the API key"""
disabled: bool
r"""Whether the API key is disabled"""
limit: Nullable[float]
r"""Spending limit for the API key in USD"""
limit_remaining: Nullable[float]
r"""Remaining spending limit in USD"""
limit_reset: Nullable[str]
r"""Type of limit reset for the API key"""
include_byok_in_limit: bool
r"""Whether to include external BYOK usage in the credit limit"""
usage: float
r"""Total OpenRouter credit usage (in USD) for the API key"""
usage_daily: float
r"""OpenRouter credit usage (in USD) for the current UTC day"""
usage_weekly: float
r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)"""
usage_monthly: float
r"""OpenRouter credit usage (in USD) for the current UTC month"""
byok_usage: float
r"""Total external BYOK usage (in USD) for the API key"""
byok_usage_daily: float
r"""External BYOK usage (in USD) for the current UTC day"""
byok_usage_weekly: float
r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)"""
byok_usage_monthly: float
r"""External BYOK usage (in USD) for current UTC month"""
created_at: str
r"""ISO 8601 timestamp of when the API key was created"""
updated_at: Nullable[str]
r"""ISO 8601 timestamp of when the API key was last updated"""
expires_at: OptionalNullable[datetime] = UNSET
r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["expires_at"]
nullable_fields = [
"limit",
"limit_remaining",
"limit_reset",
"updated_at",
"expires_at",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class GetKeyResponseTypedDict(TypedDict):
r"""API key details"""
data: GetKeyDataTypedDict
r"""The API key information"""
class GetKeyResponse(BaseModel):
r"""API key details"""
data: GetKeyData
r"""The API key information"""
+24
View File
@@ -0,0 +1,24 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import FieldMetadata, QueryParamMetadata
from typing import Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class GetModelsRequestTypedDict(TypedDict):
category: NotRequired[str]
supported_parameters: NotRequired[str]
class GetModelsRequest(BaseModel):
category: Annotated[
Optional[str],
FieldMetadata(query=QueryParamMetadata(style="form", explode=True)),
] = None
supported_parameters: Annotated[
Optional[str],
FieldMetadata(query=QueryParamMetadata(style="form", explode=True)),
] = None
+195
View File
@@ -0,0 +1,195 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, UnrecognizedStr
from openrouter.utils import (
FieldMetadata,
PathParamMetadata,
QueryParamMetadata,
SecurityMetadata,
validate_open_enum,
)
from pydantic.functional_validators import PlainValidator
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
class GetParametersSecurityTypedDict(TypedDict):
bearer: str
class GetParametersSecurity(BaseModel):
bearer: Annotated[
str,
FieldMetadata(
security=SecurityMetadata(
scheme=True,
scheme_type="http",
sub_type="bearer",
field_name="Authorization",
)
),
]
GetParametersProvider = Union[
Literal[
"AI21",
"AionLabs",
"Alibaba",
"Amazon Bedrock",
"Anthropic",
"AtlasCloud",
"Atoma",
"Avian",
"Azure",
"BaseTen",
"Cerebras",
"Chutes",
"Cirrascale",
"Clarifai",
"Cloudflare",
"Cohere",
"CrofAI",
"Crusoe",
"DeepInfra",
"DeepSeek",
"Enfer",
"Featherless",
"Fireworks",
"Friendli",
"GMICloud",
"Google",
"Google AI Studio",
"Groq",
"Hyperbolic",
"Inception",
"InferenceNet",
"Infermatic",
"Inflection",
"Kluster",
"Lambda",
"Liquid",
"Mancer 2",
"Meta",
"Minimax",
"ModelRun",
"Mistral",
"Modular",
"Moonshot AI",
"Morph",
"NCompass",
"Nebius",
"NextBit",
"Nineteen",
"Novita",
"Nvidia",
"OpenAI",
"OpenInference",
"Parasail",
"Perplexity",
"Phala",
"Relace",
"SambaNova",
"SiliconFlow",
"Stealth",
"Switchpoint",
"Targon",
"Together",
"Ubicloud",
"Venice",
"WandB",
"xAI",
"Z.AI",
"FakeProvider",
],
UnrecognizedStr,
]
class GetParametersRequestTypedDict(TypedDict):
author: str
slug: str
provider: NotRequired[GetParametersProvider]
class GetParametersRequest(BaseModel):
author: Annotated[
str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))
]
slug: Annotated[
str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))
]
provider: Annotated[
Annotated[
Optional[GetParametersProvider], PlainValidator(validate_open_enum(False))
],
FieldMetadata(query=QueryParamMetadata(style="form", explode=True)),
] = None
SupportedParameter = Union[
Literal[
"temperature",
"top_p",
"top_k",
"min_p",
"top_a",
"frequency_penalty",
"presence_penalty",
"repetition_penalty",
"max_tokens",
"logit_bias",
"logprobs",
"top_logprobs",
"seed",
"response_format",
"structured_outputs",
"stop",
"tools",
"tool_choice",
"parallel_tool_calls",
"include_reasoning",
"reasoning",
"web_search_options",
"verbosity",
],
UnrecognizedStr,
]
class GetParametersDataTypedDict(TypedDict):
r"""Parameter analytics data"""
model: str
r"""Model identifier"""
supported_parameters: List[SupportedParameter]
r"""List of parameters supported by this model"""
class GetParametersData(BaseModel):
r"""Parameter analytics data"""
model: str
r"""Model identifier"""
supported_parameters: List[
Annotated[SupportedParameter, PlainValidator(validate_open_enum(False))]
]
r"""List of parameters supported by this model"""
class GetParametersResponseTypedDict(TypedDict):
r"""Returns the parameters for the specified model"""
data: GetParametersDataTypedDict
r"""Parameter analytics data"""
class GetParametersResponse(BaseModel):
r"""Returns the parameters for the specified model"""
data: GetParametersData
r"""Parameter analytics data"""
@@ -0,0 +1,37 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .activityitem import ActivityItem, ActivityItemTypedDict
from openrouter.types import BaseModel
from openrouter.utils import FieldMetadata, QueryParamMetadata
import pydantic
from typing import List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class GetUserActivityRequestTypedDict(TypedDict):
date_: NotRequired[str]
r"""Filter by a single UTC date in the last 30 days (YYYY-MM-DD format)."""
class GetUserActivityRequest(BaseModel):
date_: Annotated[
Optional[str],
pydantic.Field(alias="date"),
FieldMetadata(query=QueryParamMetadata(style="form", explode=True)),
] = None
r"""Filter by a single UTC date in the last 30 days (YYYY-MM-DD format)."""
class GetUserActivityResponseTypedDict(TypedDict):
r"""Returns user activity data grouped by endpoint"""
data: List[ActivityItemTypedDict]
r"""List of activity items"""
class GetUserActivityResponse(BaseModel):
r"""Returns user activity data grouped by endpoint"""
data: List[ActivityItem]
r"""List of activity items"""
@@ -0,0 +1,16 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import UnrecognizedStr
from typing import Literal, Union
ImageGenerationStatus = Union[
Literal[
"in_progress",
"completed",
"generating",
"failed",
],
UnrecognizedStr,
]
+17
View File
@@ -0,0 +1,17 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import UnrecognizedStr
from typing import Literal, Union
InputModality = Union[
Literal[
"text",
"image",
"file",
"audio",
"video",
],
UnrecognizedStr,
]
+35
View File
@@ -0,0 +1,35 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import UnrecognizedStr
from typing import Literal, Union
InstructType = Union[
Literal[
"none",
"airoboros",
"alpaca",
"alpaca-modif",
"chatml",
"claude",
"code-llama",
"gemma",
"llama2",
"llama3",
"mistral",
"nemotron",
"neural",
"openchat",
"phi3",
"rwkv",
"vicuna",
"zephyr",
"deepseek-r1",
"deepseek-v3.1",
"qwq",
"qwen3",
],
UnrecognizedStr,
]
r"""Instruction format type"""
@@ -0,0 +1,61 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import Any, Dict
from typing_extensions import NotRequired, TypedDict
class InternalServerResponseErrorDataTypedDict(TypedDict):
r"""Error data for InternalServerResponse"""
code: int
message: str
metadata: NotRequired[Nullable[Dict[str, Nullable[Any]]]]
class InternalServerResponseErrorData(BaseModel):
r"""Error data for InternalServerResponse"""
code: int
message: str
metadata: OptionalNullable[Dict[str, Nullable[Any]]] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["metadata"]
nullable_fields = ["metadata"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
+61
View File
@@ -0,0 +1,61 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
import pydantic
from pydantic import model_serializer
from typing import Any, Dict, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class JSONSchemaConfigTypedDict(TypedDict):
name: str
description: NotRequired[str]
schema_: NotRequired[Dict[str, Any]]
strict: NotRequired[Nullable[bool]]
class JSONSchemaConfig(BaseModel):
name: str
description: Optional[str] = None
schema_: Annotated[Optional[Dict[str, Any]], pydantic.Field(alias="schema")] = None
strict: OptionalNullable[bool] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["description", "schema", "strict"]
nullable_fields = ["strict"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
+36
View File
@@ -0,0 +1,36 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .listendpointsresponse import ListEndpointsResponse, ListEndpointsResponseTypedDict
from openrouter.types import BaseModel
from openrouter.utils import FieldMetadata, PathParamMetadata
from typing_extensions import Annotated, TypedDict
class ListEndpointsRequestTypedDict(TypedDict):
author: str
slug: str
class ListEndpointsRequest(BaseModel):
author: Annotated[
str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))
]
slug: Annotated[
str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False))
]
class EndpointsListEndpointsResponseTypedDict(TypedDict):
r"""Returns a list of endpoints"""
data: ListEndpointsResponseTypedDict
r"""List of available endpoints for a model"""
class EndpointsListEndpointsResponse(BaseModel):
r"""Returns a list of endpoints"""
data: ListEndpointsResponse
r"""List of available endpoints for a model"""
@@ -0,0 +1,145 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .inputmodality import InputModality
from .instructtype import InstructType
from .outputmodality import OutputModality
from .publicendpoint import PublicEndpoint, PublicEndpointTypedDict
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedStr
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import List, Literal, Union
from typing_extensions import Annotated, TypedDict
Tokenizer = Union[
Literal[
"Router",
"Media",
"Other",
"GPT",
"Claude",
"Gemini",
"Grok",
"Cohere",
"Nova",
"Qwen",
"Yi",
"DeepSeek",
"Mistral",
"Llama2",
"Llama3",
"Llama4",
"PaLM",
"RWKV",
"Qwen3",
],
UnrecognizedStr,
]
r"""Tokenizer type used by the model"""
class ArchitectureTypedDict(TypedDict):
r"""Model architecture information"""
tokenizer: Nullable[Tokenizer]
instruct_type: Nullable[InstructType]
r"""Instruction format type"""
modality: Nullable[str]
r"""Primary modality of the model"""
input_modalities: List[InputModality]
r"""Supported input modalities"""
output_modalities: List[OutputModality]
r"""Supported output modalities"""
class Architecture(BaseModel):
r"""Model architecture information"""
tokenizer: Annotated[Nullable[Tokenizer], PlainValidator(validate_open_enum(False))]
instruct_type: Annotated[
Nullable[InstructType], PlainValidator(validate_open_enum(False))
]
r"""Instruction format type"""
modality: Nullable[str]
r"""Primary modality of the model"""
input_modalities: List[
Annotated[InputModality, PlainValidator(validate_open_enum(False))]
]
r"""Supported input modalities"""
output_modalities: List[
Annotated[OutputModality, PlainValidator(validate_open_enum(False))]
]
r"""Supported output modalities"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["tokenizer", "instruct_type", "modality"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class ListEndpointsResponseTypedDict(TypedDict):
r"""List of available endpoints for a model"""
id: str
r"""Unique identifier for the model"""
name: str
r"""Display name of the model"""
created: float
r"""Unix timestamp of when the model was created"""
description: str
r"""Description of the model"""
architecture: ArchitectureTypedDict
endpoints: List[PublicEndpointTypedDict]
r"""List of available endpoints for this model"""
class ListEndpointsResponse(BaseModel):
r"""List of available endpoints for a model"""
id: str
r"""Unique identifier for the model"""
name: str
r"""Display name of the model"""
created: float
r"""Unix timestamp of when the model was created"""
description: str
r"""Description of the model"""
architecture: Architecture
endpoints: List[PublicEndpoint]
r"""List of available endpoints for this model"""
@@ -0,0 +1,19 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .publicendpoint import PublicEndpoint, PublicEndpointTypedDict
from openrouter.types import BaseModel
from typing import List
from typing_extensions import TypedDict
class ListEndpointsZdrResponseTypedDict(TypedDict):
r"""Returns a list of endpoints"""
data: List[PublicEndpointTypedDict]
class ListEndpointsZdrResponse(BaseModel):
r"""Returns a list of endpoints"""
data: List[PublicEndpoint]
+24
View File
@@ -0,0 +1,24 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import FieldMetadata, SecurityMetadata
from typing_extensions import Annotated, TypedDict
class ListModelsUserSecurityTypedDict(TypedDict):
bearer: str
class ListModelsUserSecurity(BaseModel):
bearer: Annotated[
str,
FieldMetadata(
security=SecurityMetadata(
scheme=True,
scheme_type="http",
sub_type="bearer",
field_name="Authorization",
)
),
]
+186
View File
@@ -0,0 +1,186 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from datetime import datetime
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import FieldMetadata, QueryParamMetadata
from pydantic import model_serializer
from typing import List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class ListRequestTypedDict(TypedDict):
include_disabled: NotRequired[str]
r"""Whether to include disabled API keys in the response"""
offset: NotRequired[str]
r"""Number of API keys to skip for pagination"""
class ListRequest(BaseModel):
include_disabled: Annotated[
Optional[str],
FieldMetadata(query=QueryParamMetadata(style="form", explode=True)),
] = None
r"""Whether to include disabled API keys in the response"""
offset: Annotated[
Optional[str],
FieldMetadata(query=QueryParamMetadata(style="form", explode=True)),
] = None
r"""Number of API keys to skip for pagination"""
class ListDataTypedDict(TypedDict):
hash: str
r"""Unique hash identifier for the API key"""
name: str
r"""Name of the API key"""
label: str
r"""Human-readable label for the API key"""
disabled: bool
r"""Whether the API key is disabled"""
limit: Nullable[float]
r"""Spending limit for the API key in USD"""
limit_remaining: Nullable[float]
r"""Remaining spending limit in USD"""
limit_reset: Nullable[str]
r"""Type of limit reset for the API key"""
include_byok_in_limit: bool
r"""Whether to include external BYOK usage in the credit limit"""
usage: float
r"""Total OpenRouter credit usage (in USD) for the API key"""
usage_daily: float
r"""OpenRouter credit usage (in USD) for the current UTC day"""
usage_weekly: float
r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)"""
usage_monthly: float
r"""OpenRouter credit usage (in USD) for the current UTC month"""
byok_usage: float
r"""Total external BYOK usage (in USD) for the API key"""
byok_usage_daily: float
r"""External BYOK usage (in USD) for the current UTC day"""
byok_usage_weekly: float
r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)"""
byok_usage_monthly: float
r"""External BYOK usage (in USD) for current UTC month"""
created_at: str
r"""ISO 8601 timestamp of when the API key was created"""
updated_at: Nullable[str]
r"""ISO 8601 timestamp of when the API key was last updated"""
expires_at: NotRequired[Nullable[datetime]]
r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration"""
class ListData(BaseModel):
hash: str
r"""Unique hash identifier for the API key"""
name: str
r"""Name of the API key"""
label: str
r"""Human-readable label for the API key"""
disabled: bool
r"""Whether the API key is disabled"""
limit: Nullable[float]
r"""Spending limit for the API key in USD"""
limit_remaining: Nullable[float]
r"""Remaining spending limit in USD"""
limit_reset: Nullable[str]
r"""Type of limit reset for the API key"""
include_byok_in_limit: bool
r"""Whether to include external BYOK usage in the credit limit"""
usage: float
r"""Total OpenRouter credit usage (in USD) for the API key"""
usage_daily: float
r"""OpenRouter credit usage (in USD) for the current UTC day"""
usage_weekly: float
r"""OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday)"""
usage_monthly: float
r"""OpenRouter credit usage (in USD) for the current UTC month"""
byok_usage: float
r"""Total external BYOK usage (in USD) for the API key"""
byok_usage_daily: float
r"""External BYOK usage (in USD) for the current UTC day"""
byok_usage_weekly: float
r"""External BYOK usage (in USD) for the current UTC week (Monday-Sunday)"""
byok_usage_monthly: float
r"""External BYOK usage (in USD) for current UTC month"""
created_at: str
r"""ISO 8601 timestamp of when the API key was created"""
updated_at: Nullable[str]
r"""ISO 8601 timestamp of when the API key was last updated"""
expires_at: OptionalNullable[datetime] = UNSET
r"""ISO 8601 UTC timestamp when the API key expires, or null if no expiration"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["expires_at"]
nullable_fields = [
"limit",
"limit_remaining",
"limit_reset",
"updated_at",
"expires_at",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class ListResponseTypedDict(TypedDict):
r"""List of API keys"""
data: List[ListDataTypedDict]
r"""List of API keys"""
class ListResponse(BaseModel):
r"""List of API keys"""
data: List[ListData]
r"""List of API keys"""
+89
View File
@@ -0,0 +1,89 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer
from typing import List
from typing_extensions import NotRequired, TypedDict
class ListProvidersDataTypedDict(TypedDict):
name: str
r"""Display name of the provider"""
slug: str
r"""URL-friendly identifier for the provider"""
privacy_policy_url: Nullable[str]
r"""URL to the provider's privacy policy"""
terms_of_service_url: NotRequired[Nullable[str]]
r"""URL to the provider's terms of service"""
status_page_url: NotRequired[Nullable[str]]
r"""URL to the provider's status page"""
class ListProvidersData(BaseModel):
name: str
r"""Display name of the provider"""
slug: str
r"""URL-friendly identifier for the provider"""
privacy_policy_url: Nullable[str]
r"""URL to the provider's privacy policy"""
terms_of_service_url: OptionalNullable[str] = UNSET
r"""URL to the provider's terms of service"""
status_page_url: OptionalNullable[str] = UNSET
r"""URL to the provider's status page"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["terms_of_service_url", "status_page_url"]
nullable_fields = [
"privacy_policy_url",
"terms_of_service_url",
"status_page_url",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
class ListProvidersResponseTypedDict(TypedDict):
r"""Returns a list of providers"""
data: List[ListProvidersDataTypedDict]
class ListProvidersResponse(BaseModel):
r"""Returns a list of providers"""
data: List[ListProvidersData]
+68
View File
@@ -0,0 +1,68 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .assistantmessage import AssistantMessage, AssistantMessageTypedDict
from .chatmessagecontentitemtext import (
ChatMessageContentItemText,
ChatMessageContentItemTextTypedDict,
)
from .systemmessage import SystemMessage, SystemMessageTypedDict
from .toolresponsemessage import ToolResponseMessage, ToolResponseMessageTypedDict
from .usermessage import UserMessage, UserMessageTypedDict
from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
MessageContentTypedDict = TypeAliasType(
"MessageContentTypedDict", Union[str, List[ChatMessageContentItemTextTypedDict]]
)
MessageContent = TypeAliasType(
"MessageContent", Union[str, List[ChatMessageContentItemText]]
)
class MessageDeveloperTypedDict(TypedDict):
content: MessageContentTypedDict
role: Literal["developer"]
name: NotRequired[str]
class MessageDeveloper(BaseModel):
content: MessageContent
ROLE: Annotated[
Annotated[Literal["developer"], AfterValidator(validate_const("developer"))],
pydantic.Field(alias="role"),
] = "developer"
name: Optional[str] = None
MessageTypedDict = TypeAliasType(
"MessageTypedDict",
Union[
SystemMessageTypedDict,
UserMessageTypedDict,
MessageDeveloperTypedDict,
ToolResponseMessageTypedDict,
AssistantMessageTypedDict,
],
)
Message = TypeAliasType(
"Message",
Union[
SystemMessage,
UserMessage,
MessageDeveloper,
ToolResponseMessage,
AssistantMessage,
],
)
+132
View File
@@ -0,0 +1,132 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .defaultparameters import DefaultParameters, DefaultParametersTypedDict
from .modelarchitecture import ModelArchitecture, ModelArchitectureTypedDict
from .parameter import Parameter
from .perrequestlimits import PerRequestLimits, PerRequestLimitsTypedDict
from .publicpricing import PublicPricing, PublicPricingTypedDict
from .topproviderinfo import TopProviderInfo, TopProviderInfoTypedDict
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import List, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class ModelTypedDict(TypedDict):
r"""Information about an AI model available on OpenRouter"""
id: str
r"""Unique identifier for the model"""
canonical_slug: str
r"""Canonical slug for the model"""
name: str
r"""Display name of the model"""
created: float
r"""Unix timestamp of when the model was created"""
pricing: PublicPricingTypedDict
r"""Pricing information for the model"""
context_length: Nullable[float]
r"""Maximum context length in tokens"""
architecture: ModelArchitectureTypedDict
r"""Model architecture information"""
top_provider: TopProviderInfoTypedDict
r"""Information about the top provider for this model"""
per_request_limits: Nullable[PerRequestLimitsTypedDict]
r"""Per-request token limits"""
supported_parameters: List[Parameter]
r"""List of supported parameters for this model"""
default_parameters: Nullable[DefaultParametersTypedDict]
r"""Default parameters for this model"""
hugging_face_id: NotRequired[Nullable[str]]
r"""Hugging Face model identifier, if applicable"""
description: NotRequired[str]
r"""Description of the model"""
class Model(BaseModel):
r"""Information about an AI model available on OpenRouter"""
id: str
r"""Unique identifier for the model"""
canonical_slug: str
r"""Canonical slug for the model"""
name: str
r"""Display name of the model"""
created: float
r"""Unix timestamp of when the model was created"""
pricing: PublicPricing
r"""Pricing information for the model"""
context_length: Nullable[float]
r"""Maximum context length in tokens"""
architecture: ModelArchitecture
r"""Model architecture information"""
top_provider: TopProviderInfo
r"""Information about the top provider for this model"""
per_request_limits: Nullable[PerRequestLimits]
r"""Per-request token limits"""
supported_parameters: List[
Annotated[Parameter, PlainValidator(validate_open_enum(False))]
]
r"""List of supported parameters for this model"""
default_parameters: Nullable[DefaultParameters]
r"""Default parameters for this model"""
hugging_face_id: OptionalNullable[str] = UNSET
r"""Hugging Face model identifier, if applicable"""
description: Optional[str] = None
r"""Description of the model"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["hugging_face_id", "description"]
nullable_fields = [
"hugging_face_id",
"context_length",
"per_request_limits",
"default_parameters",
]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m

Some files were not shown because too many files have changed in this diff Show More