### Copy Environment File Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Copy the example environment file to `.env` for local development setup. ```bash cp .env.example .env ``` -------------------------------- ### Setup Environment for Running Tests Source: https://github.com/openrouterteam/python-sdk/blob/main/README-PYPI.md Before running tests, copy the example environment file and add your OpenRouter API key to the .env file. ```bash cp .env.example .env ``` ```bash OPENROUTER_API_KEY=your_api_key_here ``` ```bash pytest ``` -------------------------------- ### Quick Start: Basic Chat Interaction Source: https://github.com/openrouterteam/python-sdk/blob/main/OVERVIEW.md A minimal example demonstrating how to initialize the client, send a single chat message, and print the response content. Requires the OPENROUTER_API_KEY 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 Source: https://github.com/openrouterteam/python-sdk/blob/main/OVERVIEW.md Shows commands for installing the OpenRouter Python SDK using different package managers: uv, pip, and poetry. ```bash # Using uv (recommended) uv add openrouter # Using pip pip install openrouter # Using poetry poetry add openrouter ``` -------------------------------- ### Install OpenRouter SDK with pip Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Install the SDK using the standard Python package installer. ```bash pip install openrouter ``` -------------------------------- ### Actionable Error Message Example Source: https://github.com/openrouterteam/python-sdk/blob/main/OVERVIEW.md Illustrates the specific, actionable error messages provided by the SDK, guiding users on how to correct issues like insufficient message counts. ```python # Instead of generic errors, get specific guidance: # "Model 'openai/o1-preview' requires at least 2 messages. # You provided 1 message. Add a system or user message." ``` -------------------------------- ### ListMemberAssignmentsResponse Example Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/operations/listmemberassignmentsresponse.md This example shows the structure of the ListMemberAssignmentsResponse, including the 'data' array containing assignment details and the 'total_count'. ```json { "data": [ { "assigned_by": "user_abc123", "created_at": "2025-08-24T10:30:00Z", "guardrail_id": "550e8400-e29b-41d4-a716-446655440001", "id": "550e8400-e29b-41d4-a716-446655440000", "organization_id": "org_xyz789", "user_id": "user_abc123" } ], "total_count": 1 } ``` -------------------------------- ### Install OpenRouter SDK with uv Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Use 'uv add' for fast and modern Python package management. ```bash uv add openrouter ``` -------------------------------- ### Install OpenRouter SDK with Poetry Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Add the SDK as a dependency using Poetry's pyproject.toml management. ```bash poetry add openrouter ``` -------------------------------- ### Example Provider Preferences Parameter Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/responses/README.md Shows how to configure provider preferences, such as enabling fallbacks when multiple model providers are available. ```json { "allow_fallbacks": true } ``` -------------------------------- ### Example Prompt Template Parameter Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/responses/README.md Illustrates the structure for the `prompt` parameter, including the prompt ID and variables for templating. ```json { "id": "prompt-abc123", "variables": { "name": "John" } } ``` -------------------------------- ### Chat Stream Chunk Example Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/operations/sendchatcompletionrequestresponsebody.md This example shows the structure of a single chat stream chunk received as part of a successful chat completion response. It includes details about the choices, delta content, finish reason, and metadata like creation timestamp and model. ```json { "choices": [ { "delta": { "content": "Hello", "role": "assistant" }, "finish_reason": null, "index": 0 } ], "created": 1677652288, "id": "chatcmpl-123", "model": "openai/gpt-4", "object": "chat.completion.chunk" } ``` -------------------------------- ### Chat Request Example Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/operations/sendchatcompletionrequestrequest.md Example of a chat request object, specifying messages, model, and other parameters. This can be used to define the input for a chat completion. ```json { "max_tokens": 150, "messages": [ { "content": "You are a helpful assistant.", "role": "system" }, { "content": "What is the capital of France?", "role": "user" } ], "model": "openai/gpt-4", "temperature": 0.7 } ``` -------------------------------- ### Synchronous SDK Usage Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Example of making a synchronous chat completion request using the OpenRouter SDK. Ensure the OPENROUTER_API_KEY environment variable is set. ```python # Synchronous Example from openrouter import OpenRouter import os with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.chat.send(messages=[ { "role": "user", "content": "Hello, how are you?", }, ], model="anthropic/claude-4.5-sonnet", provider={ "zdr": True, "sort": "price", }, stream=True) for event in event_stream: # handle event print(event, flush=True) ``` -------------------------------- ### Asynchronous Chat Message Sending Source: https://github.com/openrouterteam/python-sdk/blob/main/OVERVIEW.md Provides an example of using the SDK asynchronously with `async`/`await` for non-blocking operations, 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()) ``` -------------------------------- ### PDFParserEnginePDFText Usage Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/components/pdfparserengine.md Example of how to use the components.PDFParserEnginePDFText type. Replace '/* values here */' with actual values. ```python value: components.PDFParserEnginePDFText = /* values here */ ``` -------------------------------- ### Asynchronous SDK Usage Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Example of making an asynchronous chat completion request using the OpenRouter SDK. This is suitable for non-blocking operations. Ensure the OPENROUTER_API_KEY environment variable is set. ```python # Asynchronous Example import asyncio from openrouter import OpenRouter import os async def main(): async with OpenRouter( api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = await open_router.chat.send_async(messages=[ { "role": "user", "content": "Hello, how are you?", }, ], model="anthropic/claude-4.5-sonnet", provider={ "zdr": True, "sort": "price", }, stream=True) async for event in event_stream: # handle event print(event, flush=True) asyncio.run(main()) ``` -------------------------------- ### CreateAuthKeysCodeRequestBody Example Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/operations/createauthkeyscoderequest.md This JSON object represents the body of a request to create authentication keys using a code challenge. It includes a callback URL, code challenge, its method, and an optional limit. ```json { "callback_url": "https://myapp.com/auth/callback", "code_challenge": "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", "code_challenge_method": "S256", "limit": 100 } ``` -------------------------------- ### List Guardrail Member Assignments (Python) Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/guardrails/README.md Use this snippet to list all organization member assignments for a specific guardrail. A management key is required. The example demonstrates pagination using a while loop. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.guardrails.list_guardrail_member_assignments(id="550e8400-e29b-41d4-a716-446655440000") while res is not None: # Handle items res = res.next() ``` -------------------------------- ### Get User Activity - Python Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/analytics/README.md Retrieves user activity data grouped by endpoint for the last 30 completed UTC days. Requires a management key. Ensure you set appropriate values for `http_referer`, `x_open_router_title`, and `x_open_router_categories`. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.analytics.get_user_activity() # Handle response print(res) ``` -------------------------------- ### get_current_key_metadata Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/apikeys/README.md Get information on the API key associated with the current authentication session. ```APIDOC ## get_current_key_metadata ### Description Get information on the API key associated with the current authentication session. ### Method GET ### Endpoint /key ### Parameters #### Query Parameters - **http_referer** (Optional[str]) - Optional - 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. - **x_open_router_title** (Optional[str]) - Optional - The app display name allows you to customize how your app appears in OpenRouter's dashboard. - **x_open_router_categories** (Optional[str]) - Optional - Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings. - **retries** ([Optional[utils.RetryConfig]](../../models/utils/retryconfig.md)) - Optional - Configuration to override the default retry behavior of the client. ### Response #### Success Response (200) **[operations.GetCurrentKeyResponse](../../operations/getcurrentkeyresponse.md)** ``` -------------------------------- ### Access New Models Instantly Source: https://github.com/openrouterteam/python-sdk/blob/main/OVERVIEW.md Demonstrates how new models become available immediately after launch without manual SDK updates. This snippet sends a request to a model. ```python # When new models launch, they're available instantly response = client.chat.send( model="minimax/minimax-m2" ) ``` -------------------------------- ### Get Generation Metadata Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/generations/README.md Retrieves the request and usage metadata for a specific generation using its ID. ```APIDOC ## Get Generation Metadata ### Description Get request & usage metadata for a generation. ### Method GET ### Endpoint /generation ### Parameters #### Query Parameters - **id** (string) - Required - The unique identifier of the generation. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.generations.get_generation(id="gen-1234567890") # Handle response print(res) ``` ### Response #### Success Response (200) - **field1** (type) - Description #### Response Example { "example": "response body" } ``` -------------------------------- ### Initialize and Send Chat Message Source: https://github.com/openrouterteam/python-sdk/blob/main/OVERVIEW.md Instantiate the OpenRouter client with an API key and send a chat message. Ensure 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 client: response = client.chat.send( model="minimax/minimax-m2", messages=[ {"role": "user", "content": "Explain quantum computing"} ] ) ``` -------------------------------- ### Run Tests Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Execute the test suite using pytest after setting up the environment. ```bash pytest ``` -------------------------------- ### PDFParserEngineEnum Usage Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/components/pdfparserengine.md Example of how to use the components.PDFParserEngineEnum type. Replace '/* values here */' with actual enum values. ```python value: components.PDFParserEngineEnum = /* values here */ ``` -------------------------------- ### CreateAuthKeys Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/oauth/README.md This section details the parameters for creating authentication keys, including options for PKCE, expiration, labels, and usage limits. ```APIDOC ## Parameters for CreateAuthKeys ### Path Parameters None ### Query Parameters None ### Request Body - **code_challenge** (Optional[str]) - PKCE code challenge for enhanced security. Example: `E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM` - **code_challenge_method** (Optional[operations.CreateAuthKeysCodeCodeChallengeMethod]) - The method used to generate the code challenge. Example: `S256` - **expires_at** (date) - Optional expiration time for the API key to be created. Example: `2027-12-31T23:59:59Z` - **key_label** (Optional[str]) - Optional custom label for the API key. Defaults to the app name if not provided. Example: `My Custom Key` - **limit** (Optional[float]) - Credit limit for the API key to be created. Example: `100` - **usage_limit_type** (Optional[operations.UsageLimitType]) - Optional credit limit reset interval. When set, the credit limit resets on this interval. Example: `monthly` ``` -------------------------------- ### Get Generation Request Parameters Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/operations/getgenerationrequest.md This section details the fields that can be used to identify and categorize a generation request. ```APIDOC ## Get Generation Request ### Description Retrieves details about a specific generation request. ### Parameters #### Query Parameters - **id** (str) - Required - The unique identifier for the generation request. - **http_referer** (Optional[str]) - Optional - The application's URL, used as a primary identifier for rankings and tracking API usage. - **x_open_router_title** (Optional[str]) - Optional - A display name for the application, customizing its appearance in the OpenRouter dashboard. - **x_open_router_categories** (Optional[str]) - Optional - A comma-separated list of application categories (e.g., "cli-agent,cloud-agent"), used for marketplace rankings. ### Request Example ```json { "id": "gen-1234567890", "http_referer": "https://example.com", "x_open_router_title": "My Awesome App", "x_open_router_categories": "cli-agent,cloud-agent" } ``` ### Response #### Success Response (200) - **generation_request_details** (object) - Contains the details of the generation request. #### Response Example ```json { "generation_request_details": { "id": "gen-1234567890", "status": "completed", "created_at": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### List API Keys Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/apikeys/README.md Use this snippet to list all API keys associated with your account. Ensure you have a management key and have configured the OpenRouter client with necessary headers and your API key. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.list() # Handle response print(res) ``` -------------------------------- ### Run Python script with uvx Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Execute a Python script using 'uvx' for isolated environments and dependency management. ```shell uvx --from openrouter python ``` -------------------------------- ### Get API Key Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/apikeys/README.md Retrieves a single API key using its hash. Requires a Management key for authentication. ```APIDOC ## get Get a single API key by hash. [Management key](/docs/guides/overview/auth/management-api-keys) required. ### Method GET ### Endpoint /keys/{hash} ### Parameters #### Path Parameters - **hash** (string) - Required - The hash of the API key to retrieve. ### Response #### Success Response (200) - **key** (string) - The API key. - **hash** (string) - The hash of the API key. - **created_at** (string) - The timestamp when the API key was created. - **last_used** (string) - The timestamp when the API key was last used. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.get(hash="f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943") # Handle response print(res) ``` ### Errors - errors.UnauthorizedResponseError (401) - errors.NotFoundResponseError (404) - errors.TooManyRequestsResponseError (429) - errors.InternalServerResponseError (500) - errors.OpenRouterDefaultError (4XX, 5XX) ``` -------------------------------- ### Prompt Parameters Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/responses/README.md Details on the `prompt` parameter, which can accept a StoredPromptTemplate. ```APIDOC ## Prompt Parameters ### Parameters - **prompt** (OptionalNullable[components.StoredPromptTemplate]) - Optional - Description: N/A ### Request Example ```json { "id": "prompt-abc123", "variables": { "name": "John" } } ``` ``` -------------------------------- ### Get Guardrail by ID Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/guardrails/README.md Retrieves a specific guardrail using its unique identifier. Optional headers can be provided for tracking and categorization. ```APIDOC ## GET /guardrails/{id} ### Description Retrieves a specific guardrail using its unique identifier. Optional headers can be provided for tracking and categorization. ### Method GET ### Endpoint /guardrails/{id} ### Parameters #### Path Parameters - **id** (str) - Required - The unique identifier of the guardrail to retrieve #### Headers - **http_referer** (Optional[str]) - Optional - 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. - **x_open_router_title** (Optional[str]) - Optional - The app display name allows you to customize how your app appears in OpenRouter's dashboard. - **x_open_router_categories** (Optional[str]) - Optional - Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings. ### Response #### Success Response (200) - **guardrail_details** (object) - Details of the requested guardrail ``` -------------------------------- ### Get Guardrail by ID Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/guardrails/README.md Retrieves a single guardrail configuration using its unique identifier. Requires a Management key for authentication. ```APIDOC ## get Guardrail by ID ### Description Get a single guardrail by ID. [Management key](/docs/guides/overview/auth/management-api-keys) required. ### Method GET ### Endpoint /guardrails/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the guardrail to retrieve. ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.guardrails.get(id="550e8400-e29b-41d4-a716-446655440000") # Handle response print(res) ``` ### Response #### Success Response (200) - **components.DeleteGuardrailResponse** - The response object containing guardrail details. (Refer to [components.DeleteGuardrailResponse](../../components/deleteguardrailresponse.md) for schema) ### Errors - **errors.UnauthorizedResponseError** (401) - **errors.NotFoundResponseError** (404) - **errors.InternalServerResponseError** (500) - **errors.OpenRouterDefaultError** (4XX, 5XX) ``` -------------------------------- ### Get Remaining Credits Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/credits/README.md Retrieves the total credits purchased and used for the authenticated user. A management key is required for this operation. ```APIDOC ## GET /credits ### Description Get total credits purchased and used for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required. ### Method GET ### Endpoint /credits ### Parameters #### Query Parameters - **http_referer** (Optional[str]) - Optional - 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. - **x_open_router_title** (Optional[str]) - Optional - The app display name allows you to customize how your app appears in OpenRouter's dashboard. - **x_open_router_categories** (Optional[str]) - Optional - Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings. - **retries** (Optional[utils.RetryConfig]) - Optional - Configuration to override the default retry behavior of the client. ### Response #### Success Response (200) - **operations.GetCreditsResponse** (object) - Details about the user's credits. ``` -------------------------------- ### Set OpenRouter API Key in .env Source: https://github.com/openrouterteam/python-sdk/blob/main/README.md Edit the `.env` file to include your OpenRouter API key. ```bash OPENROUTER_API_KEY=your_api_key_here ``` -------------------------------- ### Get Guardrail Request by ID Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/operations/getguardrailrequest.md Retrieves a specific guardrail request using its unique ID. Optional headers can be provided for context. ```APIDOC ## GET /guardrails/{id} ### Description Retrieves a specific guardrail request using its unique identifier. ### Method GET ### Endpoint /guardrails/{id} ### Parameters #### Path Parameters - **id** (str) - Required - The unique identifier of the guardrail to retrieve. #### Query Parameters - **http_referer** (Optional[str]) - Optional - The app identifier, used as the primary identifier for rankings and tracking API usage per application. - **x_open_router_title** (Optional[str]) - Optional - The app display name, used to customize how your app appears in OpenRouter's dashboard. - **x_open_router_categories** (Optional[str]) - Optional - A comma-separated list of app categories (e.g., "cli-agent,cloud-agent"), used for marketplace rankings. ### Response #### Success Response (200) - **id** (str) - The unique identifier of the guardrail. - **http_referer** (Optional[str]) - The app identifier. - **x_open_router_title** (Optional[str]) - The app display name. - **x_open_router_categories** (Optional[str]) - Comma-separated list of app categories. ``` -------------------------------- ### Create API Key - Python Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/apikeys/README.md Use this snippet to create a new API key for the authenticated user. A management key is required. Ensure you replace placeholder values for http_referer and x_open_router_title. The API key can be provided via an environment variable. ```python from openrouter import OpenRouter from openrouter.utils import parse_datetime import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.create(name="My New API Key", expires_at=parse_datetime("2027-12-31T23:59:59Z"), include_byok_in_limit=True, limit=50, limit_reset="monthly") # Handle response print(res) ``` -------------------------------- ### List All Providers Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/providers/README.md Use this snippet to retrieve a list of all available AI providers. Ensure you have set your API key and provided necessary HTTP headers like 'Referer' and 'Title'. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.providers.list() # Handle response print(res) ``` -------------------------------- ### List API Keys Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/apikeys/README.md Lists all API keys for the authenticated user. Requires a management key. ```APIDOC ## GET /keys ### Description Lists all API keys for the authenticated user. Requires a management key. ### Method GET ### Endpoint /keys ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.list() # Handle response print(res) ``` ### Response #### Success Response (200) - **keys** (list) - A list of API key objects. #### Response Example ```json { "keys": [ { "id": "key_123", "name": "My Key", "created": "2023-01-01T12:00:00Z", "last_used": null, "permissions": { "models": "*", "models_read_only": "*" } } ] } ``` ### Errors - **errors.UnauthorizedResponseError**: 401 - **errors.InternalServerResponseError**: 500 - **errors.OpenRouterDefaultError**: 4XX, 5XX ``` -------------------------------- ### Get User Activity Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/analytics/README.md Retrieves user activity data grouped by endpoint for the last 30 completed UTC days. Requires a management key. ```APIDOC ## GET /activity ### Description Returns user activity data grouped by endpoint for the last 30 (completed) UTC days. [Management key](/docs/guides/overview/auth/management-api-keys) required. ### Method GET ### Endpoint /activity ### Request Example ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.analytics.get_user_activity() # Handle response print(res) ``` ### Response #### Success Response (200) - **data** (object) - User activity data. - **total_usage** (integer) - Total usage. - **total_requests** (integer) - Total requests. #### Response Example ```json { "data": { "/v1/chat/completions": { "total_usage": 1000, "total_requests": 100 } }, "total_usage": 1000, "total_requests": 100 } ``` ``` -------------------------------- ### Get Generation Metadata Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/generations/README.md Retrieve request and usage metadata for a specific generation using its ID. Ensure your API key and referer details are correctly configured. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.generations.get_generation(id="gen-1234567890") # Handle response print(res) ``` -------------------------------- ### Asynchronous User Activity Request Source: https://github.com/openrouterteam/python-sdk/blob/main/USAGE.md This snippet demonstrates how to make asynchronous requests to fetch user activity data using asyncio. The API key should be configured via environment variables. ```python # Asynchronous Example import asyncio from openrouter import OpenRouter import os async def main(): async with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = await open_router.analytics.get_user_activity_async() # Handle response print(res) asyncio.run(main()) ``` -------------------------------- ### Create API Key Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/apikeys/README.md Create a new API key for the authenticated user. Requires a Management key. ```APIDOC ## POST /keys ### Description Create a new API key for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required. ### Method POST ### Endpoint /keys ### Parameters #### Request Body - **name** (string) - Required - The name of the API key. - **expires_at** (string) - Optional - The expiration date of the API key in ISO 8601 format. - **include_byok_in_limit** (boolean) - Optional - Whether to include BYOK in the limit. - **limit** (integer) - Optional - The rate limit for the API key. - **limit_reset** (string) - Optional - The reset period for the rate limit (e.g., 'monthly'). ### Request Example ```python from openrouter import OpenRouter from openrouter.utils import parse_datetime import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.create(name="My New API Key", expires_at=parse_datetime("2027-12-31T23:59:59Z"), include_byok_in_limit=True, limit=50, limit_reset="monthly") # Handle response print(res) ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the API key. - **key** (string) - The API key itself. - **name** (string) - The name of the API key. - **expires_at** (string) - The expiration date of the API key in ISO 8601 format. - **created_at** (string) - The creation date of the API key in ISO 8601 format. - **include_byok_in_limit** (boolean) - Whether BYOK is included in the limit. - **limit** (integer) - The rate limit for the API key. - **limit_reset** (string) - The reset period for the rate limit. #### Response Example ```json { "id": "key_abc123", "key": "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "name": "My New API Key", "expires_at": "2027-12-31T23:59:59Z", "created_at": "2023-10-27T10:00:00Z", "include_byok_in_limit": true, "limit": 50, "limit_reset": "monthly" } ``` ### Errors - **UnauthorizedResponseError** (401) - **TooManyRequestsResponseError** (429) - **InternalServerResponseError** (500) - **OpenRouterDefaultError** (4XX, 5XX) ``` -------------------------------- ### Response Parameters Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/responses/README.md This section outlines the parameters that can be configured when making requests that involve responses, such as enabling plugins or setting penalties. ```APIDOC ## Parameters ### `plugins` - **Type**: List[[components.ResponsesRequestPlugin](../../components/responsesrequestplugin.md)] - **Required**: No - **Description**: Plugins you want to enable for this request, including their settings. ### `presence_penalty` - **Type**: OptionalNullable[float] - **Required**: No - **Description**: N/A ### `previous_response_id` - **Type**: OptionalNullable[str] - **Required**: No - **Description**: N/A ``` -------------------------------- ### Get Remaining Credits Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/credits/README.md Retrieves the total credits purchased and used for the authenticated user. Ensure you have a management API key and set the necessary headers like `http_referer`, `x_open_router_title`, and `x_open_router_categories`. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.credits.get_credits() # Handle response print(res) ``` -------------------------------- ### Create Guardrail with OpenRouter SDK Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/guardrails/README.md Use this snippet to create a new guardrail using the OpenRouter SDK. Ensure you have your API key and provide necessary parameters like name, allowed models/providers, and limits. Management API keys are required for this operation. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.guardrails.create(name="My New Guardrail", allowed_models=None, allowed_providers=[ "openai", "anthropic", "deepseek", ], description="A guardrail for limiting API usage", enforce_zdr=False, ignored_models=None, ignored_providers=None, limit_usd=50, reset_interval="monthly") # Handle response print(res) ``` -------------------------------- ### Response Parameters Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/responses/README.md Configuration options for SDK responses. ```APIDOC ## Response Parameters ### Parameters - **session_id** (*Optional[str]*): A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. - **stream** (*Optional[bool]*): Controls whether the response should be streamed. - **temperature** (*OptionalNullable[float]*): Controls randomness in the output. Lower values make the output more deterministic. ``` -------------------------------- ### Get API Key by Hash Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/apikeys/README.md Retrieves a single API key using its hash. Requires a management key for authentication. Ensure the OpenRouter client is initialized with necessary headers and API key. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.api_keys.get(hash="f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943") # Handle response print(res) ``` -------------------------------- ### Reasoning Configuration Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/chat/README.md Configuration options for reasoning models, allowing control over effort and summary style. ```APIDOC ## Reasoning Configuration ### Description Configuration options for reasoning models. ### Parameters #### Query Parameters - **reasoning** (Optional[components.Reasoning]) - Optional - Configuration options for reasoning models. ### Request Example ```json { "reasoning": { "effort": "medium", "summary": "concise" } } ``` ``` -------------------------------- ### Bulk Unassign Keys from Guardrail (Python) Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/guardrails/README.md Use this snippet to unassign multiple API keys from a specific guardrail. A management key is required. Ensure you have the OpenRouter SDK installed and your API key configured. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.guardrails.bulk_unassign_keys(id="550e8400-e29b-41d4-a716-446655440000", key_hashes=[ "c56454edb818d6b14bc0d61c46025f1450b0f4012d12304ab40aacb519fcbc93", ]) # Handle response print(res) ``` -------------------------------- ### Get Guardrail by ID using Python SDK Source: https://github.com/openrouterteam/python-sdk/blob/main/docs/sdks/guardrails/README.md Use this snippet to retrieve a specific guardrail by its ID. Ensure you have your API key set as an environment variable OPENROUTER_API_KEY and provide necessary values for http_referer, x_open_router_title, and x_open_router_categories. ```python from openrouter import OpenRouter import os with OpenRouter( http_referer="", x_open_router_title="", x_open_router_categories="", api_key=os.getenv("OPENROUTER_API_KEY", ""), ) as open_router: res = open_router.guardrails.get(id="550e8400-e29b-41d4-a716-446655440000") # Handle response print(res) ```