curl --request POST \
--url https://polza.ai/api/v1/chat/completions \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "openai/gpt-4o",
"messages": [
{
"role": "system",
"content": "Ты полезный ассистент"
},
{
"role": "user",
"content": "Привет! Как дела?"
}
],
"prompt": "Напиши стихотворение про кота",
"max_tokens": 1000,
"max_completion_tokens": 1000,
"temperature": 1,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"response_format": {},
"provider": {
"allow_fallbacks": true,
"order": [
"OpenAI",
"Anthropic"
],
"only": [
"OpenAI",
"Google"
],
"ignore": [
"DeepInfra"
],
"sort": "price",
"max_price": {
"prompt": 10,
"completion": 20,
"image": 5,
"audio": 15,
"request": 1
}
},
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Получить текущую погоду для указанного местоположения",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Название города"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
},
"required": [
"location"
]
},
"strict": false
}
}
],
"tool_choice": "auto",
"reasoning": {
"effort": "medium",
"summary": "auto",
"enabled": true,
"max_tokens": 2000,
"exclude": false
},
"plugins": "<array>",
"web_search_options": {
"search_context_size": "medium"
},
"user": "user-123",
"stop": [
"\n"
],
"seed": 42,
"n": 1,
"stream": false,
"logprobs": false,
"top_logprobs": 5,
"logit_bias": {
"50256": -100
},
"parallel_tool_calls": true,
"image_config": {
"quality": "high",
"size": 512
},
"modalities": [
"text",
"audio"
],
"audio": {
"voice": "alloy",
"format": "pcm16"
}
}
'import requests
url = "https://polza.ai/api/v1/chat/completions"
payload = {
"model": "openai/gpt-4o",
"messages": [
{
"role": "system",
"content": "Ты полезный ассистент"
},
{
"role": "user",
"content": "Привет! Как дела?"
}
],
"prompt": "Напиши стихотворение про кота",
"max_tokens": 1000,
"max_completion_tokens": 1000,
"temperature": 1,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"response_format": {},
"provider": {
"allow_fallbacks": True,
"order": ["OpenAI", "Anthropic"],
"only": ["OpenAI", "Google"],
"ignore": ["DeepInfra"],
"sort": "price",
"max_price": {
"prompt": 10,
"completion": 20,
"image": 5,
"audio": 15,
"request": 1
}
},
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Получить текущую погоду для указанного местоположения",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Название города"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location"]
},
"strict": False
}
}
],
"tool_choice": "auto",
"reasoning": {
"effort": "medium",
"summary": "auto",
"enabled": True,
"max_tokens": 2000,
"exclude": False
},
"plugins": "<array>",
"web_search_options": { "search_context_size": "medium" },
"user": "user-123",
"stop": ["
"],
"seed": 42,
"n": 1,
"stream": False,
"logprobs": False,
"top_logprobs": 5,
"logit_bias": { "50256": -100 },
"parallel_tool_calls": True,
"image_config": {
"quality": "high",
"size": 512
},
"modalities": ["text", "audio"],
"audio": {
"voice": "alloy",
"format": "pcm16"
}
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
model: 'openai/gpt-4o',
messages: [
{role: 'system', content: 'Ты полезный ассистент'},
{role: 'user', content: 'Привет! Как дела?'}
],
prompt: 'Напиши стихотворение про кота',
max_tokens: 1000,
max_completion_tokens: 1000,
temperature: 1,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
response_format: {},
provider: {
allow_fallbacks: true,
order: ['OpenAI', 'Anthropic'],
only: ['OpenAI', 'Google'],
ignore: ['DeepInfra'],
sort: 'price',
max_price: {prompt: 10, completion: 20, image: 5, audio: 15, request: 1}
},
tools: [
{
type: 'function',
function: {
name: 'get_weather',
description: 'Получить текущую погоду для указанного местоположения',
parameters: {
type: 'object',
properties: {
location: {type: 'string', description: 'Название города'},
unit: {type: 'string', enum: ['celsius', 'fahrenheit']}
},
required: ['location']
},
strict: false
}
}
],
tool_choice: 'auto',
reasoning: {
effort: 'medium',
summary: 'auto',
enabled: true,
max_tokens: 2000,
exclude: false
},
plugins: '<array>',
web_search_options: {search_context_size: 'medium'},
user: 'user-123',
stop: ['\n'],
seed: 42,
n: 1,
stream: false,
logprobs: false,
top_logprobs: 5,
logit_bias: {'50256': -100},
parallel_tool_calls: true,
image_config: {quality: 'high', size: 512},
modalities: ['text', 'audio'],
audio: {voice: 'alloy', format: 'pcm16'}
})
};
fetch('https://polza.ai/api/v1/chat/completions', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://polza.ai/api/v1/chat/completions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'model' => 'openai/gpt-4o',
'messages' => [
[
'role' => 'system',
'content' => 'Ты полезный ассистент'
],
[
'role' => 'user',
'content' => 'Привет! Как дела?'
]
],
'prompt' => 'Напиши стихотворение про кота',
'max_tokens' => 1000,
'max_completion_tokens' => 1000,
'temperature' => 1,
'top_p' => 1,
'frequency_penalty' => 0,
'presence_penalty' => 0,
'response_format' => [
],
'provider' => [
'allow_fallbacks' => true,
'order' => [
'OpenAI',
'Anthropic'
],
'only' => [
'OpenAI',
'Google'
],
'ignore' => [
'DeepInfra'
],
'sort' => 'price',
'max_price' => [
'prompt' => 10,
'completion' => 20,
'image' => 5,
'audio' => 15,
'request' => 1
]
],
'tools' => [
[
'type' => 'function',
'function' => [
'name' => 'get_weather',
'description' => 'Получить текущую погоду для указанного местоположения',
'parameters' => [
'type' => 'object',
'properties' => [
'location' => [
'type' => 'string',
'description' => 'Название города'
],
'unit' => [
'type' => 'string',
'enum' => [
'celsius',
'fahrenheit'
]
]
],
'required' => [
'location'
]
],
'strict' => false
]
]
],
'tool_choice' => 'auto',
'reasoning' => [
'effort' => 'medium',
'summary' => 'auto',
'enabled' => true,
'max_tokens' => 2000,
'exclude' => false
],
'plugins' => '<array>',
'web_search_options' => [
'search_context_size' => 'medium'
],
'user' => 'user-123',
'stop' => [
'
'
],
'seed' => 42,
'n' => 1,
'stream' => false,
'logprobs' => false,
'top_logprobs' => 5,
'logit_bias' => [
'50256' => -100
],
'parallel_tool_calls' => true,
'image_config' => [
'quality' => 'high',
'size' => 512
],
'modalities' => [
'text',
'audio'
],
'audio' => [
'voice' => 'alloy',
'format' => 'pcm16'
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://polza.ai/api/v1/chat/completions"
payload := strings.NewReader("{\n \"model\": \"openai/gpt-4o\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"Ты полезный ассистент\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Привет! Как дела?\"\n }\n ],\n \"prompt\": \"Напиши стихотворение про кота\",\n \"max_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"temperature\": 1,\n \"top_p\": 1,\n \"frequency_penalty\": 0,\n \"presence_penalty\": 0,\n \"response_format\": {},\n \"provider\": {\n \"allow_fallbacks\": true,\n \"order\": [\n \"OpenAI\",\n \"Anthropic\"\n ],\n \"only\": [\n \"OpenAI\",\n \"Google\"\n ],\n \"ignore\": [\n \"DeepInfra\"\n ],\n \"sort\": \"price\",\n \"max_price\": {\n \"prompt\": 10,\n \"completion\": 20,\n \"image\": 5,\n \"audio\": 15,\n \"request\": 1\n }\n },\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Получить текущую погоду для указанного местоположения\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Название города\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"celsius\",\n \"fahrenheit\"\n ]\n }\n },\n \"required\": [\n \"location\"\n ]\n },\n \"strict\": false\n }\n }\n ],\n \"tool_choice\": \"auto\",\n \"reasoning\": {\n \"effort\": \"medium\",\n \"summary\": \"auto\",\n \"enabled\": true,\n \"max_tokens\": 2000,\n \"exclude\": false\n },\n \"plugins\": \"<array>\",\n \"web_search_options\": {\n \"search_context_size\": \"medium\"\n },\n \"user\": \"user-123\",\n \"stop\": [\n \"\\n\"\n ],\n \"seed\": 42,\n \"n\": 1,\n \"stream\": false,\n \"logprobs\": false,\n \"top_logprobs\": 5,\n \"logit_bias\": {\n \"50256\": -100\n },\n \"parallel_tool_calls\": true,\n \"image_config\": {\n \"quality\": \"high\",\n \"size\": 512\n },\n \"modalities\": [\n \"text\",\n \"audio\"\n ],\n \"audio\": {\n \"voice\": \"alloy\",\n \"format\": \"pcm16\"\n }\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://polza.ai/api/v1/chat/completions")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"openai/gpt-4o\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"Ты полезный ассистент\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Привет! Как дела?\"\n }\n ],\n \"prompt\": \"Напиши стихотворение про кота\",\n \"max_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"temperature\": 1,\n \"top_p\": 1,\n \"frequency_penalty\": 0,\n \"presence_penalty\": 0,\n \"response_format\": {},\n \"provider\": {\n \"allow_fallbacks\": true,\n \"order\": [\n \"OpenAI\",\n \"Anthropic\"\n ],\n \"only\": [\n \"OpenAI\",\n \"Google\"\n ],\n \"ignore\": [\n \"DeepInfra\"\n ],\n \"sort\": \"price\",\n \"max_price\": {\n \"prompt\": 10,\n \"completion\": 20,\n \"image\": 5,\n \"audio\": 15,\n \"request\": 1\n }\n },\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Получить текущую погоду для указанного местоположения\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Название города\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"celsius\",\n \"fahrenheit\"\n ]\n }\n },\n \"required\": [\n \"location\"\n ]\n },\n \"strict\": false\n }\n }\n ],\n \"tool_choice\": \"auto\",\n \"reasoning\": {\n \"effort\": \"medium\",\n \"summary\": \"auto\",\n \"enabled\": true,\n \"max_tokens\": 2000,\n \"exclude\": false\n },\n \"plugins\": \"<array>\",\n \"web_search_options\": {\n \"search_context_size\": \"medium\"\n },\n \"user\": \"user-123\",\n \"stop\": [\n \"\\n\"\n ],\n \"seed\": 42,\n \"n\": 1,\n \"stream\": false,\n \"logprobs\": false,\n \"top_logprobs\": 5,\n \"logit_bias\": {\n \"50256\": -100\n },\n \"parallel_tool_calls\": true,\n \"image_config\": {\n \"quality\": \"high\",\n \"size\": 512\n },\n \"modalities\": [\n \"text\",\n \"audio\"\n ],\n \"audio\": {\n \"voice\": \"alloy\",\n \"format\": \"pcm16\"\n }\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://polza.ai/api/v1/chat/completions")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"openai/gpt-4o\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"Ты полезный ассистент\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Привет! Как дела?\"\n }\n ],\n \"prompt\": \"Напиши стихотворение про кота\",\n \"max_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"temperature\": 1,\n \"top_p\": 1,\n \"frequency_penalty\": 0,\n \"presence_penalty\": 0,\n \"response_format\": {},\n \"provider\": {\n \"allow_fallbacks\": true,\n \"order\": [\n \"OpenAI\",\n \"Anthropic\"\n ],\n \"only\": [\n \"OpenAI\",\n \"Google\"\n ],\n \"ignore\": [\n \"DeepInfra\"\n ],\n \"sort\": \"price\",\n \"max_price\": {\n \"prompt\": 10,\n \"completion\": 20,\n \"image\": 5,\n \"audio\": 15,\n \"request\": 1\n }\n },\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Получить текущую погоду для указанного местоположения\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Название города\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"celsius\",\n \"fahrenheit\"\n ]\n }\n },\n \"required\": [\n \"location\"\n ]\n },\n \"strict\": false\n }\n }\n ],\n \"tool_choice\": \"auto\",\n \"reasoning\": {\n \"effort\": \"medium\",\n \"summary\": \"auto\",\n \"enabled\": true,\n \"max_tokens\": 2000,\n \"exclude\": false\n },\n \"plugins\": \"<array>\",\n \"web_search_options\": {\n \"search_context_size\": \"medium\"\n },\n \"user\": \"user-123\",\n \"stop\": [\n \"\\n\"\n ],\n \"seed\": 42,\n \"n\": 1,\n \"stream\": false,\n \"logprobs\": false,\n \"top_logprobs\": 5,\n \"logit_bias\": {\n \"50256\": -100\n },\n \"parallel_tool_calls\": true,\n \"image_config\": {\n \"quality\": \"high\",\n \"size\": 512\n },\n \"modalities\": [\n \"text\",\n \"audio\"\n ],\n \"audio\": {\n \"voice\": \"alloy\",\n \"format\": \"pcm16\"\n }\n}"
response = http.request(request)
puts response.read_body{
"id": "gen_581761234567890123",
"object": "chat.completion",
"created": 1703001234,
"model": "openai/gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Привет! Я хорошо, спасибо что спросили. Чем могу помочь?",
"name": "Ассистент",
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Moscow\"}"
}
}
],
"refusal": null,
"reasoning": null,
"audio": {
"id": "<string>",
"data": "<string>",
"transcript": "<string>",
"expires_at": 123
},
"annotations": [
{}
]
},
"finish_reason": "stop",
"reasoning_details": "<array>",
"logprobs": {
"content": [
{
"token": "hello",
"logprob": -0.5,
"bytes": [
104,
101,
108,
108,
111
],
"top_logprobs": [
{
"token": "hello",
"logprob": -0.5,
"bytes": [
104,
101,
108,
108,
111
]
}
]
}
],
"refusal": [
{
"token": "hello",
"logprob": -0.5,
"bytes": [
104,
101,
108,
108,
111
],
"top_logprobs": [
{
"token": "hello",
"logprob": -0.5,
"bytes": [
104,
101,
108,
108,
111
]
}
]
}
]
}
}
],
"system_fingerprint": "fp_29330a9688",
"usage": {
"prompt_tokens": 10,
"completion_tokens": 50,
"total_tokens": 60,
"completion_tokens_details": {
"reasoning_tokens": 100,
"audio_tokens": 0,
"image_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0
},
"prompt_tokens_details": {
"cached_tokens": 0,
"audio_tokens": 0,
"video_tokens": 0
},
"server_tool_use": {
"web_search_requests": 1
},
"cost_rub": 0.04131306,
"cost": 0.04131306,
"plugins": {
"masker": {
"operations": [
{
"operation": "mask",
"latency_ms": 15,
"cost_rub": 0.001
},
{
"operation": "unmask",
"latency_ms": 8,
"cost_rub": 0
}
],
"total_cost_rub": 0.001
}
},
"plugin_post_process_error": true
}
}POST Chat Completions
Основной эндпоинт для генерации текста и диалогов
curl --request POST \
--url https://polza.ai/api/v1/chat/completions \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"model": "openai/gpt-4o",
"messages": [
{
"role": "system",
"content": "Ты полезный ассистент"
},
{
"role": "user",
"content": "Привет! Как дела?"
}
],
"prompt": "Напиши стихотворение про кота",
"max_tokens": 1000,
"max_completion_tokens": 1000,
"temperature": 1,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"response_format": {},
"provider": {
"allow_fallbacks": true,
"order": [
"OpenAI",
"Anthropic"
],
"only": [
"OpenAI",
"Google"
],
"ignore": [
"DeepInfra"
],
"sort": "price",
"max_price": {
"prompt": 10,
"completion": 20,
"image": 5,
"audio": 15,
"request": 1
}
},
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Получить текущую погоду для указанного местоположения",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Название города"
},
"unit": {
"type": "string",
"enum": [
"celsius",
"fahrenheit"
]
}
},
"required": [
"location"
]
},
"strict": false
}
}
],
"tool_choice": "auto",
"reasoning": {
"effort": "medium",
"summary": "auto",
"enabled": true,
"max_tokens": 2000,
"exclude": false
},
"plugins": "<array>",
"web_search_options": {
"search_context_size": "medium"
},
"user": "user-123",
"stop": [
"\n"
],
"seed": 42,
"n": 1,
"stream": false,
"logprobs": false,
"top_logprobs": 5,
"logit_bias": {
"50256": -100
},
"parallel_tool_calls": true,
"image_config": {
"quality": "high",
"size": 512
},
"modalities": [
"text",
"audio"
],
"audio": {
"voice": "alloy",
"format": "pcm16"
}
}
'import requests
url = "https://polza.ai/api/v1/chat/completions"
payload = {
"model": "openai/gpt-4o",
"messages": [
{
"role": "system",
"content": "Ты полезный ассистент"
},
{
"role": "user",
"content": "Привет! Как дела?"
}
],
"prompt": "Напиши стихотворение про кота",
"max_tokens": 1000,
"max_completion_tokens": 1000,
"temperature": 1,
"top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"response_format": {},
"provider": {
"allow_fallbacks": True,
"order": ["OpenAI", "Anthropic"],
"only": ["OpenAI", "Google"],
"ignore": ["DeepInfra"],
"sort": "price",
"max_price": {
"prompt": 10,
"completion": 20,
"image": 5,
"audio": 15,
"request": 1
}
},
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Получить текущую погоду для указанного местоположения",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "Название города"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location"]
},
"strict": False
}
}
],
"tool_choice": "auto",
"reasoning": {
"effort": "medium",
"summary": "auto",
"enabled": True,
"max_tokens": 2000,
"exclude": False
},
"plugins": "<array>",
"web_search_options": { "search_context_size": "medium" },
"user": "user-123",
"stop": ["
"],
"seed": 42,
"n": 1,
"stream": False,
"logprobs": False,
"top_logprobs": 5,
"logit_bias": { "50256": -100 },
"parallel_tool_calls": True,
"image_config": {
"quality": "high",
"size": 512
},
"modalities": ["text", "audio"],
"audio": {
"voice": "alloy",
"format": "pcm16"
}
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({
model: 'openai/gpt-4o',
messages: [
{role: 'system', content: 'Ты полезный ассистент'},
{role: 'user', content: 'Привет! Как дела?'}
],
prompt: 'Напиши стихотворение про кота',
max_tokens: 1000,
max_completion_tokens: 1000,
temperature: 1,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
response_format: {},
provider: {
allow_fallbacks: true,
order: ['OpenAI', 'Anthropic'],
only: ['OpenAI', 'Google'],
ignore: ['DeepInfra'],
sort: 'price',
max_price: {prompt: 10, completion: 20, image: 5, audio: 15, request: 1}
},
tools: [
{
type: 'function',
function: {
name: 'get_weather',
description: 'Получить текущую погоду для указанного местоположения',
parameters: {
type: 'object',
properties: {
location: {type: 'string', description: 'Название города'},
unit: {type: 'string', enum: ['celsius', 'fahrenheit']}
},
required: ['location']
},
strict: false
}
}
],
tool_choice: 'auto',
reasoning: {
effort: 'medium',
summary: 'auto',
enabled: true,
max_tokens: 2000,
exclude: false
},
plugins: '<array>',
web_search_options: {search_context_size: 'medium'},
user: 'user-123',
stop: ['\n'],
seed: 42,
n: 1,
stream: false,
logprobs: false,
top_logprobs: 5,
logit_bias: {'50256': -100},
parallel_tool_calls: true,
image_config: {quality: 'high', size: 512},
modalities: ['text', 'audio'],
audio: {voice: 'alloy', format: 'pcm16'}
})
};
fetch('https://polza.ai/api/v1/chat/completions', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://polza.ai/api/v1/chat/completions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'model' => 'openai/gpt-4o',
'messages' => [
[
'role' => 'system',
'content' => 'Ты полезный ассистент'
],
[
'role' => 'user',
'content' => 'Привет! Как дела?'
]
],
'prompt' => 'Напиши стихотворение про кота',
'max_tokens' => 1000,
'max_completion_tokens' => 1000,
'temperature' => 1,
'top_p' => 1,
'frequency_penalty' => 0,
'presence_penalty' => 0,
'response_format' => [
],
'provider' => [
'allow_fallbacks' => true,
'order' => [
'OpenAI',
'Anthropic'
],
'only' => [
'OpenAI',
'Google'
],
'ignore' => [
'DeepInfra'
],
'sort' => 'price',
'max_price' => [
'prompt' => 10,
'completion' => 20,
'image' => 5,
'audio' => 15,
'request' => 1
]
],
'tools' => [
[
'type' => 'function',
'function' => [
'name' => 'get_weather',
'description' => 'Получить текущую погоду для указанного местоположения',
'parameters' => [
'type' => 'object',
'properties' => [
'location' => [
'type' => 'string',
'description' => 'Название города'
],
'unit' => [
'type' => 'string',
'enum' => [
'celsius',
'fahrenheit'
]
]
],
'required' => [
'location'
]
],
'strict' => false
]
]
],
'tool_choice' => 'auto',
'reasoning' => [
'effort' => 'medium',
'summary' => 'auto',
'enabled' => true,
'max_tokens' => 2000,
'exclude' => false
],
'plugins' => '<array>',
'web_search_options' => [
'search_context_size' => 'medium'
],
'user' => 'user-123',
'stop' => [
'
'
],
'seed' => 42,
'n' => 1,
'stream' => false,
'logprobs' => false,
'top_logprobs' => 5,
'logit_bias' => [
'50256' => -100
],
'parallel_tool_calls' => true,
'image_config' => [
'quality' => 'high',
'size' => 512
],
'modalities' => [
'text',
'audio'
],
'audio' => [
'voice' => 'alloy',
'format' => 'pcm16'
]
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://polza.ai/api/v1/chat/completions"
payload := strings.NewReader("{\n \"model\": \"openai/gpt-4o\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"Ты полезный ассистент\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Привет! Как дела?\"\n }\n ],\n \"prompt\": \"Напиши стихотворение про кота\",\n \"max_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"temperature\": 1,\n \"top_p\": 1,\n \"frequency_penalty\": 0,\n \"presence_penalty\": 0,\n \"response_format\": {},\n \"provider\": {\n \"allow_fallbacks\": true,\n \"order\": [\n \"OpenAI\",\n \"Anthropic\"\n ],\n \"only\": [\n \"OpenAI\",\n \"Google\"\n ],\n \"ignore\": [\n \"DeepInfra\"\n ],\n \"sort\": \"price\",\n \"max_price\": {\n \"prompt\": 10,\n \"completion\": 20,\n \"image\": 5,\n \"audio\": 15,\n \"request\": 1\n }\n },\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Получить текущую погоду для указанного местоположения\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Название города\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"celsius\",\n \"fahrenheit\"\n ]\n }\n },\n \"required\": [\n \"location\"\n ]\n },\n \"strict\": false\n }\n }\n ],\n \"tool_choice\": \"auto\",\n \"reasoning\": {\n \"effort\": \"medium\",\n \"summary\": \"auto\",\n \"enabled\": true,\n \"max_tokens\": 2000,\n \"exclude\": false\n },\n \"plugins\": \"<array>\",\n \"web_search_options\": {\n \"search_context_size\": \"medium\"\n },\n \"user\": \"user-123\",\n \"stop\": [\n \"\\n\"\n ],\n \"seed\": 42,\n \"n\": 1,\n \"stream\": false,\n \"logprobs\": false,\n \"top_logprobs\": 5,\n \"logit_bias\": {\n \"50256\": -100\n },\n \"parallel_tool_calls\": true,\n \"image_config\": {\n \"quality\": \"high\",\n \"size\": 512\n },\n \"modalities\": [\n \"text\",\n \"audio\"\n ],\n \"audio\": {\n \"voice\": \"alloy\",\n \"format\": \"pcm16\"\n }\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://polza.ai/api/v1/chat/completions")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"model\": \"openai/gpt-4o\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"Ты полезный ассистент\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Привет! Как дела?\"\n }\n ],\n \"prompt\": \"Напиши стихотворение про кота\",\n \"max_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"temperature\": 1,\n \"top_p\": 1,\n \"frequency_penalty\": 0,\n \"presence_penalty\": 0,\n \"response_format\": {},\n \"provider\": {\n \"allow_fallbacks\": true,\n \"order\": [\n \"OpenAI\",\n \"Anthropic\"\n ],\n \"only\": [\n \"OpenAI\",\n \"Google\"\n ],\n \"ignore\": [\n \"DeepInfra\"\n ],\n \"sort\": \"price\",\n \"max_price\": {\n \"prompt\": 10,\n \"completion\": 20,\n \"image\": 5,\n \"audio\": 15,\n \"request\": 1\n }\n },\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Получить текущую погоду для указанного местоположения\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Название города\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"celsius\",\n \"fahrenheit\"\n ]\n }\n },\n \"required\": [\n \"location\"\n ]\n },\n \"strict\": false\n }\n }\n ],\n \"tool_choice\": \"auto\",\n \"reasoning\": {\n \"effort\": \"medium\",\n \"summary\": \"auto\",\n \"enabled\": true,\n \"max_tokens\": 2000,\n \"exclude\": false\n },\n \"plugins\": \"<array>\",\n \"web_search_options\": {\n \"search_context_size\": \"medium\"\n },\n \"user\": \"user-123\",\n \"stop\": [\n \"\\n\"\n ],\n \"seed\": 42,\n \"n\": 1,\n \"stream\": false,\n \"logprobs\": false,\n \"top_logprobs\": 5,\n \"logit_bias\": {\n \"50256\": -100\n },\n \"parallel_tool_calls\": true,\n \"image_config\": {\n \"quality\": \"high\",\n \"size\": 512\n },\n \"modalities\": [\n \"text\",\n \"audio\"\n ],\n \"audio\": {\n \"voice\": \"alloy\",\n \"format\": \"pcm16\"\n }\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://polza.ai/api/v1/chat/completions")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"model\": \"openai/gpt-4o\",\n \"messages\": [\n {\n \"role\": \"system\",\n \"content\": \"Ты полезный ассистент\"\n },\n {\n \"role\": \"user\",\n \"content\": \"Привет! Как дела?\"\n }\n ],\n \"prompt\": \"Напиши стихотворение про кота\",\n \"max_tokens\": 1000,\n \"max_completion_tokens\": 1000,\n \"temperature\": 1,\n \"top_p\": 1,\n \"frequency_penalty\": 0,\n \"presence_penalty\": 0,\n \"response_format\": {},\n \"provider\": {\n \"allow_fallbacks\": true,\n \"order\": [\n \"OpenAI\",\n \"Anthropic\"\n ],\n \"only\": [\n \"OpenAI\",\n \"Google\"\n ],\n \"ignore\": [\n \"DeepInfra\"\n ],\n \"sort\": \"price\",\n \"max_price\": {\n \"prompt\": 10,\n \"completion\": 20,\n \"image\": 5,\n \"audio\": 15,\n \"request\": 1\n }\n },\n \"tools\": [\n {\n \"type\": \"function\",\n \"function\": {\n \"name\": \"get_weather\",\n \"description\": \"Получить текущую погоду для указанного местоположения\",\n \"parameters\": {\n \"type\": \"object\",\n \"properties\": {\n \"location\": {\n \"type\": \"string\",\n \"description\": \"Название города\"\n },\n \"unit\": {\n \"type\": \"string\",\n \"enum\": [\n \"celsius\",\n \"fahrenheit\"\n ]\n }\n },\n \"required\": [\n \"location\"\n ]\n },\n \"strict\": false\n }\n }\n ],\n \"tool_choice\": \"auto\",\n \"reasoning\": {\n \"effort\": \"medium\",\n \"summary\": \"auto\",\n \"enabled\": true,\n \"max_tokens\": 2000,\n \"exclude\": false\n },\n \"plugins\": \"<array>\",\n \"web_search_options\": {\n \"search_context_size\": \"medium\"\n },\n \"user\": \"user-123\",\n \"stop\": [\n \"\\n\"\n ],\n \"seed\": 42,\n \"n\": 1,\n \"stream\": false,\n \"logprobs\": false,\n \"top_logprobs\": 5,\n \"logit_bias\": {\n \"50256\": -100\n },\n \"parallel_tool_calls\": true,\n \"image_config\": {\n \"quality\": \"high\",\n \"size\": 512\n },\n \"modalities\": [\n \"text\",\n \"audio\"\n ],\n \"audio\": {\n \"voice\": \"alloy\",\n \"format\": \"pcm16\"\n }\n}"
response = http.request(request)
puts response.read_body{
"id": "gen_581761234567890123",
"object": "chat.completion",
"created": 1703001234,
"model": "openai/gpt-4o",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Привет! Я хорошо, спасибо что спросили. Чем могу помочь?",
"name": "Ассистент",
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "get_weather",
"arguments": "{\"location\": \"Moscow\"}"
}
}
],
"refusal": null,
"reasoning": null,
"audio": {
"id": "<string>",
"data": "<string>",
"transcript": "<string>",
"expires_at": 123
},
"annotations": [
{}
]
},
"finish_reason": "stop",
"reasoning_details": "<array>",
"logprobs": {
"content": [
{
"token": "hello",
"logprob": -0.5,
"bytes": [
104,
101,
108,
108,
111
],
"top_logprobs": [
{
"token": "hello",
"logprob": -0.5,
"bytes": [
104,
101,
108,
108,
111
]
}
]
}
],
"refusal": [
{
"token": "hello",
"logprob": -0.5,
"bytes": [
104,
101,
108,
108,
111
],
"top_logprobs": [
{
"token": "hello",
"logprob": -0.5,
"bytes": [
104,
101,
108,
108,
111
]
}
]
}
]
}
}
],
"system_fingerprint": "fp_29330a9688",
"usage": {
"prompt_tokens": 10,
"completion_tokens": 50,
"total_tokens": 60,
"completion_tokens_details": {
"reasoning_tokens": 100,
"audio_tokens": 0,
"image_tokens": 0,
"accepted_prediction_tokens": 0,
"rejected_prediction_tokens": 0
},
"prompt_tokens_details": {
"cached_tokens": 0,
"audio_tokens": 0,
"video_tokens": 0
},
"server_tool_use": {
"web_search_requests": 1
},
"cost_rub": 0.04131306,
"cost": 0.04131306,
"plugins": {
"masker": {
"operations": [
{
"operation": "mask",
"latency_ms": 15,
"cost_rub": 0.001
},
{
"operation": "unmask",
"latency_ms": 8,
"cost_rub": 0
}
],
"total_cost_rub": 0.001
}
},
"plugin_post_process_error": true
}
}Возможности
- Агрегация провайдеров — автоматический выбор оптимального провайдера
- Биллинг в рублях — точный учет стоимости
- Reasoning Tokens — поддержка моделей с рассуждениями
- Streaming — потоковая передача через SSE
- Tool Calling — вызов внешних функций
- Мультимодальность — обработка текста, изображений, аудио, видео и файлов
Параметры запроса
Обязательные
| Параметр | Тип | Описание |
|---|---|---|
model | string | ID модели из списка моделей |
Контент
| Параметр | Тип | Описание |
|---|---|---|
messages | array | Массив сообщений диалога (рекомендуется) |
prompt | string | Простой текстовый промпт (альтернатива messages) |
Параметры генерации
| Параметр | Тип | По умолчанию | Описание |
|---|---|---|---|
max_tokens | integer | Без лимита | Максимум токенов в ответе |
max_completion_tokens | integer | Без лимита | Альтернатива max_tokens |
temperature | float (0-2) | 1.0 | Температура (0=детерминированный, 2=креативный) |
top_p | float (0-1) | 1.0 | Nucleus sampling |
top_k | integer | — | Top-K sampling |
frequency_penalty | float (-2..2) | 0 | Штраф за повторение слов |
presence_penalty | float (-2..2) | 0 | Штраф за повторение токенов |
stop | string/array | — | Стоп-последовательности |
seed | integer | — | Seed для воспроизводимости |
Специальные возможности
| Параметр | Тип | Описание |
|---|---|---|
stream | boolean | Включить streaming (SSE) |
reasoning | object | Настройки reasoning tokens |
tools | array | Доступные функции для вызова |
tool_choice | string/object | Выбор инструмента: “none”, “auto”, “required” |
response_format | object | Формат ответа: text, json_object, json_schema, grammar |
web_search_options | object | Встроенный веб-поиск |
provider | object | Конфигурация роутинга по провайдерам |
plugins | array | Подключение плагинов |
modalities | array | Выходные модальности: “text”, “image”, “audio” |
audio | object | Конфигурация аудио-вывода (voice, format) |
user | string | Идентификатор конечного пользователя |
Структура сообщений
Базовый формат
{
"role": "user|assistant|system|developer|tool",
"content": "Текст сообщения"
}
Мультимодальные сообщения
{
"role": "user",
"content": [
{"type": "text", "text": "Что на этом изображении?"},
{"type": "image_url", "image_url": {"url": "https://example.com/image.jpg"}}
]
}
Другие типы контента
// Аудио вход
{"type": "input_audio", "input_audio": {"data": "base64...", "format": "mp3"}}
// Видео вход
{"type": "video_url", "video_url": {"url": "https://example.com/video.mp4"}}
// Файл
{"type": "file", "file": {"filename": "doc.pdf", "file_data": "data:application/pdf;base64,..."}}
Системные сообщения с кешированием
{
"role": "system",
"content": [
{
"type": "text",
"text": "Длинная системная инструкция...",
"cache_control": {"type": "ephemeral"}
}
]
}
Примеры
curl -X POST "https://polza.ai/api/v1/chat/completions" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "openai/gpt-4o",
"messages": [{"role": "user", "content": "Привет!"}]
}'
from openai import OpenAI
client = OpenAI(
base_url="https://polza.ai/api/v1",
api_key="YOUR_API_KEY"
)
response = client.chat.completions.create(
model="anthropic/claude-sonnet-4-5-20250929",
messages=[{"role": "user", "content": "Объясни квантовую механику"}]
)
print(response.choices[0].message.content)
print(f"Стоимость: {response.usage.cost_rub} руб.")
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://polza.ai/api/v1',
apiKey: 'YOUR_API_KEY'
});
const response = await client.chat.completions.create({
model: 'openai/gpt-4o',
messages: [{role: 'user', content: 'Напиши историю'}],
stream: true
});
for await (const chunk of response) {
process.stdout.write(chunk.choices[0]?.delta?.content || '');
}
Ответ
Успешный ответ (200)
{
"id": "gen_581761234567890123",
"object": "chat.completion",
"created": 1677652288,
"model": "openai/gpt-4o",
"provider": "OpenAI",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Текст ответа"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 25,
"completion_tokens": 150,
"total_tokens": 175,
"cost_rub": 0.04131306,
"cost": 0.04131306,
"prompt_tokens_details": {
"cached_tokens": 0
},
"completion_tokens_details": {
"reasoning_tokens": 0
}
}
}
Streaming (SSE)
Приstream: true ответ приходит в формате Server-Sent Events:
data: {"id":"gen_123","object":"chat.completion.chunk","created":1703001234,"model":"openai/gpt-4o","choices":[{"index":0,"delta":{"role":"assistant","content":"Привет"}}]}
data: {"id":"gen_123","object":"chat.completion.chunk","created":1703001234,"model":"openai/gpt-4o","choices":[{"index":0,"delta":{"content":" мир"}}]}
data: {"id":"gen_123","object":"chat.completion.chunk","created":1703001234,"model":"openai/gpt-4o","choices":[],"usage":{"prompt_tokens":10,"completion_tokens":20,"total_tokens":30,"cost_rub":0.015,"cost":0.015}}
data: [DONE]
Tool Calling
Определение функций
{
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Получить текущую погоду",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}],
"tool_choice": "auto"
}
Ответ модели с вызовом функции
{
"tool_calls": [{
"id": "call_123",
"function": {"name": "get_weather", "arguments": "{\"city\": \"Москва\"}"}
}]
}
Response Format
JSON Schema (структурированный вывод)
{
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "my_schema",
"schema": {
"type": "object",
"properties": {
"answer": {"type": "string"},
"confidence": {"type": "number"}
}
},
"strict": true
}
}
}
text, json_object, json_schema, grammar (GBNF).
Reasoning Tokens
Для моделей с рассуждениями (o1, o3, DeepSeek-R1 и другие):{
"model": "openai/o1-preview",
"messages": [{"role": "user", "content": "Реши: 2x + 5 = 13"}],
"reasoning": {
"effort": "high",
"max_tokens": 1000
}
}
Параметры reasoning
| Параметр | Тип | Описание |
|---|---|---|
effort | string | Уровень усилий: xhigh, high, medium, low, minimal, none |
max_tokens | integer | Максимум токенов на рассуждения |
summary | string | Детализация: auto, concise, detailed |
enabled | boolean | Включить/выключить рассуждения |
exclude | boolean | Скрыть рассуждения из ответа |
Авторизации
API ключ передаётся в заголовке: Authorization: Bearer <POLZA_AI_API_KEY>
Тело
Идентификатор модели для использования
"openai/gpt-4o"
Массив сообщений для отправки модели (обязателен если не указан prompt)
Show child attributes
Show child attributes
[
{
"role": "system",
"content": "Ты полезный ассистент"
},
{
"role": "user",
"content": "Привет! Как дела?"
}
]Текстовый промпт (альтернатива messages). Если указан, будет преобразован в messages с role=user
"Напиши стихотворение про кота"
Максимальное количество токенов для генерации
x >= 11000
Максимальное количество токенов для completion (альтернатива max_tokens)
x >= 11000
Температура сэмплинга (0-2). Более высокие значения делают вывод более случайным
0 <= x <= 21
Nucleus sampling: вероятностная масса для рассмотрения (0-1)
0 <= x <= 11
Штраф за частоту использования токенов (-2 до 2)
-2 <= x <= 20
Штраф за присутствие токенов (-2 до 2)
-2 <= x <= 20
Формат ответа модели
Настройки провайдера для роутинга и фильтрации
Show child attributes
Show child attributes
Определения инструментов (tools) для function calling
Show child attributes
Show child attributes
Выбор инструмента: none, auto, required или named function
"auto"
Настройки reasoning для reasoning моделей
Show child attributes
Show child attributes
Плагины для расширения функциональности
Настройки встроенного веб-поиска (для моделей с нативной поддержкой)
Show child attributes
Show child attributes
Уникальный идентификатор конечного пользователя для отслеживания и предотвращения злоупотреблений
"user-123"
Последовательности, при которых модель прекращает генерацию
["\n"]Seed для детерминированной генерации (best-effort)
42
Количество вариантов ответа (1-10)
1 <= x <= 101
Включить потоковую передачу ответа
false
Возвращать log probabilities для output токенов
false
Количество наиболее вероятных токенов для возврата (0-20). Требует logprobs: true
0 <= x <= 205
Смещение вероятностей токенов по их ID (-100 до 100)
{ "50256": -100 }Разрешить параллельный вызов нескольких tools
true
Настройки обработки изображений
{ "quality": "high", "size": 512 }Типы вывода модели
text, image, audio ["text", "audio"]Настройки аудио выхода для моделей с поддержкой аудио (gpt-audio и др.)
Show child attributes
Show child attributes
Ответ
Уникальный идентификатор генерации
"gen_581761234567890123"
Тип объекта
"chat.completion"
Временная метка создания (Unix timestamp)
1703001234
ID модели, которая сгенерировала ответ
"openai/gpt-4o"
Массив вариантов ответа
Show child attributes
Show child attributes
System fingerprint от провайдера
"fp_29330a9688"
Информация об использовании токенов
Show child attributes
Show child attributes
Была ли эта страница полезной?