Skip to main content
Developer handbook

From first request to production.

A shared entry point for language, image, video and audio workflows. Choose an available model, copy a request, and understand authentication, streaming and usage.

Create an API key

The API at a glance

One API key. The right endpoint for each workflow.

Start with a chat request, then use the same credentials for the capabilities your application needs. Every example is illustrative and runs only in your own environment.

Base URL
https://api.allgate.ai/v1

Include /v1 once for OpenAI clients. HTTP request paths below are appended to this base URL.

14Documented routes
3Text streaming dialects
BearerAPI key
POST/v1/chat/completions model gemini-4-argon

Start

Make your first request

Create a key, set your environment and choose a model from the current catalogue. Start with a small request before adding streaming or media.

1. Set the environment

.env.sh
export ALLGATE_BASE_URL='https://api.allgate.ai/v1'
export ALLGATE_API_KEY='YOUR_API_KEY'

This selector updates the chat, Responses, Messages and streaming examples. Your key and account must also permit access to the model.

Model catalogue

3. Send a request

request.sh
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-4-argon",
    "messages": [
      {"role": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "Hello, Allgate"}
    ]
  }'

Python examples use httpx (pip install httpx), SDK examples use openai (pip install openai / npm install openai). Node.js examples use modern Node.js with built-in fetch.

Authentication

Authentication & base URL

Every compatible-gateway request is authenticated with an API key. Keys are bound to a user and quota, and can be created, rotated or revoked at any time.

API key

Create one on the Keys page. The full secret is shown once on creation or rotation — store it in your secret manager immediately.

request header
Authorization: Bearer YOUR_API_KEY
Open the Keys page

Choose a client and protocol

OpenAI SDK base_url / baseURL includes /v1. Anthropic SDK base_url / baseURL uses the API origin without /v1; its client adds /v1/messages. Tools, vision and reasoning features still depend on the selected model and upstream protocol.

Examples use Authorization: Bearer. x-api-key or api-key is also accepted when Authorization is absent. An invalid explicit Authorization header never falls back to another key header. Only the documented routes are implemented; SDK support does not imply every SDK method is available.

Security practices

  • Keys are stored hashed — the plaintext cannot be recovered. Save it right after creation.
  • Use separate keys per environment and scope them with RPM/TPM limits and model allowlists.
  • Never hardcode a key in frontend code — browser traffic should go through your own backend.

Chat is a useful starting point. Responses and Messages provide different request and SSE formats; validate optional features when changing models.

Endpoint reference

Find the endpoint for your workflow

Core fields, copyable requests and example response shapes for each capability. Protocol support is separate from model supply; GET /v1/models is the final list visible to your key.

Endpoint support and model availability are separate. The public catalogue is not your key’s permission list.

A placeholder remains when no suitable model is available. Do not send it as a real model id.

Chat Completions

The recommended starting point for OpenAI-compatible chat. JSON and SSE responses are supported; multimodal input, tool calls and reasoning parameters depend on the selected model.

21 available catalogue models in this category

POST
/v1/chat/completions

Create a chat completion (JSON or SSE stream)

Request fields 4
modelstring · Required
Public model id. Use a model visible to your key via GET /v1/models.
messagesobject[] · Required
Non-empty message objects with role and content. Tool and multimodal content support is model-specific.
streamboolean · Optional
true returns an SSE stream. Parse the terminator and any error events for this endpoint’s dialect.
max_tokensinteger · Optional
Output budget in tokens. Allowed values and parameter support depend on the model.

Core fields are listed here; optional provider parameters and supported values depend on the selected model.

Request
curl.sh
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-4-argon",
    "messages": [
      {"role": "system", "content": "You are a concise assistant."},
      {"role": "user", "content": "Hello, Allgate"}
    ]
  }'
Response shape example
response.json
{
  "id": "chatcmpl-01a14b8e3c9d71f2a1b2c3d4e5f6",
  "object": "chat.completion",
  "created": 1792269000,
  "model": "gemini-4-argon",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Allgate is a unified model gateway…"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 22,
    "completion_tokens": 509,
    "total_tokens": 531
  }
}

Notes

  • Existing Chat Completions integrations usually need a new base_url, api_key and public model name. Validate any optional parameters your application uses.
  • model is a public Allgate model name; the channel’s model mapping is applied transparently upstream.

Responses

Native OpenAI Responses preserves the provider request shape. Other channels translate a stateless full conversation through Chat Completions. Translation rejects previous_response_id, conversation, item_reference, stored or background responses, built-in tools and file inputs with 400 before calling the supplier.

21 available catalogue models in this category

POST
/v1/responses

Create a response (JSON or Responses SSE)

