Developer Dashboard

Quick Start Guide ​

This guide will help you get started with the AvalAI platform in minutes.

Recommended first-run path:

  1. Create an API key and check your available API credit and model access.
  2. Set AVALAI_API_KEY, then configure a client or use cURL.
  3. Send the first request below. Start with Responses for a new application; keep Chat Completions if your integration already uses it.
  4. Confirm the response, then open your usage overview to see activity and cost.

1. Create and protect your API key ​

  1. Open API Keys, then sign in or create an account if needed.
  2. Generate a new API key.
  3. Store your API key securely — it will only be shown once!

Check API credit and model access ​

Open API credit to check your available balance. If you already have enough credit, including eligible signup credit, you can use it; top up only if needed. Credit packages are optional.

Check the selected model's access requirements in Models and account tiers and rate limits. A model may require a higher account tier even when your balance is positive. Chat Plus is a separate Chat subscription; it is not API credit and is not required to call the API.

Export Your API Key ​

Set AVALAI_API_KEY before running SDK or cURL examples. For deployed applications, use your secret manager or deployment environment. Never put API keys in source code, screenshots, issue reports, or frontend JavaScript.

bash
# macOS / Linux
export AVALAI_API_KEY="sk-..."
powershell
# Windows PowerShell
setx AVALAI_API_KEY "sk-..."

On macOS/Linux, run the examples in the same terminal as export; the value is not saved for a new terminal. On Windows, setx saves the value for future processes, so open a new PowerShell window before running the examples.

2. Install and configure a client ​

Install an OpenAI-compatible SDK ​

AvalAI supports three SDK approaches:

Alternative official SDK integrations
OpenAI-Compatible SDKsUnified approach — Access all models from multiple providers with consistent syntax.
Anthropic Official SDKsNative approach — Use Anthropic's official SDKs to access models from Anthropic, OpenAI, AWS Bedrock, Vertex AI, and Gemini with native syntax.
Google GenAI SDKNative approach — Use Google's official GenAI SDK for native access to Gemini models with Google's native API schema.

See the Libraries documentation before choosing a provider-native integration.

Choose your preferred language:

Python ​

bash
pip install openai

Node.js ​

bash
npm install openai

Go ​

bash
go get github.com/openai/openai-go

PHP ​

bash
composer require openai-php/client

Use the AvalAI base URL ​

AvalAI provides multiple domains to ensure optimal connectivity based on your location and network conditions.

  • Address: api.avalai.ir
  • CDN: Global
  • Best for: users seeking optimal performance with lowest latency

Usage ​

Users can choose any of these domains based on their network conditions. All API endpoints and features are identical across all domains.

Python Example ​

python
import os
from openai import OpenAI

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

Configure the client ​

Python ​

To configure the Python OpenAI client, pass the value of AVALAI_API_KEY from your environment as api_key and set base_url to the AvalAI endpoint shown in the Python example.

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
)

JavaScript/TypeScript ​

javascript
import { OpenAI } from "openai";

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

Go ​

go
package main

import (
	"os"

	openai "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"),
	)
	_ = client
}

PHP ​

php
<?php

require_once 'vendor/autoload.php';

// Using OpenAI PHP client library (https://github.com/openai-php/client)
$apiKey = getenv('AVALAI_API_KEY');

if (!$apiKey) {
    die("AvalAI API key not found. Please set the AVALAI_API_KEY environment variable.");
}

// Your custom base URL
$customBaseUrl = 'https://api.avalai.ir/v1';

// Create a custom client instance using the factory
$client = OpenAI::factory()
    ->withApiKey($apiKey)
    ->withBaseUri($customBaseUrl)
    ->make();

3. Choose your API style ​

For new text-generation applications, start with /v1/responses when your selected model supports it. Responses uses input, exposes response.output_text, and supports richer state, reasoning, and tool workflows. Keep /v1/chat/completions for existing applications, provider coverage, and SDKs or frameworks that still expect messages.

4. Send your first request ​

Start with a simple Responses request:

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
    "model": "gpt-5.6-luna",
    "instructions": "You are a helpful assistant.",
    "input": "Hello, world!"
  }'
python
response = client.responses.create(
    model="gpt-5.6-luna",
    instructions="You are a helpful assistant.",
    input="Hello, world!",
)

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

console.log(response.output_text);
go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	payload := map[string]any{
		"model":        "gpt-5.6-luna",
		"instructions": "You are a helpful assistant.",
		"input":        "Hello, world!",
	}

	body, _ := json.Marshal(payload)
	req, _ := http.NewRequest("POST", "https://api.avalai.ir/v1/responses", bytes.NewBuffer(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("AVALAI_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	responseBody, _ := io.ReadAll(resp.Body)
	fmt.Println(string(responseBody))
}
php
<?php
$apiKey = getenv('AVALAI_API_KEY');
$payload = [
    'model' => 'gpt-5.6-luna',
    'instructions' => 'You are a helpful assistant.',
    'input' => 'Hello, world!',
];

$ch = curl_init('https://api.avalai.ir/v1/responses');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ],
    CURLOPT_POSTFIELDS => json_encode($payload),
]);

