Commits included in this export:

- e1074ff86fccf5e48406b7595298873106d3cc5a
  - 123bbdaf841d299162a82ee2573adfbb70a45b8f
  - ac457b8a8dad98fdf5ddcae8dd4711361cea3084
  - ea825199f4c59dd68fec01cf8d18a582963c9f25
  - 4d48e4f6bb936e785787314a965298da6b78fea0
  - 718729a573ee98893a4408d5a52ab4686661fe54
  - b867adcde6b64f3f2a11c4626254b39098e4b0b4
  - 21912c097b4066d109766c6b4492826595cd57c5
  - bc1ed85adc976a4634ca8a41b82e4fc2c39a864f
  - d145c89c941937a312ed1357590d2bfda9a3603d
  - 12f05b5dee397ead47cfcd545a7a2e3c7ff57524
  - dd28f75a19a015809797c7abf3f8758f7c37262e
  - c96e569781e07ab44172d9c69940ec17bafd81f4
  - c9d5a90e3c2b5077a2bdd49773f1a46d1a5a79c7
  - 58b08f87116ceab9076de2fdc0a4c74c919b44c4

GitOrigin-RevId: e1074ff86fccf5e48406b7595298873106d3cc5a
This commit is contained in:
OpenRouter Team
2026-01-28 18:45:29 +00:00
parent 0c791b04d1
commit bf339d9530
51 changed files with 787 additions and 2048 deletions
+2 -2
View File
@@ -3,10 +3,10 @@
import importlib.metadata
__title__: str = "openrouter"
__version__: str = "0.1.3"
__version__: str = "0.3.2"
__openapi_doc_version__: str = "1.0.0"
__gen_version__: str = "2.768.0"
__user_agent__: str = "speakeasy-sdk/python 0.1.3 2.768.0 1.0.0 openrouter"
__user_agent__: str = "speakeasy-sdk/python 0.3.2 2.768.0 1.0.0 openrouter"
try:
if __package__ is not None:
+14 -52
View File
@@ -50,17 +50,11 @@ class Chat(BaseSDK):
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
response_format: Optional[
Union[
components.ChatGenerationParamsResponseFormatUnion,
components.ChatGenerationParamsResponseFormatUnionTypedDict,
]
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
components.ChatGenerationParamsStop,
components.ChatGenerationParamsStopTypedDict,
]
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stream: Union[Literal[False], None] = None,
stream_options: OptionalNullable[
@@ -162,17 +156,11 @@ class Chat(BaseSDK):
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
response_format: Optional[
Union[
components.ChatGenerationParamsResponseFormatUnion,
components.ChatGenerationParamsResponseFormatUnionTypedDict,
]
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
components.ChatGenerationParamsStop,
components.ChatGenerationParamsStopTypedDict,
]
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stream: Literal[True],
stream_options: OptionalNullable[
@@ -273,17 +261,11 @@ class Chat(BaseSDK):
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
response_format: Optional[
Union[
components.ChatGenerationParamsResponseFormatUnion,
components.ChatGenerationParamsResponseFormatUnionTypedDict,
]
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
components.ChatGenerationParamsStop,
components.ChatGenerationParamsStopTypedDict,
]
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
@@ -385,8 +367,7 @@ class Chat(BaseSDK):
reasoning, Optional[components.Reasoning]
),
response_format=utils.get_pydantic_model(
response_format,
Optional[components.ChatGenerationParamsResponseFormatUnion],
response_format, Optional[components.ResponseFormat]
),
seed=seed,
stop=stop,
@@ -526,17 +507,11 @@ class Chat(BaseSDK):
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
response_format: Optional[
Union[
components.ChatGenerationParamsResponseFormatUnion,
components.ChatGenerationParamsResponseFormatUnionTypedDict,
]
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
components.ChatGenerationParamsStop,
components.ChatGenerationParamsStopTypedDict,
]
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stream: Union[Literal[False], None] = None,
stream_options: OptionalNullable[
@@ -638,17 +613,11 @@ class Chat(BaseSDK):
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
response_format: Optional[
Union[
components.ChatGenerationParamsResponseFormatUnion,
components.ChatGenerationParamsResponseFormatUnionTypedDict,
]
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
components.ChatGenerationParamsStop,
components.ChatGenerationParamsStopTypedDict,
]
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stream: Literal[True],
stream_options: OptionalNullable[
@@ -749,17 +718,11 @@ class Chat(BaseSDK):
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
response_format: Optional[
Union[
components.ChatGenerationParamsResponseFormatUnion,
components.ChatGenerationParamsResponseFormatUnionTypedDict,
]
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[
Union[
components.ChatGenerationParamsStop,
components.ChatGenerationParamsStopTypedDict,
]
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
@@ -861,8 +824,7 @@ class Chat(BaseSDK):
reasoning, Optional[components.Reasoning]
),
response_format=utils.get_pydantic_model(
response_format,
Optional[components.ChatGenerationParamsResponseFormatUnion],
response_format, Optional[components.ResponseFormat]
),
seed=seed,
stop=stop,
-361
View File
@@ -1,361 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from openrouter import components, errors, 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[components.Prompt, components.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[
components.CompletionCreateParamsStop,
components.CompletionCreateParamsStopTypedDict,
]
] = UNSET,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
Union[components.StreamOptions, components.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[
components.CompletionCreateParamsResponseFormatUnion,
components.CompletionCreateParamsResponseFormatUnionTypedDict,
]
] = UNSET,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.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 = components.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[components.StreamOptions]
),
suffix=suffix,
temperature=temperature,
top_p=top_p,
user=user,
metadata=metadata,
response_format=utils.get_pydantic_model(
response_format,
OptionalNullable[components.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", components.CompletionCreateParams
),
allow_empty_value=None,
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, components.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(components.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[components.Prompt, components.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[
components.CompletionCreateParamsStop,
components.CompletionCreateParamsStopTypedDict,
]
] = UNSET,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
Union[components.StreamOptions, components.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[
components.CompletionCreateParamsResponseFormatUnion,
components.CompletionCreateParamsResponseFormatUnionTypedDict,
]
] = UNSET,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.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 = components.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[components.StreamOptions]
),
suffix=suffix,
temperature=temperature,
top_p=top_p,
user=user,
metadata=metadata,
response_format=utils.get_pydantic_model(
response_format,
OptionalNullable[components.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", components.CompletionCreateParams
),
allow_empty_value=None,
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, components.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(components.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)
+30 -106
View File
@@ -68,16 +68,6 @@ if TYPE_CHECKING:
ChatGenerationParamsPreferredMinThroughputUnionTypedDict,
ChatGenerationParamsProvider,
ChatGenerationParamsProviderTypedDict,
ChatGenerationParamsResponseFormatJSONObject,
ChatGenerationParamsResponseFormatJSONObjectTypedDict,
ChatGenerationParamsResponseFormatPython,
ChatGenerationParamsResponseFormatPythonTypedDict,
ChatGenerationParamsResponseFormatText,
ChatGenerationParamsResponseFormatTextTypedDict,
ChatGenerationParamsResponseFormatUnion,
ChatGenerationParamsResponseFormatUnionTypedDict,
ChatGenerationParamsStop,
ChatGenerationParamsStopTypedDict,
ChatGenerationParamsTypedDict,
Debug,
DebugTypedDict,
@@ -90,7 +80,17 @@ if TYPE_CHECKING:
Quantizations,
Reasoning,
ReasoningTypedDict,
ResponseFormat,
ResponseFormatJSONObject,
ResponseFormatJSONObjectTypedDict,
ResponseFormatPython,
ResponseFormatPythonTypedDict,
ResponseFormatText,
ResponseFormatTextTypedDict,
ResponseFormatTypedDict,
Route,
Stop,
StopTypedDict,
)
from .chatgenerationtokenusage import (
ChatGenerationTokenUsage,
@@ -177,32 +177,6 @@ if TYPE_CHECKING:
ChatStreamingResponseChunkTypedDict,
)
from .chatstreamoptions import ChatStreamOptions, ChatStreamOptionsTypedDict
from .completionchoice import (
CompletionChoice,
CompletionChoiceTypedDict,
CompletionFinishReason,
)
from .completioncreateparams import (
CompletionCreateParams,
CompletionCreateParamsResponseFormatJSONObject,
CompletionCreateParamsResponseFormatJSONObjectTypedDict,
CompletionCreateParamsResponseFormatPython,
CompletionCreateParamsResponseFormatPythonTypedDict,
CompletionCreateParamsResponseFormatText,
CompletionCreateParamsResponseFormatTextTypedDict,
CompletionCreateParamsResponseFormatUnion,
CompletionCreateParamsResponseFormatUnionTypedDict,
CompletionCreateParamsStop,
CompletionCreateParamsStopTypedDict,
CompletionCreateParamsTypedDict,
Prompt,
PromptTypedDict,
StreamOptions,
StreamOptionsTypedDict,
)
from .completionlogprobs import CompletionLogprobs, CompletionLogprobsTypedDict
from .completionresponse import CompletionResponse, CompletionResponseTypedDict
from .completionusage import CompletionUsage, CompletionUsageTypedDict
from .createchargerequest import (
ChainID,
CreateChargeRequest,
@@ -956,16 +930,6 @@ __all__ = [
"ChatGenerationParamsPreferredMinThroughputUnionTypedDict",
"ChatGenerationParamsProvider",
"ChatGenerationParamsProviderTypedDict",
"ChatGenerationParamsResponseFormatJSONObject",
"ChatGenerationParamsResponseFormatJSONObjectTypedDict",
"ChatGenerationParamsResponseFormatPython",
"ChatGenerationParamsResponseFormatPythonTypedDict",
"ChatGenerationParamsResponseFormatText",
"ChatGenerationParamsResponseFormatTextTypedDict",
"ChatGenerationParamsResponseFormatUnion",
"ChatGenerationParamsResponseFormatUnionTypedDict",
"ChatGenerationParamsStop",
"ChatGenerationParamsStopTypedDict",
"ChatGenerationParamsTypedDict",
"ChatGenerationTokenUsage",
"ChatGenerationTokenUsageTypedDict",
@@ -1024,29 +988,8 @@ __all__ = [
"Code",
"CodeEnum",
"CodeTypedDict",
"CompletionChoice",
"CompletionChoiceTypedDict",
"CompletionCreateParams",
"CompletionCreateParamsResponseFormatJSONObject",
"CompletionCreateParamsResponseFormatJSONObjectTypedDict",
"CompletionCreateParamsResponseFormatPython",
"CompletionCreateParamsResponseFormatPythonTypedDict",
"CompletionCreateParamsResponseFormatText",
"CompletionCreateParamsResponseFormatTextTypedDict",
"CompletionCreateParamsResponseFormatUnion",
"CompletionCreateParamsResponseFormatUnionTypedDict",
"CompletionCreateParamsStop",
"CompletionCreateParamsStopTypedDict",
"CompletionCreateParamsTypedDict",
"CompletionFinishReason",
"CompletionLogprobs",
"CompletionLogprobsTypedDict",
"CompletionResponse",
"CompletionResponseTypedDict",
"CompletionTokensDetails",
"CompletionTokensDetailsTypedDict",
"CompletionUsage",
"CompletionUsageTypedDict",
"CostDetails",
"CostDetailsTypedDict",
"CreateChargeRequest",
@@ -1406,10 +1349,8 @@ __all__ = [
"PreferredMinThroughputTypedDict",
"Pricing",
"PricingTypedDict",
"Prompt",
"PromptTokensDetails",
"PromptTokensDetailsTypedDict",
"PromptTypedDict",
"ProviderName",
"ProviderOverloadedResponseErrorData",
"ProviderOverloadedResponseErrorDataTypedDict",
@@ -1456,12 +1397,20 @@ __all__ = [
"ReasoningTypedDict",
"RequestTimeoutResponseErrorData",
"RequestTimeoutResponseErrorDataTypedDict",
"ResponseFormat",
"ResponseFormatJSONObject",
"ResponseFormatJSONObjectTypedDict",
"ResponseFormatJSONSchema",
"ResponseFormatJSONSchemaTypedDict",
"ResponseFormatPython",
"ResponseFormatPythonTypedDict",
"ResponseFormatText",
"ResponseFormatTextConfig",
"ResponseFormatTextConfigTypedDict",
"ResponseFormatTextGrammar",
"ResponseFormatTextGrammarTypedDict",
"ResponseFormatTextTypedDict",
"ResponseFormatTypedDict",
"ResponseInputAudio",
"ResponseInputAudioFormat",
"ResponseInputAudioInputAudio",
@@ -1563,8 +1512,8 @@ __all__ = [
"ServiceUnavailableResponseErrorData",
"ServiceUnavailableResponseErrorDataTypedDict",
"SortEnum",
"StreamOptions",
"StreamOptionsTypedDict",
"Stop",
"StopTypedDict",
"SystemMessage",
"SystemMessageContent",
"SystemMessageContentTypedDict",
@@ -1688,16 +1637,6 @@ _dynamic_imports: dict[str, str] = {
"ChatGenerationParamsPreferredMinThroughputUnionTypedDict": ".chatgenerationparams",
"ChatGenerationParamsProvider": ".chatgenerationparams",
"ChatGenerationParamsProviderTypedDict": ".chatgenerationparams",
"ChatGenerationParamsResponseFormatJSONObject": ".chatgenerationparams",
"ChatGenerationParamsResponseFormatJSONObjectTypedDict": ".chatgenerationparams",
"ChatGenerationParamsResponseFormatPython": ".chatgenerationparams",
"ChatGenerationParamsResponseFormatPythonTypedDict": ".chatgenerationparams",
"ChatGenerationParamsResponseFormatText": ".chatgenerationparams",
"ChatGenerationParamsResponseFormatTextTypedDict": ".chatgenerationparams",
"ChatGenerationParamsResponseFormatUnion": ".chatgenerationparams",
"ChatGenerationParamsResponseFormatUnionTypedDict": ".chatgenerationparams",
"ChatGenerationParamsStop": ".chatgenerationparams",
"ChatGenerationParamsStopTypedDict": ".chatgenerationparams",
"ChatGenerationParamsTypedDict": ".chatgenerationparams",
"Debug": ".chatgenerationparams",
"DebugTypedDict": ".chatgenerationparams",
@@ -1710,7 +1649,17 @@ _dynamic_imports: dict[str, str] = {
"Quantizations": ".chatgenerationparams",
"Reasoning": ".chatgenerationparams",
"ReasoningTypedDict": ".chatgenerationparams",
"ResponseFormat": ".chatgenerationparams",
"ResponseFormatJSONObject": ".chatgenerationparams",
"ResponseFormatJSONObjectTypedDict": ".chatgenerationparams",
"ResponseFormatPython": ".chatgenerationparams",
"ResponseFormatPythonTypedDict": ".chatgenerationparams",
"ResponseFormatText": ".chatgenerationparams",
"ResponseFormatTextTypedDict": ".chatgenerationparams",
"ResponseFormatTypedDict": ".chatgenerationparams",
"Route": ".chatgenerationparams",
"Stop": ".chatgenerationparams",
"StopTypedDict": ".chatgenerationparams",
"ChatGenerationTokenUsage": ".chatgenerationtokenusage",
"ChatGenerationTokenUsageTypedDict": ".chatgenerationtokenusage",
"CompletionTokensDetails": ".chatgenerationtokenusage",
@@ -1774,31 +1723,6 @@ _dynamic_imports: dict[str, str] = {
"ChatStreamingResponseChunkTypedDict": ".chatstreamingresponsechunk",
"ChatStreamOptions": ".chatstreamoptions",
"ChatStreamOptionsTypedDict": ".chatstreamoptions",
"CompletionChoice": ".completionchoice",
"CompletionChoiceTypedDict": ".completionchoice",
"CompletionFinishReason": ".completionchoice",
"CompletionCreateParams": ".completioncreateparams",
"CompletionCreateParamsResponseFormatJSONObject": ".completioncreateparams",
"CompletionCreateParamsResponseFormatJSONObjectTypedDict": ".completioncreateparams",
"CompletionCreateParamsResponseFormatPython": ".completioncreateparams",
"CompletionCreateParamsResponseFormatPythonTypedDict": ".completioncreateparams",
"CompletionCreateParamsResponseFormatText": ".completioncreateparams",
"CompletionCreateParamsResponseFormatTextTypedDict": ".completioncreateparams",
"CompletionCreateParamsResponseFormatUnion": ".completioncreateparams",
"CompletionCreateParamsResponseFormatUnionTypedDict": ".completioncreateparams",
"CompletionCreateParamsStop": ".completioncreateparams",
"CompletionCreateParamsStopTypedDict": ".completioncreateparams",
"CompletionCreateParamsTypedDict": ".completioncreateparams",
"Prompt": ".completioncreateparams",
"PromptTypedDict": ".completioncreateparams",
"StreamOptions": ".completioncreateparams",
"StreamOptionsTypedDict": ".completioncreateparams",
"CompletionLogprobs": ".completionlogprobs",
"CompletionLogprobsTypedDict": ".completionlogprobs",
"CompletionResponse": ".completionresponse",
"CompletionResponseTypedDict": ".completionresponse",
"CompletionUsage": ".completionusage",
"CompletionUsageTypedDict": ".completionusage",
"ChainID": ".createchargerequest",
"CreateChargeRequest": ".createchargerequest",
"CreateChargeRequestTypedDict": ".createchargerequest",
+1
View File
@@ -13,6 +13,7 @@ Schema0Enum = Union[
"AI21",
"AionLabs",
"Alibaba",
"Ambient",
"Amazon Bedrock",
"Amazon Nova",
"Anthropic",
@@ -562,22 +562,22 @@ class Reasoning(BaseModel):
return m
class ChatGenerationParamsResponseFormatPythonTypedDict(TypedDict):
class ResponseFormatPythonTypedDict(TypedDict):
type: Literal["python"]
class ChatGenerationParamsResponseFormatPython(BaseModel):
class ResponseFormatPython(BaseModel):
TYPE: Annotated[
Annotated[Literal["python"], AfterValidator(validate_const("python"))],
pydantic.Field(alias="type"),
] = "python"
class ChatGenerationParamsResponseFormatJSONObjectTypedDict(TypedDict):
class ResponseFormatJSONObjectTypedDict(TypedDict):
type: Literal["json_object"]
class ChatGenerationParamsResponseFormatJSONObject(BaseModel):
class ResponseFormatJSONObject(BaseModel):
TYPE: Annotated[
Annotated[
Literal["json_object"], AfterValidator(validate_const("json_object"))
@@ -586,49 +586,45 @@ class ChatGenerationParamsResponseFormatJSONObject(BaseModel):
] = "json_object"
class ChatGenerationParamsResponseFormatTextTypedDict(TypedDict):
class ResponseFormatTextTypedDict(TypedDict):
type: Literal["text"]
class ChatGenerationParamsResponseFormatText(BaseModel):
class ResponseFormatText(BaseModel):
TYPE: Annotated[
Annotated[Literal["text"], AfterValidator(validate_const("text"))],
pydantic.Field(alias="type"),
] = "text"
ChatGenerationParamsResponseFormatUnionTypedDict = TypeAliasType(
"ChatGenerationParamsResponseFormatUnionTypedDict",
ResponseFormatTypedDict = TypeAliasType(
"ResponseFormatTypedDict",
Union[
ChatGenerationParamsResponseFormatTextTypedDict,
ChatGenerationParamsResponseFormatJSONObjectTypedDict,
ChatGenerationParamsResponseFormatPythonTypedDict,
ResponseFormatTextTypedDict,
ResponseFormatJSONObjectTypedDict,
ResponseFormatPythonTypedDict,
ResponseFormatJSONSchemaTypedDict,
ResponseFormatTextGrammarTypedDict,
],
)
ChatGenerationParamsResponseFormatUnion = Annotated[
ResponseFormat = Annotated[
Union[
Annotated[ChatGenerationParamsResponseFormatText, Tag("text")],
Annotated[ChatGenerationParamsResponseFormatJSONObject, Tag("json_object")],
Annotated[ResponseFormatText, Tag("text")],
Annotated[ResponseFormatJSONObject, Tag("json_object")],
Annotated[ResponseFormatJSONSchema, Tag("json_schema")],
Annotated[ResponseFormatTextGrammar, Tag("grammar")],
Annotated[ChatGenerationParamsResponseFormatPython, Tag("python")],
Annotated[ResponseFormatPython, Tag("python")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
ChatGenerationParamsStopTypedDict = TypeAliasType(
"ChatGenerationParamsStopTypedDict", Union[str, List[str]]
)
StopTypedDict = TypeAliasType("StopTypedDict", Union[str, List[str]])
ChatGenerationParamsStop = TypeAliasType(
"ChatGenerationParamsStop", Union[str, List[str]]
)
Stop = TypeAliasType("Stop", Union[str, List[str]])
class DebugTypedDict(TypedDict):
@@ -679,9 +675,9 @@ class ChatGenerationParamsTypedDict(TypedDict):
metadata: NotRequired[Dict[str, str]]
presence_penalty: NotRequired[Nullable[float]]
reasoning: NotRequired[ReasoningTypedDict]
response_format: NotRequired[ChatGenerationParamsResponseFormatUnionTypedDict]
response_format: NotRequired[ResponseFormatTypedDict]
seed: NotRequired[Nullable[int]]
stop: NotRequired[Nullable[ChatGenerationParamsStopTypedDict]]
stop: NotRequired[Nullable[StopTypedDict]]
stream: NotRequired[bool]
stream_options: NotRequired[Nullable[ChatStreamOptionsTypedDict]]
temperature: NotRequired[Nullable[float]]
@@ -733,11 +729,11 @@ class ChatGenerationParams(BaseModel):
reasoning: Optional[Reasoning] = None
response_format: Optional[ChatGenerationParamsResponseFormatUnion] = None
response_format: Optional[ResponseFormat] = None
seed: OptionalNullable[int] = UNSET
stop: OptionalNullable[ChatGenerationParamsStop] = UNSET
stop: OptionalNullable[Stop] = UNSET
stream: Optional[bool] = False
@@ -1,82 +0,0 @@
"""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,
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
CompletionFinishReason = Union[
Literal[
"stop",
"length",
"content_filter",
],
UnrecognizedStr,
]
class CompletionChoiceTypedDict(TypedDict):
text: str
index: float
logprobs: Nullable[CompletionLogprobsTypedDict]
finish_reason: Nullable[CompletionFinishReason]
native_finish_reason: NotRequired[str]
reasoning: NotRequired[Nullable[str]]
class CompletionChoice(BaseModel):
text: str
index: float
logprobs: Nullable[CompletionLogprobs]
finish_reason: Annotated[
Nullable[CompletionFinishReason], PlainValidator(validate_open_enum(False))
]
native_finish_reason: Optional[str] = None
reasoning: OptionalNullable[str] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["native_finish_reason", "reasoning"]
nullable_fields = ["logprobs", "finish_reason", "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
@@ -1,277 +0,0 @@
"""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 get_discriminator, validate_const
import pydantic
from pydantic import Discriminator, Tag, 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 = Annotated[
Union[
Annotated[CompletionCreateParamsResponseFormatText, Tag("text")],
Annotated[CompletionCreateParamsResponseFormatJSONObject, Tag("json_object")],
Annotated[ResponseFormatJSONSchema, Tag("json_schema")],
Annotated[ResponseFormatTextGrammar, Tag("grammar")],
Annotated[CompletionCreateParamsResponseFormatPython, Tag("python")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
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
@@ -1,54 +0,0 @@
"""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
@@ -1,46 +0,0 @@
"""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"]
provider: NotRequired[str]
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"
provider: Optional[str] = None
system_fingerprint: Optional[str] = None
usage: Optional[CompletionUsage] = None
@@ -1,19 +0,0 @@
"""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
@@ -10,6 +10,7 @@ ProviderName = Union[
"AI21",
"AionLabs",
"Alibaba",
"Ambient",
"Amazon Bedrock",
"Amazon Nova",
"Anthropic",
+18 -4
View File
@@ -394,7 +394,9 @@ class Models(BaseSDK):
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.ModelsListResponse:
r"""List models filtered by user provider preferences
r"""List models filtered by user provider preferences, privacy settings, and guardrails
List models filtered by user provider preferences, [privacy settings](https://openrouter.ai/docs/guides/privacy/logging), and [guardrails](https://openrouter.ai/docs/guides/features/guardrails). If requesting through `eu.openrouter.ai/api/v1/...` the results will be filtered to models that satisfy [EU in-region routing](https://openrouter.ai/docs/guides/privacy/logging#enterprise-eu-in-region-routing).
:param security:
:param retries: Override the default retry configuration for this method
@@ -447,7 +449,7 @@ class Models(BaseSDK):
security_source=get_security_from_env(security, components.Security),
),
request=req,
error_status_codes=["401", "4XX", "500", "5XX"],
error_status_codes=["401", "404", "4XX", "500", "5XX"],
retry_config=retry_config,
)
@@ -459,6 +461,11 @@ class Models(BaseSDK):
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(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, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
@@ -489,7 +496,9 @@ class Models(BaseSDK):
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.ModelsListResponse:
r"""List models filtered by user provider preferences
r"""List models filtered by user provider preferences, privacy settings, and guardrails
List models filtered by user provider preferences, [privacy settings](https://openrouter.ai/docs/guides/privacy/logging), and [guardrails](https://openrouter.ai/docs/guides/features/guardrails). If requesting through `eu.openrouter.ai/api/v1/...` the results will be filtered to models that satisfy [EU in-region routing](https://openrouter.ai/docs/guides/privacy/logging#enterprise-eu-in-region-routing).
:param security:
:param retries: Override the default retry configuration for this method
@@ -542,7 +551,7 @@ class Models(BaseSDK):
security_source=get_security_from_env(security, components.Security),
),
request=req,
error_status_codes=["401", "4XX", "500", "5XX"],
error_status_codes=["401", "404", "4XX", "500", "5XX"],
retry_config=retry_config,
)
@@ -554,6 +563,11 @@ class Models(BaseSDK):
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(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, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
+9
View File
@@ -160,6 +160,9 @@ if TYPE_CHECKING:
GetGenerationRequestTypedDict,
GetGenerationResponse,
GetGenerationResponseTypedDict,
ProviderName,
ProviderResponse,
ProviderResponseTypedDict,
)
from .getguardrail import (
GetGuardrailData,
@@ -462,6 +465,9 @@ __all__ = [
"MetadataTypedDict",
"Object",
"ObjectEmbedding",
"ProviderName",
"ProviderResponse",
"ProviderResponseTypedDict",
"RateLimit",
"RateLimitTypedDict",
"SendChatCompletionRequestResponse",
@@ -619,6 +625,9 @@ _dynamic_imports: dict[str, str] = {
"GetGenerationRequestTypedDict": ".getgeneration",
"GetGenerationResponse": ".getgeneration",
"GetGenerationResponseTypedDict": ".getgeneration",
"ProviderName": ".getgeneration",
"ProviderResponse": ".getgeneration",
"ProviderResponseTypedDict": ".getgeneration",
"GetGuardrailData": ".getguardrail",
"GetGuardrailDataTypedDict": ".getguardrail",
"GetGuardrailRequest": ".getguardrail",
+179 -2
View File
@@ -5,8 +5,8 @@ from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedSt
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
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
class GetGenerationRequestTypedDict(TypedDict):
@@ -29,6 +29,177 @@ APIType = Union[
r"""Type of API used for the generation"""
ProviderName = Union[
Literal[
"AnyScale",
"Atoma",
"Cent-ML",
"CrofAI",
"Enfer",
"GoPomelo",
"HuggingFace",
"Hyperbolic 2",
"InoCloud",
"Kluster",
"Lambda",
"Lepton",
"Lynn 2",
"Lynn",
"Mancer",
"Meta",
"Modal",
"Nineteen",
"OctoAI",
"Recursal",
"Reflection",
"Replicate",
"SambaNova 2",
"SF Compute",
"Targon",
"Together 2",
"Ubicloud",
"01.AI",
"AI21",
"AionLabs",
"Alibaba",
"Ambient",
"Amazon Bedrock",
"Amazon Nova",
"Anthropic",
"Arcee AI",
"AtlasCloud",
"Avian",
"Azure",
"BaseTen",
"BytePlus",
"Black Forest Labs",
"Cerebras",
"Chutes",
"Cirrascale",
"Clarifai",
"Cloudflare",
"Cohere",
"Crusoe",
"DeepInfra",
"DeepSeek",
"Featherless",
"Fireworks",
"Friendli",
"GMICloud",
"Google",
"Google AI Studio",
"Groq",
"Hyperbolic",
"Inception",
"Inceptron",
"InferenceNet",
"Infermatic",
"Inflection",
"Liquid",
"Mara",
"Mancer 2",
"Minimax",
"ModelRun",
"Mistral",
"Modular",
"Moonshot AI",
"Morph",
"NCompass",
"Nebius",
"NextBit",
"Novita",
"Nvidia",
"OpenAI",
"OpenInference",
"Parasail",
"Perplexity",
"Phala",
"Relace",
"SambaNova",
"Seed",
"SiliconFlow",
"Sourceful",
"Stealth",
"StreamLake",
"Switchpoint",
"Together",
"Upstage",
"Venice",
"WandB",
"Xiaomi",
"xAI",
"Z.AI",
"FakeProvider",
],
UnrecognizedStr,
]
class ProviderResponseTypedDict(TypedDict):
status: Nullable[float]
id: NotRequired[str]
endpoint_id: NotRequired[str]
model_permaslug: NotRequired[str]
provider_name: NotRequired[ProviderName]
latency: NotRequired[float]
is_byok: NotRequired[bool]
class ProviderResponse(BaseModel):
status: Nullable[float]
id: Optional[str] = None
endpoint_id: Optional[str] = None
model_permaslug: Optional[str] = None
provider_name: Annotated[
Optional[ProviderName], PlainValidator(validate_open_enum(False))
] = None
latency: Optional[float] = None
is_byok: Optional[bool] = None
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = [
"id",
"endpoint_id",
"model_permaslug",
"provider_name",
"latency",
"is_byok",
]
nullable_fields = ["status"]
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 GetGenerationDataTypedDict(TypedDict):
r"""Generation data"""
@@ -98,6 +269,8 @@ class GetGenerationDataTypedDict(TypedDict):
r"""Type of API used for the generation"""
router: Nullable[str]
r"""Router used for the request (e.g., openrouter/auto)"""
provider_responses: Nullable[List[ProviderResponseTypedDict]]
r"""List of provider responses for this generation, including fallback attempts"""
class GetGenerationData(BaseModel):
@@ -202,6 +375,9 @@ class GetGenerationData(BaseModel):
router: Nullable[str]
r"""Router used for the request (e.g., openrouter/auto)"""
provider_responses: Nullable[List[ProviderResponse]]
r"""List of provider responses for this generation, including fallback attempts"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
@@ -232,6 +408,7 @@ class GetGenerationData(BaseModel):
"external_user",
"api_type",
"router",
"provider_responses",
]
null_default_fields = []
+1 -4
View File
@@ -20,7 +20,6 @@ if TYPE_CHECKING:
from openrouter.api_keys import APIKeys
from openrouter.beta import Beta
from openrouter.chat import Chat
from openrouter.completions import Completions
from openrouter.credits import Credits
from openrouter.embeddings import Embeddings
from openrouter.endpoints import Endpoints
@@ -32,7 +31,7 @@ if TYPE_CHECKING:
class OpenRouter(BaseSDK):
r"""OpenRouter API: OpenAI-compatible Chat Completions and Completions API with additional OpenRouter features
r"""OpenRouter API: OpenAI-compatible API with additional OpenRouter features
https://openrouter.ai/docs - OpenRouter Documentation
"""
@@ -58,7 +57,6 @@ class OpenRouter(BaseSDK):
o_auth: "OAuth"
r"""OAuth authentication endpoints"""
chat: "Chat"
completions: "Completions"
_sub_sdk_map = {
"beta": ("openrouter.beta", "Beta"),
"analytics": ("openrouter.analytics", "Analytics"),
@@ -72,7 +70,6 @@ class OpenRouter(BaseSDK):
"guardrails": ("openrouter.guardrails", "Guardrails"),
"o_auth": ("openrouter.oauth", "OAuth"),
"chat": ("openrouter.chat", "Chat"),
"completions": ("openrouter.completions", "Completions"),
}
def __init__(