Request fields 5
modelstring · Required
Public model id. Use a model visible to your key via GET /v1/models.
inputstring | object[] · Required
A non-empty input string or array of input items.
instructionsstring · Optional
Instructions for the response. Conversion and upstream support depend on the channel.
max_output_tokensinteger · Optional
Output budget in tokens. Allowed values and parameter support depend on the model.
streamboolean · Optional
true returns an SSE stream. Parse the terminator and any error events for this endpoint’s dialect.

Core fields are listed here; optional provider parameters and supported values depend on the selected model.

Request
curl.sh
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/responses" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-4-argon",
    "input": "Explain Allgate in one sentence, then give me three key points."
  }'
Response shape example
response.json
{
  "id": "resp_01a14b8e44aa71c2b4d7f0e1a2b3c4d5",
  "object": "response",
  "created_at": 1792269000,
  "status": "completed",
  "model": "gemini-4-argon",
  "output": [
    {
      "type": "message",
      "id": "msg_01a14b8e44ab72d3c5e8f1a2b3c4d5e6",
      "status": "completed",
      "role": "assistant",
      "content": [
        {
          "type": "output_text",
          "text": "Allgate is one gateway for every model capability…",
          "annotations": []
        }
      ]
    }
  ],
  "output_text": "Allgate is one gateway for every model capability…",
  "usage": {
    "input_tokens": 22,
    "output_tokens": 509,
    "total_tokens": 531
  }
}

Notes

  • Read message content from output; translated responses also include output_text. Streams follow the Responses event lifecycle.
  • tools, instructions and max_output_tokens depend on the model and translation path. Unlisted file, assistant and background APIs are not part of this reference.

Messages (Anthropic dialect)

The Anthropic Messages format. Native Anthropic channels preserve the dialect; compatible channels may translate to Chat Completions, with model-specific feature support.

21 available catalogue models in this category

POST
/v1/messages

Create a message (JSON or Anthropic SSE)

Request fields 5
modelstring · Required
Public model id. Use a model visible to your key via GET /v1/models.
messagesobject[] · Required
Non-empty message objects with role and content. Tool and multimodal content support is model-specific.
max_tokensinteger · Required
Output budget in tokens. Allowed values and parameter support depend on the model.
systemstring | object[] · Optional
System instructions are top-level in the Messages format.
streamboolean · Optional
true returns an SSE stream. Parse the terminator and any error events for this endpoint’s dialect.

Core fields are listed here; optional provider parameters and supported values depend on the selected model.

Request
curl.sh
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/messages" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gemini-4-argon",
    "max_tokens": 512,
    "system": "You are Allgate, a concise assistant.",
    "messages": [
      {"role": "user", "content": "Explain Allgate in one sentence."}
    ]
  }'
Response shape example
response.json
{
  "id": "msg_01a14b8e52bb73e4d6f901a2b3c4d5e6",
  "type": "message",
  "role": "assistant",
  "model": "gemini-4-argon",
  "content": [
    { "type": "text", "text": "Allgate is one OpenAI-compatible gateway in front of every model vendor." }
  ],
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": { "input_tokens": 22, "output_tokens": 24 }
}

Notes

  • Anthropic-specific cache_control, thinking and metadata require support from the native channel and model. Revalidate them when switching models.
  • Translated channels map system, multimodal content parts and tool calls onto Chat Completions.

Embeddings

Turn text into vectors for search, clustering and RAG. OpenAI-shaped embeddings request and response.

No active catalogue model in this category. These examples document the request format; a model must be enabled before you can call it.

POST
/v1/embeddings

Create text embeddings (dimensions and base64 supported)

Request fields 3
modelstring · Required
Public model id. Use a model visible to your key via GET /v1/models.
inputstring | string[] · Required
Text or a batch of texts to embed.
dimensionsinteger · Optional
Requested vector size, when the model supports dimension selection.

Core fields are listed here; optional provider parameters and supported values depend on the selected model.

Request
curl.sh
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/embeddings" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_EMBEDDING_MODEL",
    "input": ["Allgate gateway", "openai compatible gateway"]
  }'
Response shape example
response.json
{
  "object": "list",
  "data": [
    {
      "object": "embedding",
      "index": 0,
      "embedding": [0.0123, -0.0456, 0.0789]
    },
    {
      "object": "embedding",
      "index": 1,
      "embedding": [0.0234, -0.0567, 0.0891]
    }
  ],
  "model": "YOUR_EMBEDDING_MODEL",
  "usage": { "prompt_tokens": 6, "total_tokens": 6 }
}

Notes

  • input accepts a single string or an array of strings; dimensions trims the vector when the model supports it.
  • The sandbox model returns deterministic vectors, ideal for offline experiments.

Images

Generate images from a prompt. Output sizes, formats and optional parameters depend on the provider and model.

2 available catalogue models in this category

POST
/v1/images/generations

Generate images (url or b64_json)

Model names use official IDs published by the backend. Resolution, duration and quantity are separate request parameters.

