### Quick Start: Compress Text with Python SDK Source: https://thetokencompany.com/docs/python-sdk A basic example demonstrating how to initialize the TokenClient and use the compress_input method to compress text. It shows how to print the compressed output and various token metrics. ```python from tokenc import TokenClient client = TokenClient(api_key="your-api-key") response = client.compress_input( input="Your text that needs compression for optimal token usage.", aggressiveness=0.5 ) print(f"Compressed text: {response.output}") print(f"Original tokens: {response.original_input_tokens}") print(f"Compressed tokens: {response.output_tokens}") print(f"Tokens saved: {response.tokens_saved}") print(f"Compression ratio: {response.compression_ratio:.2f}x") ``` -------------------------------- ### Comparing Compression Levels in Python Source: https://thetokencompany.com/docs/python-sdk This example shows how to compare different compression levels (aggressiveness) for the same input text. It helps in understanding the trade-offs between compression ratio and potential information loss. ```python from tokenc import TokenClient client = TokenClient(api_key="your-api-key") text = "Your long text here..." # Light compression - preserve most content light = client.compress_input(input=text, aggressiveness=0.2) # Moderate compression - balanced approach moderate = client.compress_input(input=text, aggressiveness=0.5) # Aggressive compression - maximum savings aggressive = client.compress_input(input=text, aggressiveness=0.8) ``` -------------------------------- ### Install The Token Company Python SDK Source: https://thetokencompany.com/docs/python-sdk Install the official Python SDK for The Token Company API using pip. This is the first step to integrate text compression into your Python applications. ```bash pip install tokenc ``` -------------------------------- ### Compress Prompt for OpenAI with Python SDK Source: https://thetokencompany.com/docs/python-sdk This example shows how to compress a prompt using the Token Company SDK before sending it to the OpenAI API. It highlights cost reduction by minimizing token usage for LLM inference. ```python from tokenc import TokenClient from openai import OpenAI # Initialize clients tc = TokenClient(api_key="your-ttc-api-key") openai = OpenAI(api_key="your-openai-api-key") # Your prompt prompt = """ Please explain the process of photosynthesis in detail, including the light-dependent and light-independent reactions, the role of chlorophyll, and how plants convert CO2 and water into glucose and oxygen. Thank you very much for your help! """ # Compress the prompt compressed = tc.compress_input( input=prompt, aggressiveness=0.6 ) print(f"Compressed from {compressed.original_input_tokens} to {compressed.output_tokens} tokens") print(f"Compression: {compressed.compression_percentage:.1f}%") # Use compressed prompt with OpenAI response = openai.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": compressed.output}] ) print(response.choices[0].message.content) ``` -------------------------------- ### Compress Text using Python SDK Source: https://thetokencompany.com/docs/index Provides a Python code example for integrating with The Token Company API to compress text. It utilizes the `requests` library to send a POST request with the necessary headers and JSON payload. ```python import requests response = requests.post( "https://api.thetokencompany.com/v1/compress", headers={ "Content-Type": "application/json", "Authorization": "Bearer YOUR_API_KEY" }, json={ "model": "bear-1", "compression_settings": { "aggressiveness": 0.5, "max_output_tokens": None, "min_output_tokens": None }, "input": "Your text that needs compression for optimal token usage." } ) result = response.json() print(result["output"]) ``` -------------------------------- ### TokenClient Constructor Source: https://thetokencompany.com/docs/python-sdk Initializes the TokenClient with your API key and optional base URL and timeout settings. ```APIDOC ## TokenClient Constructor ### Description Initializes the TokenClient with your API key and optional base URL and timeout settings. ### Method `TokenClient(api_key: str, base_url: str = ..., timeout: int = 30)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from tokenc import TokenClient client = TokenClient(api_key="your-api-key", base_url="https://api.thetokencompany.com", timeout=60) ``` ### Response #### Success Response (200) None (Constructor does not return a response) #### Response Example None ``` -------------------------------- ### Advanced Compression with CompressionSettings in Python Source: https://thetokencompany.com/docs/python-sdk Demonstrates using the CompressionSettings dataclass to configure advanced compression parameters like max_output_tokens and min_output_tokens. This provides finer control over the compression process. ```python from tokenc import TokenClient, CompressionSettings client = TokenClient(api_key="your-api-key") # Create custom compression settings settings = CompressionSettings( aggressiveness=0.7, max_output_tokens=100, min_output_tokens=50 ) response = client.compress_input( input="Your text here...", compression_settings=settings ) print(f"Compression percentage: {response.compression_percentage:.1f}%") ``` -------------------------------- ### CompressionSettings Source: https://thetokencompany.com/docs/python-sdk Dataclass for configuring compression parameters like aggressiveness, max output tokens, and min output tokens. ```APIDOC ## CompressionSettings ### Description Dataclass for compression configuration. Use this object to specify detailed compression settings, including aggressiveness and token limits. ### Method `CompressionSettings(aggressiveness: float, max_output_tokens: int | None = None, min_output_tokens: int | None = None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from tokenc import CompressionSettings settings = CompressionSettings( aggressiveness=0.7, max_output_tokens=100, min_output_tokens=50 ) ``` ### Response #### Success Response (200) None (This is a data structure definition) #### Response Example None ``` -------------------------------- ### Using TokenClient as a Context Manager in Python Source: https://thetokencompany.com/docs/python-sdk Illustrates how to use the TokenClient as a context manager, ensuring that the client session is automatically closed upon exiting the 'with' block. This simplifies resource management. ```python from tokenc import TokenClient with TokenClient(api_key="your-api-key") as client: response = client.compress_input( input="Your text here...", aggressiveness=0.6 ) print(response.output) # Session automatically closed ``` -------------------------------- ### compress_input() Source: https://thetokencompany.com/docs/python-sdk Compresses text input for optimized LLM inference using specified parameters or custom settings. ```APIDOC ## compress_input() ### Description Compresses text input for optimized LLM inference. You can control the compression level using `aggressiveness` or provide a `CompressionSettings` object for more granular control over `max_output_tokens` and `min_output_tokens`. ### Method `compress_input(input: str, model: str = "bear-1", aggressiveness: float = 0.5, max_output_tokens: int | None = None, min_output_tokens: int | None = None, compression_settings: CompressionSettings | None = None)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from tokenc import TokenClient, CompressionSettings client = TokenClient(api_key="your-api-key") # Example 1: Using aggressiveness response1 = client.compress_input( input="Your text that needs compression for optimal token usage.", aggressiveness=0.5 ) print(f"Compressed text: {response1.output}") # Example 2: Using CompressionSettings settings = CompressionSettings( aggressiveness=0.7, max_output_tokens=100, min_output_tokens=50 ) response2 = client.compress_input( input="Another text to compress with specific token limits.", compression_settings=settings ) print(f"Compression percentage: {response2.compression_percentage:.1f}%") ``` ### Response #### Success Response (200) - **output** (str) - The compressed text. - **output_tokens** (int) - Token count of the compressed output. - **original_input_tokens** (int) - Token count of the original input. - **compression_time** (float) - Time taken to compress in seconds. - **tokens_saved** (int) - Number of tokens saved (computed property). - **compression_ratio** (float) - Ratio of original to compressed tokens (computed property). - **compression_percentage** (float) - Percentage reduction in tokens (computed property). #### Response Example ```json { "output": "Compressed text content...", "output_tokens": 50, "original_input_tokens": 100, "compression_time": 0.123, "tokens_saved": 50, "compression_ratio": 2.0, "compression_percentage": 50.0 } ``` ``` -------------------------------- ### Handle SDK Errors with Python Source: https://thetokencompany.com/docs/python-sdk Demonstrates how to handle specific exceptions raised by the Token Company SDK, such as authentication failures, invalid requests, rate limiting, and general API errors. This code snippet requires the 'tokenc' library. ```python from tokenc import ( TokenClient, AuthenticationError, InvalidRequestError, RateLimitError, APIError ) client = TokenClient(api_key="your-api-key") try: response = client.compress_input(input="Your text...") except AuthenticationError: print("Invalid API key") except InvalidRequestError as e: print(f"Invalid request: {e}") except RateLimitError: print("Rate limit exceeded, please wait") except APIError as e: print(f"API error: {e}") ``` -------------------------------- ### Compress Text using cURL Source: https://thetokencompany.com/docs/index Demonstrates how to compress text using the API's compression endpoint via cURL. It includes setting the content type, authorization header, and the JSON payload with compression settings and input text. ```shell curl -X POST https://api.thetokencompany.com/v1/compress \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_API_KEY" \ -d '{ "model": "bear-1", "compression_settings": { "aggressiveness": 0.5, "max_output_tokens": null, "min_output_tokens": null }, "input": "Your text that needs compression for optimal token usage." }' ``` -------------------------------- ### POST /v1/compress Source: https://thetokencompany.com/docs/index Compresses input text to reduce token usage for LLM inference, lowering costs and speeding up AI applications. ```APIDOC ## POST /v1/compress ### Description Compresses input text to reduce token usage for LLM inference, lowering costs and speeding up AI applications. ### Method POST ### Endpoint `https://api.thetokencompany.com/v1/compress` ### Authentication All API requests require authentication. Include your API key in the `Authorization` header. `Authorization: Bearer YOUR_API_KEY` ### Parameters #### Request Body - **model** (string) - Required - Model to use for compression. Currently only `bear-1`. - **input** (string) - Required - The text to compress. - **compression_settings.aggressiveness** (float) - Optional - How aggressively to compress. Higher values remove more tokens. Default: 0.5. (Range: 0.0–1.0) - **compression_settings.max_output_tokens** (int | null) - Optional - Maximum tokens in output. Set to `null` for no limit. - **compression_settings.min_output_tokens** (int | null) - Optional - Minimum tokens in output. Set to `null` for no minimum. ### Request Example ```json { "model": "bear-1", "compression_settings": { "aggressiveness": 0.5, "max_output_tokens": null, "min_output_tokens": null }, "input": "Your text that needs compression for optimal token usage." } ``` ### Response #### Success Response (200) - **output** (string) - The compressed text. - **output_tokens** (int) - Token count of the compressed output. - **original_input_tokens** (int) - Token count of the original input. - **compression_time** (float) - Time taken to compress (in seconds). #### Response Example ```json { "output": "text needs compression token usage.", "output_tokens": 5, "original_input_tokens": 12, "compression_time": 0.4945101737976074 } ``` ``` -------------------------------- ### Error Handling Source: https://thetokencompany.com/docs/python-sdk This section details the various exception types provided by the SDK for handling different error conditions during API interactions. ```APIDOC ## Error Handling The SDK provides specific exception types for different error conditions: ### Exception Types | Exception Type | Description | |-----------------------|---------------------------------| | AuthenticationError | Invalid API key | | InvalidRequestError | Invalid request parameters | | RateLimitError | Rate limit exceeded | | APIError | Other API errors | ### Example Usage ```python from tokenc import ( TokenClient, AuthenticationError, InvalidRequestError, RateLimitError, APIError ) client = TokenClient(api_key="your-api-key") try: response = client.compress_input(input="Your text...") except AuthenticationError: print("Invalid API key") except InvalidRequestError as e: print(f"Invalid request: {e}") except RateLimitError: print("Rate limit exceeded, please wait") except APIError as e: print(f"API error: {e}") ``` ``` -------------------------------- ### CompressResponse Attributes Source: https://thetokencompany.com/docs/python-sdk Details the attributes and computed properties available in the response object returned by the `compress_input` method. ```APIDOC ## CompressResponse Attributes ### Description Provides details on the attributes and computed properties of the `CompressResponse` object, which contains the results of a text compression operation. ### Attributes - **output** (str) - The compressed text. - **output_tokens** (int) - Token count of the compressed output. - **original_input_tokens** (int) - Token count of the original input. - **compression_time** (float) - Time taken to compress in seconds. ### Computed Properties - **tokens_saved** (int) - Number of tokens saved (calculated as `original_input_tokens` - `output_tokens`). - **compression_ratio** (float) - Ratio of original to compressed tokens (calculated as `original_input_tokens` / `output_tokens`). - **compression_percentage** (float) - Percentage reduction in tokens (calculated as `(tokens_saved / original_input_tokens) * 100`). ### Response Example ```json { "output": "This is the compressed output string.", "output_tokens": 45, "original_input_tokens": 100, "compression_time": 0.095, "tokens_saved": 55, "compression_ratio": 2.22, "compression_percentage": 55.0 } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.