### Quick Start Example (Python) Source: https://openrouter.ai/docs/sdks/python/overview A minimal example demonstrating how to instantiate the client, send a chat message, and print the response content. It assumes the API key is set as an environment variable. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY") ) as client: response = client.chat.send( model="minimax/minimax-m2", messages=[ {"role": "user", "content": "Hello!"} ] ) print(response.choices[0].message.content) ``` -------------------------------- ### Install OpenRouter SDK (Bash) Source: https://openrouter.ai/docs/sdks/python/overview Shows commands for installing the OpenRouter Python SDK using different package managers: uv (recommended), pip, and poetry. Requires Python 3.9+. ```bash # Using uv (recommended) uv add openrouter # Using pip pip install openrouter # Using poetry poetry add openrouter ``` -------------------------------- ### Asynchronous Chat Message Sending (Python) Source: https://openrouter.ai/docs/sdks/python/overview Provides an example of using the SDK asynchronously with 'async/await' syntax for non-blocking operations. This is suitable for high-concurrency applications. ```python import asyncio async def main(): async with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY") ) as client: response = await client.chat.send_async( model="minimax/minimax-m2", messages=[{"role": "user", "content": "Hello"}] ) print(response.choices[0].message.content) asyncio.run(main()) ``` -------------------------------- ### GET /keys Source: https://openrouter.ai/docs/sdks/python/apikeys List API keys with optional filtering and pagination. ```APIDOC ## GET /keys ### Description List API keys with optional filtering and pagination. ### Method GET ### Endpoint /keys ### Parameters #### Query Parameters - **include_disabled** (Optional[str]) - Optional - Whether to include disabled API keys in the response. Example: false - **offset** (Optional[str]) - Optional - Number of API keys to skip for pagination. Example: 0 ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.list(include_disabled="false", offset="0") # Handle response print(res) ``` ### Response #### Success Response (200) - **Response** (operations.ListResponse) - Details of the API keys. #### Response Example ```json { "example": "response body" } ``` ### Errors - errors.UnauthorizedResponseError (401) - errors.TooManyRequestsResponseError (429) - errors.InternalServerResponseError (500) - errors.OpenRouterDefaultError (4XX, 5XX) ``` -------------------------------- ### Using Newly Available Models (Python) Source: https://openrouter.ai/docs/sdks/python/overview Illustrates how the SDK automatically supports newly launched models without manual updates, immediately available via IDE autocompletion. This example shows sending a request to a model. ```python # When new models launch, they're available instantly response = client.chat.send( model="minimax/minimax-m2" ) ``` -------------------------------- ### Generate Completion - Python SDK Source: https://openrouter.ai/docs/sdks/python/completions Demonstrates how to create a text completion using the OpenRouter Python SDK. This example shows initializing the SDK with an API key and making a non-streaming completion request. It assumes the OPENROUTER_API_KEY environment variable is set. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.completions.generate(prompt=[], stream=False) # Handle response print(res) ``` -------------------------------- ### Create a New API Key using Python SDK Source: https://openrouter.ai/docs/sdks/python/apikeys This code example shows how to create a new API key using the OpenRouter Python SDK. It requires authentication with an API key and accepts a name for the new key. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.create(name="My New API Key") # Handle response print(res) ``` -------------------------------- ### AssistantMessage - Python SDK Source: https://openrouter.ai/docs/sdks/python/components/message Provides an example of initializing an AssistantMessage object using the OpenRouter Python SDK. This message type represents the AI's response. The SDK is in beta. ```python value: components.AssistantMessage = /* values here */ ``` -------------------------------- ### GET /credits Source: https://openrouter.ai/docs/sdks/python/credits Retrieves the remaining credits for the authenticated user, showing both purchased and used amounts. ```APIDOC ## GET /credits ### Description Get remaining credits purchased and used for the authenticated user. ### Method GET ### Endpoint /credits ### Parameters #### Query Parameters - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.credits.get_credits() # Handle response print(res) ``` ### Response #### Success Response (200) - **operations.GetCreditsResponse** (object) - The response object containing credit information. #### Response Example ```json { "credits": 1000, "credits_used": 200 } ``` ### Errors - **errors.UnauthorizedResponseError** (401) - Unauthorized access. - **errors.ForbiddenResponseError** (403) - Forbidden access. - **errors.InternalServerResponseError** (500) - Internal server error. - **errors.OpenRouterDefaultError** (4XX, 5XX) - Generic OpenRouter error. ``` -------------------------------- ### GET /parameters/{author}/{slug} Source: https://openrouter.ai/docs/sdks/python/parameters Retrieves a model's supported parameters along with data on their popularity. This endpoint requires authentication and specific model identifiers. ```APIDOC ## GET /parameters/{author}/{slug} ### Description Get a model's supported parameters and data about which are most popular. ### Method GET ### Endpoint `/parameters/{author}/{slug}` ### Parameters #### Path Parameters - **author** (str) - Required - The author of the model. - **slug** (str) - Required - The slug identifier for the model. #### Query Parameters - **provider** (Optional[operations.GetParametersProvider]) - Optional - Specifies the provider for the parameters. #### Request Body This endpoint does not accept a request body. ### Request Example ```python from openrouter import OpenRouter, operations import os with OpenRouter() as open_router: res = open_router.parameters.get_parameters( security=operations.GetParametersSecurity( bearer=os.getenv("OPENROUTER_BEARER", ""), ), author="", slug="" ) # Handle response print(res) ``` ### Response #### Success Response (200) - **operations.GetParametersResponse** - The response object containing model parameters and popularity data. #### Response Example ```json { "example": "response body" } ``` ### Errors - **errors.UnauthorizedResponseError** (401) - If authentication fails. - **errors.NotFoundResponseError** (404) - If the model is not found. - **errors.InternalServerResponseError** (500) - If there is a server error. - **errors.OpenRouterDefaultError** (4XX, 5XX) - For other general API errors. ``` -------------------------------- ### ListModelsUserSecurity Method Source: https://openrouter.ai/docs/sdks/python/operations/listmodelsusersecurity Documentation for the ListModelsUserSecurity method in the OpenRouter Python SDK. Learn how to use this API endpoint with code examples. ```APIDOC ## ListModelsUserSecurity ### Description This method retrieves a list of models available for the authenticated user. ### Method GET ### Endpoint /models ### Parameters #### Query Parameters - **bearer** (str) - Required - The authentication token for the user. ### Request Example ```python # Example usage (conceptual, actual SDK usage may vary) from openrouter.apis import ListModelsUserSecurity models = ListModelsUserSecurity(bearer='YOUR_API_KEY') print(models) ``` ### Response #### Success Response (200) - **models** (list) - A list of available models, where each model is an object containing model details. #### Response Example ```json { "models": [ { "id": "model-id-1", "name": "Model Name 1", "provider": "Provider A" }, { "id": "model-id-2", "name": "Model Name 2", "provider": "Provider B" } ] } ``` ``` -------------------------------- ### Message Components Source: https://openrouter.ai/docs/sdks/python/components/message This section details the supported message component types for the OpenRouter Python SDK, including SystemMessage, UserMessage, MessageDeveloper, AssistantMessage, and ToolResponseMessage. Examples show how to instantiate these components. ```APIDOC ## Supported Message Types This API supports various message types for constructing conversations. Below are the available component types: ### `components.SystemMessage` Used for system-level instructions or context. **Example:** ```python from openrouter.types import components system_message: components.SystemMessage = components.SystemMessage(content="You are a helpful assistant.") ``` ### `components.UserMessage` Represents a message sent by the user. **Example:** ```python from openrouter.types import components user_message: components.UserMessage = components.UserMessage(content="What is the weather like today?") ``` ### `components.MessageDeveloper` Represents a message from a developer, often used for debugging or specific development-related interactions. **Example:** ```python from openrouter.types import components developer_message: components.MessageDeveloper = components.MessageDeveloper(content="Please provide more details about the API.") ``` ### `components.AssistantMessage` Represents a message generated by the assistant. **Example:** ```python from openrouter.types import components assistant_message: components.AssistantMessage = components.AssistantMessage(content="The weather today is sunny with a high of 75 degrees.") ``` ### `components.ToolResponseMessage` Represents a response from a tool or function call invoked by the assistant. **Example:** ```python from openrouter.types import components tool_response: components.ToolResponseMessage = components.ToolResponseMessage(content="Tool executed successfully.", tool_call_id="call_123") ``` **Note:** The Python SDK and its documentation are currently in beta. Please report any issues on [GitHub](https://github.com/OpenRouterTeam/python-sdk/issues). ``` -------------------------------- ### GET /key Source: https://openrouter.ai/docs/sdks/python/apikeys Retrieves metadata for the API key currently used for authentication. This is useful for inspecting the details of the active API key without needing its hash. ```APIDOC ## GET /key ### Description Get information on the API key associated with the current authentication session. ### Method GET ### Endpoint `/key` ### Parameters #### Path Parameters None #### Query Parameters - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Response #### Success Response (200) - **operations.GetCurrentKeyResponse** - The response object containing metadata for the current API key. ### Response Example ```json { "key_hash": "sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "key_name": "My Current Key", "created_at": "2023-01-02T09:00:00Z" } ``` ### Errors - **errors.UnauthorizedResponseError** (401) - If the API key is invalid or missing. - **errors.TooManyRequestsResponseError** (429) - If the client has been rate-limited. - **errors.InternalServerResponseError** (500) - If an internal server error occurs. ``` -------------------------------- ### Get Remaining Credits using Python SDK Source: https://openrouter.ai/docs/sdks/python/credits Retrieves the total credits purchased and used for the authenticated user. This function requires an API key to be set, and it handles default retry behavior. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.credits.get_credits() # Handle response print(res) ``` -------------------------------- ### Get Model Parameters - Python SDK Source: https://openrouter.ai/docs/sdks/python/parameters Retrieves a model's supported parameters and popularity data using the OpenRouter Python SDK. Requires authentication via bearer token and model author/slug. The response includes parameter details and can be handled by printing the result. ```python from openrouter import OpenRouter, operations import os with OpenRouter() as open_router: res = open_router.parameters.get_parameters(security=operations.GetParametersSecurity( bearer=os.getenv("OPENROUTER_BEARER", ""), ), author="", slug="") # Handle response print(res) ``` -------------------------------- ### Initialize and Send Chat Message (Python) Source: https://openrouter.ai/docs/sdks/python/overview Demonstrates how to initialize the OpenRouter client with an API key and send a chat message. It requires the 'openrouter' library and an environment variable 'OPENROUTER_API_KEY'. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY") ) as client: response = client.chat.send( model="minimax/minimax-m2", messages=[ {"role": "user", "content": "Explain quantum computing"} ] ) ``` -------------------------------- ### GET /embeddings/models Source: https://openrouter.ai/docs/sdks/python/embeddings Returns a list of all available embeddings models and their properties. This endpoint helps discover which embedding models are available for use. ```APIDOC ## GET /embeddings/models ### Description Returns a list of all available embeddings models and their properties. This endpoint helps discover which embedding models are available for use. ### Method GET ### Endpoint /embeddings/models ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.embeddings.list_models() # Handle response print(res) ``` ### Response #### Success Response (200) - **response** (List[operations.Model]) - A list of available embedding models and their properties. #### Response Example ```json [ { "id": "Taurus", "name": "Taurus", "description": "A fast and efficient embedding model.", "context_length": 8192, "created": 1677650000, "updated": 1677650000, "digits": 8, "token_cost": { "prompt": 0.0001, "completion": 0.0001, "unit": "1M tokens" }, "type": "embedding" } ] ``` ``` -------------------------------- ### GET /generation Source: https://openrouter.ai/docs/sdks/python/generations Retrieves request and usage metadata for a specific generation using its ID. This endpoint allows you to access detailed information about a past generation. ```APIDOC ## GET /generation ### Description Get request & usage metadata for a generation. ### Method GET ### Endpoint /generation ### Parameters #### Query Parameters - **id** (string) - Required - The unique identifier for the generation. - **retries** (utils.RetryConfig) - Optional - Configuration to override the default retry behavior of the client. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.generations.get_generation(id="") # Handle response print(res) ``` ### Response #### Success Response (200) - **GetGenerationResponse** (operations.GetGenerationResponse) - Contains the request and usage metadata for the generation. #### Response Example ```json { "example": "response body" } ``` ### Errors - **errors.UnauthorizedResponseError** (401) - Unauthorized access. - **errors.PaymentRequiredResponseError** (402) - Payment is required. - **errors.NotFoundResponseError** (404) - The specified generation was not found. - **errors.TooManyRequestsResponseError** (429) - Too many requests. - **errors.InternalServerResponseError** (500) - Internal server error. - **errors.BadGatewayResponseError** (502) - Bad gateway. - **errors.EdgeNetworkTimeoutResponseError** (524) - Edge network timeout. - **errors.ProviderOverloadedResponseError** (529) - Provider overloaded. - **errors.OpenRouterDefaultError** (4XX, 5XX) - Generic OpenRouter error for other client or server errors. ``` -------------------------------- ### CreateCoinbaseChargeSecurity Method Source: https://openrouter.ai/docs/sdks/python/operations/createcoinbasechargesecurity This section describes the CreateCoinbaseChargeSecurity method. It outlines the necessary fields, their types, and whether they are required. ```APIDOC ## CreateCoinbaseChargeSecurity Method ### Description This method is used to create a security charge on Coinbase using the OpenRouter Python SDK. It requires a bearer token for authentication. ### Method POST ### Endpoint /v1/createCoinbaseChargeSecurity ### Parameters #### Request Body - **bearer** (string) - Required - Authentication token for accessing the API. ### Request Example ```json { "bearer": "your_bearer_token" } ``` ### Response #### Success Response (200) - **charge_id** (string) - The unique identifier for the created Coinbase charge. - **status** (string) - The current status of the charge (e.g., 'pending', 'confirmed', 'failed'). #### Response Example ```json { "charge_id": "chg_abc123xyz", "status": "pending" } ``` #### Error Response (400/401/500) - **error** (string) - A message describing the error that occurred. #### Error Response Example ```json { "error": "Invalid bearer token" } ``` ``` -------------------------------- ### POST /keys Source: https://openrouter.ai/docs/sdks/python/apikeys Create a new API key with a specified name. ```APIDOC ## POST /keys ### Description Create a new API key with a specified name. ### Method POST ### Endpoint /keys ### Parameters #### Request Body - **name** (str) - Required - The name for the new API key. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.create(name="My New API Key") # Handle response print(res) ``` ### Response #### Success Response (200) - **Response** (operations.CreateResponse) - Details of the newly created API key. #### Response Example ```json { "example": "response body" } ``` ### Errors - errors.UnauthorizedResponseError (401) - errors.TooManyRequestsResponseError (429) - errors.InternalServerResponseError (500) - errors.OpenRouterDefaultError (4XX, 5XX) ``` -------------------------------- ### GET /keys/{hash} Source: https://openrouter.ai/docs/sdks/python/apikeys Retrieves a single API key by its hash identifier. This endpoint is useful for fetching details about a specific API key that has been previously generated. ```APIDOC ## GET /keys/{hash} ### Description Get a single API key by its hash identifier. ### Method GET ### Endpoint `/keys/{hash}` ### Parameters #### Path Parameters - **hash** (str) - Required - The hash identifier of the API key to retrieve #### Query Parameters - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Response #### Success Response (200) - **[operations.GetKeyResponse]** - The response object containing the API key details. ### Response Example ```json { "key_hash": "sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "key_name": "My Test Key", "created_at": "2023-01-01T12:00:00Z" } ``` ### Errors - **errors.UnauthorizedResponseError** (401) - If the API key is invalid or missing. - **errors.NotFoundResponseError** (404) - If the specified API key hash does not exist. - **errors.TooManyRequestsResponseError** (429) - If the client has been rate-limited. - **errors.InternalServerResponseError** (500) - If an internal server error occurs. ``` -------------------------------- ### GET /endpoints/zdr Source: https://openrouter.ai/docs/sdks/python/endpoints Previews the impact of Zero Data Replication (ZDR) on the available endpoints. This can help understand how ZDR might affect endpoint availability or performance. ```APIDOC ## GET /endpoints/zdr ### Description Preview the impact of ZDR on the available endpoints. ### Method GET ### Endpoint `/endpoints/zdr` ### Parameters #### Query Parameters - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.endpoints.list_zdr_endpoints() # Handle response print(res) ``` ### Response #### Success Response (200) - **Response Type**: [operations.ListEndpointsZdrResponse](/docs/sdks/python/operations/listendpointszdrresponse) #### Response Example ```json // Example response structure based on the provided documentation { "zdr_enabled": true, "message": "ZDR impact preview" } ``` ### Errors - **errors.InternalServerResponseError** (500) - Internal Server Error. - **errors.OpenRouterDefaultError** (4XX, 5XX) - Generic OpenRouter API error. ``` -------------------------------- ### Python SDK Prompt - List of Strings Type Source: https://openrouter.ai/docs/sdks/python/components/prompt Illustrates the usage of a list of strings for prompt values in the OpenRouter Python SDK. This allows for multiple string inputs as part of a prompt. ```python value: List[str] = /* values here */ ``` -------------------------------- ### SystemMessage - Python SDK Source: https://openrouter.ai/docs/sdks/python/components/message Demonstrates the initialization of a SystemMessage object using the OpenRouter Python SDK. This type is used for system-level instructions or context within a conversation. The SDK is in beta. ```python value: components.SystemMessage = /* values here */ ``` -------------------------------- ### GET /models/{author}/{slug}/endpoints Source: https://openrouter.ai/docs/sdks/python/endpoints Lists all available endpoints for a specified model, identified by its author and slug. This endpoint is useful for discovering which models are accessible and their configurations. ```APIDOC ## GET /models/{author}/{slug}/endpoints ### Description List all endpoints for a given model. ### Method GET ### Endpoint `/models/{author}/{slug}/endpoints` ### Parameters #### Path Parameters - **author** (str) - Required - The author of the model. - **slug** (str) - Required - The slug of the model. #### Query Parameters - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.endpoints.list(author="", slug="") # Handle response print(res) ``` ### Response #### Success Response (200) - **Response Type**: [operations.ListEndpointsResponse](/docs/sdks/python/operations/listendpointsresponse) #### Response Example ```json // Example response structure based on the provided documentation { "data": [ { "id": "model_id_1", "name": "Model Name 1", "description": "Description for Model 1" }, { "id": "model_id_2", "name": "Model Name 2", "description": "Description for Model 2" } ] } ``` ### Errors - **errors.NotFoundResponseError** (404) - Not Found. - **errors.InternalServerResponseError** (500) - Internal Server Error. - **errors.OpenRouterDefaultError** (4XX, 5XX) - Generic OpenRouter API error. ``` -------------------------------- ### POST /completions Source: https://openrouter.ai/docs/sdks/python/completions Creates a text completion based on the provided prompt and parameters. This endpoint supports both streaming and non-streaming responses. ```APIDOC ## POST /completions ### Description Creates a completion for the provided prompt and parameters. Supports both streaming and non-streaming modes. ### Method POST ### Endpoint /completions ### Parameters #### Request Body - **prompt** (list[str | dict]) - Required - The prompt(s) to generate a completion for. Can be a list of strings or a list of message objects. - **model** (str) - Optional - The model to use for generating completions. - **stream** (bool) - Optional - Whether to stream the response. Defaults to False. - **max_tokens** (int) - Optional - The maximum number of tokens to generate. - **temperature** (float) - Optional - Controls randomness. Lower values make output more focused and deterministic. - **top_p** (float) - Optional - Nucleus sampling parameter. Controls diversity of output. ### Request Example ```json { "prompt": ["Write a short story about a robot."], "model": "default/gpt-3.5-turbo", "stream": false, "max_tokens": 150, "temperature": 0.7, "top_p": 0.9 } ``` ### Response #### Success Response (200) - **choices** (list[object]) - A list of completion choices. - **text** (str) - The generated text completion. - **finish_reason** (str) - The reason the completion finished (e.g., 'stop', 'length'). #### Response Example ```json { "choices": [ { "text": "Once upon a time, in a world powered by steam and ingenuity, lived a small, clockwork robot named Bolt.", "finish_reason": "stop" } ] } ``` ``` -------------------------------- ### Analytics API - Get User Activity Source: https://openrouter.ai/docs/sdks/python/analytics Retrieves user activity data grouped by endpoint for the last 30 completed UTC days. You can optionally filter by a specific date. ```APIDOC ## GET /activity ### Description Returns user activity data grouped by endpoint for the last 30 (completed) UTC days. ### Method GET ### Endpoint /activity #### Query Parameters - **date_** (string) - Optional - Filter by a single UTC date in the last 30 days (YYYY-MM-DD format). - **retries** (RetryConfig) - Optional - Configuration to override the default retry behavior of the client. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.analytics.get_user_activity(date_="2025-08-24") # Handle response print(res) ``` ### Response #### Success Response (200) - **response** (GetUserActivityResponse) - The user activity data. #### Response Example ```json { "example": "response body" } ``` ### Errors - **BadRequestResponseError** (400) - application/json - **UnauthorizedResponseError** (401) - application/json - **ForbiddenResponseError** (403) - application/json - **InternalServerResponseError** (500) - application/json - **OpenRouterDefaultError** (4XX, 5XX) - */* ``` -------------------------------- ### List All Models and Properties - Python SDK Source: https://openrouter.ai/docs/sdks/python/models/models Lists all available models and their properties using the OpenRouter Python SDK. This operation can be filtered by category or supported parameters and requires an API key. The `open_router.models.list()` method is used for this purpose. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.models.list() # Handle response print(res) ``` -------------------------------- ### Create Keys Response Source: https://openrouter.ai/docs/sdks/python/operations/createkeysresponse This section details the structure and fields of the CreateKeysResponse object returned after successfully creating an API key. ```APIDOC ## CreateKeysResponse ### Description Represents the response received after successfully creating an API key. It contains details about the created key and the key itself. ### Method POST (Implied, as it's a creation response) ### Endpoint `/keys` (Implied, likely endpoint for key creation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (This is a response object) ### Request Example ```json { "name": "My Production Key", "description": "Production API Key" } ``` ### Response #### Success Response (201 Created - Implied) - **data** (operations.CreateKeysData) - Required - The created API key information. Contains fields like hash, name, label, disabled status, limits, usage, and timestamps. - **key** (string) - Required - The actual API key string. This is typically shown only once upon creation. #### Response Example ```json { "data": { "hash": "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", "name": "My Production Key", "label": "Production API Key", "disabled": false, "limit": 100, "limit_remaining": 74.5, "limit_reset": "monthly", "include_byok_in_limit": false, "usage": 25.5, "usage_daily": 25.5, "usage_weekly": 25.5, "usage_monthly": 25.5, "byok_usage": 17.38, "byok_usage_daily": 17.38, "byok_usage_weekly": 17.38, "byok_usage_monthly": 17.38, "created_at": "2025-08-24T10:30:00Z", "updated_at": "2025-08-24T15:45:00Z", "expires_at": "2027-12-31T23:59:59Z" }, "key": "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" } ``` ``` -------------------------------- ### Create API Key Source: https://openrouter.ai/docs/sdks/python/apikeys Creates a new API key with optional spending limits, reset types, expiration dates, and retry configurations. ```APIDOC ## POST /keys ### Description Creates a new API key. ### Method POST ### Endpoint /keys ### Parameters #### Request Body - **name** (str) - Required - Name for the new API key - **limit** (Optional[float]) - Optional - Optional spending limit for the API key in USD - **limit_reset** (Optional[operations.CreateKeysLimitReset]) - Optional - Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. - **include_byok_in_limit** (Optional[bool]) - Optional - Whether to include BYOK usage in the limit - **expires_at** (date) - Optional - Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Response #### Success Response (201) - **key** (str) - The newly created API key. - **name** (str) - The name of the API key. - **limit** (Optional[float]) - The spending limit for the API key. - **limit_reset** (Optional[str]) - The reset type for the spending limit. - **include_byok_in_limit** (bool) - Whether BYOK usage is included in the limit. - **expires_at** (Optional[str]) - The expiration timestamp for the API key. #### Response Example ```json { "key": "sk-or-v1-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "name": "My New API Key", "limit": 50.0, "limit_reset": "monthly", "include_byok_in_limit": true, "expires_at": "2027-12-31T23:59:59Z" } ``` ### Errors - **errors.BadRequestResponseError** (400) - **errors.UnauthorizedResponseError** (401) - **errors.TooManyRequestsResponseError** (429) - **errors.InternalServerResponseError** (500) - **errors.OpenRouterDefaultError** (4XX, 5XX) ``` -------------------------------- ### List Providers - Python SDK Source: https://openrouter.ai/docs/sdks/python/providers This snippet demonstrates how to list all available providers using the OpenRouter Python SDK. It requires an API key for authentication and handles the response, printing it to the console. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.providers.list() # Handle response print(res) ``` -------------------------------- ### GetParametersSecurity Method Source: https://openrouter.ai/docs/sdks/python/operations/getparameterssecurity Information on how to use the GetParametersSecurity method, including its parameters and expected request/response formats. ```APIDOC ## GetParametersSecurity ### Description Retrieves security parameters for the OpenRouter API. ### Method POST ### Endpoint /get_parameters_security ### Parameters #### Request Body - **bearer** (str) - Required - Authentication token. ### Request Example ```json { "bearer": "YOUR_API_KEY" } ``` ### Response #### Success Response (200) - **message** (str) - A success message. - **status** (str) - The status of the operation. ``` -------------------------------- ### Get Current API Key Metadata - Python Source: https://openrouter.ai/docs/sdks/python/apikeys Fetches metadata for the API key currently associated with the authentication session. This operation does not require any specific parameters other than optional retry configurations. It returns a GetCurrentKeyResponse with the key's metadata. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.get_current_key_metadata() # Handle response print(res) ``` -------------------------------- ### List API Keys using Python SDK Source: https://openrouter.ai/docs/sdks/python/apikeys This snippet demonstrates how to list API keys using the OpenRouter Python SDK. It requires an API key for authentication and allows optional parameters for including disabled keys and pagination. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.list(include_disabled="false", offset="0") # Handle response print(res) ``` -------------------------------- ### Completion API Parameters Source: https://openrouter.ai/docs/sdks/python/completions This section details the parameters available for the text completion endpoint, allowing customization of the generated output. ```APIDOC ## POST /v1/completions ### Description Generates a text completion based on a provided prompt and model, with various parameters to control the output. ### Method POST ### Endpoint /v1/completions ### Parameters #### Request Body - **prompt** (components.Prompt) - Required - The input text prompt for completion. - **model** (Optional[str]) - Optional - The specific model to use for completion. - **models** (List[str]) - Optional - A list of models to consider for completion. - **best_of** (OptionalNullable[int]) - Optional - The number of best completion choices to generate. - **echo** (OptionalNullable[bool]) - Optional - Whether to include the prompt in the completion output. - **frequency_penalty** (OptionalNullable[float]) - Optional - Controls the penalty for frequent tokens. - **logit_bias** (Dict[str, float]) - Optional - Adjusts the probability of specific tokens appearing. - **logprobs** (OptionalNullable[int]) - Optional - The number of log probabilities to return. - **max_tokens** (OptionalNullable[int]) - Optional - The maximum number of tokens to generate. - **n** (OptionalNullable[int]) - Optional - The number of completions to generate. - **presence_penalty** (OptionalNullable[float]) - Optional - Controls the penalty for new tokens based on their presence. - **seed** (OptionalNullable[int]) - Optional - A seed for reproducible results. - **stop** (OptionalNullable[components.CompletionCreateParamsStop]) - Optional - Sequences where the API will stop generating further tokens. - **stream** (Optional[bool]) - Optional - Whether to stream the completion results. - **stream_options** (OptionalNullable[components.StreamOptions]) - Optional - Options for streaming the completion. - **suffix** (OptionalNullable[str]) - Optional - A suffix to append to the generated text. - **temperature** (OptionalNullable[float]) - Optional - Controls the randomness of the generated text. ### Request Example ```json { "prompt": "Once upon a time", "model": "gpt-3.5-turbo", "max_tokens": 50 } ``` ### Response #### Success Response (200) - **choices** (List[object]) - A list of completion choices. - **created** (int) - The timestamp of creation. - **id** (str) - The unique identifier for the completion. - **model** (str) - The model used for completion. - **object** (str) - The type of object returned. #### Response Example ```json { "choices": [ { "finish_reason": "stop", "index": 0, "logprobs": null, "text": " there was a great king who ruled over a vast kingdom." } ], "created": 1677652288, "id": "cmpl-72jC5j5n6z7z7z7z7z7z7z7z7z7z7z", "model": "gpt-3.5-turbo-instruct", "object": "text_completion", "usage": { "completion_tokens": 10, "prompt_tokens": 4, "total_tokens": 14 } } ``` ``` -------------------------------- ### Get User Activity - Python SDK Source: https://openrouter.ai/docs/sdks/python/analytics Retrieves user activity data grouped by endpoint for the last 30 UTC days. This function requires an API key for authentication and optionally accepts a specific date and retry configuration. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.analytics.get_user_activity(date_="2025-08-24") # Handle response print(res) ``` -------------------------------- ### CreateAuthKeysCodeResponse Source: https://openrouter.ai/docs/sdks/python/operations/createauthkeyscoderesponse This method is part of the OpenRouter Python SDK and is used to create authorization keys. It returns data related to the created authorization code. ```APIDOC ## CreateAuthKeysCodeResponse ### Description This method is used to create authorization keys and returns data related to the created authorization code. ### Method POST (Assumed, based on 'Create' action) ### Endpoint /v1/auth/code (Assumed, typical endpoint for creating auth codes) ### Parameters #### Request Body - **data** (operations.CreateAuthKeysCodeData) - Required - Auth code data containing id, app_id, and created_at. ### Request Example ```json { "data": { "id": "auth_code_xyz789", "app_id": 12345, "created_at": "2025-08-24T10:30:00Z" } } ``` ### Response #### Success Response (200) - **data** (operations.CreateAuthKeysCodeData) - Auth code data containing id, app_id, and created_at. #### Response Example ```json { "data": { "id": "auth_code_xyz789", "app_id": 12345, "created_at": "2025-08-24T10:30:00Z" } } ``` ``` -------------------------------- ### Get API Key - Python Source: https://openrouter.ai/docs/sdks/python/apikeys Retrieves a specific API key using its hash. The function takes the API key's hash as a mandatory parameter and allows for optional retry configuration. It returns a GetKeyResponse containing the API key details. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.get(hash="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") # Handle response print(res) ``` -------------------------------- ### Type-Safe Streaming Responses (Python) Source: https://openrouter.ai/docs/sdks/python/overview Demonstrates how to handle streaming responses from the chat API with full type information for each event. This is useful for real-time applications. ```python stream = client.chat.send( model="minimax/minimax-m2", messages=[{"role": "user", "content": "Write a story"}], stream=True ) for event in stream: # Full type information for streaming responses content = event.choices[0].delta.content if event.choices else None ``` -------------------------------- ### Get Total Count of Available Models - Python SDK Source: https://openrouter.ai/docs/sdks/python/models/models Retrieves the total count of available models using the OpenRouter Python SDK. This function requires an API key and returns a response object containing the count. It utilizes the `open_router.models.count()` method. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.models.count() # Handle response print(res) ``` -------------------------------- ### Get Generation Metadata with Python SDK Source: https://openrouter.ai/docs/sdks/python/generations Retrieves request and usage metadata for a specific generation using the OpenRouter Python SDK. Requires an API key for authentication. The function takes a generation ID as a required parameter and optionally accepts retry configuration. ```python from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.generations.get_generation(id="") # Handle response print(res) ``` -------------------------------- ### Completion Parameters and Response Source: https://openrouter.ai/docs/sdks/python/completions Details the optional parameters that can be passed when requesting a text completion and the structure of the response. ```APIDOC ## Completion Endpoint Details ### Description This section describes the optional parameters available for generating text completions and the expected response structure. ### Method POST ### Endpoint /v1/chat/completions (example based on common patterns) ### Parameters #### Query Parameters None #### Request Body - **model** (str) - Required - The model to use for completion. - **messages** (list) - Required - The messages to send to the model. - **top_p** (float) - Optional - Controls diversity via nucleus sampling. 1.0 means all tokens are considered. - **user** (str) - Optional - Unique identifier for the user. - **metadata** (Dict[str, str]) - Optional - Additional metadata to include with the request. - **response_format** (components.CompletionCreateParamsResponseFormatUnion) - Optional - Specifies the format of the response. - **retries** (utils.RetryConfig) - Optional - Configuration to override the default retry behavior of the client. ### Request Example ```json { "model": "openai/gpt-3.5-turbo", "messages": [ {"role": "user", "content": "Hello!"} ], "top_p": 0.9, "user": "user_123", "metadata": { "key": "value" }, "response_format": {"type": "json_object"}, "retries": { "enabled": true, "max_retries": 3, "backoff_factor": 0.5 } } ``` ### Response #### Success Response (200) - **id** (str) - The ID of the completion. - **choices** (list) - A list of completion choices. - **created** (int) - The timestamp of when the completion was created. - **model** (str) - The model used for the completion. - **object** (str) - The type of object returned. - **usage** (dict) - Usage statistics for the completion. (For detailed response structure, refer to [components.CompletionResponse](../../components/completionresponse.md)) #### Response Example ```json { "id": "chatcmpl-12345", "choices": [ { "finish_reason": "stop", "index": 0, "message": { "content": "Hello there! How can I help you today?", "role": "assistant" } } ], "created": 1677652288, "model": "openai/gpt-3.5-turbo", "object": "chat.completion", "usage": { "completion_tokens": 10, "prompt_tokens": 5, "total_tokens": 15 } } ``` ### Errors #### Error Response - **errors.ChatError** - Status Codes: 400, 401, 429, 500. Content Type: application/json. - **errors.OpenRouterDefaultError** - Status Codes: 4XX, 5XX. Content Type: */*. #### Error Example (ChatError) ```json { "error": { "message": "Invalid request: Missing required parameter.", "type": "invalid_request_error", "code": "missing_parameter" } } ``` ```