FieldEnabled valuesDefault
nNumber of images1 … 10 (step 1)1
sizeImage dimensions1024x1024 · 1536x1024 · 1024x15361024x1024
qualityImage qualityauto · low · medium · highauto
output_formatImage formatpng · webp · jpegpng

The table and examples read catalog.generation.parameters from the public catalogue. These are commercially enabled workflows; other official model capabilities may not be enabled. GET /api/v1/public/models supplies these settings. Separately use GET /v1/models for the IDs accessible to your key.

Model catalogue ↗
Request fields 2
modelstring · Required
Public model id. Use a model visible to your key via GET /v1/models.
promptstring · Required
The generation prompt. Content restrictions and optional controls follow the selected model.

Core fields are listed here; optional provider parameters and supported values depend on the selected model.

Request
curl.sh
# Submit once; a lost response is not permission to repeat a paid POST.
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/images/generations" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "gpt-image-2.5-flare",
  "prompt": "A sculptural glass sphere above a calm silver sea",
  "n": 1,
  "size": "1024x1024",
  "quality": "auto",
  "output_format": "png"
}'
Response shape example
response.json
{
  "created": 1792269000,
  "data": [
    {
      "b64_json": "BASE64_IMAGE_BYTES"
    }
  ],
  "model": "gpt-image-2.5-flare"
}

Notes

  • n is an integer from 1 to 10; providers may impose a lower limit. Supported size and response_format values depend on the model.
  • Read url or b64_json from data; providers do not all return the same encoding. Generated assets are also recorded in the console media library.

Audio

Text-to-speech and speech-to-text. Speech returns binary audio; transcription accepts a multipart/form-data upload.

No active catalogue model in this category. These examples document the request format; a model must be enabled before you can call it.

Audio includes separate speech and transcription endpoints. An audio catalogue entry alone does not imply support for both.

POST
/v1/audio/speech

Text-to-speech (binary audio response)

POST
/v1/audio/transcriptions

Speech-to-text (multipart upload → JSON/text/SRT/VTT)

Request fields 5
modelstring · Required
Public model id. Use a model visible to your key via GET /v1/models.
input · speechstring · Required
Text to synthesize. Use the speech endpoint with a speech-capable model.
voice · speechstring · Required
A voice supported by the chosen speech model.
file · transcriptionbinary · Required
A multipart file upload, up to 32 MiB of audio. Let the HTTP client set the multipart boundary.
response_formatstring · Optional
For transcription: json, text, srt or vtt where supported. Speech uses its own audio format parameter.

Core fields are listed here; optional provider parameters and supported values depend on the selected model.

Text to speech
curl.sh
# text-to-speech: the response body is audio, not JSON
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/audio/speech" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"YOUR_SPEECH_MODEL","input":"Hello, Allgate","voice":"alloy","response_format":"mp3"}' \
  -o speech.mp3
Transcription
curl.sh
# speech-to-text: multipart/form-data upload
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/audio/transcriptions" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -F model='YOUR_TRANSCRIPTION_MODEL' \
  -F response_format=json \
  -F file=@sample.wav
Response shape example · Binary response
response.txt
HTTP/1.1 200 OK
content-type: audio/mpeg
x-allgate-request-id: req_01a14b8e6a2d75c4d6e7f8a9b0c1d2e3
x-allgate-model: YOUR_SPEECH_MODEL

<binary audio bytes; Content-Type follows the provider response>
Response shape example · Transcription response
response.json
{
  "text": "Welcome to Allgate.",
  "task": "transcribe",
  "language": "en",
  "duration": 1.25,
  "segments": [
    { "id": 0, "start": 0.0, "end": 1.25, "text": "…" }
  ]
}

Notes

  • The speech content-type comes from the vendor (audio/mpeg, audio/wav, …); the sandbox always returns WAV.
  • Transcription supports response_format=json|text|srt|vtt; non-JSON responses pass through unchanged.

Video (async)

Async

Video generation is asynchronous: create a task, then poll until succeeded / failed. Synchronous and asynchronous vendors share the same task semantics.

3 available catalogue models in this category

Create → save the task id → poll → read the result

queued → running → succeeded / failed / cancelled

202 means accepted into the queue, not that a video has been generated. Poll using a key belonging to the task owner; unknown and foreign task ids return 404.

POST
/v1/videos/generations

Create a video generation task (202 Accepted)

GET
/v1/videos/generations/{id}

Poll task status and result

Model names use official IDs published by the backend. Resolution, duration and quantity are separate request parameters.

FieldEnabled valuesDefault
durationDuration / seconds4 … 15 (step 1)5
resolutionOutput resolution720p720p
ratioAspect ratio16:9 · 9:16 · 1:116:9
generate_audioGenerate audiofalsefalse
output_formatVideo formatmp4mp4

The table and examples read catalog.generation.parameters from the public catalogue. These are commercially enabled workflows; other official model capabilities may not be enabled. GET /api/v1/public/models supplies these settings. Separately use GET /v1/models for the IDs accessible to your key.

