Developer Dashboard

Chat Completions API

The Chat Completions API is the core of the AvalAI platform, allowing you to generate conversational responses from various AI models, including Anthropic Claude Opus 5, the latest OpenAI GPT-5.6 family (GPT-5.6 Sol, Terra, and Luna), GPT-5.5 series, XAI Grok 4.5 and Grok 4.3, Z.AI GLM-5.3-Flash and GLM-5.3, Moonshot Kimi K3, Google Gemini 3.7 Flash, Gemini 3.6 Flash, Gemini 3.5 Flash-Lite, Gemma 4, Alibaba Qwen3.8-Max and Qwen3.7-Plus, DeepSeek-V4-Flash-0731 through the stable deepseek-v4-flash ID, Cloudflare Nemotron-3-120B, Fireworks.ai Muse Glimmer 30B, Nemotron 3.5 Lightning and Nemotron-3-Ultra, and MiniMax M3 models.

GLM-5.3-Flash: Use glm-5.3-flash for efficient multimodal coding, visual understanding, tool use, and agent workflows with 320B total and 18B active parameters. It supports 991,000 input tokens and up to 128,000 output tokens. Support is full on v1/chat/completions and v1/messages and partial on v1/responses; see the Z.AI models documentation.

GLM-5.3: Use glm-5.3 for Z.AI's flagship coding, long-horizon agent, and authorized security-analysis workloads. Thinking is mandatory: send thinking.type: "enabled" and choose reasoning_effort: "low", "high", or "max"; requests that disable thinking fail. It supports v1/chat/completions and v1/messages, with partial v1/responses support; see the Z.AI models documentation.

New Fireworks.ai models: Use muse-glimmer-30b for Meta's multimodal, multilingual agentic model with controllable reasoning, or nemotron-3.5-lightning for NVIDIA's efficient 30B-total/3B-active reasoning and coding model. Both have full v1/chat/completions and v1/messages support and partial v1/responses support; see the Fireworks.ai provider documentation.

Claude Opus 5: Use claude-opus-5 for difficult software engineering, root-cause analysis, knowledge work, computer use, scientific analysis, and long-running agents. It supports a 1M-token input window, up to 128K output tokens, adaptive thinking, structured output, vision, PDF input, prompt caching, and tools. Support is full on v1/chat/completions and v1/messages and partial on v1/responses; see the Anthropic models documentation.

Gemini 3.7 Flash: Use gemini-3.7-flash for agentic coding, web development, complex document analysis, tool use, and workflow automation. It supports v1/chat/completions, native Gemini v1beta/, and v1/messages, with partial v1/responses support. Promotional pricing through December 31, 2026 is $0.75 input, $0.075 cached input, and $3.75 output per 1 million tokens; see the Google models documentation.

Kimi K3: Use kimi-k3 for Moonshot AI's 1M-context flagship with native vision and always-on reasoning. It supports v1/chat/completions and v1/messages fully and v1/responses partially. The kimi-latest alias now resolves to kimi-k3 and uses the same pricing. K3 currently supports reasoning_effort: "max"; omit fixed sampling fields such as temperature and top_p.

Qwen3.8 models: Use qwen3.8-max for Alibaba's managed multimodal flagship with optional thinking, a 1M-token context window, and up to 128K output. Use qwen3.8-2.4t-a95b for the underlying open-weight 2.4T-total/95B-active model: it is text-only, thinking is mandatory, and reasoning_effort accepts low, medium, or xhigh. Both routes have full v1/chat/completions and v1/messages support and partial v1/responses support; see the Alibaba models documentation.

DeepSeek-V4-Flash upgrade: Continue using deepseek-v4-flash; AvalAI now routes the stable ID to DeepSeek-V4-Flash-0731 automatically with no code or pricing change. The official release supports reasoning_effort values low, high, and max; see the DeepSeek models documentation.

Endpoint

POST https://api.avalai.ir/v1/chat/completions
Responses API version

Use this version when the selected model supports /v1/responses. messages moves to input, and the final text is read from response.output_text.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.6-sol",
    instructions="You are a helpful assistant.",
    input="Write a one-sentence summary of AvalAI.",
)

print(response.output_text)
  • messagesinput
  • system message → instructions or a developer item
  • choices[0].message.contentresponse.output_text
  • for tools and multimodal output, inspect response.output by item type.

