### Install OpenAI Go SDK Source: https://tokenmix.ai/docs/sdks Install the OpenAI Go SDK using 'go get'. This is required for the Go example. ```bash go get github.com/openai/openai-go ``` -------------------------------- ### Install OpenAI Node.js SDK Source: https://tokenmix.ai/docs/sdks Install the OpenAI Node.js package via npm. Required before using the Node.js example. ```bash npm install openai ``` -------------------------------- ### Install Anthropic SDK (Python) Source: https://tokenmix.ai/docs/sdks Install the official Anthropic SDK for Python using pip. This is required before using the Anthropic SDK examples. ```bash pip install anthropic ``` -------------------------------- ### Install OpenAI SDK with pip Source: https://tokenmix.ai/docs/quickstart Install the official OpenAI SDK for Python. TokenMix works with any OpenAI-compatible client library. ```bash pip install openai ``` -------------------------------- ### Use API key with OpenAI Python SDK Source: https://tokenmix.ai/docs/authentication Set your TokenMix API key and base URL for the OpenAI Python client. Your key must start with sk-tm-. Replace the example key with your actual key. ```python from openai import OpenAI client = OpenAI( api_key="sk-tm-your-api-key-here", base_url="https://api.tokenmix.ai/v1" ) ``` -------------------------------- ### Using Your API Key with OpenAI SDK (Python) Source: https://tokenmix.ai/docs/authentication Example of initializing the OpenAI client with a TokenMix API key and base URL in Python. ```APIDOC ## Using Your API Key - Python OpenAI SDK ### Description Pass your API key as a Bearer token in the Authorization header by initializing the OpenAI client with the TokenMix API key and base URL. ### Method SDK ### Endpoint https://api.tokenmix.ai/v1 ### Parameters #### Client Configuration - **api_key** (string) - Required - Your TokenMix API key, starting with sk-tm- - **base_url** (string) - Required - The TokenMix API base URL: https://api.tokenmix.ai/v1 ### Request Example from openai import OpenAI client = OpenAI( api_key="sk-tm-your-api-key-here", base_url="https://api.tokenmix.ai/v1" ) ``` -------------------------------- ### Detail Parameter Configuration Source: https://tokenmix.ai/docs/vision Example of setting the detail parameter to 'high' to enable high-resolution processing. ```json { "type": "image_url", "image_url": { "url": "https://example.com/detailed-chart.png", "detail": "high" } } ``` -------------------------------- ### GET /api/v1/usage Source: https://tokenmix.ai/docs/openai-compatibility OpenRouter-style usage alias. ```APIDOC ## GET /api/v1/usage ### Description OpenRouter-style usage alias. ### Method GET ### Endpoint /api/v1/usage ``` -------------------------------- ### GET /v1/models Source: https://tokenmix.ai/docs/openai-compatibility Lists available models. ```APIDOC ## GET /v1/models ### Description Lists available models. ### Method GET ### Endpoint /v1/models ``` -------------------------------- ### GET /v1/credits Source: https://tokenmix.ai/docs/openai-compatibility Provides an OpenRouter-like wallet credits summary. ```APIDOC ## GET /v1/credits ### Description Provides an OpenRouter-like wallet credits summary. ### Method GET ### Endpoint /v1/credits ``` -------------------------------- ### Example response headers Source: https://tokenmix.ai/docs/rate-limits Shows the HTTP response headers returned by the API to indicate current rate limit status. ```bash # Example response headers HTTP/2 200 x-ratelimit-limit-requests: x-ratelimit-remaining-requests: x-ratelimit-reset-requests: 12s x-ratelimit-limit-day: x-ratelimit-remaining-day: x-ratelimit-reset-day: 28800s ``` -------------------------------- ### JSON Mode with Python Source: https://tokenmix.ai/docs/structured-output Use JSON mode to get valid JSON output. Set response_format to {"type": "json_object"} and include the word "JSON" in the system or user message to avoid whitespace generation. The example extracts product info and prints the parsed JSON. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai/v1" ) response = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "system", "content": "Extract product info. Respond in JSON with fields: name, price, category." }, { "role": "user", "content": "The new UltraWidget Pro costs $49.99 and is in the electronics category." } ], response_format={"type": "json_object"} ) import json data = json.loads(response.choices[0].message.content) print(data) # {"name": "UltraWidget Pro", "price": 49.99, "category": "electronics"} ``` -------------------------------- ### GET /api/v1/models Source: https://tokenmix.ai/docs/openai-compatibility OpenRouter-like models list; defaults to text, use output_modalities=all for all models. ```APIDOC ## GET /api/v1/models ### Description OpenRouter-like models list; defaults to text, use output_modalities=all for all models. ### Method GET ### Endpoint /api/v1/models ``` -------------------------------- ### Anthropic SDK Python example Source: https://tokenmix.ai/docs/openai-compatibility Use the official Anthropic SDK with TokenMix by setting the base URL to https://api.tokenmix.ai and providing your API key. The example creates a message with model claude-sonnet-4.6. ```python import anthropic client = anthropic.Anthropic( api_key="sk-tm-your-api-key-here", base_url="https://api.tokenmix.ai" ) message = client.messages.create( model="claude-sonnet-4.6", max_tokens=1024, messages=[ {"role": "user", "content": "Hello, Claude!"} ] ) print(message.content[0].text) ``` -------------------------------- ### Single Image Analysis with Python Source: https://tokenmix.ai/docs/vision Example of sending a single image URL with a text prompt to the model using the OpenAI Python client. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai/v1" ) response = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "user", "content": [ {"type": "text", "text": "What is in this image?"}, { "type": "image_url", "image_url": { "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg" } } ] } ], max_tokens=512 ) print(response.choices[0].message.content) ``` -------------------------------- ### Using Environment Variables for API Key (Python) Source: https://tokenmix.ai/docs/authentication Example of storing the TokenMix API key in an environment variable and using it with the OpenAI SDK in Python. ```APIDOC ## Using Environment Variables - Python OpenAI SDK ### Description For production, store your API key in environment variables instead of hardcoding it in source code. ### Method SDK ### Endpoint https://api.tokenmix.ai/v1 ### Parameters #### Environment Variables - **TOKENMIX_API_KEY** (string) - Required - The TokenMix API key stored in an environment variable #### Client Configuration - **api_key** (string) - Required - Retrieved from os.environ["TOKENMIX_API_KEY"] - **base_url** (string) - Required - The TokenMix API base URL: https://api.tokenmix.ai/v1 ### Request Example import os from openai import OpenAI client = OpenAI( api_key=os.environ["TOKENMIX_API_KEY"], base_url="https://api.tokenmix.ai/v1" ) ``` -------------------------------- ### Anthropic SDK Streaming Example (Python) Source: https://tokenmix.ai/docs/sdks Streams a chat completion from the 'claude-sonnet-4.6' model using the Anthropic SDK. Prints each text chunk as it arrives. ```python with client.messages.stream( model="claude-sonnet-4.6", max_tokens=1024, messages=[{"role": "user", "content": "Tell me a short story."}] ) as stream: for text in stream.text_stream: print(text, end="", flush=True) print() ``` -------------------------------- ### Create Video Response (JSON) Source: https://tokenmix.ai/docs/videos Example response from the create video endpoint, containing the task ID, status 'pending', model, and creation timestamp. Poll the status endpoint with this ID until status is 'completed' or 'failed'. ```json { "id": "d290f1ee-6c54-4b01-90e6-d701748f0851", "status": "pending", "model": "sora-2", "created_at": 1710000000 } ``` -------------------------------- ### Text-to-Speech (TTS) Example - Python Source: https://tokenmix.ai/docs/audio Generates speech from text using the tts-1 model and saves the audio to a file. Requires an OpenAI client configured with your API key and base URL. ```python from openai import OpenAI from pathlib import Path client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai/v1" ) response = client.audio.speech.create( model="tts-1", voice="alloy", input="Hello! Welcome to TokenMix.", response_format="mp3", speed=1.0 ) speech_file = Path("output.mp3") response.stream_to_file(speech_file) print(f"Audio saved to {speech_file}") ``` -------------------------------- ### Python Example with OpenAI SDK Source: https://tokenmix.ai/docs/embeddings Use the OpenAI Python SDK with a custom base URL to create embeddings. The response contains the embedding vector; print its dimensions and first five values. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai/v1" ) response = client.embeddings.create( model="text-embedding-3-small", input="TokenMix provides unified API access to multiple AI models.", dimensions=1536 ) embedding = response.data[0].embedding print(f"Dimensions: {len(embedding)}") print(f"First 5 values: {embedding[:5]}") ``` -------------------------------- ### GET /v1/usage Source: https://tokenmix.ai/docs/openai-compatibility Provides account API usage summary for the authenticated API key owner. ```APIDOC ## GET /v1/usage ### Description Provides account API usage summary for the authenticated API key owner. ### Method GET ### Endpoint /v1/usage ``` -------------------------------- ### Anthropic SDK Chat Completion Example (Python) Source: https://tokenmix.ai/docs/sdks Creates an Anthropic client with the TokenMix base URL and sends a chat completion request to the 'claude-sonnet-4.6' model. Replace 'YOUR_API_KEY' with your actual API key. ```python import anthropic client = anthropic.Anthropic( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai" ) message = client.messages.create( model="claude-sonnet-4.6", max_tokens=1024, messages=[ {"role": "user", "content": "What is the capital of Japan?"} ] ) print(message.content[0].text) ``` -------------------------------- ### Define Tools with JSON Schema Source: https://tokenmix.ai/docs/function-calling Example of defining a tool using the tools parameter with JSON Schema, specifically for a weather retrieval function. ```json { "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City name, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "Temperature unit" } }, "required": ["location"] } } } ] } ``` -------------------------------- ### Error response example Source: https://tokenmix.ai/docs/authentication The JSON structure returned when authentication fails, containing an OpenAI-compatible error object. ```json { "error": { "message": "invalid api key", "type": "invalid_request_error", "request_id": "req_abc123" } } ``` -------------------------------- ### Use API key with Node.js Source: https://tokenmix.ai/docs/authentication Set the TokenMix API key and base URL in the Node.js OpenAI client. Replace the example key with your actual key. ```javascript import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'sk-tm-your-api-key-here', baseURL: 'https://api.tokenmix.ai/v1' }); ``` -------------------------------- ### Response Format Example Source: https://tokenmix.ai/docs/embeddings Shows the JSON structure returned by the embeddings endpoint, including the embedding array, model, and token usage. ```json { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [0.0023, -0.0091, 0.0152, -0.0033, 0.0074, ...] } ], "model": "text-embedding-3-small", "usage": { "prompt_tokens": 10, "total_tokens": 10 } } ``` -------------------------------- ### Example Response for JSON Schema Mode Source: https://tokenmix.ai/docs/structured-output Shows the expected output for the event_details schema. The model will always produce this structure when strict: true is set. ```json { "event_name": "AI Summit", "date": "March 15, 2026", "location": "San Francisco", "attendees": 500 } ``` -------------------------------- ### Generate Video from Image with Python Source: https://tokenmix.ai/docs/videos Python example using the requests library to generate a video from a reference image. The model wan2.6-i2v is used. The image_url must point to a reference image up to 20MB, with width and height at least 300px and aspect ratio between 1:2.5 and 2.5:1. The response contains the task ID. ```python import requests response = requests.post( "https://api.tokenmix.ai/v1/videos/generations", headers={ "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json", }, json={ "model": "wan2.6-i2v", "prompt": "The person in the photo starts walking through a garden", "image_url": "https://example.com/reference-photo.jpg", }, ) task = response.json() print(f"Task ID: {task['id']}") ``` -------------------------------- ### Go Chat Completion Example with OpenAI SDK Source: https://tokenmix.ai/docs/sdks Uses the OpenAI Go SDK to send a chat completion request to the 'gpt-4o-mini' model via TokenMix's OpenAI-compatible endpoint. Replace 'YOUR_API_KEY' with your actual API key. ```go package main import ( "context" "fmt" "github.com/openai/openai-go" "github.com/openai/openai-go/option" ) func main() { client := openai.NewClient( option.WithAPIKey("YOUR_API_KEY"), option.WithBaseURL("https://api.tokenmix.ai/v1"), ) response, err := client.Chat.Completions.New( context.Background(), openai.ChatCompletionNewParams{ Model: "gpt-4o-mini", Messages: []openai.ChatCompletionMessageParamUnion{ openai.SystemMessage("You are a helpful assistant."), openai.UserMessage("What is the capital of Japan?"), }, MaxTokens: openai.Int(1024), }, ) if err != nil { panic(err) } fmt.Println(response.Choices[0].Message.Content) } ``` -------------------------------- ### Implement Automatic Prompt Caching with OpenAI SDK Source: https://tokenmix.ai/docs/prompt-caching This example demonstrates how to reuse a static system prompt across multiple user turns to trigger automatic caching. It includes logic to check for cache hits using the prompt_tokens_details field in the response usage. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai/v1", ) # Same system prompt + tool schema reused across multiple user turns. # Supported models cache the shared prefix automatically — no markers needed. SYSTEM_PROMPT = """You are an expert technical support assistant... <... 1500+ tokens of product knowledge, style rules, FAQs ...>""" def ask(user_question: str): response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_question}, ], ) usage = response.usage # Read cache hits from the nested field: cached = getattr(usage, "prompt_tokens_details", None) if cached and cached.get("cached_tokens", 0) > 0: print(f"cache hit: {cached['cached_tokens']} tokens at cached input rate") return response.choices[0].message.content # First call: cache write (billed at normal input price). ask("How do I reset my password?") # Second call within ~5 minutes: cache read on the shared prefix. ask("Can I change my email?") ``` -------------------------------- ### GET /api/v1/credits Source: https://tokenmix.ai/docs/openai-compatibility OpenRouter-style credits alias. ```APIDOC ## GET /api/v1/credits ### Description OpenRouter-style credits alias. ### Method GET ### Endpoint /api/v1/credits ``` -------------------------------- ### GET /api/v1/generation Source: https://tokenmix.ai/docs/openai-compatibility OpenRouter-style generation lookup alias. ```APIDOC ## GET /api/v1/generation ### Description OpenRouter-style generation lookup alias. ### Method GET ### Endpoint /api/v1/generation ``` -------------------------------- ### GET /v1/generation Source: https://tokenmix.ai/docs/openai-compatibility Looks up a generation by TokenMix response ID (OpenRouter-like). ```APIDOC ## GET /v1/generation ### Description Looks up a generation by TokenMix response ID (OpenRouter-like). ### Method GET ### Endpoint /v1/generation ``` -------------------------------- ### Enable streaming with Python (OpenAI client) Source: https://tokenmix.ai/docs/streaming Set stream: true in the request body to enable streaming. The example prints each content delta as it arrives. Long responses must use streaming to avoid 408 request_timeout. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai/v1" ) stream = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain quantum computing in simple terms."} ], stream=True, max_tokens=1024 ) for chunk in stream: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True) print() # newline at end ``` -------------------------------- ### Image response format Source: https://tokenmix.ai/docs/images Example of a standard image generation response containing a URL. ```json { "created": 1710000000, "data": [ { "url": "https://cdn.tokenmix.ai/images/abc123.png" } ] } ``` -------------------------------- ### GET /v1/models/{model} Source: https://tokenmix.ai/docs/openai-compatibility Retrieves metadata for a single model, used for SDK probes. ```APIDOC ## GET /v1/models/{model} ### Description Retrieves metadata for a single model, used for SDK probes. ### Method GET ### Endpoint /v1/models/{model} ### Parameters #### Path Parameters - **model** (string) - Required - The model identifier. ``` -------------------------------- ### OpenAI-compatible Response Usage Fields Source: https://tokenmix.ai/docs/prompt-caching Example of an OpenAI-compatible response showing the nested prompt_tokens_details.cached_tokens field. ```json { "usage": { "prompt_tokens": 1500, "completion_tokens": 120, "total_tokens": 1620, "prompt_tokens_details": { "cached_tokens": 1400 } } } ``` -------------------------------- ### Anthropic Response Usage Fields Source: https://tokenmix.ai/docs/prompt-caching Example of an Anthropic-compatible response containing cache_creation_input_tokens and cache_read_input_tokens fields. ```json { "usage": { "prompt_tokens": 11, "completion_tokens": 4, "total_tokens": 15, "cache_creation_input_tokens": 1041, "cache_read_input_tokens": 0 } } ``` -------------------------------- ### Generate Image-to-Image with Python Source: https://tokenmix.ai/docs/images Use the requests library to send a POST request to the TokenMix API with a reference image URL and a text prompt. Ensure you replace YOUR_API_KEY with your actual API key. ```python import requests response = requests.post( "https://api.tokenmix.ai/v1/images/generations", headers={ "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json", }, json={ "model": "flux-1-kontext-pro", "prompt": "Transform this photo into a watercolor painting style", "image_url": "https://example.com/my-photo.jpg", "size": "1024x1024", }, ) print(response.json()["data"][0]["url"]) ``` -------------------------------- ### Submit video generation request with reference images (HappyHorse R2V) - Python Source: https://tokenmix.ai/docs/videos Sends a POST request to /videos/generations with the happyhorse-1.0-r2v model, providing two reference images. The response contains the task ID. Requires a valid API key. The example uses 720p resolution, 9:16 aspect ratio, and 7-second duration. ```python import requests response = requests.post( "https://api.tokenmix.ai/v1/videos/generations", headers={ "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json", }, json={ "model": "happyhorse-1.0-r2v", "prompt": "Keep the product shape and logo consistent while showing a slow cinematic rotation", "images": [ "https://example.com/reference-1.jpg", "https://example.com/reference-2.jpg", ], "resolution": "720p", "aspect_ratio": "9:16", "duration": 7, }, ) task = response.json() print(f"Task ID: {task['id']}") ``` -------------------------------- ### Retry-After header example Source: https://tokenmix.ai/docs/rate-limits The HTTP header indicating the duration to wait before retrying after a 429 error. ```bash # The Retry-After header tells you how long to wait HTTP/2 429 Retry-After: 2 ``` -------------------------------- ### GET /api/v1/models/{author}/{slug}/endpoints Source: https://tokenmix.ai/docs/openai-compatibility OpenRouter-like aggregate endpoint availability for one model. ```APIDOC ## GET /api/v1/models/{author}/{slug}/endpoints ### Description OpenRouter-like aggregate endpoint availability for one model. ### Method GET ### Endpoint /api/v1/models/{author}/{slug}/endpoints ### Parameters #### Path Parameters - **author** (string) - Required - The model author. - **slug** (string) - Required - The model slug. ``` -------------------------------- ### Make First Chat Completion Request with Python Source: https://tokenmix.ai/docs/quickstart Send a chat completion request using the OpenAI SDK with the TokenMix base URL. Replace YOUR_API_KEY with the key you created. The response content is printed to the console. ```python from openai import OpenAI client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai/v1" ) response = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "What is machine learning?"} ], temperature=0.7, max_tokens=1024 ) print(response.choices[0].message.content) ``` -------------------------------- ### List Models with cURL Source: https://tokenmix.ai/docs/quickstart Retrieve the list of currently available models. Returns all enabled models with basic info. Replace YOUR_API_KEY with your actual API key. ```bash curl https://api.tokenmix.ai/v1/models \ -H "Authorization: Bearer YOUR_API_KEY" ``` -------------------------------- ### GET /v1/models (cURL) Source: https://tokenmix.ai/docs/sdks Lists the available models from the TokenMix AI API using cURL. ```APIDOC ## GET /v1/models ### Description Lists the available models from the TokenMix AI API using cURL. ### Method GET ### Endpoint https://api.tokenmix.ai/v1/models ### Parameters #### Headers - **Authorization** (string) - Required - Bearer token for authentication. ### Request Example curl https://api.tokenmix.ai/v1/models \ -H "Authorization: Bearer YOUR_API_KEY" ### Response #### Success Response (200) - **data** (array) - The list of available models. #### Response Example { "data": [ { "id": "gpt-4o-mini" } ] } ``` -------------------------------- ### Function Calling Workflow in Python Source: https://tokenmix.ai/docs/function-calling A complete implementation showing the initial request, local function execution, and sending the tool result back to the model. ```python from openai import OpenAI import json client = OpenAI( api_key="YOUR_API_KEY", base_url="https://api.tokenmix.ai/v1" ) # Your function implementation def get_weather(location, unit="celsius"): # In production, call a real weather API return {"temperature": 22, "unit": unit, "condition": "sunny"} tools = [ { "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a given location", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "City name"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["location"] } } } ] messages = [{"role": "user", "content": "What's the weather in Tokyo?"}] # Step 1: Initial request response = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools ) assistant_message = response.choices[0].message messages.append(assistant_message) # Step 2: Execute function if assistant_message.tool_calls: for tool_call in assistant_message.tool_calls: args = json.loads(tool_call.function.arguments) result = get_weather(**args) # Step 3: Send result back messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result) }) # Final response with function results final_response = client.chat.completions.create( model="gpt-4o", messages=messages, tools=tools ) print(final_response.choices[0].message.content) # "The current weather in Tokyo is 22°C and sunny." ``` -------------------------------- ### STT Transcription Response - JSON Source: https://tokenmix.ai/docs/audio Example JSON response containing the transcribed text from the speech-to-text endpoint. ```json { "text": "Hello, this is a test recording for speech-to-text transcription." } ``` -------------------------------- ### Streaming Response Format Source: https://tokenmix.ai/docs/chat-completions Example of the Server-Sent Events (SSE) format where each event contains a delta field, concluding with [DONE]. ```text 1data: {"id":"chatcmpl-abc123","choices":[{"delta":{"role":"assistant"},"index":0}]} 2 3data: {"id":"chatcmpl-abc123","choices":[{"delta":{"content":"Once"},"index":0}]} 4 5data: {"id":"chatcmpl-abc123","choices":[{"delta":{"content":" upon"},"index":0}]} 6 7data: {"id":"chatcmpl-abc123","choices":[{"delta":{"content":" a"},"index":0}]} 8 9data: [DONE] ```