Image input: true · Last-frame input: true. A last frame also requires a first frame. Each capability must be true before use.

Model catalogue ↗
Request fields 2
modelstring · Required
Public model id. Use a model visible to your key via GET /v1/models.
promptstring · Required
The generation prompt. Content restrictions and optional controls follow the selected model.

Core fields are listed here; optional provider parameters and supported values depend on the selected model.

Request
curl.sh
# Submit once; a lost response is not permission to repeat a paid POST.
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/videos/generations" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "doubao-seedance-2-0-fast",
  "prompt": "A sculptural glass sphere above a calm silver sea",
  "duration": 5,
  "resolution": "720p",
  "ratio": "16:9",
  "generate_audio": false,
  "output_format": "mp4"
}'

# Save the returned id. Resume this GET after a connection loss.
TASK_ID='YOUR_TASK_ID'
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/videos/generations/$TASK_ID" \
  -H "Authorization: Bearer $ALLGATE_API_KEY"
Response shape example · Create response · 202
response.txt
HTTP/1.1 202 Accepted

{
  "id": "01a14b8e7b3c74d5e6f7a8b9c0d1e2f3",
  "object": "video.generation",
  "status": "queued",
  "model": "doubao-seedance-2-0-fast",
  "created": 1792269000,
  "progress": 0,
  "prompt": "A sculptural glass sphere above a calm silver sea"
}
Response shape example · Poll response · 200
response.json
{
  "id": "01a14b8e7b3c74d5e6f7a8b9c0d1e2f3",
  "object": "video.generation",
  "status": "succeeded",
  "model": "doubao-seedance-2-0-fast",
  "created": 1792269000,
  "completed": 1792269005,
  "progress": 100,
  "prompt": "A sculptural glass sphere above a calm silver sea",
  "result": {
    "url": "https://media.example.com/private-video.mp4",
    "duration_secs": 5
  }
}

Notes

  • Poll about every 2 seconds with a client-side deadline. progress is a task state indicator, not a completion-time estimate.
  • Read result.url only after succeeded; handle error for failed / cancelled. Save the id and resume polling after a network interruption instead of creating a duplicate task.
ARK / API V3

Native ARK video tasks

Create and retrieve video tasks on Allgate with the official ARK request structure and Python SDK. It shares tasks, permissions and settlement with the /v1 video API.

POST
/api/v3/contents/generations/tasks

Create a task; 200 returns {id}

GET
/api/v3/contents/generations/tasks/{id}

Retrieve an owned task and its private result URL

ARK base_url is the API origin + /api/v3; OpenAI clients use /v1. Both use your Allgate Bearer key. Do not combine these path prefixes. The Python example uses arkruntime.Ark with automatic retries disabled.

Model names use official IDs published by the backend. Resolution, duration and quantity are separate request parameters.

FieldEnabled valuesDefault
durationDuration / seconds4 … 15 (step 1)5
resolutionOutput resolution720p720p
ratioAspect ratio16:9 · 9:16 · 1:116:9
generate_audioGenerate audiofalsefalse
output_formatVideo formatmp4mp4

The table and examples read catalog.generation.parameters from the public catalogue. These are commercially enabled workflows; other official model capabilities may not be enabled. GET /api/v1/public/models supplies these settings. Separately use GET /v1/models for the IDs accessible to your key.

Image input: true · Last-frame input: true. A last frame also requires a first frame. Each capability must be true before use.

Model catalogue ↗
Request fields
model
Public model id. Use a model visible to your key via GET /v1/models.
content
One {type:"text",text:"…"} item. When image input is enabled, add {type:"image_url",image_url:{url:"https://…"},role:"first_frame"}. Use last_frame for a last image, at most one per role; a last frame requires a first frame.
resolution · ratio · duration
Only the published parameters, types and values in the table are accepted. Omitted options use these same defaults. Unconfigured fields and out-of-range values return 400 unsupported_generation_parameter.
generate_audio · watermark · camera_fixed · seed · service_tier · output_format
Only the published parameters, types and values in the table are accepted. Omitted options use these same defaults. Unconfigured fields and out-of-range values return 400 unsupported_generation_parameter.
return_last_frame
Only false is accepted, and only if the parameter is published. The true last-frame file output workflow is not enabled.

callback_url, draft/draft_task, video or audio references, editing, adaptive duration (-1), unconfigured service tiers and other unpriced options are not enabled. Unsupported fields fail explicitly rather than being ignored.

Retrieve with the task id returned by Allgate. Keys belonging to the same user can resume retrieval; unknown and foreign tasks both return 404. content.video_url is a private result link. Use it as returned and retrieve the task again to refresh the URL.

A 200 creation response means accepted, not completed. Save the id and poll queued / running until succeeded / failed / cancelled. Resume GET after a connection loss; do not automatically repeat a paid POST with an unknown outcome.

