### Text-to-Speech API Examples Source: https://proxyapi.ru/docs/openai-text-to-speech Examples of using ProxyAPI's TTS endpoint for basic speech synthesis and streaming playback. Supports multiple audio formats and voice customization through instructions parameter. Requires valid API key and handles Russian text input. ```shell curl "https://api.proxyapi.ru/openai/v1/audio/speech" \ -H "Authorization: Bearer <КЛЮЧ>" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini-tts", "input": "Привет! Сегодня замечательный день для создания чего-то удивительного.", "voice": "coral", "instructions": "Говори с радостной и позитивной интонацией." }' \ --output speech.mp3 ``` ```shell curl "https://api.proxyapi.ru/openai/v1/audio/speech" \ -H "Authorization: Bearer <КЛЮЧ>" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-4o-mini-tts", "input": "Это пример потокового синтеза речи в реальном времени.", "voice": "coral", "response_format": "wav", "instructions": "Говори четко и размеренно." }' | ffplay -i - ``` -------------------------------- ### Example Request to OpenRouter via ProxyAPI Source: https://proxyapi.ru/docs/openrouter Demonstrates how to send a chat completion request to OpenRouter using ProxyAPI. It includes the necessary headers, the endpoint, and a sample JSON payload with a user message. ```curl curl "https://api.proxyapi.ru/openrouter/v1/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer <КЛЮЧ>" \ -d '{ "model": "mistralai/mistral-medium-3.1", "messages": [ { "role": "user", "content": "Привет!" } ] }' ``` ```python import requests url = "https://api.proxyapi.ru/openrouter/v1/chat/completions" headers = { "Content-Type": "application/json", "Authorization": "Bearer <КЛЮЧ>" } data = { "model": "mistralai/mistral-medium-3.1", "messages": [ { "role": "user", "content": "Привет!" } ] } response = requests.post(url, headers=headers, json=data) print(response.json()) ``` ```javascript const fetch = require('node-fetch'); const url = 'https://api.proxyapi.ru/openrouter/v1/chat/completions'; const headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer <КЛЮЧ>' }; const data = { 'model': 'mistralai/mistral-medium-3.1', 'messages': [ { 'role': 'user', 'content': 'Привет!' } ] }; fetch(url, { method: 'POST', headers: headers, body: JSON.stringify(data) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error)); ``` -------------------------------- ### OpenAI GPT-4o Prompt and Response Token Estimation Example Source: https://proxyapi.ru/docs/cost-of-request This example demonstrates the structure of a request to the OpenAI gpt-4o model and illustrates how prompt tokens are calculated. The response tokens are estimated based on the model's maximum possible output. ```json { "model": "gpt-4o", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Привет! Расскажи про то, как устроена солнечная система" } ] } ] } ``` -------------------------------- ### Transcribe audio with custom prompt via ProxyAPI Source: https://proxyapi.ru/docs/openai-speech-to-text Sends an audio file together with a prompt to guide the transcription, using the gpt-4o-transcribe model. The prompt helps improve recognition of specific terminology. Returns the transcribed text incorporating the prompt context. ```bash curl --request POST \ --url "https://api.proxyapi.ru/openai/v1/audio/transcriptions" \ --header "Authorization: Bearer <КЛЮЧ>" \ --header "Content-Type: multipart/form-data" \ --form file=@/path/to/file/speech.mp3 \ --form model=gpt-4o-transcribe \ --form prompt="Следующий разговор - лекция о последних разработках OpenAI, GPT-4.5 и будущем ИИ." ``` -------------------------------- ### Perform basic audio transcription via ProxyAPI Source: https://proxyapi.ru/docs/openai-speech-to-text Uses a curl POST request to send an audio file for transcription with the gpt-4o-transcribe model. Requires an API key in the Authorization header and multipart/form-data encoding. Returns the transcription in the default format. ```bash curl --request POST \ --url "https://api.proxyapi.ru/openai/v1/audio/transcriptions" \ --header "Authorization: Bearer <КЛЮЧ>" \ --header "Content-Type: multipart/form-data" \ --form file=@/path/to/file/audio.mp3 \ --form model=gpt-4o-transcribe ``` -------------------------------- ### Create transcription with custom prompt using Python SDK Source: https://proxyapi.ru/docs/openai-speech-to-text Shows how to improve recognition of specific terms by providing a `prompt` to the Whisper‑1 model via the Python client. The prompt influences the model to favor the listed terminology during transcription. Returns the processed transcription text. ```python transcription = client.audio.transcriptions.create( model="whisper-1", file=audio_file, prompt="OpenAI, ChatGPT, GPT-4, API, машинное обучение, нейронные сети" ) ``` -------------------------------- ### Handle safety check response from ProxyAPI Source: https://proxyapi.ru/docs/openai-computer-use Example of how to handle safety check responses from the ProxyAPI. The response includes pending safety checks that need to be addressed before continuing execution. This helps protect against malicious instructions and risky domains. ```json "output": [ { "type": "computer_call", ... "pending_safety_checks": [ { "id": "cu_sc_67cb...", "code": "malicious_instructions", "message": "We've detected instructions that may..." } ], } ] ``` -------------------------------- ### OpenAI API: Web Search using Chat Completions API (curl) Source: https://proxyapi.ru/docs/openai-web-search This example shows how to perform a web search using the Chat Completions API with specialized models like `gpt-4o-search-preview`. Web search is mandatory for these models. The `web_search_options` object configures the search context size and user location. ```curl curl "https://api.proxyapi.ru/openai/v1/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer <КЛЮЧ>" \ -d '{ "model": "gpt-4o-search-preview", "web_search_options": { "search_context_size": "low", "user_location": { "type": "approximate", "approximate": { "country": "RU", "city": "Moscow", "region": "Moscow" } } }, "messages": [ { "role": "user", "content": "Какая сегодня погода?" } ] }' ``` -------------------------------- ### Stream audio transcription via ProxyAPI Source: https://proxyapi.ru/docs/openai-speech-to-text Performs a streaming transcription using the gpt-4o-mini-transcribe model. The `stream=True` parameter enables incremental results, useful for real‑time applications. The request follows the same multipart format as standard transcription. ```bash curl --request POST \ --url "https://api.proxyapi.ru/openai/v1/audio/transcriptions" \ --header "Authorization: Bearer <КЛЮЧ>" \ --header "Content-Type: multipart/form-data" \ --form file=@example.wav \ --form model=gpt-4o-mini-transcribe \ --form stream=True ``` -------------------------------- ### Initialize Anthropic client in Python Source: https://proxyapi.ru/docs/anthropic-web-search This Python code snippet initializes an Anthropic client using the anthropic library, configured with a ProxyAPI key and base URL. Useful for making API calls in Python scripts; requires the anthropic package installed via pip. ```python import anthropic client = anthropic.Anthropic( api_key="<КЛЮЧ>", base_url="https://api.proxyapi.ru/anthropic", ) ``` -------------------------------- ### Include Current URL for Enhanced Safety Checks (JSON) Source: https://proxyapi.ru/docs/openai-computer-use This JSON example shows how to include the `current_url` field in the `computer_call_output`. Providing the current URL helps in enhancing the accuracy of safety checks performed by the AI model. ```json { "type": "computer_call_output", "call_id": "call_7OU...", "acknowledged_safety_checks": [], "output": { "type": "computer_screenshot", "image_url": "..." }, "current_url": "https://proxyapi.ru" } ``` -------------------------------- ### Create transcription with timestamps using Python SDK Source: https://proxyapi.ru/docs/openai-speech-to-text Demonstrates the Python client for obtaining word‑level timestamps from Whisper‑1. The `timestamp_granularities` parameter can be set to "word", "segment", or both. Returns a verbose JSON containing timestamps for each word or segment. ```python transcription = client.audio.transcriptions.create( file=audio_file, model="whisper-1", response_format="verbose_json", timestamp_granularities=["word"] # or ["segment"] ["word", "segment"] ) ``` -------------------------------- ### Разбиение длинного аудиофайла на части с помощью PyDub Source: https://proxyapi.ru/docs/openai-speech-to-text Этот код демонстрирует, как разделить длинный MP3-файл на части с использованием библиотеки pydub. Он загружает аудиофайл, вычисляет длительность в миллисекундах для 10 минут, извлекает первые 10 минут и экспортирует их как новый MP3-файл. Требуется установка библиотеки pydub. ```python from pydub import AudioSegment song = AudioSegment.from_mp3("long_audio.mp3") ten_minutes = 10 * 60 * 1000 # PyDub работает с миллисекундами first_10_minutes = song[:ten_minutes] first_10_minutes.export("audio_part1.mp3", format="mp3") ``` -------------------------------- ### GET /api/balance Source: https://proxyapi.ru/docs/index Retrieve the current account balance in the ProxyAPI dashboard. This endpoint requires authentication via the API key. ```APIDOC ## GET /api/balance ### Description Retrieve the current account balance in the ProxyAPI dashboard. This endpoint requires authentication via the API key. ### Method GET ### Endpoint /api/balance ### Parameters #### Header Parameters - **Authorization** (string) - Required - Bearer token with the ProxyAPI key ### Request Example ``` Authorization: Bearer abc123xyz ``` ### Response #### Success Response (200) - **balance** (number) - The remaining account balance #### Response Example { "balance": 150.75 } ``` -------------------------------- ### GET /v1/models Source: https://proxyapi.ru/docs/openai-compatible-api Возвращает список доступных моделей и их метаданные. Используется для получения информации о поддерживаемых провайдерах и моделях. ```APIDOC ## GET /v1/models ### Description Возвращает список доступных моделей и их метаданные для всех поддерживаемых провайдеров. ### Method GET ### Endpoint https://openai.api.proxyapi.ru/v1/models ### Parameters #### Path Parameters - **models** (string) - Optional - ID модели для получения конкретной модели #### Query Parameters Нет параметров #### Request Body Нет тела запроса ### Request Example GET https://openai.api.proxyapi.ru/v1/models ### Response #### Success Response (200) - **data** (array) - Список объектов моделей - **object** (string) - Тип объекта (обычно "list") #### Response Example { "data": [ { "id": "openai/gpt-4o", "object": "model", "created": 1699000000, "owned_by": "openai" }, { "id": "anthropic/claude-sonnet-4-20250514", "object": "model", "created": 1699000000, "owned_by": "anthropic" } ], "object": "list" } ``` -------------------------------- ### POST /openai/v1/chat/completions Source: https://proxyapi.ru/docs/openai-web-search Chat completions endpoint with mandatory web search for specialized search-preview models. Requires web search configuration for location and context size. ```APIDOC ## POST /openai/v1/chat/completions ### Description Specialized chat completion endpoint for models with built-in web search (gpt-4o-search-preview). Web search is mandatory for these models. ### Method POST ### Endpoint https://api.proxyapi.ru/openai/v1/chat/completions ### Parameters #### Request Body - **model** (string) - Required - Must be a search-preview model ("gpt-4o-search-preview" or "gpt-4o-mini-search-preview") - **web_search_options** (object) - Required - Web search configuration - **search_context_size** (string) - Optional - Context size ("low", "medium", "high") - **user_location** (object) - Optional - User location details - **type** (string) - Required - Always "approximate" - **approximate** (object) - Required - Location details - **country** (string) - Optional - ISO country code (e.g., "RU") - **city** (string) - Optional - City name - **region** (string) - Optional - Region name - **messages** (array) - Required - Chat message history - **role** (string) - Required - "user" or "assistant" - **content** (string) - Required - Message content ### Request Example { "model": "gpt-4o-search-preview", "web_search_options": { "search_context_size": "low", "user_location": { "type": "approximate", "approximate": { "country": "RU", "city": "Moscow", "region": "Moscow" } } }, "messages": [ { "role": "user", "content": "Какая сегодня погода?" } ] } ### Response #### Success Response (200) - Returns chat completion response with incorporated web search results #### Response Example { "choices": [ { "message": { "role": "assistant", "content": "Generated response with web search context" } } ] } ``` -------------------------------- ### OpenAI Request with Max Completion Tokens Limit Source: https://proxyapi.ru/docs/cost-of-request This example shows how to limit the approximate cost calculation for an OpenAI request by specifying the `max_completion_tokens` parameter. This sets an upper bound for response tokens used in the pre-calculation. ```json { "model": "gpt-4o", "max_completion_tokens": 300, "messages": [ ... ``` -------------------------------- ### Translate audio to English via ProxyAPI Source: https://proxyapi.ru/docs/openai-speech-to-text Uses the translations endpoint to convert spoken Russian (or other languages) into English text. The request uploads an audio file and specifies the whisper-1 model. The response is the translated English transcription. ```bash curl --request POST \ --url "https://api.proxyapi.ru/openai/v1/audio/translations" \ --header "Authorization: Bearer <КЛЮЧ>" \ --header "Content-Type: multipart/form-data" \ --form file=@/path/to/file/russian.mp3 \ --form model=whisper-1 ``` -------------------------------- ### Send request to computer-use-preview model in Python Source: https://proxyapi.ru/docs/openai-computer-use This Python code snippet demonstrates how to send a request to the computer-use-preview model using the OpenAI client. It includes setting up the client, configuring the model with the computer_use_preview tool, and sending a user query with optional parameters like generate_summary and truncation. ```python from openai import OpenAI client = OpenAI( api_key="<КЛЮЧ>", base_url="https://api.proxyapi.ru/openai/v1" ) response = client.responses.create( model="computer-use-preview", tools=[{ "type": "computer_use_preview", "display_width": 1024, "display_height": 768, "environment": "browser" # другие значения: "mac", "windows", "ubuntu" }], input=[ { "role": "user", "content": "Прочитай посдений заголовок на Хабре" } # Опционально: включите скриншот начального состояния среды # { # type: "input_image", # image_url: f"data:image/png;base64,{screenshot_base64}" # } ], reasoning={ "generate_summary": "concise", }, truncation="auto" ) print(response.output) ``` -------------------------------- ### Anthropic Request with Max Tokens Limit Source: https://proxyapi.ru/docs/cost-of-request This example demonstrates how to limit the approximate cost calculation for an Anthropic request by specifying the `max_tokens` parameter. This parameter restricts the maximum number of tokens the model can use for its response during pre-calculation. ```json { "model": "claude-3-7-sonnet-20250219", "max_tokens": 300, "messages": [ ... ``` -------------------------------- ### GET /proxyapi/balance Source: https://proxyapi.ru/docs/proxyapi-balance This endpoint allows users to query the balance of their ProxyAPI account or a specific API key. Access must be enabled in the personal cabinet for the key. The response format varies depending on whether the key has a budget limit or not. ```APIDOC ## GET /proxyapi/balance ### Description Retrieves the current balance for the ProxyAPI account or API key. For keys without budget limits, it returns the total account balance. For keys with budget limits, it returns the remaining budget for that key. ### Method GET ### Endpoint https://api.proxyapi.ru/proxyapi/balance ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ``` curl --location 'https://api.proxyapi.ru/proxyapi/balance' --header 'Authorization: Bearer ' ``` Replace `` with your actual API key that has balance query access enabled. ### Response #### Success Response (200) - **balance** (number) - The current balance; for unlimited keys, this is the account balance; for limited keys, it's the remaining budget (limit - used). - **budget** (object, optional) - Present only for keys with budget limits. - **budget.limit** (number) - The set budget limit for the key. - **budget.used** (number) - The amount used by the key. #### Response Example For keys without budget limits: ```json { "balance": 123.45 } ``` For keys with budget limits: ```json { "balance": 37.66, "budget": { "limit": 50.00, "used": 12.34 } } ``` #### Error Handling - Common errors may include authentication failures if the key lacks permission. Refer to ProxyAPI documentation for a list of common errors. ``` -------------------------------- ### Google Gemini CLI Integration with ProxyAPI Source: https://proxyapi.ru/docs/gemini-cli This section details how to configure the Gemini CLI tool to work with ProxyAPI by setting environment variables for the API key and base URL. ```APIDOC ## Gemini CLI Integration with ProxyAPI ### Description This guide explains how to configure the Gemini CLI, an open-source command-line interface tool by Google for interacting with Gemini models, to use ProxyAPI instead of the direct Google API. This allows access to Gemini models through ProxyAPI's infrastructure, supporting developers in tasks related to programming and code analysis directly from their terminal. ### Method Environment Variable Configuration ### Endpoint N/A (Environment Variables) ### Parameters #### Environment Variables - **GEMINI_API_KEY** (string) - Required - Your API key obtained from ProxyAPI. - **GOOGLE_GEMINI_BASE_URL** (string) - Required - The base URL for the ProxyAPI endpoint for Google Gemini, which is `https://api.proxyapi.ru/google`. ### Request Example ```bash export GEMINI_API_KEY="" export GOOGLE_GEMINI_BASE_URL="https://api.proxyapi.ru/google" ``` ### Response #### Success Response Successful configuration is indicated by the Gemini CLI successfully connecting to and making requests through ProxyAPI without authentication errors. No direct API response is generated by setting environment variables; success is validated by subsequent CLI command execution. #### Response Example N/A (Configuration step) ``` -------------------------------- ### POST /responses Source: https://proxyapi.ru/docs/openai-computer-use Send a request to generate a response using the computer-use-preview model. This endpoint requires specific tool configuration and environment details. ```APIDOC ## POST /responses ### Description Send a request to generate a response using the computer-use-preview model equipped with the computer_use_preview tool. This request must include information about your environment as well as the initial prompt. ### Method POST ### Endpoint /responses ### Parameters #### Request Body - **model** (string) - Required - The model identifier, should be "computer-use-preview" - **tools** (array) - Required - Array of tool configurations, must include computer_use_preview tool with display dimensions and environment - **input** (array) - Required - Array of input messages with role and content - **reasoning** (object) - Optional - Configuration for reasoning summary generation - **truncation** (string) - Required - Must be set to "auto" for computer_use_preview tool ### Request Example { "model": "computer-use-preview", "tools": [{ "type": "computer_use_preview", "display_width": 1024, "display_height": 768, "environment": "browser" }], "input": [ { "role": "user", "content": "Прочитай посдений заголовок на Хабре" } ], "reasoning": { "generate_summary": "concise" }, "truncation": "auto" } ### Response #### Success Response (200) - **output** (array) - Array of response elements including reasoning summaries and computer calls #### Response Example { "output": [ { "type": "reasoning", "id": "rs_67cc...", "summary": [ { "type": "summary_text", "text": "Clicking on the browser address bar." } ] }, { "type": "computer_call", "id": "cu_67cc...", "call_id": "call_zw3...", "action": { "type": "click", "button": "left", "x": 156, "y": 50 }, "pending_safety_checks": [], "status": "completed" } ] } ``` -------------------------------- ### POST /openai/v1/chat/completions Source: https://proxyapi.ru/docs/openai-vision Endpoint for chat completions, supporting image analysis via URLs. ```APIDOC ## POST /openai/v1/chat/completions ### Description This endpoint provides chat completions, allowing users to send text and image URLs for analysis within a conversational context. ### Method POST ### Endpoint /openai/v1/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use for chat completions (e.g., "gpt-4o-mini"). - **messages** (array) - Required - An array of message objects representing the conversation history. - **role** (string) - Required - The role of the message sender (e.g., "user"). - **content** (array) - Required - An array of content parts for the message. - **type** (string) - Required - The type of content (e.g., "text", "image_url"). - **text** (string) - Required (if type is "text") - The text content of the message. - **image_url** (object) - Required (if type is "image_url") - An object containing the image URL. - **url** (string) - Required - The URL of the image. ### Request Example ```json { "model": "gpt-4o-mini", "messages": [ { "role": "user", "content": [ {"type": "text", "text": "What is shown in the picture?"}, { "type": "image_url", "image_url": "https://domain.com/your_image.jpg" } ] } ] } ``` ### Response #### Success Response (200) - **choices** (array) - An array of chat completion choices. - **message** (object) - The message from the model. - **role** (string) - The role of the sender (e.g., "assistant"). - **content** (string) - The content of the message. ``` -------------------------------- ### POST /v1/responses Source: https://proxyapi.ru/docs/openai-compatible-api Новый унифицированный API для генерации ответов, заменяющий /v1/chat/completions. Предоставляет расширенные возможности работы с различными типами контента. ```APIDOC ## POST /v1/responses ### Description Новый унифицированный API для генерации ответов, заменяющий /v1/chat/completions. Поддерживает расширенные возможности работы с различными типами контента и инструментами. ### Method POST ### Endpoint https://openai.api.proxyapi.ru/v1/responses ### Parameters #### Path Parameters Нет параметров #### Query Parameters Нет параметров #### Request Body - **model** (string) - Required - Идентификатор модели в формате провайдер/название-модели - **input** (string|array) - Required - Входные данные для генерации - **tools** (array) - Optional - Массив доступных инструментов - **tool_choice** (string) - Optional - Выбор инструмента для использования - **max_output_tokens** (integer) - Optional - Максимальное количество выходных токенов - **temperature** (float) - Optional - Параметр креативности ### Request Example { "model": "anthropic/claude-sonnet-4-20250514", "input": "Расскажи о возможностях ProxyAPI", "max_output_tokens": 1000, "temperature": 0.7 } ### Response #### Success Response (200) - **id** (string) - Уникальный идентификатор запроса - **object** (string) - Тип объекта ("response") - **created** (integer) - Временная метка создания - **output** (array) - Массив сгенерированных ответов - **usage** (object) - Статистика использования #### Response Example { "id": "resp_abc123", "object": "response", "created": 1699000000, "output": [ { "id": "msg_123", "content": [ { "type": "text", "text": "ProxyAPI предоставляет универсальный API..." } ] } ], "usage": { "input_tokens": 10, "output_tokens": 50, "total_tokens": 60 } } ``` -------------------------------- ### Gemini API Text Generation Example (curl) Source: https://proxyapi.ru/docs/gemini-text-generation This snippet demonstrates how to generate text using the Gemini API through ProxyAPI. It requires specifying the API endpoint, content type, authorization token, and the text content for generation. The output is a JSON response containing the generated text. ```curl curl "https://api.proxyapi.ru/google/v1beta/models/gemini-2.0-flash:generateContent" \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer <КЛЮЧ>' \ -X POST \ -d '{ "contents": [{"parts":[{"text": "Привет!"}]}] }' ``` -------------------------------- ### Image Request: Responses API with Base64 (Python) Source: https://proxyapi.ru/docs/openai-vision This Python example demonstrates sending an image encoded in base64 to the ProxyAPI's Responses API. It includes a helper function to encode the image and constructs the API request payload. ```python import base64 from openai import OpenAI client = OpenAI( api_key="<КЛЮЧ>", base_url="https://api.proxyapi.ru/openai/v1", ) # Кодирование изображения в base64 def encode_image(image_path): with open(image_path, "rb") as image_file: return base64.b64encode(image_file.read()).decode("utf-8") # Путь к изображению image_path = "path_to_your_image.jpg" # Получение строки base64 base64_image = encode_image(image_path) response = client.responses.create( model="gpt-4o-mini", input=[ { "role": "user", "content": [ { "type": "input_text", "text": "Что изображено на картинке?" }, { "type": "input_image", "image_url": f"data:image/jpeg;base64,{base64_image}", }, ], } ], ) ```