Files
openrouter-python-sdk-retry…/src/openrouter/guardrails.py
T
github-actions[bot]GitHubspeakeasybotspeakeasy-github[bot] <128539517+speakeasy-github[bot]@users.noreply.github.com>
0f116c9792 chore: 🐝 Update SDK - Generate 0.9.2 (#205)
Co-authored-by: speakeasybot <bot@speakeasyapi.dev>
Co-authored-by: speakeasy-github[bot] <128539517+speakeasy-github[bot]@users.noreply.github.com>
2026-06-11 12:10:31 -04:00

4074 lines
181 KiB
Python

"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from jsonpath import JSONPath
from openrouter import components, errors, operations, 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, Awaitable, Dict, List, Mapping, Optional, Union
class Guardrails(BaseSDK):
r"""Guardrails endpoints"""
def list(
self,
*,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
workspace_id: 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,
) -> Optional[operations.ListGuardrailsResponse]:
r"""List guardrails
List all guardrails for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
:param workspace_id: Filter guardrails by workspace ID. By default, guardrails in the default workspace are returned.
: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 = operations.ListGuardrailsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=offset,
limit=limit,
workspace_id=workspace_id,
)
req = self._build_request(
method="GET",
path="/guardrails",
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,
_globals=operations.ListGuardrailsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listGuardrails",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> Optional[operations.ListGuardrailsResponse]:
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return None
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return None
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return None
next_offset = offset + len(results[0])
return self.list(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
workspace_id=workspace_id,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListGuardrailsResponse(
result=unmarshal_json_response(
components.ListGuardrailsResponse, http_res
),
next=next_func,
)
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, "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,
*,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
workspace_id: 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,
) -> Optional[operations.ListGuardrailsResponse]:
r"""List guardrails
List all guardrails for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
:param workspace_id: Filter guardrails by workspace ID. By default, guardrails in the default workspace are returned.
: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 = operations.ListGuardrailsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=offset,
limit=limit,
workspace_id=workspace_id,
)
req = self._build_request_async(
method="GET",
path="/guardrails",
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,
_globals=operations.ListGuardrailsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listGuardrails",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> Awaitable[Optional[operations.ListGuardrailsResponse]]:
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
async def empty_result():
return None
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return empty_result()
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return empty_result()
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return empty_result()
next_offset = offset + len(results[0])
return self.list_async(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
workspace_id=workspace_id,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListGuardrailsResponse(
result=unmarshal_json_response(
components.ListGuardrailsResponse, http_res
),
next=next_func,
)
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, "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(
self,
*,
name: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
allowed_models: OptionalNullable[List[str]] = UNSET,
allowed_providers: OptionalNullable[List[str]] = UNSET,
content_filter_builtins: OptionalNullable[
Union[
List[components.ContentFilterBuiltinEntryInput],
List[components.ContentFilterBuiltinEntryInputTypedDict],
]
] = UNSET,
content_filters: OptionalNullable[
Union[
List[components.ContentFilterEntry],
List[components.ContentFilterEntryTypedDict],
]
] = UNSET,
description: OptionalNullable[str] = UNSET,
enforce_zdr: OptionalNullable[bool] = UNSET,
enforce_zdr_anthropic: OptionalNullable[bool] = UNSET,
enforce_zdr_google: OptionalNullable[bool] = UNSET,
enforce_zdr_openai: OptionalNullable[bool] = UNSET,
enforce_zdr_other: OptionalNullable[bool] = UNSET,
ignored_models: OptionalNullable[List[str]] = UNSET,
ignored_providers: OptionalNullable[List[str]] = UNSET,
limit_usd: OptionalNullable[float] = UNSET,
reset_interval: OptionalNullable[components.GuardrailInterval] = UNSET,
workspace_id: 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,
) -> components.CreateGuardrailResponse:
r"""Create a guardrail
Create a new guardrail for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param name: Name for the new guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param allowed_models: Array of model identifiers (slug or canonical_slug accepted)
:param allowed_providers: List of allowed provider IDs
:param content_filter_builtins: Builtin content filters to apply. The \"flag\" action is only supported for \"regex-prompt-injection\"; PII slugs (email, phone, ssn, credit-card, ip-address, person-name, address) accept \"block\" or \"redact\" only.
:param content_filters: Custom regex content filters to apply to request messages
:param description: Description of the guardrail
:param enforce_zdr: Deprecated. Use enforce_zdr_anthropic, enforce_zdr_openai, enforce_zdr_google, and enforce_zdr_other instead. When provided, its value is copied into any of those per-provider fields that are not explicitly specified on the request.
:param enforce_zdr_anthropic: Whether to enforce zero data retention for Anthropic models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_google: Whether to enforce zero data retention for Google models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_openai: Whether to enforce zero data retention for OpenAI models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_other: Whether to enforce zero data retention for models that are not from Anthropic, OpenAI, or Google. Falls back to enforce_zdr when not provided.
:param ignored_models: Array of model identifiers to exclude from routing (slug or canonical_slug accepted)
:param ignored_providers: List of provider IDs to exclude from routing
:param limit_usd: Spending limit in USD
:param reset_interval: Interval at which the limit resets (daily, weekly, monthly)
:param workspace_id: The workspace to create the guardrail in. Defaults to the default workspace if not provided.
: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 = operations.CreateGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
create_guardrail_request=components.CreateGuardrailRequest(
allowed_models=allowed_models,
allowed_providers=allowed_providers,
content_filter_builtins=utils.get_pydantic_model(
content_filter_builtins,
OptionalNullable[List[components.ContentFilterBuiltinEntryInput]],
),
content_filters=utils.get_pydantic_model(
content_filters,
OptionalNullable[List[components.ContentFilterEntry]],
),
description=description,
enforce_zdr=enforce_zdr,
enforce_zdr_anthropic=enforce_zdr_anthropic,
enforce_zdr_google=enforce_zdr_google,
enforce_zdr_openai=enforce_zdr_openai,
enforce_zdr_other=enforce_zdr_other,
ignored_models=ignored_models,
ignored_providers=ignored_providers,
limit_usd=limit_usd,
name=name,
reset_interval=reset_interval,
workspace_id=workspace_id,
),
)
req = self._build_request(
method="POST",
path="/guardrails",
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,
_globals=operations.CreateGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.create_guardrail_request,
False,
False,
"json",
components.CreateGuardrailRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="createGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.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, "201", "application/json"):
return unmarshal_json_response(components.CreateGuardrailResponse, 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 create_async(
self,
*,
name: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
allowed_models: OptionalNullable[List[str]] = UNSET,
allowed_providers: OptionalNullable[List[str]] = UNSET,
content_filter_builtins: OptionalNullable[
Union[
List[components.ContentFilterBuiltinEntryInput],
List[components.ContentFilterBuiltinEntryInputTypedDict],
]
] = UNSET,
content_filters: OptionalNullable[
Union[
List[components.ContentFilterEntry],
List[components.ContentFilterEntryTypedDict],
]
] = UNSET,
description: OptionalNullable[str] = UNSET,
enforce_zdr: OptionalNullable[bool] = UNSET,
enforce_zdr_anthropic: OptionalNullable[bool] = UNSET,
enforce_zdr_google: OptionalNullable[bool] = UNSET,
enforce_zdr_openai: OptionalNullable[bool] = UNSET,
enforce_zdr_other: OptionalNullable[bool] = UNSET,
ignored_models: OptionalNullable[List[str]] = UNSET,
ignored_providers: OptionalNullable[List[str]] = UNSET,
limit_usd: OptionalNullable[float] = UNSET,
reset_interval: OptionalNullable[components.GuardrailInterval] = UNSET,
workspace_id: 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,
) -> components.CreateGuardrailResponse:
r"""Create a guardrail
Create a new guardrail for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param name: Name for the new guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param allowed_models: Array of model identifiers (slug or canonical_slug accepted)
:param allowed_providers: List of allowed provider IDs
:param content_filter_builtins: Builtin content filters to apply. The \"flag\" action is only supported for \"regex-prompt-injection\"; PII slugs (email, phone, ssn, credit-card, ip-address, person-name, address) accept \"block\" or \"redact\" only.
:param content_filters: Custom regex content filters to apply to request messages
:param description: Description of the guardrail
:param enforce_zdr: Deprecated. Use enforce_zdr_anthropic, enforce_zdr_openai, enforce_zdr_google, and enforce_zdr_other instead. When provided, its value is copied into any of those per-provider fields that are not explicitly specified on the request.
:param enforce_zdr_anthropic: Whether to enforce zero data retention for Anthropic models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_google: Whether to enforce zero data retention for Google models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_openai: Whether to enforce zero data retention for OpenAI models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_other: Whether to enforce zero data retention for models that are not from Anthropic, OpenAI, or Google. Falls back to enforce_zdr when not provided.
:param ignored_models: Array of model identifiers to exclude from routing (slug or canonical_slug accepted)
:param ignored_providers: List of provider IDs to exclude from routing
:param limit_usd: Spending limit in USD
:param reset_interval: Interval at which the limit resets (daily, weekly, monthly)
:param workspace_id: The workspace to create the guardrail in. Defaults to the default workspace if not provided.
: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 = operations.CreateGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
create_guardrail_request=components.CreateGuardrailRequest(
allowed_models=allowed_models,
allowed_providers=allowed_providers,
content_filter_builtins=utils.get_pydantic_model(
content_filter_builtins,
OptionalNullable[List[components.ContentFilterBuiltinEntryInput]],
),
content_filters=utils.get_pydantic_model(
content_filters,
OptionalNullable[List[components.ContentFilterEntry]],
),
description=description,
enforce_zdr=enforce_zdr,
enforce_zdr_anthropic=enforce_zdr_anthropic,
enforce_zdr_google=enforce_zdr_google,
enforce_zdr_openai=enforce_zdr_openai,
enforce_zdr_other=enforce_zdr_other,
ignored_models=ignored_models,
ignored_providers=ignored_providers,
limit_usd=limit_usd,
name=name,
reset_interval=reset_interval,
workspace_id=workspace_id,
),
)
req = self._build_request_async(
method="POST",
path="/guardrails",
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,
_globals=operations.CreateGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.create_guardrail_request,
False,
False,
"json",
components.CreateGuardrailRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="createGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.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, "201", "application/json"):
return unmarshal_json_response(components.CreateGuardrailResponse, 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)
def delete(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.DeleteGuardrailResponse:
r"""Delete a guardrail
Delete an existing guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail to delete
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.DeleteGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
)
req = self._build_request(
method="DELETE",
path="/guardrails/{id}",
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,
_globals=operations.DeleteGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="deleteGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "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(components.DeleteGuardrailResponse, 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, "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 delete_async(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.DeleteGuardrailResponse:
r"""Delete a guardrail
Delete an existing guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail to delete
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.DeleteGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
)
req = self._build_request_async(
method="DELETE",
path="/guardrails/{id}",
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,
_globals=operations.DeleteGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="deleteGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "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(components.DeleteGuardrailResponse, 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, "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 get(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.GetGuardrailResponse:
r"""Get a guardrail
Get a single guardrail by ID. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail to retrieve
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.GetGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
)
req = self._build_request(
method="GET",
path="/guardrails/{id}",
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,
_globals=operations.GetGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "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(components.GetGuardrailResponse, 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, "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 get_async(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.GetGuardrailResponse:
r"""Get a guardrail
Get a single guardrail by ID. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail to retrieve
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.GetGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
)
req = self._build_request_async(
method="GET",
path="/guardrails/{id}",
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,
_globals=operations.GetGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "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(components.GetGuardrailResponse, 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, "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 update(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
allowed_models: OptionalNullable[List[str]] = UNSET,
allowed_providers: OptionalNullable[List[str]] = UNSET,
content_filter_builtins: OptionalNullable[
Union[
List[components.ContentFilterBuiltinEntryInput],
List[components.ContentFilterBuiltinEntryInputTypedDict],
]
] = UNSET,
content_filters: OptionalNullable[
Union[
List[components.ContentFilterEntry],
List[components.ContentFilterEntryTypedDict],
]
] = UNSET,
description: OptionalNullable[str] = UNSET,
enforce_zdr: OptionalNullable[bool] = UNSET,
enforce_zdr_anthropic: OptionalNullable[bool] = UNSET,
enforce_zdr_google: OptionalNullable[bool] = UNSET,
enforce_zdr_openai: OptionalNullable[bool] = UNSET,
enforce_zdr_other: OptionalNullable[bool] = UNSET,
ignored_models: OptionalNullable[List[str]] = UNSET,
ignored_providers: OptionalNullable[List[str]] = UNSET,
limit_usd: OptionalNullable[float] = UNSET,
name: Optional[str] = None,
reset_interval: OptionalNullable[components.GuardrailInterval] = UNSET,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.UpdateGuardrailResponse:
r"""Update a guardrail
Update an existing guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail to update
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param allowed_models: Array of model identifiers (slug or canonical_slug accepted)
:param allowed_providers: New list of allowed provider IDs
:param content_filter_builtins: Builtin content filters to apply. Set to null to remove. The \"flag\" action is only supported for \"regex-prompt-injection\"; PII slugs (email, phone, ssn, credit-card, ip-address, person-name, address) accept \"block\" or \"redact\" only.
:param content_filters: Custom regex content filters to apply. Set to null to remove.
:param description: New description for the guardrail
:param enforce_zdr: Deprecated. Use enforce_zdr_anthropic, enforce_zdr_openai, enforce_zdr_google, and enforce_zdr_other instead. When provided, its value is copied into any of those per-provider fields that are not explicitly specified on the request.
:param enforce_zdr_anthropic: Whether to enforce zero data retention for Anthropic models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_google: Whether to enforce zero data retention for Google models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_openai: Whether to enforce zero data retention for OpenAI models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_other: Whether to enforce zero data retention for models that are not from Anthropic, OpenAI, or Google. Falls back to enforce_zdr when not provided.
:param ignored_models: Array of model identifiers to exclude from routing (slug or canonical_slug accepted)
:param ignored_providers: List of provider IDs to exclude from routing
:param limit_usd: New spending limit in USD
:param name: New name for the guardrail
:param reset_interval: Interval at which the limit resets (daily, weekly, monthly)
: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 = operations.UpdateGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
update_guardrail_request=components.UpdateGuardrailRequest(
allowed_models=allowed_models,
allowed_providers=allowed_providers,
content_filter_builtins=utils.get_pydantic_model(
content_filter_builtins,
OptionalNullable[List[components.ContentFilterBuiltinEntryInput]],
),
content_filters=utils.get_pydantic_model(
content_filters,
OptionalNullable[List[components.ContentFilterEntry]],
),
description=description,
enforce_zdr=enforce_zdr,
enforce_zdr_anthropic=enforce_zdr_anthropic,
enforce_zdr_google=enforce_zdr_google,
enforce_zdr_openai=enforce_zdr_openai,
enforce_zdr_other=enforce_zdr_other,
ignored_models=ignored_models,
ignored_providers=ignored_providers,
limit_usd=limit_usd,
name=name,
reset_interval=reset_interval,
),
)
req = self._build_request(
method="PATCH",
path="/guardrails/{id}",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.UpdateGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.update_guardrail_request,
False,
False,
"json",
components.UpdateGuardrailRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="updateGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(components.UpdateGuardrailResponse, 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, "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 update_async(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
allowed_models: OptionalNullable[List[str]] = UNSET,
allowed_providers: OptionalNullable[List[str]] = UNSET,
content_filter_builtins: OptionalNullable[
Union[
List[components.ContentFilterBuiltinEntryInput],
List[components.ContentFilterBuiltinEntryInputTypedDict],
]
] = UNSET,
content_filters: OptionalNullable[
Union[
List[components.ContentFilterEntry],
List[components.ContentFilterEntryTypedDict],
]
] = UNSET,
description: OptionalNullable[str] = UNSET,
enforce_zdr: OptionalNullable[bool] = UNSET,
enforce_zdr_anthropic: OptionalNullable[bool] = UNSET,
enforce_zdr_google: OptionalNullable[bool] = UNSET,
enforce_zdr_openai: OptionalNullable[bool] = UNSET,
enforce_zdr_other: OptionalNullable[bool] = UNSET,
ignored_models: OptionalNullable[List[str]] = UNSET,
ignored_providers: OptionalNullable[List[str]] = UNSET,
limit_usd: OptionalNullable[float] = UNSET,
name: Optional[str] = None,
reset_interval: OptionalNullable[components.GuardrailInterval] = UNSET,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.UpdateGuardrailResponse:
r"""Update a guardrail
Update an existing guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail to update
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param allowed_models: Array of model identifiers (slug or canonical_slug accepted)
:param allowed_providers: New list of allowed provider IDs
:param content_filter_builtins: Builtin content filters to apply. Set to null to remove. The \"flag\" action is only supported for \"regex-prompt-injection\"; PII slugs (email, phone, ssn, credit-card, ip-address, person-name, address) accept \"block\" or \"redact\" only.
:param content_filters: Custom regex content filters to apply. Set to null to remove.
:param description: New description for the guardrail
:param enforce_zdr: Deprecated. Use enforce_zdr_anthropic, enforce_zdr_openai, enforce_zdr_google, and enforce_zdr_other instead. When provided, its value is copied into any of those per-provider fields that are not explicitly specified on the request.
:param enforce_zdr_anthropic: Whether to enforce zero data retention for Anthropic models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_google: Whether to enforce zero data retention for Google models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_openai: Whether to enforce zero data retention for OpenAI models. Falls back to enforce_zdr when not provided.
:param enforce_zdr_other: Whether to enforce zero data retention for models that are not from Anthropic, OpenAI, or Google. Falls back to enforce_zdr when not provided.
:param ignored_models: Array of model identifiers to exclude from routing (slug or canonical_slug accepted)
:param ignored_providers: List of provider IDs to exclude from routing
:param limit_usd: New spending limit in USD
:param name: New name for the guardrail
:param reset_interval: Interval at which the limit resets (daily, weekly, monthly)
: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 = operations.UpdateGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
update_guardrail_request=components.UpdateGuardrailRequest(
allowed_models=allowed_models,
allowed_providers=allowed_providers,
content_filter_builtins=utils.get_pydantic_model(
content_filter_builtins,
OptionalNullable[List[components.ContentFilterBuiltinEntryInput]],
),
content_filters=utils.get_pydantic_model(
content_filters,
OptionalNullable[List[components.ContentFilterEntry]],
),
description=description,
enforce_zdr=enforce_zdr,
enforce_zdr_anthropic=enforce_zdr_anthropic,
enforce_zdr_google=enforce_zdr_google,
enforce_zdr_openai=enforce_zdr_openai,
enforce_zdr_other=enforce_zdr_other,
ignored_models=ignored_models,
ignored_providers=ignored_providers,
limit_usd=limit_usd,
name=name,
reset_interval=reset_interval,
),
)
req = self._build_request_async(
method="PATCH",
path="/guardrails/{id}",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.UpdateGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.update_guardrail_request,
False,
False,
"json",
components.UpdateGuardrailRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="updateGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(components.UpdateGuardrailResponse, 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, "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_guardrail_key_assignments(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> Optional[operations.ListGuardrailKeyAssignmentsResponse]:
r"""List key assignments for a guardrail
List all API key assignments for a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
: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 = operations.ListGuardrailKeyAssignmentsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
offset=offset,
limit=limit,
)
req = self._build_request(
method="GET",
path="/guardrails/{id}/assignments/keys",
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,
_globals=operations.ListGuardrailKeyAssignmentsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listGuardrailKeyAssignments",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "404", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> Optional[operations.ListGuardrailKeyAssignmentsResponse]:
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return None
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return None
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return None
next_offset = offset + len(results[0])
return self.list_guardrail_key_assignments(
id=id,
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListGuardrailKeyAssignmentsResponse(
result=unmarshal_json_response(
components.ListKeyAssignmentsResponse, http_res
),
next=next_func,
)
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, "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_guardrail_key_assignments_async(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> Optional[operations.ListGuardrailKeyAssignmentsResponse]:
r"""List key assignments for a guardrail
List all API key assignments for a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
: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 = operations.ListGuardrailKeyAssignmentsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
offset=offset,
limit=limit,
)
req = self._build_request_async(
method="GET",
path="/guardrails/{id}/assignments/keys",
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,
_globals=operations.ListGuardrailKeyAssignmentsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listGuardrailKeyAssignments",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "404", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> (
Awaitable[Optional[operations.ListGuardrailKeyAssignmentsResponse]]
):
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
async def empty_result():
return None
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return empty_result()
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return empty_result()
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return empty_result()
next_offset = offset + len(results[0])
return self.list_guardrail_key_assignments_async(
id=id,
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListGuardrailKeyAssignmentsResponse(
result=unmarshal_json_response(
components.ListKeyAssignmentsResponse, http_res
),
next=next_func,
)
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, "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 bulk_assign_keys(
self,
*,
id: str,
key_hashes: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.BulkAssignKeysResponse:
r"""Bulk assign keys to a guardrail
Assign multiple API keys to a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param key_hashes: Array of API key hashes to assign to the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.BulkAssignKeysToGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
bulk_assign_keys_request=components.BulkAssignKeysRequest(
key_hashes=key_hashes,
),
)
req = self._build_request(
method="POST",
path="/guardrails/{id}/assignments/keys",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.BulkAssignKeysToGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.bulk_assign_keys_request,
False,
False,
"json",
components.BulkAssignKeysRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="bulkAssignKeysToGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(components.BulkAssignKeysResponse, 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, "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 bulk_assign_keys_async(
self,
*,
id: str,
key_hashes: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.BulkAssignKeysResponse:
r"""Bulk assign keys to a guardrail
Assign multiple API keys to a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param key_hashes: Array of API key hashes to assign to the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.BulkAssignKeysToGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
bulk_assign_keys_request=components.BulkAssignKeysRequest(
key_hashes=key_hashes,
),
)
req = self._build_request_async(
method="POST",
path="/guardrails/{id}/assignments/keys",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.BulkAssignKeysToGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.bulk_assign_keys_request,
False,
False,
"json",
components.BulkAssignKeysRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="bulkAssignKeysToGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(components.BulkAssignKeysResponse, 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, "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 bulk_unassign_keys(
self,
*,
id: str,
key_hashes: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.BulkUnassignKeysResponse:
r"""Bulk unassign keys from a guardrail
Unassign multiple API keys from a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param key_hashes: Array of API key hashes to unassign from the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.BulkUnassignKeysFromGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
bulk_unassign_keys_request=components.BulkUnassignKeysRequest(
key_hashes=key_hashes,
),
)
req = self._build_request(
method="POST",
path="/guardrails/{id}/assignments/keys/remove",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.BulkUnassignKeysFromGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.bulk_unassign_keys_request,
False,
False,
"json",
components.BulkUnassignKeysRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="bulkUnassignKeysFromGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(
components.BulkUnassignKeysResponse, 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, "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 bulk_unassign_keys_async(
self,
*,
id: str,
key_hashes: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.BulkUnassignKeysResponse:
r"""Bulk unassign keys from a guardrail
Unassign multiple API keys from a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param key_hashes: Array of API key hashes to unassign from the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.BulkUnassignKeysFromGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
bulk_unassign_keys_request=components.BulkUnassignKeysRequest(
key_hashes=key_hashes,
),
)
req = self._build_request_async(
method="POST",
path="/guardrails/{id}/assignments/keys/remove",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.BulkUnassignKeysFromGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.bulk_unassign_keys_request,
False,
False,
"json",
components.BulkUnassignKeysRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="bulkUnassignKeysFromGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(
components.BulkUnassignKeysResponse, 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, "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_guardrail_member_assignments(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> Optional[operations.ListGuardrailMemberAssignmentsResponse]:
r"""List member assignments for a guardrail
List all organization member assignments for a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
: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 = operations.ListGuardrailMemberAssignmentsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
offset=offset,
limit=limit,
)
req = self._build_request(
method="GET",
path="/guardrails/{id}/assignments/members",
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,
_globals=operations.ListGuardrailMemberAssignmentsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listGuardrailMemberAssignments",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "404", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> Optional[operations.ListGuardrailMemberAssignmentsResponse]:
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return None
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return None
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return None
next_offset = offset + len(results[0])
return self.list_guardrail_member_assignments(
id=id,
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListGuardrailMemberAssignmentsResponse(
result=unmarshal_json_response(
components.ListMemberAssignmentsResponse, http_res
),
next=next_func,
)
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, "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_guardrail_member_assignments_async(
self,
*,
id: str,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> Optional[operations.ListGuardrailMemberAssignmentsResponse]:
r"""List member assignments for a guardrail
List all organization member assignments for a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
: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 = operations.ListGuardrailMemberAssignmentsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
offset=offset,
limit=limit,
)
req = self._build_request_async(
method="GET",
path="/guardrails/{id}/assignments/members",
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,
_globals=operations.ListGuardrailMemberAssignmentsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listGuardrailMemberAssignments",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "404", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> (
Awaitable[Optional[operations.ListGuardrailMemberAssignmentsResponse]]
):
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
async def empty_result():
return None
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return empty_result()
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return empty_result()
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return empty_result()
next_offset = offset + len(results[0])
return self.list_guardrail_member_assignments_async(
id=id,
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListGuardrailMemberAssignmentsResponse(
result=unmarshal_json_response(
components.ListMemberAssignmentsResponse, http_res
),
next=next_func,
)
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, "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 bulk_assign_members(
self,
*,
id: str,
member_user_ids: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.BulkAssignMembersResponse:
r"""Bulk assign members to a guardrail
Assign multiple organization members to a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param member_user_ids: Array of member user IDs to assign to the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.BulkAssignMembersToGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
bulk_assign_members_request=components.BulkAssignMembersRequest(
member_user_ids=member_user_ids,
),
)
req = self._build_request(
method="POST",
path="/guardrails/{id}/assignments/members",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.BulkAssignMembersToGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.bulk_assign_members_request,
False,
False,
"json",
components.BulkAssignMembersRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="bulkAssignMembersToGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(
components.BulkAssignMembersResponse, 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, "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 bulk_assign_members_async(
self,
*,
id: str,
member_user_ids: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.BulkAssignMembersResponse:
r"""Bulk assign members to a guardrail
Assign multiple organization members to a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param member_user_ids: Array of member user IDs to assign to the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.BulkAssignMembersToGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
bulk_assign_members_request=components.BulkAssignMembersRequest(
member_user_ids=member_user_ids,
),
)
req = self._build_request_async(
method="POST",
path="/guardrails/{id}/assignments/members",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.BulkAssignMembersToGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.bulk_assign_members_request,
False,
False,
"json",
components.BulkAssignMembersRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="bulkAssignMembersToGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(
components.BulkAssignMembersResponse, 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, "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 bulk_unassign_members(
self,
*,
id: str,
member_user_ids: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.BulkUnassignMembersResponse:
r"""Bulk unassign members from a guardrail
Unassign multiple organization members from a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param member_user_ids: Array of member user IDs to unassign from the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.BulkUnassignMembersFromGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
bulk_unassign_members_request=components.BulkUnassignMembersRequest(
member_user_ids=member_user_ids,
),
)
req = self._build_request(
method="POST",
path="/guardrails/{id}/assignments/members/remove",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.BulkUnassignMembersFromGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.bulk_unassign_members_request,
False,
False,
"json",
components.BulkUnassignMembersRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="bulkUnassignMembersFromGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(
components.BulkUnassignMembersResponse, 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, "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 bulk_unassign_members_async(
self,
*,
id: str,
member_user_ids: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: 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,
) -> components.BulkUnassignMembersResponse:
r"""Bulk unassign members from a guardrail
Unassign multiple organization members from a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param id: The unique identifier of the guardrail
:param member_user_ids: Array of member user IDs to unassign from the guardrail
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 = operations.BulkUnassignMembersFromGuardrailRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
id=id,
bulk_unassign_members_request=components.BulkUnassignMembersRequest(
member_user_ids=member_user_ids,
),
)
req = self._build_request_async(
method="POST",
path="/guardrails/{id}/assignments/members/remove",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=True,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.BulkUnassignMembersFromGuardrailGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.bulk_unassign_members_request,
False,
False,
"json",
components.BulkUnassignMembersRequest,
),
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="bulkUnassignMembersFromGuardrail",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "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(
components.BulkUnassignMembersResponse, 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, "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_key_assignments(
self,
*,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> Optional[operations.ListKeyAssignmentsResponse]:
r"""List all key assignments
List all API key guardrail assignments for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
: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 = operations.ListKeyAssignmentsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=offset,
limit=limit,
)
req = self._build_request(
method="GET",
path="/guardrails/assignments/keys",
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,
_globals=operations.ListKeyAssignmentsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listKeyAssignments",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> Optional[operations.ListKeyAssignmentsResponse]:
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return None
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return None
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return None
next_offset = offset + len(results[0])
return self.list_key_assignments(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListKeyAssignmentsResponse(
result=unmarshal_json_response(
components.ListKeyAssignmentsResponse, http_res
),
next=next_func,
)
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, "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_key_assignments_async(
self,
*,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> Optional[operations.ListKeyAssignmentsResponse]:
r"""List all key assignments
List all API key guardrail assignments for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
: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 = operations.ListKeyAssignmentsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=offset,
limit=limit,
)
req = self._build_request_async(
method="GET",
path="/guardrails/assignments/keys",
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,
_globals=operations.ListKeyAssignmentsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listKeyAssignments",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> Awaitable[Optional[operations.ListKeyAssignmentsResponse]]:
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
async def empty_result():
return None
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return empty_result()
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return empty_result()
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return empty_result()
next_offset = offset + len(results[0])
return self.list_key_assignments_async(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListKeyAssignmentsResponse(
result=unmarshal_json_response(
components.ListKeyAssignmentsResponse, http_res
),
next=next_func,
)
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, "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_member_assignments(
self,
*,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> Optional[operations.ListMemberAssignmentsResponse]:
r"""List all member assignments
List all organization member guardrail assignments for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
: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 = operations.ListMemberAssignmentsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=offset,
limit=limit,
)
req = self._build_request(
method="GET",
path="/guardrails/assignments/members",
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,
_globals=operations.ListMemberAssignmentsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listMemberAssignments",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> Optional[operations.ListMemberAssignmentsResponse]:
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return None
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return None
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return None
next_offset = offset + len(results[0])
return self.list_member_assignments(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListMemberAssignmentsResponse(
result=unmarshal_json_response(
components.ListMemberAssignmentsResponse, http_res
),
next=next_func,
)
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, "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_member_assignments_async(
self,
*,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
offset: Optional[int] = None,
limit: Optional[int] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> Optional[operations.ListMemberAssignmentsResponse]:
r"""List all member assignments
List all organization member guardrail assignments for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param http_referer: The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param offset: Number of records to skip for pagination
:param limit: Maximum number of records to return (max 100)
: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 = operations.ListMemberAssignmentsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=offset,
limit=limit,
)
req = self._build_request_async(
method="GET",
path="/guardrails/assignments/members",
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,
_globals=operations.ListMemberAssignmentsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
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
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="listMemberAssignments",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "4XX", "500", "5XX"],
retry_config=retry_config,
)
def next_func() -> (
Awaitable[Optional[operations.ListMemberAssignmentsResponse]]
):
body = utils.unmarshal_json(http_res.text, Union[Dict[Any, Any], List[Any]])
async def empty_result():
return None
offset = request.offset if not request.offset is None else 0
if not http_res.text:
return empty_result()
results = JSONPath("$.data").parse(body)
if len(results) == 0 or len(results[0]) == 0:
return empty_result()
limit = request.limit if not request.limit is None else 0
if len(results[0]) < limit:
return empty_result()
next_offset = offset + len(results[0])
return self.list_member_assignments_async(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
offset=next_offset,
limit=limit,
retries=retries,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return operations.ListMemberAssignmentsResponse(
result=unmarshal_json_response(
components.ListMemberAssignmentsResponse, http_res
),
next=next_func,
)
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, "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)