ark.sh
export ALLGATE_ARK_BASE_URL='https://api.allgate.ai/api/v3'

# Submit once; a lost response is not permission to repeat a paid POST.
curl --fail-with-body --silent --show-error "$ALLGATE_ARK_BASE_URL/contents/generations/tasks" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "doubao-seedance-2-0-fast",
  "content": [
    {
      "type": "text",
      "text": "A sculptural glass sphere above a calm silver sea"
    }
  ],
  "duration": 5,
  "resolution": "720p",
  "ratio": "16:9",
  "generate_audio": false,
  "output_format": "mp4"
}'

# Save the returned id. Resume this GET after a connection loss.
TASK_ID='YOUR_TASK_ID'
curl --fail-with-body --silent --show-error "$ALLGATE_ARK_BASE_URL/contents/generations/tasks/$TASK_ID" \
  -H "Authorization: Bearer $ALLGATE_API_KEY"
Task accepted · 200 OK
create.json · 200 OK
{
  "id": "01a14b8e7b3c74d5e6f7a8b9c0d1e2f3"
}
Task completed · 200 OK
task.json · 200 OK
{
  "id": "01a14b8e7b3c74d5e6f7a8b9c0d1e2f3",
  "model": "doubao-seedance-2-0-fast",
  "status": "succeeded",
  "created_at": 1792269000,
  "updated_at": 1792269005,
  "resolution": "720p",
  "ratio": "16:9",
  "duration": 5,
  "generate_audio": false,
  "content": {
    "video_url": "https://media.example.com/private-video.mp4"
  }
}
Official ARK SDK and protocol reference ↗
ARK / MATERIALS

Material management, with official request semantics.

Organize media in your library and reference persistent asset://IDs in code. Authentication depends on the channel: official ARK uses AK/SK signing for materials; Letsllm native ARK uses your Allgate Bearer API key.

Material control plane

POST https://api.allgate.ai/?Action=CreateAsset&Version=2024-01-01

For official ARK material requests, use AK/SK HMAC-SHA256 signing, Region=cn-beijing and Service=ark. Create native credentials bound to your own API key in the signed-in asset library.

Video generation data plane

POST https://api.allgate.ai/api/v3/contents/generations/tasks

For Letsllm native ARK materials and video generation, use Authorization: Bearer <Allgate API key>. Official ARK material requests use separate AK/SK credentials.

Supported official material actions
ActionPurpose
CreateAssetGroupCreate an AIGC group
GetAssetGroupGet a group
ListAssetGroupsFilter and paginate groups
UpdateAssetGroupUpdate name and description
DeleteAssetGroupDelete a group and its assets
CreateAssetImport an asset asynchronously from a public URL
GetAssetGet status and a temporary preview URL
ListAssetsPaginate by group, name and status
UpdateAssetUpdate an asset name
DeleteAssetDelete an asset
CreateVisualValidateSessionStart real-person H5 verification
GetVisualValidateResultVerify the result and obtain the person group

Use the official Python SDK

Save the AK/SK shown once in the library. This example creates an AIGC group, imports an image and polls its real state. It does not repeat an uncertain create.

terminal
pip install volcengine-python-sdk
assets.py
import os, time
import volcenginesdkcore

config = volcenginesdkcore.Configuration()
config.host = "api.allgate.ai"
config.scheme = "https"
config.region = "cn-beijing"
config.ak = os.environ["ALLGATE_ARK_AK"]
config.sk = os.environ["ALLGATE_ARK_SK"]
config.auto_retry = False  # do not repeat a create with an unknown outcome
client = volcenginesdkcore.ApiClient(config)
project = os.environ.get("ALLGATE_ARK_PROJECT", "default")

def call(action, body):
    reply = client.call_api(
        f"/{action}/2024-01-01/ark/post/application_json/", "POST",
        path_params={}, query_params=[],
        header_params={"Content-Type": "application/json"},
        body={**body, "ProjectName": project}, post_params=[], files={},
        response_type="object", auth_settings=["volcengineSign"],
        _return_http_data_only=True, collection_formats={})
    if "Error" in reply["ResponseMetadata"]:
        raise RuntimeError(reply["ResponseMetadata"]["Error"])
    return reply["Result"]

group_id = call("CreateAssetGroup", {
    "Name": "Product references", "GroupType": "AIGC"})["Id"]
asset_id = call("CreateAsset", {
    "GroupId": group_id, "AssetType": "Image",
    "Name": "Product image", "URL": os.environ["PUBLIC_IMAGE_URL"]})["Id"]

deadline = time.monotonic() + 300
while time.monotonic() < deadline:
    asset = call("GetAsset", {"Id": asset_id})
    if asset["Status"] == "Active":
        print(f"asset://{asset_id}")
        break
    if asset["Status"] == "Failed":
        raise RuntimeError("Asset processing failed; inspect GetAsset.")
    time.sleep(3)
