Developer Dashboard

Responses API Reference

OpenAI's most advanced interface for generating model responses. Supports text and image inputs, and text outputs. Create stateful interactions with the model, using the output of previous responses as input. Extend the model's capabilities with built-in tools for file search, web search, computer use, and more. Allow the model access to external systems and data using function calling.

Related guides:

Related examples:

When to use Responses

Use /v1/responses first for new reasoning, tool-calling, multimodal, structured-output, and multi-turn workflows. /v1/chat/completions remains useful for existing integrations, framework compatibility, and models that are chat-only in AvalAI.

When migrating from Chat Completions:

  • send messages as input, or split stable system guidance into top-level instructions;
  • read final text from response.output_text, and inspect response.output when you use tools, reasoning, or multimodal output;
  • use previous_response_id with store: true for simple stateful chains, or replay prior output items manually for stateless flows;
  • make separate requests if you need multiple candidate outputs because Responses does not support the Chat Completions n parameter;
  • move Structured Outputs schemas from response_format to text.format;
  • update streaming consumers to handle typed SSE events such as response.created, response.output_text.delta, response.function_call_arguments.delta, response.function_call_arguments.done, and response.completed.

Create a model response

POST https://api.avalai.ir/v1/responses

Creates a model response. Provide text or image inputs to generate text or JSON outputs. Have the model call your own custom code or use built-in tools like web search or file search to use your own data as input for the model's response.

Request Body

ParameterTypeRequiredDefaultDescription
inputstring or arrayRequiredText, image, or file inputs to the model, used to generate a response. File inputs use input_file and can reference file_url, file_id, or Base64 file_data.
Learn more:
modelstringRequiredModel ID used to generate the response, like gpt-5.5, gpt-5.4-pro, or gpt-5.4. Selected non-OpenAI models are supported with a limited subset of features (text input/output and basic tool use only — advanced built-in tools and the reasoning field remain OpenAI-specific). Models with partial Responses-API support include Alibaba's qwen3.7-max, Anthropic's claude-sonnet-5 and claude-opus-4-8, and MiniMax's minimax-m3. Refer to the model guide to browse and compare available models.
backgroundboolean or nullOptionalfalseRun the response as a background job when the selected route/account supports background processing. Use Background Processing for polling, terminal-state handling, and webhook handoff patterns.
context_managementobject or nullOptionalRoute-dependent context controls such as server-side compaction. If unavailable, compact in your own application and pass the summarized context explicitly.
conversationstring or objectOptionalConversation object or ID whose items are prepended to the request and updated after the response completes. Do not combine it with previous_response_id; use it only when the AvalAI route explicitly supports persistent conversations.
includearray or nullOptionalAdditional output data to include in the response. Common OpenAI-compatible values include:
  • file_search_call.results: file-search results.
  • web_search_call.action.sources: web-search sources.
  • code_interpreter_call.outputs: code-interpreter outputs.
  • computer_call_output.output.image_url: computer output image URLs.
  • message.input_image.image_url: input image URLs.
  • message.output_text.logprobs: output-token logprobs.
  • reasoning.encrypted_content: encrypted reasoning items for stateless reasoning continuation.
Availability is model, route, and account dependent in AvalAI.
instructionsstring or nullOptionalInserts a system (or developer) message as the first item in the model's context. When using along with previous_response_id, the instructions from a previous response will not be carried over to the next response.
max_output_tokensinteger or nullOptionalA shared upper bound for generated visible output and reasoning tokens. If hidden reasoning consumes the budget, the response can be incomplete with incomplete_details.reason: "max_output_tokens" and contain no visible text. Leave headroom, lower reasoning effort, or increase the limit within the model maximum.
max_tool_callsinteger or nullOptionalMaximum total number of built-in tool calls processed in one response. The limit applies across all built-in tools, not per tool.
metadatamapOptionalSet of 16 key-value pairs that can be attached to an object. Useful for storing additional information. Keys max length 64 chars, values max length 512 chars.
parallel_tool_callsboolean or nullOptionaltrueWhether to allow the model to run tool calls in parallel.
previous_response_idstring or nullOptionalThe unique ID of the previous response to the model. Use this to create multi-turn conversations. Learn more about conversation state.
promptobject or nullOptionalReference to a prompt template and variables when prompt-template support is enabled for the selected route/account. Otherwise keep reusable prompts in your application and send instructions/input.
reasoningobject or nullOptionalConfiguration options for supported OpenAI reasoning models, including GPT-5-series and o-series models. Use reasoning.effort to tune quality, latency, and cost; availability is model and route dependent. See Reasoning.
storeboolean or nullOptionaltrueWhether to store the generated model response for later retrieval via API.
streamboolean or nullOptionalfalseIf set to true, the model response data will be streamed using server-sent events. See Streaming Responses.
stream_optionsobject or nullOptionalOptions for streaming responses. Only set this when stream: true; route-dependent options may include stream obfuscation controls for trusted internal links.
temperaturenumber or nullOptional1Sampling temperature (0-2). Higher values = more random, lower = more deterministic. Alter this OR top_p.
textobjectOptionalConfiguration options for a text response. Use text.format for plain text, JSON mode, or Structured Outputs, and text.verbosity (when supported) to control final-answer length separately from reasoning depth. Learn more:
tool_choicestring or objectOptionalHow the model should select which tool(s) to use. See tools parameter.
toolsarrayOptionalAn array of tools the model may call. Categories include:
  • Built-in tools: OpenAI-hosted capabilities such as web search and file search, when enabled for the selected AvalAI route/account.
  • Function tools: JSON Schema-defined calls to your application code. Learn more: function calling.
  • Custom tools: freeform text payload tools, optionally grammar-constrained, when supported by the selected model/route.
  • Remote MCP tools: connector-style tool access when explicitly available.
