TokenFab Docs Center

A large LLM inference service platform, compatible with OpenAI SDK to help developers quickly build AI applications.

first_call.py
from openai import OpenAI

client = OpenAI(
    api_key="your-api-key",
    base_url="https://api.tokenfab.cn/v1"
)

resp = client.chat.completions.create(
    model="glm-5.2",
    messages=[{"role": "user", "content": "hello, TokenFab"}]
)
print(resp.choices[0].message.content)

Questions?See the FAQ or Contact Us.

Get API Key

Follow these steps to create an API key and start calling the TokenFab API.

1Create API Key

  1. Visit TokenFab Console,log in or register.
  2. Go to Console → API Keys.
  3. Click "Create API Key", enter a note, then confirm.
  4. Copy the key (format:tk-xxxx...), it cannot be viewed again after closing.

⚠️ Warning

Keep your API Key secure. Do not commit it to version control or hardcode it in frontend code.

2Configure Environment Variables

export TOKENFAB_API_KEY="your-api-key"
# Windows PowerShell
$env:TOKENFAB_API_KEY="your-api-key"

The api_key in later examples can be replaced with your key directly; if you use the environment variable above, read TOKENFAB_API_KEY in your code.

First API Call

Use the Python SDK to make your first API call.

Install Dependencies

pip install openai

Call Example

from openai import OpenAI

client = OpenAI(api_key="your-api-key", base_url="https://api.tokenfab.cn/v1")

resp = client.chat.completions.create(model="glm-5.2", messages=[{"role":"user","content":"Introduce the TokenFab platform"}])
print(resp.choices[0].message.content)

SDK Guide

TokenFab API is compatible with the OpenAI SDK.

Install

pip install openai

Initialize

from openai import OpenAI
client = OpenAI(api_key="your-api-key", base_url="https://api.tokenfab.cn/v1")

Error Handling

try:
    r = client.chat.completions.create(model="glm-5.2", messages=[{"role":"user","content":"Hello"}])
except Exception as e:
    print(f"Error: {e}")

OpenAI SDK Compatibility

TokenFab provides an OpenAI-compatible interface. Basic Chat Completions calls require only two changes to migrate; configure extensions such as Thinking Mode and Web Search according to this guide.

Config FieldOpenAITokenFab
api_keysk-xxx...tk-xxxx...
base_urlhttps://api.openai.com/v1https://api.tokenfab.cn/v1

💡 Tip

OpenAI-compatible features can be used directly; for TokenFab extensions such as Thinking Mode and Web Search, follow the corresponding sections.

Anthropic SDK Compatibility

TokenFab API is compatible with the Anthropic SDK (Messages API). Simply modify the base_url to migrate your existing Anthropic applications to TokenFab.

⚠️ Tip

Anthropic protocol currently supports the following models: glm-5.2, qwen3.7-max, qwen3.7-plus, kimi-k3

Migration Guide

Update the following two required configuration items; set the optional ANTHROPIC_AUTH_TOKEN only if your client requires it:

Environment VariableDescriptionTokenFab Configuration Value
ANTHROPIC_API_KEYAPI Keytk-xxxx...
ANTHROPIC_BASE_URLCompatible endpoint URLhttps://api.tokenfab.cn/anthropic
ANTHROPIC_AUTH_TOKENAuth token (optional, equivalent to API_KEY)tk-xxxx...

Quick Start

Text Chat

import anthropic

client = anthropic.Anthropic(
    api_key="your-api-key",
    base_url="https://api.tokenfab.cn/anthropic",
)

message = client.messages.create(
    model="glm-5.2",
    max_tokens=1024,
    messages=[{"role": "user", "content": "hello"}],
    thinking={"type": "disabled"},
)
print(message.content[0].text)

Streaming Output

