Files
openrouter-python-sdk-retry…/src/openrouter/chat.py
T
2025-09-07 21:23:12 +01:00

592 lines
25 KiB
Python

"""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, Mapping, Optional, Union
# region imports
from typing import overload
from typing_extensions import Literal
# endregion imports
class CompleteAcceptEnum(str, Enum):
APPLICATION_JSON = "application/json"
TEXT_EVENT_STREAM = "text/event-stream"
class Chat(BaseSDK):
# region sdk-class-body
@overload
def complete(
self,
*,
messages: Union[
List[models.ChatCompletionMessageParam],
List[models.ChatCompletionMessageParamTypedDict],
],
model: Optional[str] = None,
stream: Literal[True],
stream_options: OptionalNullable[
Union[models.StreamOptions, models.StreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = 1,
tool_choice: Optional[
Union[
models.ChatCompletionToolChoiceOption,
models.ChatCompletionToolChoiceOptionTypedDict,
]
] = None,
tools: Optional[
Union[
List[models.ChatCompletionTool],
List[models.ChatCompletionToolTypedDict],
]
] = None,
top_p: OptionalNullable[float] = 1,
user: Optional[str] = None,
model_list: OptionalNullable[List[str]] = UNSET,
reasoning_effort: OptionalNullable[models.ReasoningEffort] = UNSET,
provider: OptionalNullable[
Union[models.Provider, models.ProviderTypedDict]
] = UNSET,
plugins: Optional[
Union[List[models.Plugin], List[models.PluginTypedDict]]
] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
accept_header_override: Optional[CompleteAcceptEnum] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> eventstreaming.EventStream[models.ChatCompletionChunkWrapper]: ...
@overload
def complete(
self,
*,
messages: Union[
List[models.ChatCompletionMessageParam],
List[models.ChatCompletionMessageParamTypedDict],
],
model: Optional[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: OptionalNullable[
Union[models.Reasoning, models.ReasoningTypedDict]
] = UNSET,
response_format: Optional[
Union[models.ResponseFormat, models.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[Union[models.Stop, models.StopTypedDict]] = UNSET,
stream: Union[Literal[False], None] = None,
stream_options: OptionalNullable[
Union[models.StreamOptions, models.StreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = 1,
tool_choice: Optional[
Union[
models.ChatCompletionToolChoiceOption,
models.ChatCompletionToolChoiceOptionTypedDict,
]
] = None,
tools: Optional[
Union[
List[models.ChatCompletionTool],
List[models.ChatCompletionToolTypedDict],
]
] = None,
top_p: OptionalNullable[float] = 1,
user: Optional[str] = None,
model_list: OptionalNullable[List[str]] = UNSET,
reasoning_effort: OptionalNullable[models.ReasoningEffort] = UNSET,
provider: OptionalNullable[
Union[models.Provider, models.ProviderTypedDict]
] = UNSET,
plugins: Optional[
Union[List[models.Plugin], List[models.PluginTypedDict]]
] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
accept_header_override: Optional[CompleteAcceptEnum] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.ChatCompletion: ...
# endregion sdk-class-body
def complete(
self,
*,
messages: Union[
List[models.ChatCompletionMessageParam],
List[models.ChatCompletionMessageParamTypedDict],
],
model: Optional[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: OptionalNullable[
Union[models.Reasoning, models.ReasoningTypedDict]
] = UNSET,
response_format: Optional[
Union[models.ResponseFormat, models.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[Union[models.Stop, models.StopTypedDict]] = UNSET,
stream: OptionalNullable[bool] = False,
stream_options: OptionalNullable[
Union[models.StreamOptions, models.StreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = 1,
tool_choice: Optional[
Union[
models.ChatCompletionToolChoiceOption,
models.ChatCompletionToolChoiceOptionTypedDict,
]
] = None,
tools: Optional[
Union[
List[models.ChatCompletionTool],
List[models.ChatCompletionToolTypedDict],
]
] = None,
top_p: OptionalNullable[float] = 1,
user: Optional[str] = None,
model_list: OptionalNullable[List[str]] = UNSET,
reasoning_effort: OptionalNullable[models.ReasoningEffort] = UNSET,
provider: OptionalNullable[
Union[models.Provider, models.ProviderTypedDict]
] = UNSET,
plugins: Optional[
Union[List[models.Plugin], List[models.PluginTypedDict]]
] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
accept_header_override: Optional[CompleteAcceptEnum] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.CreateChatCompletionResponse:
r"""Create a chat completion
Creates a model response for the given chat conversation. Supports both streaming and non-streaming modes.
:param messages: List of messages for the conversation
:param model: Model to use for completion
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
:param logit_bias: Token logit bias adjustments
:param logprobs: Return log probabilities
:param top_logprobs: Number of top log probabilities to return (0-20)
:param max_completion_tokens: Maximum tokens in completion
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens)
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
:param presence_penalty: Presence penalty (-2.0 to 2.0)
:param reasoning: Reasoning configuration
:param response_format: Response format configuration
:param seed: Random seed for deterministic outputs
:param stop: Stop sequences (up to 4)
:param stream: Enable streaming response
:param stream_options:
:param temperature: Sampling temperature (0-2)
:param tool_choice: Tool choice configuration
:param tools: Available tools for function calling
:param top_p: Nucleus sampling parameter (0-1)
:param user: Unique user identifier
:param model_list: Order of models to fallback to for this request
:param reasoning_effort: Reasoning effort
:param provider: When multiple model providers are available, optionally indicate your routing preference.
:param plugins: Plugins you want to enable for this request, including their settings.
: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.ChatCompletionCreateParams(
messages=utils.get_pydantic_model(
messages, List[models.ChatCompletionMessageParam]
),
model=model,
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, OptionalNullable[models.Reasoning]
),
response_format=utils.get_pydantic_model(
response_format, Optional[models.ResponseFormat]
),
seed=seed,
stop=stop,
stream=stream,
stream_options=utils.get_pydantic_model(
stream_options, OptionalNullable[models.StreamOptions]
),
temperature=temperature,
tool_choice=utils.get_pydantic_model(
tool_choice, Optional[models.ChatCompletionToolChoiceOption]
),
tools=utils.get_pydantic_model(
tools, Optional[List[models.ChatCompletionTool]]
),
top_p=top_p,
user=user,
model_list=model_list,
reasoning_effort=reasoning_effort,
provider=utils.get_pydantic_model(
provider, OptionalNullable[models.Provider]
),
plugins=utils.get_pydantic_model(plugins, Optional[List[models.Plugin]]),
)
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=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.ChatCompletionCreateParams
),
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="createChatCompletion",
oauth2_scopes=[],
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.ChatCompletion, 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.ChatCompletionChunkWrapper
),
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.ChatCompletionErrorData, http_res, http_res_text
)
raise errors.ChatCompletionError(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.ChatCompletionErrorData, http_res, http_res_text
)
raise errors.ChatCompletionError(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
)
async def complete_async(
self,
*,
messages: Union[
List[models.ChatCompletionMessageParam],
List[models.ChatCompletionMessageParamTypedDict],
],
model: Optional[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: OptionalNullable[
Union[models.Reasoning, models.ReasoningTypedDict]
] = UNSET,
response_format: Optional[
Union[models.ResponseFormat, models.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
stop: OptionalNullable[Union[models.Stop, models.StopTypedDict]] = UNSET,
stream: OptionalNullable[bool] = False,
stream_options: OptionalNullable[
Union[models.StreamOptions, models.StreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = 1,
tool_choice: Optional[
Union[
models.ChatCompletionToolChoiceOption,
models.ChatCompletionToolChoiceOptionTypedDict,
]
] = None,
tools: Optional[
Union[
List[models.ChatCompletionTool],
List[models.ChatCompletionToolTypedDict],
]
] = None,
top_p: OptionalNullable[float] = 1,
user: Optional[str] = None,
model_list: OptionalNullable[List[str]] = UNSET,
reasoning_effort: OptionalNullable[models.ReasoningEffort] = UNSET,
provider: OptionalNullable[
Union[models.Provider, models.ProviderTypedDict]
] = UNSET,
plugins: Optional[
Union[List[models.Plugin], List[models.PluginTypedDict]]
] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
accept_header_override: Optional[CompleteAcceptEnum] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> models.CreateChatCompletionResponse:
r"""Create a chat completion
Creates a model response for the given chat conversation. Supports both streaming and non-streaming modes.
:param messages: List of messages for the conversation
:param model: Model to use for completion
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
:param logit_bias: Token logit bias adjustments
:param logprobs: Return log probabilities
:param top_logprobs: Number of top log probabilities to return (0-20)
:param max_completion_tokens: Maximum tokens in completion
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens)
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
:param presence_penalty: Presence penalty (-2.0 to 2.0)
:param reasoning: Reasoning configuration
:param response_format: Response format configuration
:param seed: Random seed for deterministic outputs
:param stop: Stop sequences (up to 4)
:param stream: Enable streaming response
:param stream_options:
:param temperature: Sampling temperature (0-2)
:param tool_choice: Tool choice configuration
:param tools: Available tools for function calling
:param top_p: Nucleus sampling parameter (0-1)
:param user: Unique user identifier
:param model_list: Order of models to fallback to for this request
:param reasoning_effort: Reasoning effort
:param provider: When multiple model providers are available, optionally indicate your routing preference.
:param plugins: Plugins you want to enable for this request, including their settings.
: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.ChatCompletionCreateParams(
messages=utils.get_pydantic_model(
messages, List[models.ChatCompletionMessageParam]
),
model=model,
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, OptionalNullable[models.Reasoning]
),
response_format=utils.get_pydantic_model(
response_format, Optional[models.ResponseFormat]
),
seed=seed,
stop=stop,
stream=stream,
stream_options=utils.get_pydantic_model(
stream_options, OptionalNullable[models.StreamOptions]
),
temperature=temperature,
tool_choice=utils.get_pydantic_model(
tool_choice, Optional[models.ChatCompletionToolChoiceOption]
),
tools=utils.get_pydantic_model(
tools, Optional[List[models.ChatCompletionTool]]
),
top_p=top_p,
user=user,
model_list=model_list,
reasoning_effort=reasoning_effort,
provider=utils.get_pydantic_model(
provider, OptionalNullable[models.Provider]
),
plugins=utils.get_pydantic_model(plugins, Optional[List[models.Plugin]]),
)
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=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.ChatCompletionCreateParams
),
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="createChatCompletion",
oauth2_scopes=[],
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.ChatCompletion, 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.ChatCompletionChunkWrapper
),
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.ChatCompletionErrorData, http_res, http_res_text
)
raise errors.ChatCompletionError(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.ChatCompletionErrorData, http_res, http_res_text
)
raise errors.ChatCompletionError(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
)