top_logprobsinteger or nullOptional0Number of most likely output tokens to return at each generated token position, from 0 to 20. Use with include: ["message.output_text.logprobs"] when the selected model/route supports output log probabilities.
top_pnumber or nullOptional1Nucleus sampling. Considers tokens with top_p probability mass (e.g., 0.1 = top 10%). Alter this OR temperature.
truncationstring or nullOptionaldisabledTruncation strategy:
  • auto: Truncate by dropping older items from the beginning of the conversation if context exceeds the window.
  • disabled (default): Fail with 400 error if context window exceeded.
safety_identifierstringOptionalPrivacy-preserving identifier for abuse monitoring. Use a stable hash or opaque internal ID, maximum 64 characters, and do not send raw PII. See Safety best practices.
prompt_cache_keystringOptionalCache-bucketing key for similar repeated prefixes. Keep it opaque and stable per assistant, tenant, policy, or schema; do not put raw PII or request IDs in it. See Prompt caching.
prompt_cache_retentionstringOptionalLegacy 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.
moderationobjectOptionalInline moderation configuration, for example { "model": "omni-moderation-latest" }, when enabled for the selected route/model. If inline moderation is unavailable, call /v1/moderations before and/or after generation.
userstringOptionalLegacy end-user field. Prefer safety_identifier for abuse monitoring and prompt_cache_key for cache bucketing; keep user only for older integrations that still require it.
service_tierstringOptionaldefaultThe 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.

Tool configuration notes

Use OpenAI's tool model as the request shape, then confirm the selected AvalAI route exposes each tool type:

  • Function tools: use strict: true, additionalProperties: false, and explicit required fields for reliable arguments. Execute only allowlisted functions in your application.
  • tool_choice: use "auto" for normal routing, "required" when a tool must run, "none" for text-only output, or an explicit function/web-search choice when a specific tool should be used. allowed_tools can restrict the callable subset without changing the full tools array when the route supports it.
  • Parallel calls: set parallel_tool_calls: false for tools that mutate state, require approval, or depend on each other. Parallel calling applies to custom functions; built-in tools may have their own sequencing rules.
  • Web search: route-dependent controls may include search_context_size, filters.allowed_domains, filters.blocked_domains, external_web_access, return_token_budget, and include: ["web_search_call.action.sources"].
  • File search: future hosted support follows the OpenAI shape with vector_store_ids, max_num_results, filters, ranking_options, and include: ["file_search_call.results"]. Until AvalAI announces hosted vector stores, use the manual RAG path in File Search Tool.
  • Remote MCP/connectors: expose only trusted servers, pass OAuth authorization values outside prompts, constrain allowed_tools, and use require_approval for sensitive actions. If type: "mcp" is unavailable on the selected route, wrap the external service behind your own function tool.
  • Deferred tools: tool_search, namespaced tools, defer_loading, and additional_tools reduce initial context size for large tool catalogs, but they are model and route dependent.

Text and structured output notes

Use text.format deliberately:

  • Structured Outputs: prefer {"type": "json_schema", "strict": true, "schema": ...} for typed final answers. It enforces schema adherence, while JSON mode only ensures valid JSON.
  • JSON mode fallback: use {"type": "json_object"} only when schema adherence is unavailable or unnecessary, and include an explicit instruction that the model must output JSON.
  • Refusals and incomplete output: inspect response.output content parts and response.status / incomplete_details before parsing response.output_text; safety refusals and interrupted generations may not match your schema.
  • Schema operations: keep schemas stable and versioned. Providers may process and cache schemas for performance, so test the exact AvalAI route before using sensitive schemas or generating per-user schemas.

State, compaction, and billing notes