Request Body

ParameterTypeRequiredDescription
modelstringYesID of the model to use. See Models for available options.
messagesarrayYesArray of message objects representing the conversation history.
temperaturenumberNoSampling temperature between 0 and 2. Higher values like 0.8 make output more random, while lower values like 0.2 make it more focused. Default is 1.
top_pnumberNoAlternative to temperature, nucleus sampling. Default is 1.
nintegerNoNumber of chat completion choices to generate. Default is 1.
streambooleanNoIf set to true, partial message deltas will be sent. Default is false.
stream_optionsobjectNoOptions for streaming responses. Only set this when stream: true; support varies by route and SDK.
modalitiesarrayNoOutput types to generate. Most chat models return ["text"]; audio output requires model/route support and the audio parameter.
audioobjectNoAudio-output configuration when modalities includes "audio". For most AvalAI workflows, prefer dedicated Audio or Realtime routes.
predictionobjectNoPredicted output content for latency-sensitive rewrites where most completion tokens are already known. Provider/model support varies; see Predicted Outputs.
stopstring or arrayNoUp to 4 sequences where the API will stop generating further tokens.
max_completion_tokensintegerNoUpper bound for generated tokens, including visible output and hidden reasoning tokens. If reasoning consumes the budget, the model can stop with finish_reason: "length" before producing visible text; leave headroom or lower reasoning effort. See Reasoning token budgets.
max_tokensintegerNoLegacy maximum output-token setting. Deprecated in OpenAI's current API shape in favor of max_completion_tokens and not compatible with some reasoning models. Where it applies to a reasoning model, the same shared-budget warning applies.
presence_penaltynumberNoNumber between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far. Default is 0.
frequency_penaltynumberNoNumber between -2.0 and 2.0. Positive values penalize new tokens based on their frequency in the text so far. Default is 0.
logit_biasobjectNoModify the likelihood of specified tokens appearing in the completion.
logprobsbooleanNoWhether to return log probabilities for output tokens when supported.
top_logprobsintegerNoNumber of most likely tokens to return at each output-token position, from 0 to 20. Requires logprobs: true and model/route support.
metadataobjectNoUp to 16 key-value pairs for filtering stored completions and dashboard/API queries. Keys can be up to 64 characters and values up to 512 characters.
safety_identifierstringNoPrivacy-preserving identifier for abuse monitoring. Use a stable hash or opaque internal ID, maximum 64 characters, and avoid raw PII. See Safety best practices.
prompt_cache_keystringNoCache-bucketing key for similar repeated prefixes. Keep it opaque and stable per assistant, tenant, policy, or schema; prefer safety_identifier for abuse monitoring. See Prompt caching.
prompt_cache_retentionstringNoLegacy maximum-retention policy for pre-GPT-5.6 models. It is deprecated for GPT-5.6 and later, where OpenAI uses prompt_cache_options.ttl; AvalAI pass-through for the newer controls is route-dependent. Omit unsupported cache controls.
moderationobjectNoInline moderation configuration, for example { "model": "omni-moderation-latest" }, when enabled for the selected route/model. If unavailable, call /v1/moderations separately.
userstringNoLegacy end-user field. Prefer safety_identifier for abuse monitoring and prompt_cache_key for cache bucketing.
response_formatobjectNoOutput format constraint. Use {"type":"json_schema","json_schema":...} for Structured Outputs when the model supports schema adherence, or {"type":"json_object"} for JSON mode fallback. Prefer /v1/responses text.format for new structured-output workflows.
reasoning_effortstringNoReasoning-effort control for supported reasoning models. Supported values and defaults are model-specific; verify with the selected AvalAI route. DeepSeek-V4-Flash-0731 supports low, high, and max; Claude Opus 5 uses provider-specific adaptive thinking and output_config.effort through extra_body.
verbositystringNoControls final-answer verbosity for supported models (low, medium, or high) without changing reasoning depth.
seedintegerNoIf specified, system will make a best effort to sample deterministically.
storebooleanNoWhether to store the chat completion for later retrieval, distillation, or evals when the selected route/account supports stored chat completions.
toolsarrayNoA list of tools the model may call.
tool_choicestring or objectNoControls which (if any) tool is called by the model.
parallel_tool_callsbooleanNoWhether to allow parallel function/tool calls. Set false for state-mutating tools or flows that require sequential execution.
web_search_optionsobjectNoChat-compatible web-search options when the selected OpenAI-style model supports built-in web search. For provider-independent retrieval, prefer /v1/search.
service_tierstringNoThe service tier to use for this request. AvalAI generally supports "default" (default) and "flex". Flex offers 50% reduced pricing for select OpenAI models but has higher latency and may time out (up to 900s). OpenAI examples may mention "priority"; use "default" on AvalAI unless priority processing is explicitly enabled for your account. See Pricing.