else:
    raise TimeoutError("Still processing; keep the asset ID and query again.")

Queries and pagination

ListAssets / ListAssetGroups require Filter.GroupType. Prefer MaxResults (1–100) with NextToken. A next token appears only when another page exists; keep the same filters. PageNumber / PageSize are also supported together and cannot be mixed with cursor parameters. Results contain only objects owned by your account.

ListAssets.json
{
  "ProjectName": "default",
  "Filter": {"GroupType": "AIGC", "Statuses": ["Active"]},
  "MaxResults": 20
}

Real-person verification

Call CreateVisualValidateSession with CallbackURL and ProjectName, then complete verification at H5Link. BytedToken expires in 30 minutes. Call GetVisualValidateResult after the callback to verify server-side and obtain GroupId. A resultCode or redirect alone does not prove success. LivenessFace groups are created through this official flow.

Use assets in video generation

The content fragment below applies to a model with the corresponding published reference capabilities and tariff scope. Use its exact current catalogue model ID. Image, video and audio indices each follow their order in content. The studio shows supported types and limits; do not infer them from a model name.

content.json
[
  {"type":"text","text":"A cinematic scene. Keep the person in image 1 and the movement in video 1."},
  {"type":"image_url","image_url":{"url":"asset://YOUR_IMAGE_ID"},"role":"reference_image"},
  {"type":"video_url","video_url":{"url":"asset://YOUR_VIDEO_ID"},"role":"reference_video"},
  {"type":"audio_url","audio_url":{"url":"asset://YOUR_AUDIO_ID"},"role":"reference_audio"}
]

Frame workflows use first_frame / last_frame and cannot mix with reference_image / reference_video / reference_audio; a last frame requires a first frame. Only Active assets are usable. Assets in one task must belong to the same configured project and channel. Assets are account-private and tasks do not fail over to another supplier account.

  • Asset imports accept public HTTP(S) URLs, not Base64. Images: under 30 MB. Video: 2–30 seconds, up to 200 MB. Audio: 2–30 seconds, up to 15 MB. See the official reference for full format, dimension and supplier entitlement requirements.
  • Processing / Active / Failed reflect supplier state. GetAsset preview URLs expire after 12 hours; query again to renew them. Use asset IDs as persistent identifiers.
  • Success responses contain ResponseMetadata and Result. Errors use ResponseMetadata.Error with a request ID. For UpstreamOutcomeUnknown, query or contact support before creating again. Deleting a group also deletes its assets and cannot be undone.
  • Token-priced video reserves the published budget, then settles on supplier-reported completion_tokens. A configured flat workflow tariff is not compared against an official price for a different parameter scope.

Rerank

Re-order candidate documents by relevance to a query, with Cohere / Jina-style request and response shapes.

No active catalogue model in this category. These examples document the request format; a model must be enabled before you can call it.

POST
/v1/rerank

Rerank documents (returns relevance scores)

Request fields 4
modelstring · Required
Public model id. Use a model visible to your key via GET /v1/models.
querystring · Required
The search query used to rank documents.
documentsstring[] | object[] · Required
Candidate strings or objects containing text.
top_ninteger · Optional
Maximum number of ranked results to return.

Core fields are listed here; optional provider parameters and supported values depend on the selected model.

Request
curl.sh
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/rerank" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "YOUR_RERANK_MODEL",
    "query": "Allgate model gateway",
    "documents": [
      "The weather is nice today",
      "Allgate is a unified model gateway",
      "A cat is sitting on a mat"
    ],
    "top_n": 2
  }'
Response shape example
response.json
{
  "id": "rerank-01a14b8e8c5d76f7a8b9c0d1e2f3a4b5",
  "object": "rerank",
  "model": "YOUR_RERANK_MODEL",
  "results": [
    { "index": 1, "relevance_score": 0.792937 },
    { "index": 2, "relevance_score": 0.412108 }
  ],
  "usage": { "prompt_tokens": 31, "total_tokens": 31 }
}

Notes

  • documents accepts strings or { text } objects; top_n limits the result count.

Models

List the public models available to this key and retrieve a single entry by model name.

GET
/v1/models

List available models

GET
/v1/models/{model}

Retrieve a single model

List models
curl.sh
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/models" \
  -H "Authorization: Bearer $ALLGATE_API_KEY"
Retrieve model
curl.sh
curl --fail-with-body --silent --show-error "$ALLGATE_BASE_URL/models/gemini-4-argon" \
  -H "Authorization: Bearer $ALLGATE_API_KEY"
Response shape example · List response
response.json
{
  "object": "list",
  "data": [
    { "id": "gemini-4-argon", "object": "model", "created": 1704067200, "owned_by": "Allgate" }
  ]
}
Response shape example · Retrieve response
response.json
{
  "id": "gemini-4-argon",
  "object": "model",
  "created": 1704067200,
  "owned_by": "Allgate"
}