with client.messages.stream(
    model="glm-5.2",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Tell me a story"}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

Integrate Claude Code

Claude Code is an AI coding assistant that runs in your terminal. By replacing the model in the configuration file, you can point Claude Code to the TokenFab API and use our models for an advanced coding experience.

Migrate from Existing Installation

If you have already installed Claude Code, follow these steps to complete the configuration:

Linux / Mac

export ANTHROPIC_BASE_URL="https://api.tokenfab.cn/anthropic"
export ANTHROPIC_AUTH_TOKEN="your-api-key"
export ANTHROPIC_DEFAULT_MODEL="glm-5.2"
export ANTHROPIC_DEFAULT_HAIKU_MODEL="glm-5.2"
export ANTHROPIC_SMALL_FAST_MODEL="glm-5.2"
export CLAUDE_CODE_DEFAULT_HAIKU_MODEL="glm-5.2"
export CLAUDE_CODE_SUBAGENT_MODEL="glm-5.2"

Windows (PowerShell)

$env:ANTHROPIC_BASE_URL="https://api.tokenfab.cn/anthropic"
$env:ANTHROPIC_AUTH_TOKEN="your-api-key"
$env:ANTHROPIC_DEFAULT_MODEL="glm-5.2"
$env:ANTHROPIC_DEFAULT_HAIKU_MODEL="glm-5.2"
$env:ANTHROPIC_SMALL_FAST_MODEL="glm-5.2"
$env:CLAUDE_CODE_DEFAULT_HAIKU_MODEL="glm-5.2"
$env:CLAUDE_CODE_SUBAGENT_MODEL="glm-5.2"

Tip

The "Migrate from Existing Installation" section above contains the configuration variables. Get the API Key from the console.

After configuration, run claude --version to verify the version. If the version displays correctly, you can proceed with the next steps.

Getting Started

cd /path/to/my-project
claude

Web Search Feature

TokenFab API supports the Claude Code Web Search feature. When the model determines your question needs searching, it returns search results with citations. Since different models have different Web Search usage, you can refer to the official Claude Code documentation.

Model Mapping

With Claude Code, we can automatically map incoming Claude model names:

Claude ModelsMaps To
claude-opus-4 / claude-opus-4-1glm-5.2
claude-sonnet-4 / claude-haiku-4glm-5.2

By modifying ~/.claude/settings.json to customize the imported Claude models for automatic mapping.

Integrate OpenClaw

OpenClaw is an open-source personal AI assistant that integrates with chat tools like Feishu and WeChat, and extends capabilities through Skills. With simple configuration, you can point OpenClaw to the TokenFab API.

Migrate from Existing Installation

If you have already installed OpenClaw, run the following command to re-enter the configuration phase and switch to the TokenFab provider:

openclaw onboard --install-daemon

Then follow the prompts:

  • When you see I understand this is personally-by-default... select Yes
  • When you see Skip onboarding by default? select No to continue configuration

Install OpenClaw

Linux / Mac

curl -fsSL https://openclaw.ai/install.sh | bash

Windows (PowerShell)

iwr -useb https://openclaw.ai/install.ps1 | iex

Configure Default Model

After first installation, it will automatically enter the configuration phase; existing users can run openclaw onboard --install-daemon to enter the configuration phase.

  1. When you see I understand this is personally-by-default... select Yes
  2. Select Setup node recommended: QuickStart
  3. When you see ModelAuth provider select TokenFab
  4. When you see Enter API key:Enter your TokenFab API Key
  5. When you see Default model:enter the model name(glm-5.2)
  6. When you see Skip permissions for... configure as needed; beginners can choose Skip for now

Getting Started

Open Web UI

openclaw dashboard

Chat in terminal

openclaw terminal

Chat with a specific model

openclaw terminal --model glm-5.2

Integrate Hermes

Hermes is an open-source self-evolving AI Agent built by Nous Research. It has a built-in learning loop that generates skills from experience, continuously optimizes during use, accumulates knowledge, and gradually builds a dynamic model around your preferred topics.

Install Hermes

Quick Install

With a single install command, you can launch the Hermes Agent in under two minutes.

Linux / macOS / WSL2

curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash

The only dependency is Git. The command clones the Hermes repository from GitHub and provides a ready-to-use set of scripts and commands.

Quick Start

  1. Run hermes setup
  2. Select Quick Setup
  3. When prompted to select a model provider, choose TokenFab
  4. Enter your TokenFab API Key
  5. Base URL::https://api.tokenfab.cn/v1
  6. Select glm-5.2 Models
  7. Continue with the remaining configuration options

Integrate WorkBuddy

WorkBuddy / CodeBuddy is an AI Agent and coding assistant tool. It supports adding custom models through local model configuration files and can connect to TokenFab using the OpenAI-compatible Chat Completions API.

Configure Model

In the WorkBuddy model configuration file, add the following JSON config. The API Key is obtained from the console. Replace ${{API_KEY}} with your actual TokenFab API Key; do not leave the placeholder in the config.

{
  "models": [
    {
      "id": "deepseek-v4-pro",
      "name": "DeepSeek V4 Pro",
      "vendor": "TokenFab",
      "url": "https://api.tokenfab.cn/v1/chat/completions",
      "apiKey": "${{API_KEY}}",
      "maxInputTokens": 128000,
      "maxOutputTokens": 8192,
      "supportsToolCall": true,
      "supportsImages": false,
      "relatedModels": {
        "lite": "deepseek-v4-flash",
        "reasoning": "deepseek-v4-pro"
      }
    },
    {
      "id": "deepseek-v4-flash",
      "name": "DeepSeek V4 Flash",
      "vendor": "TokenFab",
      "url": "https://api.tokenfab.cn/v1/chat/completions",
      "apiKey": "${{API_KEY}}",
      "maxInputTokens": 128000,
      "maxOutputTokens": 8192,
      "supportsToolCall": true,
      "supportsImages": false
    }
  ],
  "availableModels": [
    "deepseek-v4-pro",
    "deepseek-v4-flash"
  ]
}

💡 Tip

The url in the config uses the OpenAI-compatible Chat Completions endpoint. Make sure apiKey contains your actual TokenFab API Key and that the placeholder is removed.

Voucher Usage Guide

View, use, and manage your vouchers

What Is a Voucher

A voucher is a monetary benefit granted by TokenFab in the form of a virtual coupon, which can be used to offset the fees you incur from using our products. A voucher has a fixed face value and can be applied multiple times within its remaining balance, until the balance is used up or the voucher expires.

Viewing Vouchers

Sign in to TokenFab Console, go to Billing > Voucher Management, and you can view all vouchers in your account.

The list page provides the following filters to help you quickly locate a voucher:

  • Effective period: filter by the voucher's effective time range
  • Keyword search: search by voucher name or ID
  • Status filter: filter vouchers that are available, used up, expired, or voided

The voucher attributes are as follows:

AttributeDescription
Voucher IDThe unique identifier of the voucher
Face valueThe face value of the voucher
BalanceThe remaining deductible amount of the voucher
Applicable productsThe product scope eligible for voucher deduction, e.g. all products or specific products
Payment methodThe payment methods eligible for voucher deduction, e.g. pay-as-you-go
Validity periodThe valid usage period of the voucher
Granted atThe time when the voucher was credited to your account
StatusAvailable, used up, expired, or voided

Click View Details in the actions column of the list to go to the voucher details page and view the complete information of the voucher (summary, applicable products, deduction records).

How to Use Vouchers

A voucher comes with usage conditions such as the applicable product scope, eligible payment methods, and a valid usage period. For details, see the voucher details page.

Deduction Rules

  • Automatic matching: the system prioritizes vouchers that are expiring soon.
  • Multiple vouchers: if the balance of a single voucher is not enough to cover the entire bill, the system automatically applies the next available voucher and continues deducting until the bill is fully covered or all available vouchers are used up.
  • Balance payment: if any amount remains on the bill after voucher deductions, the remaining amount must be paid with your account balance.

Deduction Scope and Limitations

  • Product scope: only model invocation fees within the voucher's applicable product scope are deductible. When the applicable products are set to all products, any pay-as-you-go product can be deducted; when set to specific products, only the fees of the corresponding products are deductible. The voucher details page shall prevail.
  • No deduction of outstanding payments: vouchers cannot be used to cover historical overdue charges. Overdue charges must be paid off by topping up your account.

Viewing Deduction Details

In the Voucher Management list, click View Details to go to the voucher details page. Under "Usage Details", you can view all deduction records of the voucher, including the deduction record ID, deduction time, and deduction amount.

Usage Details supports filtering by time and transaction type, and can be exported for reconciliation.

Validity Rules

Voucher validity periods come in two types, as shown on the voucher details page:

  • Fixed period: the voucher is valid between the specified effective date and expiration date.
  • N days after grant: starts counting N days from the date the voucher is credited to your account, and expires automatically when due.

FAQ

Why hasn't my voucher been deducted from my bill?

Common reasons include:

  • Product restrictions: the product consumed in this billing cycle is not within the voucher's applicable product scope
  • Expired: the bill issuance time is past the voucher's validity period
  • Insufficient balance: the voucher is used up, so the system automatically uses another available voucher or your account balance
  • Voided: the voucher has been voided by our operations team and its balance has been cleared
  • Overdue status: when your account has overdue charges, vouchers cannot cover the overdue portion
  • Bill not yet issued: pay-as-you-go bills may take time to settle. Please check back later

If the cause still cannot be identified, verify the applicable products and validity period on the voucher details page, or contact customer support with the voucher ID (e.g. VF15474540) for troubleshooting.

Can vouchers be cashed out, withdrawn, or transferred to the account balance?

No. Vouchers cannot be converted to cash, topped up, or transferred to your account balance. They can only be used to automatically deduct pay-as-you-go bills. To top up your account, go to "Top-Up > Online Top-Up".

Can vouchers be transferred to or shared with another account?

No. Vouchers are bound to the tenant account verified at grant time and cannot be transferred to, shared with, or paid on behalf of another account. Vouchers granted to your account can only be used to deduct pay-as-you-go bills of that account.

Can expired vouchers be restored or extended?

No. Once a voucher expires, its remaining balance is automatically cleared and cannot be restored, extended, or reissued. The system deducts in the "expiring soonest first" order to help you minimize losses from expiration.

Does claiming a voucher incur any charges?

No. Vouchers credited to your account incur no fees and require no activation. Deduction is triggered only when a pay-as-you-go bill is generated from model invocations.

Can I get an invoice for the fees deducted by vouchers?

Amounts deducted by vouchers are not invoiced twice: invoices are issued based on the amount actually paid (the portion paid from your account balance), and the portion deducted by vouchers is not included in the invoiced amount. For invoicing rules, see the "Invoice Management" page.

TokenFab Console · Voucher Usage GuideLast updated: 2026-08-28 · All times are UTC+8

TokenFab Domain Change Notice

Published: September 19, 2026

Dear TokenFab users,

To standardise our domain management and improve your experience, the TokenFab website will move to www.tokenfab.cn, and the previous domain www.tokenfab.com will stop serving at 18:00 on September 21, 2026 (UTC+8). Please update your configuration and integrations in time:

1. Update your API endpoint: replace api.tokenfab.com/v1 with api.tokenfab.cn/v1 in your code, SDK configuration and environment variables (e.g. the base_url of an OpenAI-compatible SDK);

2. Update your network allowlists and bookmarks: if your corporate firewall, proxy or gateway restricts outbound traffic by domain, add the new domain to the allowlist. Also update your browser bookmarks — save the new website www.tokenfab.cn and the new console www.tokenfab.cn/console;

3. Update your callbacks and integrations: if you have configured Webhook callbacks or third-party integrations, point them to the new domain and verify connectivity.

We apologise for any inconvenience this may cause, and thank you for your continued trust and support.

Shenzhen Xiangyuan Workshop Technology Co., Ltd.
September 19, 2026

Model Overview

Learn about the available models and capabilities on TokenFab. All models share the same API.

Text Models

Models IDContextMax output tokensFeatures
glm-5.21M128KLatest flagship, 1M ultra-long context, supports Web Search
glm-5.31MSupports Web Search and tool calling
kimi-k3Flagship model; capabilities follow the API response
kimi-k2.7-code128K128KStrong coding ability, excellent math reasoning
kimi-k2.6Capabilities follow the API response
deepseek-v4-pro1M384KDeep reasoning and coding
deepseek-v4-flash1M384KFast response for coding and RAG
qwen3.7-max1M64KFlagship model for complex reasoning and agents
qwen3.7-plus128K96KBalanced quality, speed, and cost

Video Models

Models IDInputsSupported modesUse Case
viduq3-proText + imageT2V / I2V / FLF2VQuality-first, 540P / 720P / 1080P
viduq3-turboText + imageT2V / I2V / FLF2VSpeed and throughput, suited to frequent drafts
happyhorse-1.1-t2vTextT2VText-to-video, 720P / 1080P
happyhorse-1.1-i2vText + imageI2VImage-to-video, 720P / 1080P
happyhorse-1.1-r2vText + reference imagesR2VReference consistency, 1-9 images

See Video Generation Scenarios for the video endpoint request format and model parameters.

Recommended Scenarios

🏆 Best Overall — glm-5.2

1M ultra-large context, flagship performance.

💻 Coding — deepseek-v4-pro

Code generation, debugging, review.

⚡ High Concurrency — qwen3.7-max

Millisecond response, suitable for simple tasks like customer service and classification.

Token & Context Window

Understand billing units and context limits.

What is a Token

A Token is the basic unit of text processing for models:

1

English words ≈ 1 Token

1-2

Chinese characters ≈ 1-2 Tokens

usage

Actual token count returned per call

Context Window

The maximum number of tokens a model can process in one go = input + output + reasoning intermediate content.

⚠️ Warning

Exceeding the context limit may result in degraded response quality or errors.

Long Text Processing Strategies

  • Use large-context models like glm-5.2.
  • Process in segments and merge results.
  • Use keyword search or an external retrieval service to retain relevant snippets.
  • First extract key information via summarization.

Streaming Output

Real-time token-by-token output via SSE.

Enable Streaming Output

from openai import OpenAI

client = OpenAI(api_key="your-api-key", base_url="https://api.tokenfab.cn/v1")

stream = client.chat.completions.create(model="glm-5.2", messages=[{"role":"user","content":"Tell me a story"}], stream=True)
for chunk in stream:
    if chunk.choices:
        if chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)

