gateai

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 19 Imported by: 0

README

Gate AI Go SDK

A lightweight, type-safe Go client for calling Gate AI model and media APIs. The SDK stays close to the HTTP API: it handles authentication, typed request and response envelopes, streaming, multipart uploads, retries, and error decoding while your application owns orchestration and conversation state.

Documentation: https://gate.ai/docs

Languages: English | 简体中文

When to Use This SDK

Use the client when your application needs direct access to:

  • Chat Completions and Responses APIs
  • Anthropic Messages, Gemini, and Vertex-compatible APIs
  • Embeddings and image generation or editing
  • Speech-to-text and text-to-speech, including streaming
  • Asynchronous video generation and result download
  • Generation usage and credit balance queries

This is an API client, not an agent framework. Agent loops, tool dispatch, memory, and application state remain in your code.

Requirements

  • Go 1.20 or newer
  • A Gate AI base URL
  • A Gate AI API key for authenticated operations

The module has no third-party runtime dependencies.

Installation

go get github.com/gate/gate-ai-go

Quickstart

Set the base URL to the Gate AI root URL. Do not append an API suffix such as /openai/v1. Custom reverse-proxy path prefixes are preserved, so a base URL such as https://proxy.example.com/gateai routes requests under /gateai.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	gateai "github.com/gate/gate-ai-go"
	"github.com/gate/gate-ai-go/models/components"
)