$response = curl_exec($ch);
curl_close($ch);

echo $response;

Required headers and rate limits ​

Every authenticated request requires Authorization: Bearer $AVALAI_API_KEY. Send Content-Type: application/json whenever the request has a JSON body. If the API returns HTTP 429, respect any Retry-After header, retry with exponential backoff and jitter, and cap retries instead of immediately repeating the request. See Rate limits for current behavior and tier guidance.

Chat Completions for an existing integration

Chat Completions API (existing integrations) ​

Keep this version when you already use messages or when your selected model only supports /v1/chat/completions.

Python ​

python
completion = client.chat.completions.create(
    model="gpt-5.6-luna",  # You can use any supported model
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello, world!"},
    ],
)

print(completion.choices[0].message.content)

JavaScript/TypeScript ​

javascript
const completion = await client.chat.completions.create({
  model: "gpt-5.6-luna", // You can use any supported model
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Hello, world!" },
  ],
});

console.log(completion.choices[0].message.content);

Go ​

go
package main

import (
	"context"
	"fmt"
	"os"

	openai "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"),
	)
	response, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
		Model: "gpt-5.6-luna",
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.SystemMessage("You are a helpful assistant."),
			openai.UserMessage("Hello, world!"),
		},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	if len(response.Choices) > 0 {
		fmt.Println(response.Choices[0].Message.Content)
	}
}

PHP ​

php
try {
 // Make the chat completion request
 $response = $client->chat()->create([
 'model' => 'gpt-5.6-luna', // You can use any supported model
 'messages' => [
 ['role' => 'system', 'content' => 'You are a helpful assistant.'],
 ['role' => 'user', 'content' => 'Hello, world!']
 ]
 ]);

 // Output the response content
 echo $response->choices[0]->message->content;
} catch (\Exception $e) {
 echo "Error: " . $e->getMessage() . "\n";
}

5. Discover models and extend your integration ​

The public model catalog is available at https://api.avalai.ir/public/models without authentication. Use /v1/models with your API key when your application needs the authenticated catalog.

Provider-specific parameters and TypeScript alternatives

Using provider-specific parameters ​

When working with non-OpenAI providers through AvalAI (such as Stability AI, Anthropic, etc.), you may need to use parameters that aren't directly supported by the OpenAI client library. AvalAI provides two ways to pass these parameters.

Using extra_body ​

The extra_body parameter allows you to pass any additional parameters required by the specific provider:

Python ​

python
# Example using provider-specific parameters
response = client.chat.completions.create(
    model="claude-sonnet-5",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello, world!"},
    ],
    extra_body={"provider_param1": "value1", "provider_param2": "value2"},
)

JavaScript/TypeScript ​

Using Undocumented Parameters Directly ​

For TypeScript users, you can also pass undocumented parameters directly by using // @ts-expect-error:

javascript
// Example using undocumented parameters directly
const response = await client.chat.completions.create({
  model: "claude-sonnet-5",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Hello, world!" },
  ],
  // @ts-expect-error undocumented parameter
  provider_param1: "value1",
  // @ts-expect-error another undocumented parameter
  provider_param2: "value2",
});

This library doesn't validate at runtime that the request matches the type, so any extra values you send will be sent as-is to the provider's API. For GET requests, these extra parameters will be in the query string, while for all other requests, they will be sent in the body.

If you want to explicitly send extra arguments, you can also do so with the query, body, and headers request options.

Explore available models ​

AvalAI provides access to models from multiple providers. You can specify which model to use in your requests:

  • OpenAI models: gpt-5.6-sol, gpt-5.6-terra, gpt-5.6-luna, gpt-5.5, gpt-5.4-pro, gpt-5.3-codex, gpt-image-2, etc.
  • Anthropic models: claude-opus-4-8, claude-opus-4-7, claude-opus-4-6, claude-sonnet-4-6, claude-haiku-4-5, etc.
  • Google models: gemini-3.5-flash, gemini-3.1-pro-preview, gemini-3.1-flash-lite, gemini-3.1-flash-image, gemini-embedding-2, gemini-3-flash-preview, gemini-2.5-pro, gemma-4-26b-a4b-it, etc.
  • XAI models: grok-4.3, grok-4.20-reasoning, grok-4.20-non-reasoning, grok-4-1-fast-reasoning, etc.
  • DeepSeek models: deepseek-v4-pro, deepseek-v4-flash, deepseek-chat, etc.
  • Alibaba models: qwen3.7-max, qwen3.7-plus, qwen3.6-plus, qwen3.6-flash, qwen3.6-max-preview, qwen-image-2.0-pro, qwen-image-2.0, etc.
  • Moonshot.ai models: kimi-k2.7-code, kimi-k2.7-code-highspeed, kimi-k2.6, kimi-k2-thinking, kimi-latest, etc.
  • Z.AI models: glm-5.2, glm-5.1, glm-5v-turbo, glm-5-turbo, etc.
  • MiniMax models: minimax-m3, minimax-m2.7, minimax-m2.7-highspeed, minimax-m2.5, etc.
  • Fireworks.ai models: nemotron-3-ultra and other fast open-weight models.
  • Meta, Mistral, Cohere, Cloudflare, BytePlus, and other provider models are also available.

