Client SDKs

    Gate AI Client SDKs provide lightweight, type-safe access to Gate AI model, media, generation usage, and credit APIs. The SDKs stay close to the HTTP API: they handle authentication, request and response types, streaming, multipart uploads, retries, and error decoding while applications retain control of orchestration and state.

    Available SDKs

    LanguagePackageRequirementsInstallation
    TypeScriptgate-ai-sdkNode.js 18+ or a modern browsernpm add gate-ai-sdk
    Gogithub.com/gate/gate-ai-go-sdkGo 1.20+go get github.com/gate/gate-ai-go-sdk

    Both SDKs are currently version 0.1.0. The TypeScript package is ESM-only. Neither SDK has third-party runtime dependencies.

    When to Use the Client SDKs

    Use the SDKs when an application needs direct access to:

    • Chat Completions and Responses APIs
    • Anthropic Messages, Gemini, and Vertex-compatible APIs
    • Embeddings
    • Image generation, editing, and result lookup
    • Speech-to-text and text-to-speech
    • Asynchronous video generation and result download
    • Generation usage and credit balance queries
    • Streaming Server-Sent Events

    The SDKs are API clients, not agent frameworks. Applications remain responsible for agent loops, tool dispatch, memory, conversation state, and other orchestration.

    Environment Variables

    VariablePurpose
    GATEAI_BASE_URLGate AI root server URL, without /openai/v1 or another API suffix
    GATEAI_API_KEYAPI key used by authenticated operations

    Both SDKs automatically read GATEAI_API_KEY when an API key or security source is not supplied explicitly.

    TypeScript Quickstart

    Installation

    bash
    1npm add gate-ai-sdk

    The package can also be installed with pnpm, yarn, or bun.

    Chat Completion

    javascript
    1import { GateAI } from "gate-ai-sdk";23const client = new GateAI(process.env.GATEAI_BASE_URL!, {4  apiKey: process.env.GATEAI_API_KEY,5});67const response = await client.chat.send({8  model: "openai/gpt-5.2",9  messages: [10    { role: "user", content: "Explain embeddings in one sentence." },11  ],12});1314console.log(response.data.choices?.[0]?.message?.content);

    Streaming

    javascript
    1const stream = await client.chat.stream({2  model: "openai/gpt-5.2",3  messages: [{ role: "user", content: "Write a short haiku." }],4});56for await (const event of stream) {7  console.log(event.data.choices?.[0]?.delta);8}

    Each event contains parsed data, original raw JSON, and optional SSE id, type, and retry metadata. Call await stream.close() when abandoning a stream before it is exhausted. A stream can be consumed only once.

    Client Configuration

    javascript
    1const client = new GateAI(serverURL, {2  apiKey: process.env.GATEAI_API_KEY,3  securitySource: async (signal) => loadRotatingAPIKey(signal),4  headers: { "X-Gate-Request-Source": "my-service" },5  userAgent: "my-service/1.0.0",6  retry: {7    maxRetries: 2,8    initialBackoffMs: 250,9    maxBackoffMs: 5_000,10  },11});

    securitySource is evaluated before each authenticated request and takes precedence over apiKey. A custom fetch implementation can be provided for testing or non-standard runtimes.

    Go Quickstart

    Installation

    bash
    1go get github.com/gate/gate-ai-go-sdk

    Chat Completion

    go
    1package main23import (4	"context"5	"fmt"6	"log"7	"os"89	gateai "github.com/gate/gate-ai-go-sdk"10	"github.com/gate/gate-ai-go-sdk/models/components"11)1213func main() {14	client, err := gateai.New(15		os.Getenv("GATEAI_BASE_URL"),16		gateai.WithAPIKey(os.Getenv("GATEAI_API_KEY")),17	)18	if err != nil {19		log.Fatal(err)20	}2122	response, err := client.Chat.Send(context.Background(), components.ChatRequest{23		Model: "openai/gpt-5.2",24		Messages: []components.ChatMessage{25			{Role: "user", Content: "Explain embeddings in one sentence."},26		},27	})28	if err != nil {29		log.Fatal(err)30	}3132	fmt.Println(response.Data.Choices[0].Message.Content)33}

    Streaming

    go
    1events, err := client.Chat.Stream(ctx, components.ChatRequest{2	Model: "openai/gpt-5.2",3	Messages: []components.ChatMessage{4		{Role: "user", Content: "Write a short haiku."},5	},6})7if err != nil {8	log.Fatal(err)9}10defer events.Close()1112for events.Next() {13	chunk := events.Value()14	fmt.Println(string(chunk.Choices[0].Delta))15}16if err := events.Err(); err != nil {17	log.Fatal(err)18}

    Value() returns the decoded event and Event() returns its SSE metadata. Always close streams. Cancelling the context closes the underlying HTTP request.

    Client Configuration

    go
    1client, err := gateai.New(2	serverURL,3	gateai.WithAPIKey(apiKey),4	gateai.WithDefaultHeader("X-Gate-Request-Source", "my-service"),5	gateai.WithUserAgent("my-service/1.0.0"),6	gateai.WithRetryConfig(gateai.RetryConfig{7		MaxRetries:     2,8		InitialBackoff: 250 * time.Millisecond,9		MaxBackoff:     5 * time.Second,10	}),11)

    Use WithSecuritySource for rotating credentials and WithHTTPClient for a custom HTTP transport or test client.

    API Resources

    CapabilityTypeScriptGoEndpoint
    Chat completionchat.send, chat.streamChat.Send, Chat.StreamPOST /openai/v1/chat/completions
    Responses APIresponses.send, responses.streamResponses.Send, Responses.StreamPOST /openai/v1/responses
    Embeddingsembeddings.generateEmbeddings.GeneratePOST /openai/v1/embeddings
    Anthropic Messagesanthropic.messages.send, streamAnthropic.Messages.Send, StreamPOST /anthropic/v1/messages
    Geminigemini.generateContent, streamGenerateContentGemini.GenerateContent, StreamGenerateContentGemini native paths
    Vertexvertex.generateContent, streamGenerateContentVertex.GenerateContent, StreamGenerateContentVertex publisher paths
    Image generationimages.generateImages.GeneratePOST /openai/v1/images/generations
    Image editingimages.editImages.EditPOST /openai/v1/images/edits
    Image lookupimages.getImages.GetGET /api/v1/images/{image_id}
    Speech-to-textstt.createTranscription, streamTranscriptionSTT.CreateTranscription, StreamTranscriptionPOST /openai/v1/audio/transcriptions
    Text-to-speechtts.createSpeech, streamSpeechTTS.CreateSpeech, StreamSpeechPOST /openai/v1/audio/speech
    Video generationvideoGeneration.generateVideoGeneration.GeneratePOST /api/v1/videos
    Video statusvideoGeneration.getGenerationVideoGeneration.GetGenerationGET /api/v1/videos/{job_id}
    Video contentvideoGeneration.getVideoContentVideoGeneration.GetVideoContentGET /api/v1/videos/{job_id}/content
    Generation usagegenerations.getGenerations.GetGET /api/v1/generation
    Credit balancecredits.getBalanceCredits.GetBalanceGET /api/v1/credits/balance

    The model-list operation is intentionally not exposed by either SDK.

    Response Handling

    TypeScript

    JSON methods return SDKResponse<T> with:

    • data : decoded response body
    • raw : original response text
    • status and headers : HTTP metadata
    • response : native Fetch Response

    Binary methods return BinaryResponse, which exposes the response stream, content type, headers, native response, and arrayBuffer(). Text-to-speech responses expose generationId when the server returns X-Gate-Generation-Id.

    Go

    JSON methods return *gateai.Response[T] with:

    • Data : decoded response body
    • Raw : exact response bytes
    • StatusCode and Header : HTTP metadata
    • HTTPResponse : original *http.Response

    Binary methods return *gateai.BinaryResponse. The caller owns and must close Body. Text-to-speech responses expose GenerationID when returned by the server.

    Errors and Retries

    TypeScript HTTP failures throw APIError; missing credentials throw MissingAPIKeyError. Go HTTP failures return *gateai.APIError; missing credentials return gateai.ErrMissingAPIKey.

    API errors retain the HTTP status, provider error type, code and message, request ID, trace ID, raw body, and original HTTP response.

    GET operations retry transient network failures and HTTP 408, 429, 500, 502, 503, and 504 responses. POST operations do not retry by default because they may be billed. Enable POST retries only when replay is safe, preferably with an idempotency key. Multipart uploads are never retried. Retry-After and retry-after-ms are respected.

    Forward-Compatible Raw Calls

    Provider-facing resources expose raw variants such as sendRaw, streamRaw, generateRaw, and generateContentRaw in TypeScript, with corresponding PascalCase methods in Go. Raw calls are useful when a provider adds fields before the SDK types are updated.

    Prefer typed methods when the required fields are already represented by the SDK.

    Detailed Documentation