Tip

Parameter support differs by model and provider. New reasoning models may ignore or reject older sampling/stop/token fields, and hosted tools are route/account dependent in AvalAI. If you are starting a new OpenAI-style workflow with tools, state, or reasoning, compare this page with Responses before choosing Chat Completions.

For response_format, prefer json_schema over json_object whenever the selected model and route support it. JSON mode only guarantees syntactically valid JSON; it does not guarantee required keys, enum values, or application-specific types, so validate the parsed result in your app. See Structured Outputs for schema design, refusal handling, and migration to Responses text.format.

Message Object

Each message in the messages array should have the following structure:

ParameterTypeRequiredDescription
rolestringYesThe role of the message author. Common roles are developer, system, user, assistant, and tool. Use developer or system for durable instructions depending on model support.
contentstring or arrayYesThe content of the message. Can be a string or an array of content parts when using multimodal inputs.
namestringNoThe name of the author of this message. Required for tool roles.
tool_call_idstringNoRequired for tool role messages. The ID of the tool call that this message is responding to.

Examples

Basic Chat Completion

bash
curl https://api.avalai.ir/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
  "model": "gpt-5.6-sol",
  "messages": [
  {
    "role": "system",
    "content": "You are a helpful assistant."
  },
  {
    "role": "user",
    "content": "Hello!"
  }
  ]
}'
python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",  # AvalAI API endpoint
)

response = client.chat.completions.create(
    model="gpt-5.6-sol",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"},
    ],
)

print(response.choices[0].message.content)
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
  model: "gpt-5.5",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Hello!" },
  ],
});

console.log(response.choices[0].message.content);
go
package main

import (
	"context"
	"fmt"
	openai "github.com/openai/openai-go"
)

func main() {
	client := openai.NewClient("AVALAI_API_KEY")
	client.BaseURL = "https://api.avalai.ir/v1"

	resp, err := client.CreateChatCompletion(
		context.Background(),
		openai.ChatCompletionRequest{
			Model: "gpt-5.6-sol",
			Messages: []openai.ChatCompletionMessage{
				{
					Role:    openai.ChatMessageRoleSystem,
					Content: "You are a helpful assistant.",
				},
				{
					Role:    openai.ChatMessageRoleUser,
					Content: "Hello!",
				},
			},
		},
	)

	if err != nil {
		fmt.Printf("ChatCompletion error: %v\n", err)
		return
	}

	fmt.Println(resp.Choices[0].Message.Content) // Corrected access to response content
}
php
<?php
// PHP Example for Chat Completion via AvalAI

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your key directly
$apiUrl = 'https://api.avalai.ir/v1/chat/completions';

$data = [
'model' => 'gpt-5.6-sol',
'messages' => [
['role' => 'system', 'content' => 'You are a helpful assistant.'],
['role' => 'user', 'content' => 'Hello!']
]
// Add other parameters like temperature, max_tokens etc. if needed
// 'temperature' => 0.7,
// 'max_tokens' => 150
];

$jsonData = json_encode($data);

$ch = curl_init($apiUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
'Content-Length: ' . strlen($jsonData)
]);

$response = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$err = curl_error($ch);

curl_close($ch);

if ($err) {
  echo "cURL Error #:" . $err;
} elseif ($httpcode >= 400) {
  echo "HTTP Error: " . $httpcode . "\n";
  echo $response;
} else {
  $responseData = json_decode($response, true);
  if (isset($responseData['choices'][0]['message']['content'])) {
    echo "Assistant: " . $responseData['choices'][0]['message']['content'] . "\n";
  } else {
    echo "Response received:\n";
    print_r($responseData);
  }
}
?>
Responses API version

Use this version when the selected model supports /v1/responses. messages moves to input, and the final text is read from response.output_text.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.6-sol",
    instructions="You are a helpful assistant.",
    input="Hello!",
)

print(response.output_text)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.responses.create({
  model: "gpt-5.5",
  instructions: "You are a helpful assistant.",
  input: "Hello!",
});

console.log(response.output_text);
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '
  {
    "model": "gpt-5.6-sol",
    "input": "Hello!",
    "instructions": "You are a helpful assistant."
  }'
  • messagesinput
  • system message → instructions or a developer item
  • choices[0].message.contentresponse.output_text
  • for tools and multimodal output, inspect response.output by item type.

Response Format

json
{
  "id": "chatcmpl-123abc",
  "object": "chat.completion",
  "created": 1677858242,
  "model": "gpt-5.6-sol",
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Hello! How can I assist you today?"
      },
      "finish_reason": "stop",
      "index": 0
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 8,
    "total_tokens": 18
  },
  "service_tier": "default"
}

Response Parameters

ParameterTypeDescription
idstringA unique identifier for the chat completion.
objectstringThe object type, which is always "chat.completion".
createdintegerThe Unix timestamp (in seconds) of when the chat completion was created.
modelstringThe model used for the chat completion.
choicesarrayAn array of chat completion choices.
usageobjectAn object containing token usage information.
moderationobjectInline input/output moderation results when requested and supported.
service_tierstringThe service tier used for this request. Public AvalAI values are generally "default" or "flex"; "priority" is account-specific unless explicitly enabled.

Choice Object

ParameterTypeDescription
messageobjectA message object containing the response content.
finish_reasonstringThe reason why the model stopped generating tokens. Can be "stop", "length", "tool_calls", "content_filter", or "function_call".
indexintegerThe index of the choice in the array.

Usage Object

ParameterTypeDescription
prompt_tokensintegerThe number of tokens used in the prompt.
completion_tokensintegerThe number of tokens used in the completion.
total_tokensintegerThe total number of tokens used (prompt + completion).

Streaming

To receive incremental model responses, set stream: true in your request:

javascript
const stream = await client.chat.completions.create({
  model: "gpt-5.5",
  messages: [{ role: "user", content: "Write a long story about a dog." }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || "");
}
Responses API version

Use this version when the selected model supports /v1/responses. messages moves to input, and the final text is read from response.output_text.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.6-sol",
    instructions="You are a helpful assistant.",
    input="Write a long story about a dog.",
)

print(response.output_text)
  • messagesinput
  • system message → instructions or a developer item
  • choices[0].message.contentresponse.output_text
  • for tools and multimodal output, inspect response.output by item type.

Function Calling / Tool Use

You can specify tools that the model can call:

javascript
const response = await client.chat.completions.create({
  model: "gpt-5.5",
  messages: [{ role: "user", content: "What's the weather in San Francisco?" }],
  tools: [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get the current weather in a given location",
        strict: true,
        parameters: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "The city and state, e.g. San Francisco, CA",
            },
            unit: {
              type: "string",
              enum: ["celsius", "fahrenheit"],
              description: "The temperature unit",
            },
          },
          required: ["location", "unit"],
          additionalProperties: false,
        },
      },
    },
  ],
});
Responses API version

Use this version when the selected model supports /v1/responses. messages moves to input, and the final text is read from response.output_text.

python
import os
import json
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)


def get_current_weather(location, unit):
    return {
        "location": location,
        "temperature": "18",
        "unit": unit or "celsius",
        "condition": "partly cloudy",
    }


tools = [
    {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location.",
        "strict": True,
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string"},
                "unit": {
                    "type": ["string", "null"],
                    "enum": ["celsius", "fahrenheit", None],
                },
            },
            "required": ["location", "unit"],
            "additionalProperties": False,
        },
    }
]

input_items = [
    {
        "role": "user",
        "content": "What's the weather in San Francisco in celsius?",
    }
]

response = client.responses.create(
    model="gpt-5.6-sol",
    input=input_items,
    tools=tools,
)

input_items += response.output

for item in response.output:
    if item.type == "function_call":
        args = json.loads(item.arguments)
        result = get_current_weather(args["location"], args.get("unit"))
        input_items.append(
            {
                "type": "function_call_output",
                "call_id": item.call_id,
                "output": json.dumps(result),
            }
        )

final_response = client.responses.create(
    model="gpt-5.6-sol",
    input=input_items,
    tools=tools,
)

print(final_response.output_text)
  • messagesinput
  • system message → instructions or a developer item
  • choices[0].message.contentresponse.output_text
  • tool_callsresponse.output items where type == "function_call"; return results as function_call_output with the same call_id.
  • preserve prior response.output items when you manage the tool loop manually, especially for reasoning-capable models.

Audio Input and Output

OpenAI's audio models (gpt-audio and gpt-audio-mini) support both audio and text inputs/outputs through the Chat Completions API. These models enable voice-based conversational applications with native audio processing capabilities.

Audio Parameters

When using audio models, you can specify additional parameters:

ParameterTypeRequiredDescription
modalitiesarrayNoSpecifies output modalities. Use ["text", "audio"] for audio output. For image generation models such as gemini-3-pro-image, gemini-3.1-flash-image, gemini-3.1-flash-lite-image, and gemini-2.5-flash-image, use ["image", "text"]. Default is ["text"].
audioobjectNoAudio output configuration. Required when requesting audio output.

Audio Configuration Object

ParameterTypeRequiredDescription
formatstringNoAudio output format. Options: mp3, wav, pcm16, opus, aac, flac. Default is mp3.
voicestringNoVoice to use for audio output. Options: alloy, echo, fable, onyx, nova, shimmer. Default is alloy.

Basic Audio Generation

bash
curl https://api.avalai.ir/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
    "model": "gpt-audio",
    "messages": [
      {
        "role": "user",
        "content": "Explain quantum computing in simple terms."
      }
    ],
    "modalities": ["text", "audio"],
    "audio": {
      "format": "mp3",
      "voice": "nova"
    }
  }'
python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.chat.completions.create(
    model="gpt-audio",
    messages=[
        {"role": "user", "content": "Explain quantum computing in simple terms."}
    ],
    modalities=["text", "audio"],
    audio={"format": "mp3", "voice": "nova"},
)

# Access the audio data and transcript
audio_data = response.choices[0].message.audio.data  # Base64 encoded audio
transcript = response.choices[0].message.audio.transcript  # Text transcript
javascript
import { OpenAI } from "openai";

const client = new OpenAI({
    apiKey: process.env.AVALAI_API_KEY,
    baseURL: "https://api.avalai.ir/v1",
});

const response = await client.chat.completions.create({
    model: "gpt-audio",
    messages: [
        {
            role: "user",
            content: "Explain quantum computing in simple terms.",
        },
    ],
    modalities: ["text", "audio"],
    audio: {
        format: "mp3",
        voice: "nova",
    },
});

// Access the audio data and transcript
const audioData = response.choices[0].message.audio.data;
const transcript = response.choices[0].message.audio.transcript;
go
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
)

func main() {
	client := openai.NewClient(
		option.WithAPIKey(os.Getenv("AVALAI_API_KEY")),
		option.WithBaseURL("https://api.avalai.ir/v1"),
	)

	completion, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
		Model: openai.F("gpt-audio"),
		Messages: openai.F([]openai.ChatCompletionMessageParamUnion{
			openai.UserMessage("Explain quantum computing in simple terms."),
		}),
		Modalities: openai.F([]openai.ChatCompletionModality{
			openai.ChatCompletionModalityText,
			openai.ChatCompletionModalityAudio,
		}),
		Audio: openai.F(openai.ChatCompletionAudioParam{
			Format: openai.F(openai.ChatCompletionAudioFormatMp3),
			Voice:  openai.F(openai.ChatCompletionAudioVoiceNova),
		}),
	})

	if err != nil {
		panic(err)
	}

	fmt.Printf("Audio Data: %s\n", completion.Choices[0].Message.Audio.Data)
	fmt.Printf("Transcript: %s\n", completion.Choices[0].Message.Audio.Transcript)
}
php
<?php

require 'vendor/autoload.php';

use OpenAI\Client;

$client = OpenAI::factory()
    ->withApiKey(getenv('AVALAI_API_KEY'))
    ->withBaseUri('https://api.avalai.ir/v1')
    ->make();

$response = $client->chat()->create([
    'model' => 'gpt-audio',
    'messages' => [
        [
            'role' => 'user',
            'content' => 'Explain quantum computing in simple terms.',
        ],
    ],
    'modalities' => ['text', 'audio'],
    'audio' => [
        'format' => 'mp3',
        'voice' => 'nova',
    ],
]);

$audioData = $response['choices'][0]['message']['audio']['data'];
$transcript = $response['choices'][0]['message']['audio']['transcript'];

echo "Transcript: " . $transcript . "\n";
Responses API version

Use this version when the selected model supports /v1/responses. messages moves to input, and the final text is read from response.output_text.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-audio",
    input="Explain quantum computing in simple terms.",
)

print(response.output_text)
javascript
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.AVALAI_API_KEY,
  baseURL: "https://api.avalai.ir/v1",
});

const response = await client.responses.create({
  model: "gpt-audio",
  instructions: "You are a helpful assistant.",
  input: "Explain quantum computing in simple terms.",
});

console.log(response.output_text);
bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '
  {
    "model": "gpt-audio",
    "input": "Explain quantum computing in simple terms.",
    "instructions": "You are a helpful assistant."
  }'
  • messagesinput
  • system message → instructions or a developer item
  • choices[0].message.contentresponse.output_text
  • for tools and multimodal output, inspect response.output by item type.

Audio Response Format

When using audio models with the audio modality, the response includes an audio object in the message:

json
{
  "id": "chatcmpl-123",
  "object": "chat.completion",
  "created": 1763042146,
  "model": "gpt-audio-2025-08-28",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "audio": {
          "id": "audio_abc123",
          "data": "SUQzBAAAAA...", // Base64 encoded audio

          "expires_at": 1763045747,
          "transcript": "Quantum computing is a revolutionary technology..."
        }
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 12,
    "completion_tokens": 75,
    "total_tokens": 87,
    "completion_tokens_details": {
      "audio_tokens": 58,
      "text_tokens": 17
    },
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "text_tokens": 12
    }
  }
}

Using gpt-audio-1.5 for Premium Audio Quality

For the highest quality voice synthesis and audio understanding, use gpt-audio-1.5:

python
response = client.chat.completions.create(
    model="gpt-audio-1.5",  # Best voice model with 256K context
    messages=[{"role": "user", "content": "What's the weather like today?"}],
    modalities=["text", "audio"],
    audio={"format": "mp3", "voice": "nova"},
)
Responses API version This version uses `gpt-5.5` because `gpt-audio-1.5` may not be enabled for `/v1/responses` in the current AvalAI model data.

Use this version when the selected model supports /v1/responses. messages moves to input, and the final text is read from response.output_text.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-5.6-sol",
    input="What's the weather like today? Answer in one sentence.",
)

print(response.output_text)
  • messagesinput
  • system message → instructions or a developer item
  • choices[0].message.contentresponse.output_text
  • for tools and multimodal output, inspect response.output by item type.

Using gpt-audio-mini for Cost-Effective Processing

For high-volume applications, use gpt-audio-mini which offers the same capabilities at a lower cost:

python
response = client.chat.completions.create(
    model="gpt-audio-mini",  # More cost-effective option
    messages=[{"role": "user", "content": "What's the weather like today?"}],
    modalities=["text", "audio"],
    audio={"format": "mp3", "voice": "alloy"},
)
Responses API version

Use this version when the selected model supports /v1/responses. messages moves to input, and the final text is read from response.output_text.

python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AVALAI_API_KEY"],
    base_url="https://api.avalai.ir/v1",
)

response = client.responses.create(
    model="gpt-audio-mini",
    input="What's the weather like today? Answer in one sentence.",
)

print(response.output_text)
  • messagesinput
  • system message → instructions or a developer item
  • choices[0].message.contentresponse.output_text
  • for tools and multimodal output, inspect response.output by item type.

Legacy Audio Models

For backwards compatibility, the following preview models are still available:

  • gpt-4o-audio-preview
  • gpt-4o-mini-audio-preview

Note

Audio input (uploading audio files) is not yet supported in the Chat Completions API. For transcribing audio to text, use the Audio Transcriptions API.

Error Handling

The API may return various error codes:

Status CodeDescription
400Bad Request - Your request is invalid.
401Unauthorized - Your API key is wrong.
403Forbidden - You don't have permission to access this resource.
404Not Found - The specified resource could not be found.
429Too Many Requests - You have exceeded your rate limit.
500Internal Server Error - We had a problem with our server.

For more information on handling errors, see the Error Handling guide.