Notes

  • The payload matches OpenAI /v1/models and only includes models served by at least one healthy channel.
  • The key’s model allowlist applies to both this list and actual routing.

Streaming

Server-sent events

Set stream to true and the response becomes an incremental text/event-stream. Allgate accounts token usage and time-to-first-token when the stream ends.

01

Set "stream": true and send Accept: text/event-stream.

02

Each data: line is one incremental event; event names depend on the client dialect (three dialects below).

03

When the stream ends the connection closes; [DONE], message_stop and response.completed are the per-dialect terminators.

Three client dialects

OpenAI SSE

The default stream format for OpenAI-compatible endpoints; every event is a chat.completion.chunk.

  1. 1 chat.completion.chunk (delta.content)
  2. 2 chat.completion.chunk (finish_reason)
  3. 3 chat.completion.chunk (usage, optional)
  4. 4 [DONE]
Terminates with data: [DONE]
Open a stream
stream.sh
curl -N "$ALLGATE_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $ALLGATE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "model": "gemini-4-argon",
    "stream": true,
    "stream_options": {"include_usage": true},
    "messages": [{"role": "user", "content": "Explain Allgate step by step"}]
  }'

Usage, TTFT and aborts

  • Billing uses the actual tokens when the stream ends; when an upstream omits usage the gateway falls back to a conservative estimate.
  • x-allgate-request-id, x-allgate-model and x-allgate-channel are returned as headers; x-allgate-cost-micros is only available on unary responses.
  • Client disconnects cancel the upstream request and finalize usage exactly once.

Client parsing example

Parse SSE incrementally and inspect terminal events. HTTP 200 does not guarantee success: an error event or unexpected EOF without a terminator is a failure. Delivered partial output can still incur usage.

stream.py
import json
import os
import httpx

base = os.environ["ALLGATE_BASE_URL"]
headers = {"Authorization": "Bearer " + os.environ["ALLGATE_API_KEY"]}

with httpx.stream(
    "POST",
    base + "/chat/completions",
    headers=headers,
    json={
        "model": "gemini-4-argon",
        "stream": True,
        "messages": [{"role": "user", "content": "Explain Allgate step by step"}],
    },
    timeout=None,
) as response:
    response.raise_for_status()
    for line in response.iter_lines():
        if not line.startswith("data:"):
            continue
        payload = line[5:].strip()
        if payload == "[DONE]":
            break
        event = json.loads(payload)
        if "error" in event:
            raise RuntimeError(event["error"]["message"])
        choices = event.get("choices", [])
        if choices:
            print(choices[0].get("delta", {}).get("content", ""), end="", flush=True)

Errors

Error envelopes and codes

OpenAI-compatible endpoints return the OpenAI error envelope; /v1/messages returns the Anthropic envelope. Messages are sanitized — keys and headers are never included.

OpenAI endpoints · OpenAI envelope
error.openai.json
{
  "error": {
    "message": "The model `unknown-model` does not exist or you do not have access to it.",
    "type": "invalid_request_error",
    "param": null,
    "code": "model_not_found"
  }
}
Messages endpoint · Anthropic envelope
error.anthropic.json
{
  "type": "error",
  "error": {
    "type": "not_found_error",
    "message": "The model `unknown-model` does not exist or you do not have access to it."
  }
}
StatustypecodeMeaning
400invalid_request_errorinvalid_json / invalid_model / invalid_requestMalformed request, parameters or JSON.
401authentication_errorinvalid_api_keyAPI key missing, invalid or revoked.
402insufficient_quotainsufficient_balance / quota_exceededInsufficient balance, or this key reached its spend quota.
403permission_errorapi_key_unusable / account_disabled / activation_requiredKey disabled or expired, account inactive, or account activation is required before the first request. Complete activation in Billing; activated Free and Paid have the same model capabilities.
404invalid_request_errormodel_not_foundUnknown, inactive or not in the key’s model allowlist.
424api_errorupstream_outcome_unknownAn image or speech request has an uncertain supplier outcome. x-should-retry: false means no automatic POST retry; check request logs and supplier results first.
429rate_limit_errorrate_limit_exceededRPM / TPM limit hit — retry after Retry-After.
500server_errorinternal_errorInternal gateway error; it has been logged.
502connection_error / upstream_errorupstream_unreachable / upstream_errorUpstream failed before producing output: no charge. A stream that already delivered output can still incur usage.
503api_errorno_available_channelEvery candidate channel is cooling down; wait for Retry-After before trying again.
504timeout_errorupstream_timeout / request_timeoutThe request exceeded a deadline. Check usage logs and any created task before retrying a generation request.

Before you retry