Use the Responses state model deliberately:

  • Choose one state strategy: use previous_response_id for simple stored chains, conversation only when persistent conversation objects are explicitly enabled, or manual Item replay when you need application-side trimming or stateless control. Resend stable instructions on each call because previous_response_id does not carry top-level instructions forward.
  • Keep stateless reasoning portable: for store: false flows on supported OpenAI routes, add include: ["reasoning.encrypted_content"] and append the returned reasoning/output Items into the next input so reasoning context can continue without server-side storage.
  • Compact long interactions: when supported, context_management with compact_threshold runs server-side compaction inside responses.create. For standalone /v1/responses/compact, pass the returned compacted window into the next request as-is; if the route is unavailable, compact in your application and send an explicit summary.
  • Budget for the full chain: previous_response_id is a state shortcut, not a free context window. Prior chain context can still count as input tokens. Use response usage and POST /v1/responses/input_tokens (when enabled) before expensive calls.
  • Know the related endpoints: POST /v1/responses/{response_id}/cancel cancels supported background responses, GET /v1/responses/{response_id}/input_items lists stored inputs, POST /v1/responses/input_tokens estimates request size, and POST /v1/responses/compact compacts long windows when enabled for your AvalAI route.

Returns

Returns a Response object.

Example Request (Text Input)

bash
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -d '{
"model": "gpt-5.5",
"input": "Tell me a three sentence bedtime story about a unicorn."
}'
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.responses.create(
    model="gpt-5.5", input="Tell me a three sentence bedtime story about a unicorn."
)

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",

  input: "Tell me a three sentence bedtime story about a unicorn.",
});

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

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

func main() {
	apiKey := os.Getenv("AVALAI_API_KEY")
	if apiKey == "" {
		fmt.Println("AVALAI_API_KEY environment variable not set.")
		return
	}

	body := []byte(`{
		"model": "gpt-5.5",
		"input": "Tell me a three sentence bedtime story about a unicorn."
	}`)

	req, err := http.NewRequest("POST", "https://api.avalai.ir/v1/responses", bytes.NewReader(body))
	if err != nil {
		fmt.Printf("Request creation error: %v\n", err)
		return
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Printf("API request error: %v\n", err)
		return
	}
	defer resp.Body.Close()

	responseBody, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Response read error: %v\n", err)
		return
	}

	if resp.StatusCode >= 400 {
		fmt.Printf("HTTP error %d: %s\n", resp.StatusCode, responseBody)
		return
	}

	var result struct {
		Output []struct {
			Type    string `json:"type"`
			Content []struct {
				Type string `json:"type"`
				Text string `json:"text"`
			} `json:"content"`
		} `json:"output"`
	}
	if err := json.Unmarshal(responseBody, &result); err != nil {
		fmt.Printf("JSON decode error: %v\n", err)
		return
	}

	for _, item := range result.Output {
		if item.Type != "message" {
			continue
		}
		for _, part := range item.Content {
			if part.Type == "output_text" {
				fmt.Println(part.Text)
			}
		}
	}
}
php
<?php
// PHP Example for AvalAI Responses API (/v1/responses)

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your key directly
if (!$apiKey) {
  die("Error: AVALAI_API_KEY environment variable not set.\n");
}

$apiUrl = 'https://api.avalai.ir/v1/responses';

$data = [
'model' => 'gpt-5.5', // Specify the desired model
'input' => 'Tell me a three sentence bedtime story about a unicorn.'
// Add other parameters as needed, e.g.:
// 'temperature' => 0.7,
// 'max_output_tokens' => 100,
];

$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, // Make sure this is your AVALAI_API_KEY
'Content-Length: ' . strlen($jsonData)
]);
// Optional: Add timeout settings
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
// curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

curl_close($ch);

if ($err) {
  echo "cURL Error #: " . $err . "\n";
} elseif ($httpcode >= 400) {
  echo "HTTP Error: " . $httpcode . "\n";
  echo "Response Body: " . $response . "\n";
} else {
  $responseData = json_decode($response, true);
  if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Error decoding JSON response: " . json_last_error_msg() . "\n";
    echo "Raw Response: " . $response . "\n";
  } elseif (isset($responseData['output'][0]['content'][0]['text'])) {
    // Accessing the text based on the provided example response structure
    echo "Assistant: " . $responseData['output'][0]['content'][0]['text'] . "\n";
  } else {
    echo "Response received, but expected text content not found.\n";
    echo "Full Response:\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",
)

tools = [
    {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location.",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string"}},
            "required": ["location"],
            "additionalProperties": False,
        },
    }
]

response = client.responses.create(
    model="gpt-5.5",
    input="Tell me a three sentence bedtime story about a unicorn.",
    tools=tools,
)

for item in response.output:
    if item.type == "function_call":
        print(item.name, item.arguments)
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 tools = [
  {
    type: "function",
    name: "get_current_weather",
    description: "Get the current weather in a given location.",
    parameters: {
      type: "object",
      properties: { location: { type: "string" } },
      required: ["location"],
      additionalProperties: false,
    },
  },
];

const response = await client.responses.create({
  model: "gpt-5.5",
  input: "Tell me a three sentence bedtime story about a unicorn.",
  tools,
});

for (const item of response.output) {
  if (item.type === "function_call") {
    console.log(item.name, item.arguments);
  }
}
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.5",
    "input": "Tell me a three sentence bedtime story about a unicorn.",
    "tools": [
      {
        "type": "function",
        "name": "get_current_weather",
        "description": "Get the current weather in a given location.",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string"
            }
          },
          "required": [
            "location"
          ],
          "additionalProperties": false
        }
      }
    ]
  }'
  • 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.

Example Response

json
{
  "id": "resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b",
  "object": "response",
  "created_at": 1741476542,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-5.5",
  "output": [
    {
      "type": "message",
      "id": "msg_67ccd2bf17f0819081ff3bb2cf6508e60bb6a6b452d3795b",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "In a peaceful grove beneath a silver moon, a unicorn named Lumina discovered a hidden pool that reflected the stars. As she dipped her horn into the water, the pool began to shimmer, revealing a pathway to a magical realm of endless night skies. Filled with wonder, Lumina whispered a wish for all who dream to find their own hidden magic, and as she glanced back, her hoofprints sparkled like stardust.",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 36,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 87,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 123
  },
  "user": null,
  "metadata": {},
  "service_tier": "default"
}

Get a model response

GET https://api.avalai.ir/v1/responses/{response_id}

Retrieves a model response with the given ID.

Path Parameters

ParameterTypeRequiredDescription
response_idstringRequiredThe ID of the response to retrieve.

Query Parameters

ParameterTypeRequiredDescription
includearrayOptionalAdditional fields to include in the response. See the include parameter for Response creation for more information.
streambooleanOptionalIf true, stream the response data over SSE while it is still being generated or resumed. Use only when the selected route supports response retrieval streaming.
starting_afterintegerOptionalResume streaming after the event with this sequence number. Persist the latest sequence_number from long-running streams before reconnecting.
include_obfuscationbooleanOptionalControls whether streaming delta events include obfuscation fields that normalize payload sizes. Keep the default unless you control the network path and need lower bandwidth.

Returns

The Response object matching the specified ID.

Example Request

bash
curl https://api.avalai.ir/v1/responses/resp_123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY"
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.responses.retrieve("resp_123")
print(response)
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.retrieve("resp_123");
console.log(response);
go
package main

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

func main() {
	apiKey := os.Getenv("AVALAI_API_KEY")
	if apiKey == "" {
		fmt.Println("AVALAI_API_KEY environment variable not set.")
		return
	}
	responseID := "resp_123" // The ID of the response to retrieve

	req, err := http.NewRequestWithContext(
		context.Background(),
		http.MethodGet,
		"https://api.avalai.ir/v1/responses/"+responseID,
		nil,
	)
	if err != nil {
		fmt.Printf("Request creation error: %v\n", err)
		return
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Accept", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Printf("API request error: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Response read error: %v\n", err)
		return
	}

	if resp.StatusCode >= 400 {
		fmt.Printf("HTTP error %d: %s\n", resp.StatusCode, body)
		return
	}

	var result map[string]any
	if err := json.Unmarshal(body, &result); err != nil {
		fmt.Printf("JSON decode error: %v\n", err)
		return
	}
	fmt.Printf("%+v\n", result)
}
php
<?php
// PHP Example for Retrieving a specific AvalAI Response (/v1/responses/{response_id})

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your key directly
if (!$apiKey) {
  die("Error: AVALAI_API_KEY environment variable not set.\n");
}

$responseId = 'resp_123'; // The ID of the response to retrieve
$apiUrl = 'https://api.avalai.ir/v1/responses/' . $responseId;

// Optional: Add query parameters like 'include'
// $queryParams = ['include' => 'message.input_image.image_url'];
// $apiUrl .= '?' . http_build_query($queryParams);


$ch = curl_init($apiUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json', // Content-Type might not be strictly needed for GET, but good practice
'Authorization: Bearer ' . $apiKey
]);
// Optional: Add timeout settings
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
// curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

curl_close($ch);

if ($err) {
  echo "cURL Error #: " . $err . "\n";
} elseif ($httpcode >= 400) {
  echo "HTTP Error: " . $httpcode . "\n";
  echo "Response Body: " . $response . "\n";
} else {
  $responseData = json_decode($response, true);
  if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Error decoding JSON response: " . json_last_error_msg() . "\n";
    echo "Raw Response: " . $response . "\n";
  } else {
    echo "Response Retrieved Successfully:\n";
    print_r($responseData);
  }
}
?>

Example Response

json
{
  "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44",
  "object": "response",
  "created_at": 1741386163,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-5.5",
  "output": [
    {
      "type": "message",
      "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "Silent circuits hum, \nThoughts emerge in data streams— \nDigital dawn breaks.",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 32,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 18,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 50
  },
  "user": null,
  "metadata": {}
}

Delete a model response

DELETE https://api.avalai.ir/v1/responses/{response_id}

Deletes a model response with the given ID.

Path Parameters

ParameterTypeRequiredDescription
response_idstringRequiredThe ID of the response to delete.

Returns

A success message indicating the deletion status.

Example Request

bash
curl -X DELETE https://api.avalai.ir/v1/responses/resp_123 \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY"
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.responses.delete("resp_123")  # Corrected method name
print(response)
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.del("resp_123"); // Corrected method name
console.log(response);
go
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	// "io" // Uncomment to read response body

	openai "github.com/openai/openai-go" // Library might not support this directly
)