List Available Models via API ​

You can retrieve a list of all available models programmatically:

python
# List all models
models = client.models.list()
for model in models.data:
    print(f"{model.id} - {model.owned_by}")

# Get detailed info for a specific model (includes pricing, capabilities, rate limits)
model = client.models.retrieve("gpt-5.6-luna")
print(model)
bash
# Public endpoint (no auth required)
curl https://api.avalai.ir/public/models

# Authenticated endpoint
curl https://api.avalai.ir/v1/models -H "Authorization: Bearer $AVALAI_API_KEY"

# Get specific model details
curl https://api.avalai.ir/v1/models/gpt-5.5 -H "Authorization: Bearer $AVALAI_API_KEY"

For a complete list of available models, see the Models documentation or the Models API Reference.

6. Track usage and choose next steps ​

The Python and JavaScript Responses examples print the model's text with output_text. The cURL and direct HTTP examples return JSON; the generated message is in output. A successful HTTP response with the expected content is your first working API integration.

Open Usage overview to review activity and cost. Reporting can arrive after the API response; refresh the overview if the request has not appeared yet instead of sending another paid request just to test the chart.

If your first request fails ​

What you seeWhat to do next
Missing key or invalid_api_keyCheck the terminal instructions above and your API Keys. A newly created key may take up to 60 seconds to activate.
insufficient_quotaCheck API credit and add credit only if your available balance cannot cover the request.
insufficient_tier or an unsupported modelCheck account tiers and the model's supported endpoint in Models.
Rate limit or temporary service errorFollow the error-handling guide and check service status before retrying.
You still cannot complete a requestCreate a support ticket with the model, endpoint, HTTP status, error message, timestamp and timezone, and avalai-request-id if available. Do not include your API key.
Optional: programmatic cost tracking for applications and resellers

Track API costs and usage (optional) ​

For production applications, resellers, and enterprises, AvalAI provides the User API for precise cost tracking and usage analytics.

Get the Request ID ​

Every API response includes an avalai-request-id header that uniquely identifies the request:

python
# Python example - capture response headers
response = client.chat.completions.create(
    model="gpt-5.4-mini", messages=[{"role": "user", "content": "Hello!"}]
)

# The response object doesn't expose headers directly in OpenAI SDK
# To get headers, use HTTP client directly or check your application logs
bash
# Using curl to see headers
curl -i "https://api.avalai.ir/v1/chat/completions" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-5.4-mini", "messages": [{"role": "user", "content": "hi"}]}'

# Look for: avalai-request-id: 019ac4a0-a8f4-7041-845f-3ea8f15dcf1a

For a Responses request, capture the same header from /v1/responses:

bash
curl -i "https://api.avalai.ir/v1/responses" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-5.6-luna", "input": "hi"}'

Get Precise Costs ​

Use the avalai-request-id to lookup exact costs (available within 30 seconds):

python
import requests
import os

# Lookup precise cost
response = requests.post(
    "https://api.avalai.ir/user/v1/transactions/lookup",
    headers={
        "Authorization": f"Bearer {os.environ['AVALAI_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={"transaction_ids": ["019ac4a0-a8f4-7041-845f-3ea8f15dcf1a"]},
)

data = response.json()
# Returns exact cost in USD and IRT with full transaction details

Why Use User API? ​

  • 100% Accurate Costs - Unlike estimated_cost in responses, User API provides guaranteed accurate costs
  • Billing for Resellers - Charge customers based on actual costs without discrepancies
  • Usage Analytics - Track spending by model, provider, date, or hour
  • Audit Trail - Complete transaction history for compliance

Learn More:

Troubleshoot with a documentation URL

Get help with documentation ​

💡 Pro Tip: You can copy any documentation page URL from docs.avalai.ir and paste it directly into your prompt at chat.avalai.ir (AvalAI Chat Platform). When you include a docs URL in your message, the AI models can access that page's content, allowing you to:

  • Ask any model to explain specific documentation sections
  • Get help debugging issues using the relevant docs
  • Request implementation examples based on the documentation
  • Clarify complex concepts with interactive Q&A

Simply paste the documentation URL into your chat message along with your question, and the model will fetch and use that documentation to assist you. This enables faster debugging and implementation by combining our comprehensive documentation with AI-powered assistance.

Next steps ​