API Documentation

Complete guide to integrating ZachAI. 100% OpenAI-compatible — drop-in replacement.

Quick Start

  1. 1Sign up and create an API key in the API Keys page.
  2. 2Install the OpenAI SDK: pip install openai or npm install openai
  3. 3Set base_url to https://your-domain.com/api/v1 and use your ZachAI key.
Python — Quick Start
python
# Using the official OpenAI SDK (recommended)
from openai import OpenAI

client = OpenAI(
    api_key="sk-zacht-...",
    base_url="https://your-domain.com/api/v1",
)

# Non-streaming
response = client.chat.completions.create(
    model="zachai-reason",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Write a Python function to check if a number is prime."},
    ],
)
print(response.choices[0].message.content)
print(f"Usage: {response.usage.total_tokens} tokens")
JavaScript — Quick Start
javascript
// Using the official OpenAI SDK for Node.js
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: "sk-zacht-...",
  baseURL: "https://your-domain.com/api/v1",
});

const response = await client.chat.completions.create({
  model: "zachai-reason",
  messages: [
    { role: "user", content: "What is the capital of France?" },
  ],
});

console.log(response.choices[0].message.content);
console.log(`Usage: ${response.usage.total_tokens} tokens`);

API Reference

POST/v1/chat/completions

Creates a model response for the given chat conversation. Fully compatible with the OpenAI Chat Completions API.

Request Body

ParameterTypeRequiredDescription
modelstringYesModel ID: "zachai-flash", "zachai-reason", or "zachai-pro"
messagesarrayYesArray of message objects with role and content
temperaturenumberNo0-2, default 0.7. Higher = more creative
max_tokensintegerNoMax output tokens (default 8192)
streambooleanNoEnable SSE streaming (default false)
top_pnumberNoNucleus sampling, 0-1 (default 1)
stopstring/arrayNoUp to 4 stop sequences
GET/v1/models

Returns the list of available models with pricing, context length, and performance metrics.

GET/health

Health check endpoint for monitoring. Returns service status, database connectivity, and deployment region.

Streaming Responses

ZachAI supports Server-Sent Events (SSE) streaming for real-time, token-by-token responses. Set stream: true in your request.

Python — Streaming
python
# Streaming with OpenAI SDK
from openai import OpenAI

client = OpenAI(
    api_key="sk-zacht-...",
    base_url="https://your-domain.com/api/v1",
)

stream = client.chat.completions.create(
    model="zachai-flash",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True,
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
JavaScript — Streaming
javascript
// Streaming in Node.js
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: "sk-zacht-...",
  baseURL: "https://your-domain.com/api/v1",
});

const stream = await client.chat.completions.create({
  model: "zachai-flash",
  messages: [{ role: "user", content: "Write a poem about the sea" }],
  stream: true,
});

for await (const chunk of stream) {
  const content = chunk.choices[0]?.delta?.content;
  if (content) process.stdout.write(content);
}
curl — Streaming
bash
# Streaming response (SSE)
curl -X POST https://your-domain.com/api/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer sk-zacht-..." \
  -d '{
    "model": "zachai-flash",
    "messages": [
      { "role": "user", "content": "Write a haiku about coding" }
    ],
    "stream": true
  }'

Advanced Examples

Multi-Turn Conversation

Python — Multi-turn chat
python
# Multi-turn conversation
from openai import OpenAI

client = OpenAI(api_key="sk-zacht-...", base_url="https://your-domain.com/api/v1")

messages = [{"role": "system", "content": "You are a coding tutor."}]

while True:
    user_input = input("You: ")
    if user_input.lower() in ["quit", "exit"]:
        break

    messages.append({"role": "user", "content": user_input})

    response = client.chat.completions.create(
        model="zachai-reason",
        messages=messages,
    )

    reply = response.choices[0].message.content
    print(f"AI: {reply}")
    messages.append({"role": "assistant", "content": reply})

Go

Go — Using go-openai
go
// Using the OpenAI Go SDK
package main

import (
    "context"
    "fmt"
    openai "github.com/sashabaranov/go-openai"
)

func main() {
    config := openai.DefaultConfig("sk-zacht-...")
    config.BaseURL = "https://your-domain.com/api/v1"
    client := openai.NewClientWithConfig(config)

    resp, err := client.CreateChatCompletion(context.Background(),
        openai.ChatCompletionRequest{
            Model: "zachai-reason",
            Messages: []openai.ChatCompletionMessage{
                {Role: "user", Content: "Hello, what is 2+2?"},
            },
        },
    )
    if err != nil {
        panic(err)
    }
    fmt.Println(resp.Choices[0].Message.Content)
}

Error Handling

ZachAI uses standard HTTP status codes. Here's how to handle common errors:

Status CodeError TypeMeaning
200OKRequest successful
400Bad RequestInvalid request body or parameters
401UnauthorizedMissing or invalid API key
402Payment RequiredInsufficient balance
429Rate LimitToo many requests. Retry after delay
500Server ErrorInternal error. Retry with backoff
503Service UnavailableUpstream model temporarily unavailable
Python — Error handling with retries
python
# Error handling with retries
import openai
from openai import OpenAI
import time

client = OpenAI(api_key="sk-zacht-...", base_url="https://your-domain.com/api/v1")

def chat_with_retry(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model="zachai-reason",
                messages=messages,
            )
            return response.choices[0].message.content
        except openai.RateLimitError:
            wait = 2 ** attempt
            print(f"Rate limited, waiting {wait}s...")
            time.sleep(wait)
        except openai.APIStatusError as e:
            if e.status_code >= 500:
                print(f"Server error {e.status_code}, retrying...")
                time.sleep(2 ** attempt)
            else:
                raise

    raise Exception("Max retries exceeded")

Models & Pricing

ModelBase ModelContextTTFTInput $/MOutput $/M
zachai-flashDeepSeek V4 Flash128K~180ms$0.08$0.18
zachai-reasonGLM 5.3128K~350ms$0.30$0.65
zachai-proHunyuan 3128K~600ms$0.75$1.60

All prices in USD per million tokens. Powered by Tencent Cloud TokenHub.

Rate Limits

2,000 requests/min per API key
2M prompt tokens/min per API key
1M completion tokens/min per API key
Rate limit headers included in every response: X-RateLimit-Remaining, X-RateLimit-Reset
When rate limited (429), wait and retry. The Retry-After header tells you how long to wait.

Infrastructure & Compliance

Deployment Region

AP-Singapore. All inference runs on servers in Singapore.

Model License

Models powered by Tencent Cloud TokenHub. Commercial use included with all plans.

Uptime Target

99.9% uptime SLA. Health check available at /health.

Data Storage

API keys stored as SHA-256 hashes. Usage logs retained for 30 days. No prompt content stored.

Ready to Build?

Get your API key and start in 2 minutes.

Get Your API Key