func main() {
	apiKey := os.Getenv("AVALAI_API_KEY")
	if apiKey == "" {
		fmt.Println("AVALAI_API_KEY environment variable not set.")
		return
	}
	responseID := "resp_123" // The ID of the response to delete

	config := openai.DefaultConfig(apiKey)
	// Set AvalAI base URL
	config.BaseURL = "https://api.avalai.ir/v1"

	// Note: The openai-go library likely does not have a method for deleting custom 'responses'.
	// A raw HTTP DELETE request is the default approach.

	fmt.Printf("Attempting to delete response with ID: %s using raw HTTP DELETE\n", responseID)

	req, err := http.NewRequestWithContext(context.Background(), "DELETE", config.BaseURL+"/responses/"+responseID, nil)
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)

	httpClient := &http.Client{}
	resp, err := httpClient.Do(req)
	if err != nil {
		fmt.Printf("Error performing request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	// body, _ := io.ReadAll(resp.Body) // Read body for potential error messages

	if resp.StatusCode >= 200 && resp.StatusCode < 300 {
		fmt.Printf("Response %s deleted successfully (Status Code: %d)\n", responseID, resp.StatusCode)
		// Parse body if needed: e.g., json.Unmarshal(body, &deleteConfirmation)
	} else {
		fmt.Printf("HTTP Error: %d\n", resp.StatusCode)
		// fmt.Printf("Response Body: %s\n", string(body))
	}
}
php
<?php
// PHP Example for Deleting a specific AvalAI Response (/v1/responses/{response_id})

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your key directly
if (!$apiKey) {
  die("Error: AVALAI_API_KEY environment variable not set.\n");
}

$responseId = 'resp_123'; // The ID of the response to delete
$apiUrl = 'https://api.avalai.ir/v1/responses/' . $responseId;

$ch = curl_init($apiUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); // Specify DELETE method
curl_setopt($ch, CURLOPT_HTTPHEADER, [
// 'Content-Type: application/json', // Not usually needed for DELETE
'Authorization: Bearer ' . $apiKey
]);
// Optional: Add timeout settings
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
// curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

curl_close($ch);

if ($err) {
  echo "cURL Error #: " . $err . "\n";
} elseif ($httpcode >= 400) {
  echo "HTTP Error: " . $httpcode . "\n";
  echo "Response Body: " . $response . "\n";
} else {
  $responseData = json_decode($response, true);
  if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Error decoding JSON response: " . json_last_error_msg() . "\n";
    echo "Raw Response: " . $response . "\n";
  } elseif (isset($responseData['deleted']) && $responseData['deleted'] === true) {
    echo "Response ID " . (isset($responseData['id']) ? $responseData['id'] : $responseId) . " deleted successfully.\n";
  } else {
    echo "Response received, but deletion confirmation not found or invalid.\n";
    echo "Full Response:\n";
    print_r($responseData);
  }
}
?>

Example Response

json
{
  "id": "resp_6786a1bec27481909a17d673315b29f6",
  "object": "response",
  "deleted": true
}

List input items

GET https://api.avalai.ir/v1/responses/{response_id}/input_items

Returns a list of input items for a given response.

Path Parameters

ParameterTypeRequiredDescription
response_idstringRequiredThe ID of the response to retrieve input items for.

Query Parameters

ParameterTypeRequiredDefaultDescription
afterstringOptionalAn item ID to list items after, used in pagination.
beforestringOptionalAn item ID to list items before, used in pagination.
includearrayOptionalAdditional fields to include in the response. See the include parameter for Response creation.
limitintegerOptional20A limit on the number of objects to be returned (1-100).
orderstringOptionalascThe order to return the input items in (asc or desc).

Returns

A list object containing input item objects.

Example Request

bash
curl https://api.avalai.ir/v1/responses/resp_abc123/input_items \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY"
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.responses.input_items.list("resp_123")
print(response.data)
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.inputItems.list("resp_123");
console.log(response.data);
go
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"

	openai "github.com/openai/openai-go" // Used for config, but request is raw HTTP
)

// Define structs to represent the expected JSON response structure
type InputItemList struct {
	Object  string      `json:"object"`
	Data    []InputItem `json:"data"`
	FirstID string      `json:"first_id"`
	LastID  string      `json:"last_id"`
	HasMore bool        `json:"has_more"`
}

type InputItem struct {
	ID      string         `json:"id"`
	Type    string         `json:"type"`
	Role    string         `json:"role"` // Assuming 'message' type has role
	Content []InputContent `json:"content"`
}

type InputContent struct {
	Type string `json:"type"`
	Text string `json:"text"` // Assuming 'input_text' type
}

func main() {
	apiKey := os.Getenv("AVALAI_API_KEY")
	if apiKey == "" {
		fmt.Println("AVALAI_API_KEY environment variable not set.")
		return
	}
	responseID := "resp_abc123" // The ID of the response

	config := openai.DefaultConfig(apiKey)
	// Set AvalAI base URL
	config.BaseURL = "https://api.avalai.ir/v1"

	// Note: The openai-go library does not have a method for listing input items of a custom 'response'.
	// A raw HTTP GET request is required.

	fmt.Printf("Attempting to list input items for response ID: %s using raw HTTP GET\n", responseID)

	// Construct URL with potential query parameters
	endpointURL, _ := url.Parse(config.BaseURL + "/responses/" + responseID + "/input_items")
	queryParams := url.Values{}
	// queryParams.Add("limit", "10") // Example query param
	endpointURL.RawQuery = queryParams.Encode()

	req, err := http.NewRequestWithContext(context.Background(), "GET", endpointURL.String(), nil)
	if err != nil {
		fmt.Printf("Error creating request: %v\n", err)
		return
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Accept", "application/json")

	httpClient := &http.Client{}
	resp, err := httpClient.Do(req)
	if err != nil {
		fmt.Printf("Error performing request: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error reading response body: %v\n", err)
		return
	}

	if resp.StatusCode >= 400 {
		fmt.Printf("HTTP Error: %d\n", resp.StatusCode)
		fmt.Printf("Response Body: %s\n", string(body))
		return
	}

	var itemList InputItemList
	err = json.Unmarshal(body, &itemList)
	if err != nil {
		fmt.Printf("Error unmarshalling JSON response: %v\n", err)
		fmt.Printf("Raw Response Body: %s\n", string(body))
		return
	}

	fmt.Printf("Successfully retrieved input items list:\n")
	// Process itemList as needed
	fmt.Printf("%+v\n", itemList)
}
php
<?php
// PHP Example for Listing Input Items for an AvalAI Response (/v1/responses/{response_id}/input_items)

$apiKey = getenv('AVALAI_API_KEY'); // Or replace with your key directly
if (!$apiKey) {
  die("Error: AVALAI_API_KEY environment variable not set.\n");
}

$responseId = 'resp_abc123'; // The ID of the response
$apiUrlBase = 'https://api.avalai.ir/v1/responses/' . $responseId . '/input_items';

// Optional: Add query parameters
$queryParams = [
// 'limit' => 10,
// 'order' => 'desc',
// 'after' => 'msg_xyz789',
// 'include' => 'message.input_image.image_url'
];
$apiUrl = $apiUrlBase . (empty($queryParams) ? '' : '?' . http_build_query($queryParams));


$ch = curl_init($apiUrl);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json', // Might not be strictly needed for GET
'Authorization: Bearer ' . $apiKey
]);
// Optional: Add timeout settings
// curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
// curl_setopt($ch, CURLOPT_TIMEOUT, 30);

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

curl_close($ch);

if ($err) {
  echo "cURL Error #: " . $err . "\n";
} elseif ($httpcode >= 400) {
  echo "HTTP Error: " . $httpcode . "\n";
  echo "Response Body: " . $response . "\n";
} else {
  $responseData = json_decode($response, true);
  if (json_last_error() !== JSON_ERROR_NONE) {
    echo "Error decoding JSON response: " . json_last_error_msg() . "\n";
    echo "Raw Response: " . $response . "\n";
  } else {
    echo "Input Items List Retrieved Successfully:\n";
    print_r($responseData);
  }
}
?>

Example Response

json
{
  "object": "list",
  "data": [
    {
      "id": "msg_abc123",
      "type": "message",
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": "Tell me a three sentence bedtime story about a unicorn."
        }
      ]
    }
  ],
  "first_id": "msg_abc123",
  "last_id": "msg_abc123",
  "has_more": false
}

The response object

Represents a response generated by the model.

AttributeTypeDescription
idstringUnique identifier for this Response.
objectstringThe object type, always response.
created_atnumberUnix timestamp (in seconds) of when this Response was created.
completed_atnumber or nullUnix timestamp (in seconds) of when this Response completed, when returned by the selected route.
statusstringThe status of the response generation. One of completed, failed, in_progress, or incomplete.
backgroundboolean or nullWhether the response ran as a background job, when returned by the selected route.
errorobject or nullAn error object returned when the model fails to generate a Response. Contains code and message.
incomplete_detailsobject or nullDetails about why the response is incomplete. Contains reason.
conversationstring or object or nullConversation reference used for this response, when persistent conversations are enabled.
context_managementobject or nullContext-management configuration used for this response, when returned by the route.
instructionsstring or nullThe system (or developer) message provided in the request.
max_output_tokensinteger or nullThe upper bound for generated tokens specified in the request.
max_tool_callsinteger or nullThe maximum built-in tool calls allowed for this response, when specified or returned.
metadatamapKey-value pairs attached to the object.
modelstringModel ID used to generate the response.
outputarrayAn array of content items generated by the model (e.g., message, tool_call). Order and content depend on the model's response.
output_textstring or nullSDK Only: Aggregated text output from all output_text items in the output array.
parallel_tool_callsbooleanWhether parallel tool calls were enabled.
previous_response_idstring or nullThe ID of the previous response used for conversation state.
promptobject or nullPrompt-template reference and variables, when used and returned by the selected route/account.
reasoningobject or nullReasoning configuration and summary settings for supported GPT-5-series and o-series reasoning models.
storebooleanWhether the response was stored.
temperaturenumber or nullThe sampling temperature used.
textobjectConfiguration options for text response used (e.g., format).
tool_choicestring or objectThe tool choice setting used.
toolsarrayThe array of tools provided in the request.
top_logprobsinteger or nullNumber of output logprob alternatives requested for generated tokens, when supported.
top_pnumber or nullThe nucleus sampling probability used.
truncationstring or nullThe truncation strategy used (auto or disabled).
usageobjectToken usage details: input_tokens, input_tokens_details (cached_tokens and, for compatible GPT-5.6 routes, cache_write_tokens), output_tokens, output_tokens_details (reasoning_tokens), total_tokens.
safety_identifierstring or nullThe privacy-preserving safety identifier provided, when returned by the selected route/model.
prompt_cache_keystring or nullThe prompt cache bucketing key provided, when returned by the selected route/model.
prompt_cache_retentionstring or nullLegacy prompt-cache retention policy used for a pre-GPT-5.6 response, when supported and returned.
moderationobject or nullInline input/output moderation results when requested and supported.
userstring or nullLegacy end-user identifier, when provided by older clients.
service_tierstringThe service tier used for this request. Public AvalAI values are generally "default" or "flex"; "priority" is account-specific unless explicitly enabled.