SSE Data Format

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1784950000,"model":"glm-5.2","choices":[{"index":0,"delta":{"role":"assistant","content":"Today"},"finish_reason":null}]}
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","created":1784950000,"model":"glm-5.2","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]

Thinking Mode

Let models that support this capability perform internal reasoning before output. The example uses deepseek-v4-pro.

Enable Thinking Mode

from openai import OpenAI

client = OpenAI(api_key="your-api-key", base_url="https://api.tokenfab.cn/v1")

response = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "What are the latest AI industry trends in 2026?"}],
    extra_body={"enable_thinking":True}
)

print(response.choices[0].message.reasoning)

Note

Thinking Mode is available on models that support it, such as deepseek-v4-pro, glm-5.2, and qwen3.7-max; check the model capability configuration. In Thinking Mode, temperature and other parameters do not take effect.

Function Calling

Let the model call external tools and APIs to build agent applications.

How It Works

  1. Send request.Include user question and tool definitions.
  2. Model returns tool_calls.Function name and arguments.
  3. Execute tool.Get results.
  4. Return results.Call again to get the final answer.

Full Example

tools = [{"type":"function","function":{"name":"get_weather","description":"Check weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]
messages = [{"role":"user","content":"What is the weather like in Beijing?"}]
r1 = client.chat.completions.create(model="glm-5.2", messages=messages, tools=tools)
tc = r1.choices[0].message.tool_calls[0]
              result = "Beijing is sunny today, 25°C"
messages.append(r1.choices[0].message)
messages.append({"role":"tool","tool_call_id":tc.id,"content":result})
r2 = client.chat.completions.create(model="glm-5.2", messages=messages)
print(r2.choices[0].message.content)

Best Practices

  • Tool descriptions should be clear.Affects call accuracy.
  • Control the number of tools.Too many can reduce quality.
  • Principle of least privilege.

Multi-turn Conversation

Maintain a messages array for multi-turn contextual conversations.

Basic Usage

messages = [{"role":"user","content":"What is the weather like in Beijing?"}]
r1 = client.chat.completions.create(model="glm-5.2", messages=messages)
messages.append({"role":"assistant","content":r1.choices[0].message.content})
messages.append({"role":"user","content":"What about Shanghai?"})
r2 = client.chat.completions.create(model="glm-5.2", messages=messages)

Message Role Types

roleDescription
systemSystem instruction (optional)
userUser input
assistantModel response
toolTool execution result

JSON Mode / Structured Output

Let the model return structured data conforming to JSON Schema.

Usage Example

r = client.chat.completions.create(model="glm-5.2", messages=[{"role":"user","content":"List 3 fruits and their prices"}],
    response_format={"type":"json_schema","json_schema":{"name":"fruits","schema":{"type":"object","properties":{"fruits":{"type":"array","items":{"type":"object","properties":{"name":{"type":"string"},"price":{"type":"number"}},"required":["name","price"]}}},"required":["fruits"]}}})
print(r.choices[0].message.content)

Supported JSON Schema Types

CodeDescription
objectNested object
stringString
number / integerNumber
arrayArray
booleanBoolean
enumEnum

Async Call

Use async client for concurrent requests to improve throughput in high-concurrency scenarios.

Python Async Example

import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(api_key="your-api-key", base_url="https://api.tokenfab.cn/v1")

async def ask(q):
    r = await client.chat.completions.create(model="glm-5.2", messages=[{"role":"user","content":q}])
    print(r.choices[0].message.content)

async def main():
    tasks = [ask(q) for q in ["Summarize AI", "Translate Hello", "Recommend 3 books"]]
    await asyncio.gather(*tasks)

asyncio.run(main())

💡 Tip

Suitable for batch processing. Make sure not to exceed model rate limits.

Chat Completions API

Call large language models for chat completion.

Endpoint

POST https://api.tokenfab.cn/v1/chat/completions

Request Parameters

ParameterCodeRequiredDescription
modelstringModels ID
messagesarrayMessage array
streambooleanStreaming Output
temperaturenumberSampling temperature
max_tokensintegerMax output tokens
enable_web_searchbooleanWeb Search
toolsarrayTool definitions
response_formatobjectJSON Mode
enable_thinkingbooleanThinking Mode, available on models that support it

Request Example

curl -X POST https://api.tokenfab.cn/v1/chat/completions \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "glm-5.2",
    "messages": [
      {"role": "system", "content": "You are a translation assistant"},
      {"role": "user", "content": "Translate the following English to Chinese: Hello World"}
    ],
    "temperature": 0.7,
    "max_tokens": 1024
  }'

Response Example

{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "model": "glm-5.2",
  "choices": [{
    "index": 0,
    "message": {
      "role": "assistant",
      "content": "Hello World"
    },
    "finish_reason": "stop"
  }],
  "usage": {
    "prompt_tokens": 28,
    "completion_tokens": 5,
    "total_tokens": 33
  }
}

Models List API

Query currently available models.

Endpoint

GET https://api.tokenfab.cn/v1/models

Request Example

curl https://api.tokenfab.cn/v1/models \
  -H "Authorization: Bearer your-api-key"

Response Example

{"object":"list","data":[
  {"id":"aicc-doubao-seedance-2-0","object":"model","owned_by":"tokenfab"},
  {"id":"deepseek-v4-flash","object":"model","owned_by":"tokenfab"},
  {"id":"deepseek-v4-pro","object":"model","owned_by":"tokenfab"},
  {"id":"glm-5.2","object":"model","owned_by":"tokenfab"},
  {"id":"glm-5.3","object":"model","owned_by":"tokenfab"},
  {"id":"happyhorse-1.1-i2v","object":"model","owned_by":"tokenfab"},
  {"id":"happyhorse-1.1-r2v","object":"model","owned_by":"tokenfab"},
  {"id":"happyhorse-1.1-t2v","object":"model","owned_by":"tokenfab"},
  {"id":"kimi-k2.6","object":"model","owned_by":"tokenfab"},
  {"id":"kimi-k2.7-code","object":"model","owned_by":"tokenfab"},
  {"id":"kimi-k3","object":"model","owned_by":"tokenfab"},
  {"id":"occupancy-hold","object":"model","owned_by":"tokenfab"},
  {"id":"qwen3.7-max","object":"model","owned_by":"tokenfab"},
  {"id":"qwen3.7-max-2026-06-08","object":"model","owned_by":"tokenfab"},
  {"id":"qwen3.7-plus","object":"model","owned_by":"tokenfab"},
  {"id":"viduq3-pro","object":"model","owned_by":"tokenfab"},
  {"id":"viduq3-turbo","object":"model","owned_by":"tokenfab"}
]}

Rate Limit & Concurrency

Rate limits are calculated at the account level.

Rate Limits (RPM / TPM)

ModelsRPMTPM
glm-5.22003,000,000
deepseek-v4-pro15,0001,200,000
qwen3.7-plus30,0005,000,000
qwen3.7-max30,0005,000,000

Note

For higher concurrency needs, contact technical support to upgrade. Exceeding limits returns HTTP 429.

Error Codes

Common error codes for API calls and troubleshooting methods.

Error Response Format

{"error":{"code":"invalid_api_key","message":"Authentication failed, please check your API Key"}}

Common Error Codes

HTTPCodeTypeDescriptionSolution
401invalid_api_keyUnauthorizedInvalid API KeyCheck Authorization header
403ForbiddenNo AccessCheck permissions
404Not FoundModel Not FoundCheck model name
429Rate LimitRate LimitedReduce frequency
500Server ErrorServer ErrorWait and retry

FAQ

How to optimize costs?

Choose a model suitable for your task, reduce unnecessary context, set max_tokens appropriately, and use smaller models for testing during development.

How to handle long text?

Use large-context models like glm-5.2, process in segments and merge results, or use keyword search or an external retrieval service to retain relevant snippets.

Getting a 429 error?

Concurrency limit exceeded. Reduce call frequency, use exponential backoff retry, or request an upgrade.

Is there a billing difference between streaming and non-streaming?

No difference. Both are billed based on actual prompt_tokens + completion_tokens.

Environment variable not working?

Check: whether it's persisted in the config file, whether you restarted the IDE, and whether you used sudo.

Which programming languages are supported?

TokenFab API is compatible with the OpenAI SDK, so it supports Python, Node.js, Go, Java, and all languages with OpenAI SDKs. You can also call it directly via HTTP requests.

How to choose the right model?

For general tasks, use glm-5.2 (flagship, 1M context); for coding, use deepseek-v4-pro; for high-concurrency simple tasks, use qwen3.7-max. SeeModel Overview.

How is data security ensured?

API communication is fully encrypted via HTTPS. The platform does not store your request content for training. Data is only temporarily processed during inference. Keep your API Key secure and do not hardcode it in frontend code.

Which models support video generation?

Supports Vidu (viduq3-pro / viduq3-turbo) and HappyHorse (1.1-t2v / 1.1-i2v / 1.1-r2v) model series, covering Text-to-Video, Image-to-Video, Reference-to-Video and First-Last Frame to Video. Reference-to-Video uses HappyHorse 1.1-r2v. See Video Scenarios Overview.

LangChain Integration

TokenFab API integrates with LangChain through the OpenAI-compatible interface.

Chat Model

from langchain_openai import ChatOpenAI
llm = ChatOpenAI(model="glm-5.2", api_key="your-api-key", base_url="https://api.tokenfab.cn/v1")
response = llm.invoke("Introduce deep learning")

💡 Tip

Frameworks compatible with the OpenAI SDK, such as LlamaIndex and Semantic Kernel, can all be directly integrated.

Video Generation Scenarios

Learn about Text-to-Video (T2V), Image-to-Video (I2V), Reference-to-Video (R2V), and First-Last Frame to Video (FLF2V) to quickly understand the available video models on TokenFab, their use cases, input methods, and model selection.

Four Video Generation Modes

T2V

Text-to-Video

Input only a text prompt, and the model generates a complete video. Suitable for creative exploration without image assets.

I2V

Image-to-Video

Input an image + prompt to animate static scenes with camera movement and character actions.

R2V

Reference-to-Video

Reference images constrain characters/products/styles, reducing subject and style drift.

FLF2V

First-Last Frame to Video

First frame + last frame, the model fills in the intermediate transitions. Suitable for scene transitions and storyboard tweening.

Model-Scenario Support Matrix

ModelsT2VI2VR2VFLF2VPositioning
viduq3-proQuality-focused
viduq3-turboSpeed-focused
happyhorse-1.1-t2vText-to-Video focused
happyhorse-1.1-i2vImage-to-Video focused
happyhorse-1.1-r2vReference-to-Video focused

Choose a Scenario by Need

  1. No image assets, only text ideas → Text-to-Video T2V
  2. Have a product image/poster and want to animate it → Image-to-Video I2V
  3. Need to keep characters/products/brand style consistent → Reference-to-Video R2V
  4. Already designed the first and last frames, control the start and end → First-Last Frame to Video FLF2V

Text-to-Video T2V

Generate video from text prompts only. All video generation uses the unified POST /v1/videos endpoint to submit async tasks.

Create a Task with the Unified Endpoint

curl -X POST https://api.tokenfab.cn/v1/videos \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "happyhorse-1.1-t2v",
    "prompt": "A golden puppy running on the grass, sunny, camera following",
    "seconds": "5",
    "size": "1080P"
  }'

# Response Example
# {"id":"vid-abc123","status":"queued","created_at":"2026-07-01T12:00:00Z"}

Mode Selection Rules

ModeRequired FieldsMust OmitReference Models
Text-to-Video T2VpromptOmit input_reference, last_frame, reference_imageshappyhorse-1.1-t2v, viduq3-turbo
Image-to-Video I2Vinput_reference + promptOmit last_frame and reference_imageshappyhorse-1.1-i2v
Reference-to-Video R2Vreference_images + promptDo not pass last_frame;1-9 imageshappyhorse-1.1-r2v
First-Last Frame FLF2Vinput_reference + last_frame + promptDo not combine with reference_images togetherviduq3-turbo

Unified Request Field Reference

FieldCodePurpose
modelstringRequired, use the model ID returned by /v1/models, e.g. happyhorse-1.1-t2v, viduq3-turbo
promptstringRequired, subject/scene/action/camera/style/lighting
input_referencestringI2V source image or FLF2V first frame, public URL or Base64
last_framestringFLF2V last frame
reference_imagesstring[]R2V reference image array
secondsstringVideo duration in seconds, e.g. "3"
sizestringResolution, e.g. 720P, 1080P
watermarkbooleanWatermark toggle
negative_promptstringDescription of content to avoid
seedintegerReproducible random seed

Async Lifecycle

1. Create

POST /v1/videos returns id

2. Poll

GET /v1/videos/{id}

3. Complete

status=completed

4. Download

GET /v1/videos/{id}/content

Poll Task Status

# Query task status
curl https://api.tokenfab.cn/v1/videos/vid-abc123 \
  -H "Authorization: Bearer your-api-key"

# Response Example (processing)
# {"id":"vid-abc123","status":"processing","progress":45}

# Response Example (completed)
# {"id":"vid-abc123","status":"completed","url":"https://cdn.tokenfab.cn/...mp4"}

# Download video
curl -O https://api.tokenfab.cn/v1/videos/vid-abc123/content \
  -H "Authorization: Bearer your-api-key"

Note

Video generation tasks can take a long time. Creation is not idempotent - check for existing tasks first on network timeout, do not blindly retry POST.

Image-to-Video I2V

Input an image with a prompt to animate static scenes with camera movement, character actions, or environmental changes.

Create a Task with the Unified Endpoint

curl -X POST https://api.tokenfab.cn/v1/videos \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "happyhorse-1.1-i2v",
    "prompt": "Camera slowly pushes in, a girl slightly turns her head and smiles",
    "input_reference": "https://example.com/photo.jpg",
    "seconds": "5",
    "size": "1080P"
  }'

Integration Checklist

  • Request structure: Pass model + input_reference + prompt, omit last_frame and reference_images.
  • Image requirements:Images should be clear with distinct subjects and minimal occlusion; describe camera movement direction and elements to preserve in the prompt.
  • Image format:Only publicly accessible URLs or complete Base64 Data URLs are accepted. Do not use local paths or private network URLs.

Production Integration Tips

Polling Backoff

Start with 2-5 seconds, gradually back off, set a business timeout.

Idempotency & Tracking

Save the request ID and returned video_id; check logs first on timeout.

Security Boundaries

Do not expose API tokens on the frontend; control the expiration of public URLs.

Reference-to-Video R2V

Reference images serve as consistency constraints for subjects, products, styles, or compositions, generating new videos that match the reference. The key is reducing subject and style drift during generation.

Create a Task with the Unified Endpoint

curl -X POST https://api.tokenfab.cn/v1/videos \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "happyhorse-1.1-r2v",
    "prompt": "The person in [Image 1] walks down the street, keeping the outfit style consistent",
    "reference_images": [
      "https://example.com/ref1.jpg",
      "https://example.com/ref2.jpg"
    ],
    "seconds": "5",
    "size": "1080P"
  }'

Integration Checklist

  • Request structure: Pass model + reference_images + prompt,Omit last_frame.
  • Number of images:HappyHorse supports 1-9 reference images; Vidu does not support Reference-to-Video.
  • Prompt tips:Use [Image 1], [Image 2] to reference the order of reference images, specifying which elements must remain consistent and which can vary.

Key Differences

I2V focuses on animating the input image;R2V focuses on referencing the features of the input image,to generate new frames that remain consistent.

First-Last Frame to Video FLF2V

Provide both the first and last frames, and the model fills in the transition from A to B. Suitable for product transitions, pose changes, Before/After, and storyboard tweening.

Create a Task with the Unified Endpoint

curl -X POST https://api.tokenfab.cn/v1/videos \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "viduq3-turbo",
    "prompt": "City skyline transitioning from day to night, lights gradually turning on",
    "input_reference": "https://example.com/first_frame.jpg",
    "last_frame": "https://example.com/last_frame.jpg",
    "seconds": "5",
    "size": "1080P"
  }'

Integration Checklist

  • Request structure: Pass model + input_reference + last_frame + prompt,Must not be used with reference_images at the same time.
  • Asset tips:The subject, style, and composition of the first and last frames should be as continuous as possible. If the frames differ significantly, describe the motion path in the prompt.
  • Recommended models:ViduQ3-Pro (quality-focused) or ViduQ3-Turbo (speed-focused).