### Configure Lark SDK (Python) Source: https://docs.uselark.ai/index Initializes the Lark client using your API key. This client is then used to interact with Lark's services. Ensure you have the 'lark-billing' Python package installed. ```python from lark import Lark lark_client = Lark( api_key=LARK_API_KEY, ) ``` -------------------------------- ### Create Rate Card Source: https://docs.uselark.ai/index This section describes how to create a rate card, which defines the pricing structure for services. It includes options for fixed rates and usage-based rates, with examples for setting up a starter plan. ```APIDOC ## POST /rate_cards ### Description Creates a rate card that defines pricing rules for services, including fixed and usage-based rates. ### Method POST ### Endpoint /rate_cards ### Parameters #### Request Body - **name** (string) - Required - The name of the rate card (e.g., "Starter plan"). - **description** (string) - Optional - A description of the rate card. - **billing_interval** (string) - Required - The billing cycle (e.g., "monthly", "yearly"). - **fixed_rates** (array) - Optional - A list of fixed charges. - **name** (string) - Required - Name of the fixed rate. - **price** (object) - Required - Pricing details. - **type** (string) - Required - Type of price ('flat'). - **amount** (string) - Required - The amount in cents (e.g., "2900" for $29.00). - **currency_code** (string) - Required - ISO currency code (e.g., "usd"). - **usage_based_rates** (array) - Optional - A list of usage-based charges. - **name** (string) - Required - Name of the usage-based rate. - **usage_based_rate_type** (string) - Required - Type of usage-based rate ('simple'). - **included_units** (integer) - Optional - Number of units included before overage charges apply. - **price** (object) - Required - Pricing details for overage. - **type** (string) - Required - Type of price ('flat'). - **amount** (string) - Required - The amount per unit in cents (e.g., "50" for $0.50). - **currency_code** (string) - Required - ISO currency code (e.g., "usd"). - **pricing_metric_id** (string) - Required - The ID of the pricing metric to associate with this rate. ### Request Example ```json { "name": "Starter plan", "description": "Perfect for small teams.", "billing_interval": "monthly", "fixed_rates": [ { "name": "Base rate", "price": { "type": "flat", "amount": "2900", "currency_code": "usd" } } ], "usage_based_rates": [ { "name": "AI chat requests", "usage_based_rate_type": "simple", "included_units": 100, "price": { "type": "flat", "amount": "50", "currency_code": "usd" }, "pricing_metric_id": "pm_123abc" } ] } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created rate card. - **name** (string) - The name of the rate card. - **description** (string) - The description of the rate card. - **billing_interval** (string) - The billing interval. - **fixed_rates** (array) - The list of fixed rates. - **usage_based_rates** (array) - The list of usage-based rates. #### Response Example ```json { "id": "rc_xyz789", "name": "Starter plan", "description": "Perfect for small teams.", "billing_interval": "monthly", "fixed_rates": [ { "name": "Base rate", "price": { "type": "flat", "amount": "2900", "currency_code": "usd" } } ], "usage_based_rates": [ { "name": "AI chat requests", "usage_based_rate_type": "simple", "included_units": 100, "price": { "type": "flat", "amount": "50", "currency_code": "usd" }, "pricing_metric_id": "pm_123abc" } ] } ``` ``` -------------------------------- ### Install lark-billing with aiohttp support Source: https://pypi.org/project/lark-billing This command installs the lark-billing package along with the aiohttp extra, which enables the use of aiohttp as the HTTP backend for the asynchronous client, potentially improving concurrency performance. ```bash pip install lark-billing[aiohttp] ``` -------------------------------- ### Install Lark Billing Library Source: https://www.npmjs.com/package/lark-billing Installs the Lark Billing npm package using npm. This is the first step to integrating the library into your project. ```bash npm install lark-billing ``` -------------------------------- ### Create Pricing Metric Source: https://docs.uselark.ai/index This section details how to create a pricing metric to track AI chat requests using the Lark SDK or the dashboard. It outlines the necessary parameters for the metric, such as name, event name, aggregation type, and unit. ```APIDOC ## POST /pricing_metrics ### Description Creates a pricing metric to track usage, such as AI chat requests. ### Method POST ### Endpoint /pricing_metrics ### Parameters #### Request Body - **name** (string) - Required - The name of the pricing metric (e.g., "AI chat requests"). - **event_name** (string) - Required - The name of the event to track (e.g., "ai_chat_request"). - **aggregation** (object) - Required - The aggregation configuration for the metric. - **aggregation_type** (string) - Required - The type of aggregation (e.g., "count"). - **unit** (string) - Required - The unit of measurement for the metric (e.g., "AI chat request"). ### Request Example ```json { "name": "AI chat requests", "event_name": "ai_chat_request", "aggregation": { "aggregation_type": "count" }, "unit": "AI chat request" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created pricing metric. - **name** (string) - The name of the pricing metric. - **event_name** (string) - The event name associated with the metric. - **aggregation** (object) - The aggregation configuration. - **unit** (string) - The unit of measurement. #### Response Example ```json { "id": "pm_123abc", "name": "AI chat requests", "event_name": "ai_chat_request", "aggregation": { "aggregation_type": "count" }, "unit": "AI chat request" } ``` ``` -------------------------------- ### Install lark-billing using pip Source: https://pypi.org/project/lark-billing This command installs the lark-billing package from the Python Package Index (PyPI). It is the standard method for adding the library to your Python environment. ```bash pip install lark-billing ``` -------------------------------- ### Create Customer Subject via SDK (Python) Source: https://docs.uselark.ai/index Creates a new customer 'subject' in Lark using the SDK. This subject represents a customer in your system and can be associated with billing and usage. The 'external_id' is optional but recommended for referencing. ```python subject = lark_client.subjects.create( external_id="1234567890", # optional name="John Doe", email="john.doe@example.com", ) ``` -------------------------------- ### Create Starter Plan Rate Card Source: https://docs.uselark.ai/index Creates a rate card named 'Starter plan' for monthly billing. It includes a fixed base rate and a usage-based rate for 'AI chat requests', specifying included units and price per unit. This rate card is linked to the previously created pricing metric. ```python rate_card = lark_client.rate_cards.create( name="Starter plan", description="Perfect for small teams.", billing_interval="monthly", fixed_rates=[ { "name": "Base rate", "price": { "type": "flat", "amount": "2900", "currency_code": "usd" } } ], usage_based_rates=[ { "name": "AI chat requests", "usage_based_rate_type": "simple", "included_units": 100, "price": { "type": "flat", "amount": "50", "currency_code": "usd" }, "pricing_metric_id": pricing_metric.id }, ], ) ``` -------------------------------- ### Create Customer Subscription to Rate Card Source: https://docs.uselark.ai/index Creates a subscription for a customer to the 'Starter plan' rate card. Since it's a paid plan without a payment method on file, it generates a checkout URL for the customer to complete the payment. It also defines success and cancellation URLs. ```python subscription_response = lark_client.subscriptions.create( subject_id="1234567890", rate_card_id=rate_card.id, checkout_callback_urls={ "success_url": "https://example.com/success", "cancelled_url": "https://example.com/cancelled", }, ) print(subscription_response.result.action.checkout_url) # Redirect the customer to this URL to complete the checkout process ``` -------------------------------- ### Test Pricing Metric with Usage Event Source: https://docs.uselark.ai/index Tests a created pricing metric by sending a usage event and then retrieving the pricing metric summary. This confirms that events are being tracked correctly. It requires importing `uuid`, `datetime`, `timezone`, and `timedelta`. ```python import uuid from datetime import datetime, timezone, timedelta lark_client.usage_events.create( idempotency_key=uuid.uuid4().hex, timestamp=datetime.now(timezone.utc), subject_id="1234567890", event_name="ai_chat_request", data={"foo": "bar"}, ) summary = lark_client.pricing_metrics.create_summary( pricing_metric_id=pricing_metric.id, subject_id=subject.id, period=lark.Period( start=datetime.now(timezone.utc) - timedelta(days=30), end=datetime.now(timezone.utc), ), ) print(summary.value) # will be 1 because we sent one usage event ``` -------------------------------- ### Install Lark Billing Package (npm) Source: https://www.npmjs.com/package/lark-billing Provides the command to install the Lark Billing package using npm. This is the primary method for integrating the library into a Node.js or web project. ```bash npm i lark-billing ``` -------------------------------- ### Create Subscription Source: https://docs.uselark.ai/index This section explains how to create a customer subscription to a specific rate card. It includes parameters for the subject ID, rate card ID, and callback URLs for checkout completion. It also provides test card details for checkout simulation. ```APIDOC ## POST /subscriptions ### Description Creates a new subscription for a subject to a specific rate card. If the plan requires payment and no payment method is on file, a checkout URL is returned. ### Method POST ### Endpoint /subscriptions ### Parameters #### Request Body - **subject_id** (string) - Required - The ID of the subject (customer) to subscribe. - **rate_card_id** (string) - Required - The ID of the rate card to subscribe to. - **checkout_callback_urls** (object) - Optional - URLs for redirecting the customer after checkout. - **success_url** (string) - Required if checkout is initiated - URL to redirect on successful checkout. - **cancelled_url** (string) - Required if checkout is initiated - URL to redirect if checkout is cancelled. ### Request Example ```json { "subject_id": "sub_1234567890", "rate_card_id": "rc_xyz789", "checkout_callback_urls": { "success_url": "https://example.com/success", "cancelled_url": "https://example.com/cancelled" } } ``` ### Response #### Success Response (200) - **result** (object) - The result of the subscription creation. - **action** (object) - Details about the required action. - **type** (string) - The type of action (e.g., "checkout"). - **checkout_url** (string) - The URL for the customer to complete checkout. - **subscription** (object) - Details of the created subscription (if no checkout is required). #### Response Example (with checkout URL) ```json { "result": { "action": { "type": "checkout", "checkout_url": "https://checkout.uselark.ai/sub_123abc/confirm?token=..." } } } ``` #### Response Example (immediate subscription) ```json { "subscription": { "id": "sub_abc123", "status": "active", "rate_card_id": "rc_xyz789", "subject_id": "sub_1234567890", "start_date": "2023-10-27T10:00:00Z", "end_date": null } } ``` ``` -------------------------------- ### Create Usage Event Source: https://docs.uselark.ai/index This section explains how to send a usage event to the Lark API, which is useful for testing pricing metrics. It includes parameters like idempotency key, timestamp, subject ID, event name, and additional data. ```APIDOC ## POST /usage_events ### Description Records a usage event for a specific subject, used for tracking and billing purposes. ### Method POST ### Endpoint /usage_events ### Parameters #### Request Body - **idempotency_key** (string) - Required - A unique key to ensure the event is processed only once. - **timestamp** (string) - Required - The time the event occurred (ISO 8601 format). - **subject_id** (string) - Required - The identifier of the subject (customer) associated with the event. - **event_name** (string) - Required - The name of the event that occurred. - **data** (object) - Optional - Additional metadata associated with the event. ### Request Example ```json { "idempotency_key": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "timestamp": "2023-10-27T10:00:00Z", "subject_id": "sub_1234567890", "event_name": "ai_chat_request", "data": { "model": "gpt-4", "tokens": 100 } } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created usage event. - **status** (string) - The status of the event processing. #### Response Example ```json { "id": "ue_abcdef123456", "status": "processed" } ``` ``` -------------------------------- ### Create Lark Customer Portal Session (Python) Source: https://docs.uselark.ai/index This function creates a session for the Lark customer portal, enabling customers to view subscriptions, usage, invoices, and manage billing information. It requires a subject ID and a return URL. The returned session URL should be used to redirect the customer. ```python customer_portal_session = lark_client.customer_portal.create_session( subject_id="1234567890", return_url="https://example.com/return", ) print(customer_portal_session.url) # Redirect the customer to this URL to access their customer portal ``` -------------------------------- ### Retrieve Billing State Source: https://docs.uselark.ai/index This section describes how to retrieve the billing state for a given subject, which indicates whether they have an active subscription. ```APIDOC ## GET /billing_state/{subject_id} ### Description Retrieves the current billing state for a given subject, including information about active subscriptions. ### Method GET ### Endpoint /billing_state/{subject_id} ### Parameters #### Path Parameters - **subject_id** (string) - Required - The unique identifier of the subject. ### Response #### Success Response (200) - **has_active_subscription** (boolean) - True if the subject has at least one active subscription, false otherwise. - **active_subscriptions** (array) - A list of active subscriptions (can be empty). - **id** (string) - Subscription ID. - **rate_card_id** (string) - ID of the associated rate card. - **start_date** (string) - Subscription start date (ISO 8601 format). - **end_date** (string) - Subscription end date (ISO 8601 format) or null if ongoing. #### Response Example ```json { "has_active_subscription": true, "active_subscriptions": [ { "id": "sub_abc123", "rate_card_id": "rc_xyz789", "start_date": "2023-10-27T10:00:00Z", "end_date": null } ] } ``` ``` -------------------------------- ### Determining Installed Lark Version Source: https://pypi.org/project/lark-billing Provides a simple Python snippet to check the currently installed version of the Lark library at runtime. This is useful for verifying upgrades or debugging version-related issues. ```python import lark print(lark.__version__) ``` -------------------------------- ### Send Usage Events to Lark (Python) Source: https://docs.uselark.ai/index This function sends usage events to Lark, allowing you to track customer activity. It requires the Lark client, event details like timestamp, idempotency key, event name, subject ID, and custom data. This is crucial for accurate billing after a customer subscribes to a rate card. ```python lark_client.usage_events.create( timestamp=datetime.now(timezone.utc), idempotency_key="your-unique-idempotency-key", event_name="ai_chat_request", subject_id=subject.id, data={"value": "1"}, ) ``` -------------------------------- ### Create AI Chat Request Pricing Metric Source: https://docs.uselark.ai/index Creates a pricing metric to track the count of AI chat requests. It uses the 'count' aggregation type and specifies the event name and unit for clarity. This metric is essential for usage-based billing. ```python pricing_metric = lark_client.pricing_metrics.create( name="AI chat requests", event_name="ai_chat_request", aggregation={"aggregation_type": "count"}, unit="AI chat request", ) ``` -------------------------------- ### Configuring Request Timeouts Source: https://www.npmjs.com/package/lark-billing Demonstrates how to set the timeout duration for API requests. The `timeout` option can be configured globally during client initialization or specified for individual requests. The example shows setting a 20-second timeout. ```typescript // Configure the default for all requests: const client = new Lark({ timeout: 20 * 1000, // 20 seconds (default is 1 minute) }); // Override per-request: await client.subjects.create({ timeout: 5 * 1000, }); ``` -------------------------------- ### Example Usage Event JSON Structure Source: https://docs.uselark.ai/guides/getting_started/concepts/index Represents a single customer usage activity, such as an LLM API call. It includes details like event name, token counts, model used, user ID, timestamp, and an idempotency key for de-duplication. ```json { "event_name": "message", "input_tokens": "500", "output_tokens": "200", "model": "gpt-4", "subject_id": "user_123", "timestamp": "2025-01-01T00:00:00Z", "idempotency_key": "1234567890" } ``` -------------------------------- ### GET /customer-access/{subject_id}/billing-state Source: https://docs.uselark.ai/api/resources/customer_access/methods/retrieve_billing_state/index Retrieves the billing state for a specific customer, including details about active subscriptions and usage. ```APIDOC ## GET /customer-access/{subject_id}/billing-state ### Description Retrieves the billing state for a specific customer, including details about active subscriptions and usage. ### Method GET ### Endpoint `/customer-access/{subject_id}/billing-state` ### Parameters #### Path Parameters - **subject_id** (string) - Required - The unique identifier of the subject (customer). ### Response #### Success Response (200) - **active_subscriptions** (array of object) - List of active subscriptions the subject is subscribed to. - **rate_card_id** (string) - The ID of the rate card for the subscription. - **subscription_id** (string) - The ID of the subscription. - **has_active_subscription** (boolean) - Whether the subject has an active subscription. - **has_overage_for_usage** (boolean) - Whether the subject has exceeded the included usage for a usage-based rate. - **usage_data** (array of object) - The usage data for the usage-based rates the subject is subscribed to. - **included_units** (number) - The number of included units for the usage. - **pricing_metric_id** (string) - The ID of the pricing metric. - **rate_name** (string) - The name of the usage-based rate. - **used_units** (string) - The number of units used. #### Response Example ```json { "active_subscriptions": [ { "rate_card_id": "rc_123", "subscription_id": "sub_abc" } ], "has_active_subscription": true, "has_overage_for_usage": false, "usage_data": [ { "included_units": 1000, "pricing_metric_id": "pm_xyz", "rate_name": "API Calls", "used_units": "500" } ] } ``` ``` -------------------------------- ### Retrieve Customer Billing State Source: https://docs.uselark.ai/index Retrieves the billing state for a given customer subject ID. This is useful after a customer completes checkout to verify if they have an active subscription. It returns a boolean indicating the presence of an active subscription. ```python billing_state = lark.customer_access.retrieve_billing_state( subject_id="1234567890", ) print(billing_state.has_active_subscription) # -> True ``` -------------------------------- ### Configuring HTTP Client with Proxies and Transports Source: https://pypi.org/project/lark-billing Demonstrates how to override the default httpx client to include custom configurations like proxies and transports. This allows for advanced customization of network requests. ```python import httpx from lark import Lark, DefaultHttpxClient client = Lark( base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Initialize Lark Client with Custom HTTP Client (TypeScript) Source: https://www.npmjs.com/package/lark-billing Demonstrates how to initialize the Lark client by providing a custom HTTP client configuration. This allows for advanced control over network requests, such as adding interceptors or custom headers. ```typescript import { Lark } from "lark-billing-typescript"; import { httpClient } from "./http-client"; // Assuming httpClient is defined elsewhere const client = new Lark({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### Configure Proxy for Deno Fetch in Lark Source: https://www.npmjs.com/package/lark-billing Set up a proxy for Deno's fetch client by creating a `Deno.HttpClient` with proxy configuration and passing it to the Lark client. This allows routing Deno requests through a specified proxy server. ```javascript import Lark from 'npm:lark-billing'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888', }, }); const client = new Lark({ fetch: httpClient.fetch.bind(httpClient), }); ``` -------------------------------- ### Create Subscription with Nested Parameters (Python) Source: https://pypi.org/project/lark-billing Demonstrates creating a subscription using nested dictionaries for callback URLs and specifying rate card and subject IDs. This utilizes Python's TypedDict for structure and Pydantic for response handling. ```python from lark import Lark client = Lark() subscription = client.subscriptions.create( checkout_callback_urls={ "cancelled_url": "https://example.com/try-again", "success_url": "https://example.com/welcome", }, rate_card_id="rc_AJWMxR81jxoRlli6p13uf3JB", subject_id="subj_VyX6Q96h5avMho8O7QWlKeXE", ) print(subscription.checkout_callback_urls) ``` -------------------------------- ### POST /subscriptions Source: https://docs.uselark.ai/api/resources/subscriptions/methods/create/index Creates a new subscription. The response indicates success with subscription details or requires further action, such as checkout. ```APIDOC ## POST /subscriptions ### Description Creates a new subscription. The response indicates success with subscription details or requires further action, such as checkout. ### Method POST ### Endpoint /subscriptions ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body specified for this endpoint." } ``` ### Response #### Success Response (200) - **result** (object) - The result of the request. Can be `RequiresAction` or `Success`. - **RequiresAction** (object) - **action** (object) - **checkout_url** (string) - The URL of the checkout page. - **requires_action_type** (string) - Must be "checkout". - **result_type** (string) - Must be "requires_action". - **Success** (object) - **result_type** (string) - Must be "success". - **subscription** (object) - The created subscription resource. - **id** (string) - The ID of the subscription. - **cancels_at_end_of_cycle** (boolean) - Whether the subscription will be cancelled at the end of the current cycle. - **current_period** (object) - The current period of the subscription if it is active. - **end** (string) - **start** (string) - **inclusive_end** (boolean) - Optional. - **inclusive_start** (boolean) - Optional. - **cycles_next_at** (string) - The date and time the next cycle of the subscription will start. - **effective_at** (string) - The date and time the subscription became effective. - **metadata** (map[string]) - Key-value pairs for metadata. - **rate_card_id** (string) - The ID of the rate card. - **status** (string) - The status of the subscription ("active", "cancelled", or "paused"). - **subject_id** (string) - The ID of the subject for the subscription. #### Response Example ```json { "example": { "result_type": "success", "subscription": { "id": "sub_12345", "cancels_at_end_of_cycle": false, "current_period": { "end": "2024-12-31T23:59:59Z", "start": "2024-01-01T00:00:00Z" }, "cycles_next_at": "2025-01-01T00:00:00Z", "effective_at": "2024-01-01T00:00:00Z", "metadata": {}, "rate_card_id": "rc_abcde", "status": "active", "subject_id": "user_xyz" } } } ``` ``` -------------------------------- ### Basic Usage: Create a Subject Source: https://www.npmjs.com/package/lark-billing Demonstrates how to initialize the Lark client with an API key and create a new subject. It shows accessing the `subjects` resource and calling the `create` method with necessary parameters like email, external_id, and name. The subject's ID is then logged to the console. ```typescript import Lark from 'lark-billing'; const client = new Lark({ apiKey: process.env['LARK_API_KEY'], // This is the default and can be omitted }); const subject = await client.subjects.create({ email: 'john.doe@example.com', external_id: 'user_1234567890', name: 'John Doe', }); console.log(subject.id); ``` -------------------------------- ### Query Usage Data Summary with Lark API (Python) Source: https://docs.uselark.ai/guides/events/usage_tracking/index This snippet shows how to fetch the pricing metric summary for a specific subject and period. It requires the pricing metric ID, subject ID, and a period object with start and end timestamps. The result provides the aggregated usage value. ```python summary = lark_client.pricing_metrics.create_summary( pricing_metric_id=pricing_metric.id, subject_id=subject.id, period={ "start": datetime.now(timezone.utc) - timedelta(days=30), "end": datetime.now(timezone.utc), }, ) print(summary) ``` -------------------------------- ### POST /pricing-metrics Source: https://docs.uselark.ai/api/resources/pricing_metrics/methods/create/index Creates a new pricing metric. Pricing metrics are used to compute values based on event data and can be aggregated using various methods. ```APIDOC ## POST /pricing-metrics ### Description Creates a new pricing metric. Pricing metrics are used to compute values based on event data and can be aggregated using various methods. ### Method POST ### Endpoint /pricing-metrics ### Parameters #### Request Body - **event_name** (string) - Required - The event name that the pricing metric is computed on. - **name** (string) - Required - The name of the pricing metric. - **unit** (string) - Required - The unit of the value computed by the pricing metric. - **aggregation** (object) - Required - The aggregation function used to compute the value of the pricing metric. Can be one of Sum, Count, Max, or Last. - **aggregation_type** (string) - Required - The type of aggregation. Allowed values: "sum", "count", "max", "last". - **value_field** (string) - Optional - The field to use for aggregation (required for "sum", "max", "last"). - **dimensions** (array of string) - Optional - The dimensions by which the events are grouped to compute the pricing metric. ### Request Example ```json { "event_name": "purchase", "name": "Total Purchase Value", "unit": "USD", "aggregation": { "aggregation_type": "sum", "value_field": "price" }, "dimensions": ["country", "product_id"] } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the pricing metric. - **event_name** (string) - The event name that the pricing metric is computed on. - **name** (string) - The name of the pricing metric. - **unit** (string) - The unit of the value computed by the pricing metric. - **aggregation** (object) - The aggregation function used to compute the value of the pricing metric. - **dimensions** (optional array of string) - The dimensions by which the events are grouped to compute the pricing metric. #### Response Example ```json { "id": "metric_123", "event_name": "purchase", "name": "Total Purchase Value", "unit": "USD", "aggregation": { "aggregation_type": "sum", "value_field": "price" }, "dimensions": ["country", "product_id"] } ``` ``` -------------------------------- ### Pricing Metric and Rate Details Source: https://docs.uselark.ai/api/resources/rate_cards/methods/create/index This section covers the pricing metric ID, usage-based rate type, and an optional description for the rate card. ```APIDOC ## Pricing Details ### Fields - **pricing_metric_id** (string) - Required - The identifier for the pricing metric. - **usage_based_rate_type** (string) - Optional - The type of usage-based rate. Currently, only `"dimensional"` is supported. - `"dimensional"`: Indicates a dimensional usage-based rate. - **description** (string) - Optional - A description of the rate card. ``` -------------------------------- ### Add Undocumented Parameter to Lark Request Source: https://www.npmjs.com/package/lark-billing Include undocumented parameters in requests by using `// @ts-expect-error`. For GET requests, extra parameters are added to the query string. For other verbs, they are sent in the request body. You can explicitly control where extra parameters are sent using `query`, `body`, and `headers` options. ```javascript client.subjects.create({ // ... // @ts-expect-error baz is not yet public baz: 'undocumented option', }); ``` -------------------------------- ### Handling API Responses with Lark Client Source: https://pypi.org/project/lark-billing Demonstrates how to make a subscription creation request and access the response headers and parsed subscription object. This method eagerly reads the full response body. ```python import httpx from lark import Lark client = Lark() response = client.subscriptions.create( checkout_callback_urls={ "cancelled_url": "https://example.com/try-again", "success_url": "https://example.com/welcome", }, rate_card_id="rc_AJWMxR81jxoRlli6p13uf3JB", subject_id="subj_VyX6Q96h5avMho8O7QWlKeXE", ) print(response.headers.get('X-My-Header')) subscription = response.parse() print(subscription.result) ``` -------------------------------- ### Per-Request HTTP Client Customization Source: https://pypi.org/project/lark-billing Shows how to customize the HTTP client on a per-request basis using the `with_options` method. This allows for applying specific configurations to individual requests without altering the global client settings. ```python from lark import Lark, DefaultHttpxClient client = Lark() client.with_options(http_client=DefaultHttpxClient(...)) ``` -------------------------------- ### Create Rate Card using Lark SDK Source: https://docs.uselark.ai/guides/rate_cards/rate_cards/index This Python snippet demonstrates how to create a new rate card using the Lark SDK. It includes defining a name, description, billing interval, fixed rates, and usage-based rates with associated pricing metrics. Ensure the Lark client and pricing_metric object are properly initialized before execution. ```python rate_card = lark_client.rate_cards.create( name="Starter plan", description="Perfect for small teams.", billing_interval="monthly", fixed_rates=[ { "name": "Base rate", "price": { "type": "flat", "amount": "2900", "currency_code": "usd" } } ], usage_based_rates=[ { "name": "AI chat requests", "included_units": 100, "price": { "type": "flat", "amount": "50", "currency_code": "usd" }, "pricing_metric_id": pricing_metric.id } ], ) ``` -------------------------------- ### Package Pricing Information Source: https://docs.uselark.ai/api/resources/rate_cards/methods/create/index This section details the structure of PackagePriceOutput, which represents a price charged for a fixed number of units. ```APIDOC ## PackagePriceOutput Object ### Description Represents a price that is charged for a fixed number of units. For example, $10 per 1000 units. If the quantity is not a multiple of the package units, the rounding behavior will be applied. ### Fields - **amount** (AmountOutput) - Required - The monetary value of the package price. - **currency_code** (string) - Required - The currency code of the amount. - **value** (string) - Required - The value of the amount in the smallest unit of the currency. - **package_units** (number) - Required - The number of units included in the package. - **rounding_behavior** (string) - Required - Specifies how to round if the quantity is not a multiple of package units. Can be either `"round_up"` or `"round_down"`. - `"round_up"`: Rounds up to the nearest package unit. - `"round_down"`: Rounds down to the nearest package unit. - **price_type** (string) - Optional - The type of pricing. Currently, only `"package"` is supported. - `"package"`: Indicates a package-based price. ### Example ```json { "amount": { "currency_code": "USD", "value": "1000" }, "package_units": 1000, "rounding_behavior": "round_up", "price_type": "package" } ``` ``` -------------------------------- ### Synchronous Lark API Usage in Python Source: https://pypi.org/project/lark-billing This Python code demonstrates how to use the synchronous Lark client to create a subject. It imports the Lark class, initializes the client with an API key (preferably from environment variables), and then calls the subjects.create method. The subject's ID is then printed. ```python import os from lark import Lark client = Lark( api_key=os.environ.get("LARK_API_KEY"), # This is the default and can be omitted ) subject = client.subjects.create( email="john.doe@example.com", external_id="user_1234567890", name="John Doe", ) print(subject.id) ``` -------------------------------- ### Advanced Features Source: https://pypi.org/project/lark-billing Information on logging, differentiating null vs. missing fields, and accessing raw response data. ```APIDOC ## Advanced Features ### Description This section details advanced features such as logging, handling null vs. missing fields, and accessing raw response data. ### Logging - Lark uses the standard `logging` module. - Enable logging by setting the `LARK_LOG` environment variable: - `export LARK_LOG=info` (for info level logging) - `export LARK_LOG=debug` (for verbose logging) ### Differentiating `None` (Null vs. Missing) - In API responses, `None` can represent either an explicit `null` value or a missing field. - Use `.model_fields_set` to distinguish: ```python # Assuming 'response' is a Pydantic model instance if response.my_field is None: if 'my_field' not in response.model_fields_set: print('Field "my_field" is missing from the response.') else: print('Field "my_field" is present but its value is null.') ``` ### Accessing Raw Response Data - Prefix an HTTP method call with `.with_raw_response.` to access the raw `Response` object (e.g., headers). #### Example (Raw Response) ```python from lark import Lark client = Lark() response = client.subscriptions.with_raw_response.create( checkout_callback_urls={ "cancelled_url": "https://example.com/try-again", "success_url": "https://example.com/welcome", }, rate_card_id="rc_AJWMxR81jxoRlli6p13uf3JB", subject_id="subj_VyX6Q96h5avMho8O7QWlKeXE", ) # Access headers, status code, etc. from the 'response' object print(response.headers) print(response.status_code) # The actual data can be accessed via response.parse() subscription_data = response.parse() ``` ``` -------------------------------- ### Configure Proxy for Node.js Fetch in Lark Source: https://www.npmjs.com/package/lark-billing Set up a proxy agent for Node.js environments to route requests through a specified proxy server. This is achieved by configuring the `dispatcher` option within `fetchOptions` using a compatible agent like `undici.ProxyAgent`. ```javascript import Lark from 'lark-billing'; import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new Lark({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` -------------------------------- ### POST /subscriptions Source: https://pypi.org/project/lark-billing Creates a new subscription with specified callback URLs, rate card ID, and subject ID. Supports nested parameters using TypedDict for requests and Pydantic models for responses. ```APIDOC ## POST /subscriptions ### Description Creates a new subscription with the provided details. The request body uses nested dictionaries typed as `TypedDict`, and responses are Pydantic models that can be serialized to JSON or dictionaries. ### Method POST ### Endpoint /subscriptions ### Parameters #### Request Body - **checkout_callback_urls** (dict) - Required - A dictionary containing 'cancelled_url' and 'success_url'. - **cancelled_url** (str) - Required - The URL to redirect to if the checkout is cancelled. - **success_url** (str) - Required - The URL to redirect to upon successful checkout. - **rate_card_id** (str) - Required - The ID of the rate card to associate with the subscription. - **subject_id** (str) - Required - The ID of the subject for the subscription. ### Request Example ```json { "checkout_callback_urls": { "cancelled_url": "https://example.com/try-again", "success_url": "https://example.com/welcome" }, "rate_card_id": "rc_AJWMxR81jxoRlli6p13uf3JB", "subject_id": "subj_VyX6Q96h5avMho8O7QWlKeXE" } ``` ### Response #### Success Response (200) - **subscription** (object) - The created subscription object, conforming to a Pydantic model. - **checkout_callback_urls** (dict) - The callback URLs associated with the subscription. - Other subscription details... #### Response Example ```json { "checkout_callback_urls": { "cancelled_url": "https://example.com/try-again", "success_url": "https://example.com/welcome" }, "rate_card_id": "rc_AJWMxR81jxoRlli6p13uf3JB", "subject_id": "subj_VyX6Q96h5avMho8O7QWlKeXE", "id": "sub_abc123", "status": "active" } ``` ``` -------------------------------- ### Configure Proxy for Bun Fetch in Lark Source: https://www.npmjs.com/package/lark-billing Enable proxy usage for requests made with Bun by specifying the proxy URL in the `fetchOptions`. Bun's fetch implementation directly supports a `proxy` option for this purpose. ```javascript import Lark from 'lark-billing'; const client = new Lark({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### Async Lark API with aiohttp client in Python Source: https://pypi.org/project/lark-billing This Python code shows how to use the asynchronous Lark client with aiohttp as the HTTP backend. It imports AsyncLark and DefaultAioHttpClient, instantiates the client with `http_client=DefaultAioHttpClient()`, and then proceeds to make an asynchronous API call within an async context manager. ```python import os import asyncio from lark import DefaultAioHttpClient from lark import AsyncLark async def main() -> None: async with AsyncLark( api_key=os.environ.get("LARK_API_KEY"), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: subject = await client.subjects.create( email="john.doe@example.com", external_id="user_1234567890", name="John Doe", ) print(subject.id) asyncio.run(main()) ``` -------------------------------- ### Configure Fetch Options for Lark Client Source: https://www.npmjs.com/package/lark-billing Set custom `fetch` options at the client level that will be applied to all requests. These options can include headers, credentials, and other `RequestInit` properties. Request-specific options will override client-level options. ```javascript import Lark from 'lark-billing'; const client = new Lark({ fetchOptions: { // `RequestInit` options }, }); ``` -------------------------------- ### POST /rate-cards Source: https://docs.uselark.ai/api/resources/rate_cards/methods/create/index Creates a new rate card. ```APIDOC ## POST /rate-cards ### Description Creates a new rate card. ### Method POST ### Endpoint /rate-cards ### Parameters #### Query Parameters (No query parameters defined) #### Request Body (Request body details not provided in the source text) ### Request Example (No request example provided in the source text) ### Response #### Success Response (200) (Response details not provided in the source text) #### Response Example (No response example provided in the source text) ``` -------------------------------- ### Streaming API Responses with Lark Client Source: https://pypi.org/project/lark-billing Illustrates how to use `.with_streaming_response` to stream the response body, processing it line by line. This is useful for large responses where eager loading is not desired. Requires a context manager for reliable closing. ```python from lark import Lark client = Lark() with client.subscriptions.with_streaming_response.create( checkout_callback_urls={ "cancelled_url": "https://example.com/try-again", "success_url": "https://example.com/welcome", }, rate_card_id="rc_AJWMxR81jxoRlli6p13uf3JB", subject_id="subj_VyX6Q96h5avMho8O7QWlKeXE", ) as response: print(response.headers.get("X-My-Header")) for line in response.iter_lines(): print(line) ``` -------------------------------- ### Managing HTTP Resources with Lark Client Context Manager Source: https://pypi.org/project/lark-billing Illustrates how to manually close HTTP connections using a context manager. When the `with` block is exited, the client and its underlying HTTP connections are automatically closed. ```python from lark import Lark with Lark() as client: # make requests here pass # HTTP client is now closed ``` -------------------------------- ### Create Dimensional Pricing Metric with Lark SDK Source: https://docs.uselark.ai/guides/pricing/defining-pricing-metrics/index Demonstrates how to programmatically create a dimensional pricing metric using the Lark SDK. This metric aggregates 'compute_seconds' events and uses 'region' and 'instance_type' as dimensions. It requires the lark_client to be initialized. ```python pricing_metric = lark_client.pricing_metrics.create( name="Compute usage", event_name="compute_seconds", aggregation={"aggregation_type": "sum"}, dimensions=[ "region", "instance_type", ], ) ```