Example Response Object

json
{
  "id": "resp_67ccd3a9da748190baa7f1570fe91ac604becb25c45c1d41",
  "object": "response",
  "created_at": 1741476777,
  "status": "completed",
  "error": null,
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "model": "gpt-5.5",
  "output": [
    {
      "type": "message",
      "id": "msg_67ccd3acc8d48190a77525dc6de64b4104becb25c45c1d41",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "The image depicts a scenic landscape with a wooden boardwalk or pathway leading through lush, green grass under a blue sky with some clouds. The setting suggests a peaceful natural area, possibly a park or nature reserve. There are trees and shrubs in the background.",
          "annotations": []
        }
      ]
    }
  ],
  "parallel_tool_calls": true,
  "previous_response_id": null,
  "reasoning": {
    "effort": null,
    "summary": null
  },
  "store": true,
  "temperature": 1.0,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_p": 1.0,
  "truncation": "disabled",
  "usage": {
    "input_tokens": 328,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "output_tokens": 52,
    "output_tokens_details": {
      "reasoning_tokens": 0
    },
    "total_tokens": 380
  },
  "user": null,
  "service_tier": "default",
  "metadata": {}
}

The input item list object

Represents a paginated list of input items for a response.

AttributeTypeDescription
objectstringThe type of object returned, always list.
dataarrayA list of input items (e.g., message objects) used to generate the response.
first_idstringThe ID of the first item in the list for pagination.
last_idstringThe ID of the last item in the list for pagination.
has_morebooleanWhether there are more items available after this page.

Example List Object

json
{
  "object": "list",
  "data": [
    {
      "id": "msg_abc123",
      "type": "message",
      "role": "user",
      "content": [
        {
          "type": "input_text",
          "text": "Tell me a three sentence bedtime story about a unicorn."
        }
      ]
    }
  ],
  "first_id": "msg_abc123",
  "last_id": "msg_abc123",
  "has_more": false
}

Streaming

When you create a Response with stream: true, AvalAI returns a server-sent events (SSE) stream. Responses streaming does not use Chat Completions-style choices[].delta chunks. Instead, each SSE payload is a typed event with an event.type such as response.created, response.output_text.delta, response.output_text.done, response.completed, response.failed, or error.

For text streaming, listen for these common event families:

EventWhen to handle it
response.created / response.in_progressInitialize UI state, attach the response ID, and show generation has started.
response.output_item.added / response.output_item.doneTrack typed output items such as messages, tool calls, and reasoning items.
response.content_part.added / response.content_part.doneTrack content parts inside a message item.
response.output_text.deltaAppend delta to the visible assistant text.
response.output_text.doneReconcile or replace the buffered text with the final text for that content part.
response.output_text.annotation.addedCapture citations, file references, or search annotations for rendering after the related text stabilizes.
response.refusal.delta / response.refusal.doneKeep safety refusal text separate from normal answer text and treat the final refusal as a terminal assistant response.
response.function_call_arguments.delta / response.function_call_arguments.doneBuffer tool-call arguments and execute the function only after the done event.
response.file_search_call.in_progress / response.file_search_call.searching / response.file_search_call.completedUpdate retrieval progress when hosted file search is enabled for the selected AvalAI route.
response.code_interpreter_call.in_progress / response.code_interpreter_call_code.delta / response.code_interpreter_call.completedStream interpreter status and generated code to a dedicated panel; publish outputs only after completion.
response.completedFinalize the stream and read final usage, status, and output metadata.
response.failed / errorStop rendering and surface or retry the error.

Use the streaming guide for implementation patterns and safety notes: Streaming API Responses.

For long-running or background responses, persist the latest event sequence_number when present. If your route supports response-retrieval streaming, reconnect with GET /v1/responses/{response_id}?stream=true&starting_after=<sequence_number> and keep include_obfuscation enabled unless you are optimizing a trusted internal stream.

Example SSE Events

text
event: response.created
data: {"type":"response.created","response":{"id":"resp_123","status":"in_progress"}}

event: response.output_text.delta
data: {"type":"response.output_text.delta","delta":"Hello"}

event: response.output_text.delta
data: {"type":"response.output_text.delta","delta":" world"}

event: response.output_text.done
data: {"type":"response.output_text.done","text":"Hello world"}

event: response.completed
data: {"type":"response.completed","response":{"id":"resp_123","status":"completed"}}

Handling the Stream

Accumulate event.delta from response.output_text.delta events, then reconcile with response.output_text.done and final metadata from response.completed. Do not read choices[0].delta.content or chunk.output[0].delta.content; those are stale Chat Completions-style patterns.

bash
# Start an SSE stream from AvalAI. A production client should parse
# event: and data: lines, branch on the event type, and handle errors.
curl https://api.avalai.ir/v1/responses \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AVALAI_API_KEY" \
  -H "Accept: text/event-stream" \
  -d '{
    "model": "gpt-5.5",
    "input": "Tell me a story.",
    "stream": true
  }' \
  --no-buffer
python
import os
from openai import OpenAI

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

stream = client.responses.create(
    model="gpt-5.5",
    input="Tell me a story.",
    stream=True,
)

print("Assistant: ", end="", flush=True)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
    elif event.type == "response.completed":
        print()
    elif event.type == "error":
        raise RuntimeError(event.error)
javascript
import OpenAI from "openai";

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

const stream = await openai.responses.create({
  model: "gpt-5.5",
  input: "Tell me a story.",
  stream: true,
});

process.stdout.write("Assistant: ");
for await (const event of stream) {
  if (event.type === "response.output_text.delta") {
    process.stdout.write(event.delta);
  } else if (event.type === "response.completed") {
    process.stdout.write("\n");
  } else if (event.type === "error") {
    throw new Error(event.error?.message || "Streaming error");
  }
}
go
package main

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

type streamEvent struct {
	Type  string `json:"type"`
	Delta string `json:"delta"`
	Error *struct {
		Message string `json:"message"`
	} `json:"error"`
}

func main() {
	payload := []byte(`{
		"model":"gpt-5.5",
		"input":"Tell me a story.",
		"stream":true
	}`)

	req, err := http.NewRequest("POST", "https://api.avalai.ir/v1/responses", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Accept", "text/event-stream")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("AVALAI_API_KEY"))

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

	fmt.Print("Assistant: ")
	scanner := bufio.NewScanner(resp.Body)
	for scanner.Scan() {
		line := scanner.Text()
		if !strings.HasPrefix(line, "data: ") {
			continue
		}

		data := strings.TrimPrefix(line, "data: ")
		if data == "[DONE]" {
			break
		}

		var event streamEvent
		if err := json.Unmarshal([]byte(data), &event); err != nil {
			continue
		}

		switch event.Type {
		case "response.output_text.delta":
			fmt.Print(event.Delta)
		case "response.completed":
			fmt.Println()
		case "error":
			if event.Error != nil {
				panic(event.Error.Message)
			}
		}
	}
}
php
<?php
$apiKey = getenv('AVALAI_API_KEY');
if (!$apiKey) {
  die("Error: AVALAI_API_KEY environment variable not set.\n");
}

$payload = json_encode([
  'model' => 'gpt-5.5',
  'input' => 'Tell me a story.',
  'stream' => true,
]);

$ch = curl_init('https://api.avalai.ir/v1/responses');
curl_setopt_array($ch, [
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => $payload,
  CURLOPT_RETURNTRANSFER => false,
  CURLOPT_HTTPHEADER => [
    'Content-Type: application/json',
    'Accept: text/event-stream',
    'Authorization: Bearer ' . $apiKey,
  ],
  CURLOPT_WRITEFUNCTION => function ($curl, $chunk) {
    foreach (explode("\n", $chunk) as $line) {
      if (!str_starts_with($line, 'data: ')) {
        continue;
      }

      $data = substr($line, 6);
      if ($data === '[DONE]') {
        return strlen($chunk);
      }

      $event = json_decode($data, true);
      if (($event['type'] ?? null) === 'response.output_text.delta') {
        echo $event['delta'] ?? '';
        flush();
      }
    }

    return strlen($chunk);
  },
]);

curl_exec($ch);
if (curl_errno($ch)) {
  fwrite(STDERR, "\nStream error: " . curl_error($ch) . "\n");
}
curl_close($ch);
echo "\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-5.5",
    instructions="You are a helpful assistant.",
    input="Tell me a story.",
)

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: "Tell me a story.",
});

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.5",
    "input": "Tell me a story.",
    "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.

Refer to the SDK documentation for specific stream handling helpers.