Quick Start Guide
This guide will help you get started with the AvalAI platform in minutes.
Recommended first-run path:
- Install an SDK.
- Export
AVALAI_API_KEY. - Choose the API style:
/v1/responsesfor new text, reasoning, and tool workflows;/v1/chat/completionsfor existing chat integrations and broad provider compatibility. - Make a first request, then use
/v1/modelsandavalai-request-idfor model discovery and cost tracking.
1. Create and protect your API key
- Create an account at AvalAI Dashboard
- Navigate to the API Keys section
- Generate a new API key
- Store your API key securely - it will only be shown once!
Export Your API Key
Set AVALAI_API_KEY before running SDK or curl examples. Keep it in your shell profile, secret manager, or deployment environment; do not paste API keys into source code, screenshots, issue reports, or frontend JavaScript.
# macOS / Linux
export AVALAI_API_KEY="sk-..."# Windows PowerShell
setx AVALAI_API_KEY "sk-..."After setting it, open a new terminal or reload your shell profile before running the examples below.
2. Install and configure a client
Install an OpenAI-compatible SDK
AvalAI supports three SDK approaches:
Alternative official SDK integrations
See the Libraries documentation before choosing a provider-native integration.
Choose your preferred language:
Python
pip install openaiNode.js
npm install openaiGo
go get github.com/openai/openai-goPHP
composer require openai-php/clientUse the AvalAI base URL
AvalAI provides multiple domains to ensure optimal connectivity based on your location and network conditions.
1. Primary Domain - Recommended
- 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
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
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
import { OpenAI } from "openai";
const client = new OpenAI({
apiKey: process.env.AVALAI_API_KEY,
baseURL: "https://api.avalai.ir/v1", // AvalAI API endpoint
});Go
package main
import (
openai "github.com/openai/openai-go"
"os"
)
func main() {
client := openai.NewClient(os.Getenv("AVALAI_API_KEY"))
client.BaseURL = "https://api.avalai.ir/v1" // AvalAI API endpoint
}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:
Responses API (recommended for new apps)
curl https://api.avalai.ir/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $AVALAI_API_KEY" \
-d '{
"model": "gpt-5.5",
"instructions": "You are a helpful assistant.",
"input": "Hello, world!"
}'response = client.responses.create(
model="gpt-5.5",
instructions="You are a helpful assistant.",
input="Hello, world!",
)
print(response.output_text)const response = await client.responses.create({
model: "gpt-5.5",
instructions: "You are a helpful assistant.",
input: "Hello, world!",
});
console.log(response.output_text);package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
payload := map[string]any{
"model": "gpt-5.5",
"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
$apiKey = getenv('AVALAI_API_KEY');
$payload = [
'model' => 'gpt-5.5',
'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
completion = client.chat.completions.create(
model="gpt-5.5", # 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
const completion = await client.chat.completions.create({
model: "gpt-5.5", // 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
resp, err := client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: "gpt-5.5", // You can use any supported model
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: "You are a helpful assistant.",
},
{
Role: openai.ChatMessageRoleUser,
Content: "Hello, world!",
},
},
},
)
if err != nil {
fmt.Printf("ChatCompletion error: %v\n", err)
return
}
fmt.Println(resp.Choices[0].Message.Content)PHP
try {
// Make the chat completion request
$response = $client->chat()->create([
'model' => 'gpt-5.5', // 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
# Example using provider-specific parameters
response = client.chat.completions.create(
model="claude-sonnet-4-6",
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:
// Example using undocumented parameters directly
const response = await client.chat.completions.create({
model: "claude-sonnet-4-6",
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.5,gpt-5.4-pro,gpt-5.4,gpt-5.4-mini,gpt-5.4-nano,gpt-5.3-chat,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-ultraand 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:
# 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.5")
print(model)# 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
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 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# 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-3ea8f15dcf1aFor a Responses request, capture the same header from /v1/responses:
curl -i "https://api.avalai.ir/v1/responses" \
-H "Authorization: Bearer $AVALAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "gpt-5.5", "input": "hi"}'Get Precise Costs
Use the avalai-request-id to lookup exact costs (available within 30 seconds):
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 detailsWhy Use User API?
- 100% Accurate Costs - Unlike
estimated_costin 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:
- User API Documentation - Complete API reference
- Reseller Cost Tracking Guide - Step-by-step guide for accurate billing
- Enterprise Usage Guide - Advanced patterns for large-scale deployments
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
- Learn about Anthropic SDK Multi-Provider Support - Use official Anthropic SDKs for multiple provider models
- Read about the original Anthropic SDK Support announcement
- Explore the Libraries Documentation for complete SDK setup guides including Anthropic SDKs
- Explore the API Reference for detailed information about all available endpoints
- Learn about Authentication methods and best practices
- Check out our Guides for tips on using the API effectively
- Review our API Content Policy for details on data handling and privacy