Record x-request-id / x-allgate-request-id and check Usage logs. A request id is assigned by the server; sending your own does not provide client-side idempotency. An image or speech POST returning 424 upstream_outcome_unknown with x-should-retry: false has an uncertain supplier outcome: check logs before resubmitting. Do not retry it automatically. Task polling GETs can be retried.

Usage logs

/v1/messages also returns the Anthropic envelope for authentication and rate-limit errors: {"type":"error","error":{"type":"authentication_error","message":"…"}}.

Rate limits

Rate limits and headers

Activated Free and Paid accounts have the same account speed and available model capabilities, with no automatic account RPM/TPM ceiling or fixed media-task cap. Explicit key limits, spendable balance, account status and supplier capabilities still apply. Actual window limits return 429 with Retry-After.

Headers

HeaderMeaning
X-RateLimit-Limit-RequestsRequest budget for the enforced key or account RPM window.
X-RateLimit-Remaining-RequestsRemaining requests in the current window.
X-RateLimit-Limit-TokensEstimated input-token budget for the enforced key or account TPM window.
X-RateLimit-Remaining-TokensRemaining tokens in the current window.
Retry-AfterSeconds until the request may be retried.
429 example
rate-limit.http
HTTP/1.1 429 Too Many Requests
Retry-After: 2
X-RateLimit-Limit-Requests: 2
X-RateLimit-Remaining-Requests: 0
X-RateLimit-Limit-Tokens: 240000
X-RateLimit-Remaining-Tokens: 239812

{
  "error": {
    "message": "Rate limit reached for requests per minute — retry in 2s.",
    "type": "rate_limit_error",
    "param": null,
    "code": "rate_limit_exceeded"
  }
}

Respect Retry-After and use backoff with jitter. Unenforced windows omit their limit headers. The numbers above illustrate the response format; they are not plan allowances.

Production essentials

Understand usage before scaling

The catalogue lists public prices. Your account, model and pricing policy determine the effective rate; inspect the console for the final charge.

Match the unit to the workload

Chat models are typically priced by input/output tokens. Other models may use images, seconds, characters or requests. Read the model’s price unit rather than assuming every endpoint is token-priced.

A reservation is not the final charge

Requests reserve estimated capacity before dispatch and settle measured usage. Async video settles on completion. Completed /v1 video tasks expose cost_micros; inspect usage logs for native ARK charges.

Partial output still has usage

The initial hold is an estimate, not an output cap. Holds grow atomically as streaming usage increases when balance and key quota cover the increase. Only a real balance, key-quota or service-validation failure stops delivery. Delivered usage is retained and settled on completion, error or disconnect.

Keep a trace for every request

x-allgate-request-id identifies the gateway call; x-allgate-model and x-allgate-channel describe routed responses. x-allgate-cost-micros is available on unary responses when the cost is known, not in the initial SSE headers.

Save task ids, protect output URLs

Store the task id and fetch status again to resume an async workflow. Result URLs can be temporary: use the returned URL as-is, keep signed URLs private, and retrieve task status again when you need a fresh link.

Sandbox

Sandbox: test the pipeline with demo outputs

Allgate supports an offline sandbox channel for chat, embeddings, images, video, audio and rerank request flows. A sandbox model is callable only when an operator enables it and makes it visible to your key.

Offline demo channel

Sandbox outputs are demo data, not provider model quality. An Allgate API key is still required; catalogue visibility and account policy apply. Sandbox support is not a promise of free calls.

Sandbox model catalogue

Sandbox model ids are examples, not an availability list. Check GET /v1/models before using them.

ModelCapabilityOutput
allgate-sandbox-chatChat / streaming MarkdownBilingual Markdown with usage and TTFT
allgate-sandbox-embeddingDeterministic text vectorsFloat arrays or base64 vectors
allgate-sandbox-imageText to imageSVG artwork file /media/…
allgate-sandbox-videoAsync text to videoAnimated SVG task result /media/…
allgate-sandbox-ttsText to speech / transcriptionPlayable WAV (speech) / demo transcript
allgate-sandbox-rerankRelevance rerankRanked relevance scores

Ready to connect your application?

Keep credentials on your server, validate a small request and inspect its usage before increasing traffic.

Create an API key

Integration questions, answered.

How do I connect to the Allgate API?
Create an account and API key. For an OpenAI-compatible client, set the base URL to https://api.allgate.ai/v1 and choose a currently available model ID from the catalogue. Follow the protocol-specific setup in the reference for other SDKs. HTTP examples use a Bearer token; keep keys on your server.
Does a documented endpoint guarantee model availability?
The API reference describes request formats. The live catalogue lists models and their current routing availability. An endpoint does not mean that every model or capability has an available route.
Where can I check request formats and costs?
The public API reference covers authentication, request shapes, streaming and errors. Model detail pages publish billing units and base rates; your console shows the applicable account price.

Catalogue snapshot: · Public model data · Models and prices · Image and video Studio · API reference