func main() {
	client, err := gateai.New(
		gateai.DefaultBaseURL,
		gateai.WithAPIKey(os.Getenv("GATEAI_API_KEY")),
	)
	if err != nil {
		log.Fatal(err)
	}

	response, err := client.Chat.Send(context.Background(), components.ChatRequest{
		Model: "openai/gpt-5.2",
		Messages: []components.ChatMessage{
			{Role: "user", Content: "Explain embeddings in one sentence."},
		},
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(response.Data.Choices[0].Message.Content)
}

The client reads GATEAI_API_KEY automatically when neither WithAPIKey nor WithSecuritySource is supplied.

Streaming

Streaming operations return a context-aware Server-Sent Events reader.

events, err := client.Chat.Stream(ctx, components.ChatRequest{
	Model: "openai/gpt-5.2",
	Messages: []components.ChatMessage{
		{Role: "user", Content: "Write a short haiku."},
	},
})
if err != nil {
	log.Fatal(err)
}
defer events.Close()

for events.Next() {
	chunk := events.Value()
	fmt.Println(string(chunk.Choices[0].Delta))
}
if err := events.Err(); err != nil {
	log.Fatal(err)
}

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

API Reference

The client exposes resources grouped by API domain:

Resource Main operations
Chat Chat completions and streaming
Responses Responses API calls and streaming
Embeddings Vector embeddings
Anthropic.Messages Anthropic-compatible messages
Gemini, Vertex Gemini-compatible content generation
Images Image generation and editing
STT, TTS Speech transcription and synthesis
VideoGeneration Submit, inspect, and download video jobs
Generations Query persisted generation usage
Credits Query the current credit balance

See the Go API Reference for method signatures, endpoints, response types, raw-call variants, and request options.

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

Client Configuration

client, err := gateai.New(
	gateai.DefaultBaseURL,
	gateai.WithAPIKey(apiKey),
	gateai.WithDefaultHeader("X-Gate-Request-Source", "my-service"),
	gateai.WithUserAgent("my-service/1.0.0"),
	gateai.WithRetryConfig(gateai.RetryConfig{
		MaxRetries:     2,
		InitialBackoff: 250 * time.Millisecond,
		MaxBackoff:     5 * time.Second,
	}),
)

gateai.DefaultBaseURL is the production API root, https://api.gate.ai. Pass a different absolute HTTP or HTTPS URL to use a proxy, test environment, or other deployment.

Use WithSecuritySource for credentials that rotate between calls and WithHTTPClient to supply a custom transport or test client.

Responses and Errors

JSON operations return *gateai.Response[T], which contains:

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

Binary operations return *gateai.BinaryResponse. The caller owns and must close Body. Text-to-speech responses also expose GenerationID when the server returns X-Gate-Generation-Id.

HTTP failures return *gateai.APIError. Use errors.As to inspect status, provider error type, code and message, request ID, trace ID, raw body, and the HTTP response. Missing credentials fail before a request is sent with gateai.ErrMissingAPIKey.

GET requests retry transient network failures and HTTP 408, 429, 500, 502, 503, and 504 responses. POST requests do not retry by default because they may be billed. Use WithRequestRetries or WithIdempotencyKey only when replay is safe. Multipart uploads are never retried. Retry-After and retry-after-ms are respected; when both are present, retry-after-ms takes precedence.

The default HTTP client has no whole-response timeout so long-lived streams are not interrupted. Use context deadlines or WithHTTPClient to control timeouts.

Examples

Development

go test ./...
go vet ./...

The canonical HTTP contract is maintained in the Gate AI documentation.

Documentation

Overview

Package gateai provides a dependency-free Go client for Gate AI's public model invocation, media, generation, and credits APIs.

Index

Constants

View Source
const (
	SDKVersion     = "0.1.0"
	DefaultBaseURL = "https://api.gate.ai"
)

Variables

View Source
var ErrMissingAPIKey = errors.New("gateai: API key is required for this operation")

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode   int
	Type         string
	Code         string
	Message      string
	RequestID    string
	TraceID      string
	Body         []byte
	HTTPResponse *http.Response
}

func (*APIError) Error

func (e *APIError) Error() string

type Anthropic

type Anthropic struct {
	Messages *AnthropicMessages
}

type AnthropicMessages

type AnthropicMessages struct {
	// contains filtered or unexported fields
}

func (*AnthropicMessages) Send

func (*AnthropicMessages) SendRaw

func (resource *AnthropicMessages) SendRaw(ctx context.Context, request json.RawMessage, options ...RequestOption) (*Response[json.RawMessage], error)

func (*AnthropicMessages) Stream

func (*AnthropicMessages) StreamRaw

func (resource *AnthropicMessages) StreamRaw(ctx context.Context, request json.RawMessage, options ...RequestOption) (*stream.EventStream[json.RawMessage], error)

type BinaryResponse

type BinaryResponse struct {
	Body         io.ReadCloser
	StatusCode   int
	Header       http.Header
	ContentType  string
	GenerationID string
	HTTPResponse *http.Response
}

type Chat

type Chat struct {
	// contains filtered or unexported fields
}

func (*Chat) Send

func (resource *Chat) Send(ctx context.Context, request components.ChatRequest, options ...RequestOption) (*Response[components.ChatCompletion], error)

func (*Chat) SendRaw

func (resource *Chat) SendRaw(ctx context.Context, request json.RawMessage, options ...RequestOption) (*Response[json.RawMessage], error)

func (*Chat) Stream

func (*Chat) StreamRaw

func (resource *Chat) StreamRaw(ctx context.Context, request json.RawMessage, options ...RequestOption) (*stream.EventStream[json.RawMessage], error)

type Credits

type Credits struct {
	// contains filtered or unexported fields
}

func (*Credits) GetBalance

func (resource *Credits) GetBalance(ctx context.Context, options ...RequestOption) (*Response[components.CreditsBalanceEnvelope], error)

type Embeddings

type Embeddings struct {
	// contains filtered or unexported fields
}

func (*Embeddings) Generate

func (*Embeddings) GenerateRaw

func (resource *Embeddings) GenerateRaw(ctx context.Context, request json.RawMessage, options ...RequestOption) (*Response[json.RawMessage], error)

type GateAI

type GateAI struct {
	Chat            *Chat
	Responses       *Responses
	Embeddings      *Embeddings
	Anthropic       *Anthropic
	Gemini          *Gemini
	Vertex          *Vertex
	Images          *Images
	STT             *STT
	TTS             *TTS
	VideoGeneration *VideoGeneration
	Generations     *Generations
	Credits         *Credits
	// contains filtered or unexported fields
}

func New

func New(baseURL string, options ...Option) (*GateAI, error)

type Gemini

type Gemini struct {
	// contains filtered or unexported fields
}

func (*Gemini) GenerateContent

func (*Gemini) GenerateContentRaw

func (resource *Gemini) GenerateContentRaw(ctx context.Context, model string, request json.RawMessage, options ...RequestOption) (*Response[json.RawMessage], error)

func (*Gemini) StreamGenerateContent

func (resource *Gemini) StreamGenerateContent(ctx context.Context, model string, request components.GeminiGenerateContentRequest, options ...RequestOption) (*stream.EventStream[components.GeminiStreamEvent], error)

func (*Gemini) StreamGenerateContentRaw

func (resource *Gemini) StreamGenerateContentRaw(ctx context.Context, model string, request json.RawMessage, options ...RequestOption) (*stream.EventStream[json.RawMessage], error)

type Generations

type Generations struct {
	// contains filtered or unexported fields
}

func (*Generations) Get

func (resource *Generations) Get(ctx context.Context, id string, options ...RequestOption) (*Response[components.GenerationEnvelope], error)

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type Images

type Images struct {
	// contains filtered or unexported fields
}

func (*Images) Edit

func (resource *Images) Edit(ctx context.Context, request components.ImageEditRequest, options ...RequestOption) (*Response[components.ImageResponse], error)

func (*Images) Generate

func (resource *Images) Generate(ctx context.Context, request components.ImageGenerationRequest, options ...RequestOption) (*Response[components.ImageResponse], error)

func (*Images) GenerateRaw

func (resource *Images) GenerateRaw(ctx context.Context, request json.RawMessage, options ...RequestOption) (*Response[json.RawMessage], error)

type Option

type Option func(*GateAI) error

func WithAPIKey

func WithAPIKey(apiKey string) Option

func WithDefaultHeader

func WithDefaultHeader(name, value string) Option

func WithHTTPClient

func WithHTTPClient(httpClient HTTPClient) Option

func WithRetryConfig

func WithRetryConfig(config RetryConfig) Option

func WithSecuritySource

func WithSecuritySource(source SecuritySource) Option

func WithUserAgent

func WithUserAgent(userAgent string) Option

type RequestOption

type RequestOption func(*requestOptions) error

func WithHeader

func WithHeader(name, value string) RequestOption

func WithIdempotencyKey

func WithIdempotencyKey(key string) RequestOption

func WithQueryParameter

func WithQueryParameter(name, value string) RequestOption

func WithRequestRetries

func WithRequestRetries(maxRetries int) RequestOption

type Response

type Response[T any] struct {
	Data         T
	Raw          []byte
	StatusCode   int
	Header       http.Header
	HTTPResponse *http.Response
}

type Responses

type Responses struct {
	// contains filtered or unexported fields
}

func (*Responses) Send

func (*Responses) SendRaw

func (resource *Responses) SendRaw(ctx context.Context, request json.RawMessage, options ...RequestOption) (*Response[json.RawMessage], error)

func (*Responses) Stream

func (*Responses) StreamRaw

func (resource *Responses) StreamRaw(ctx context.Context, request json.RawMessage, options ...RequestOption) (*stream.EventStream[json.RawMessage], error)

type RetryConfig

type RetryConfig struct {
	MaxRetries     int
	InitialBackoff time.Duration
	MaxBackoff     time.Duration
}

type STT

type STT struct {
	// contains filtered or unexported fields
}

func (*STT) CreateTranscription

func (resource *STT) CreateTranscription(ctx context.Context, request components.TranscriptionRequest, options ...RequestOption) (*Response[components.TranscriptionResponse], error)

func (*STT) StreamTranscription

func (resource *STT) StreamTranscription(ctx context.Context, request components.TranscriptionRequest, options ...RequestOption) (*stream.EventStream[components.TranscriptionStreamEvent], error)

type SecuritySource

type SecuritySource func(context.Context) (string, error)

type TTS

type TTS struct {
	// contains filtered or unexported fields
}

func (*TTS) CreateSpeech

func (resource *TTS) CreateSpeech(ctx context.Context, request components.SpeechRequest, options ...RequestOption) (*BinaryResponse, error)

func (*TTS) StreamSpeech

func (resource *TTS) StreamSpeech(ctx context.Context, request components.SpeechRequest, options ...RequestOption) (*stream.EventStream[components.SpeechStreamEvent], error)

type Vertex

type Vertex struct {
	// contains filtered or unexported fields
}

func (*Vertex) GenerateContent

func (*Vertex) GenerateContentRaw

func (resource *Vertex) GenerateContentRaw(ctx context.Context, model string, request json.RawMessage, options ...RequestOption) (*Response[json.RawMessage], error)

func (*Vertex) StreamGenerateContent

func (resource *Vertex) StreamGenerateContent(ctx context.Context, model string, request components.GeminiGenerateContentRequest, options ...RequestOption) (*stream.EventStream[components.GeminiStreamEvent], error)

func (*Vertex) StreamGenerateContentRaw

func (resource *Vertex) StreamGenerateContentRaw(ctx context.Context, model string, request json.RawMessage, options ...RequestOption) (*stream.EventStream[json.RawMessage], error)

type VideoGeneration

type VideoGeneration struct {
	// contains filtered or unexported fields
}

func (*VideoGeneration) Generate

func (*VideoGeneration) GetGeneration

func (resource *VideoGeneration) GetGeneration(ctx context.Context, jobID string, options ...RequestOption) (*Response[components.VideoGenerationEnvelope], error)

func (*VideoGeneration) GetVideoContent

func (resource *VideoGeneration) GetVideoContent(ctx context.Context, jobID string, options ...RequestOption) (*BinaryResponse, error)

Directories

Path Synopsis
examples
chat command
chat-stream command
credits command
embeddings command
models
types
stream
Package stream implements a small, context-aware SSE reader.
Package stream implements a small, context-aware SSE reader.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL