meshapi

package module
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2026 License: MIT Imports: 21 Imported by: 0

README

meshapi-go-sdk

Go client for the MeshAPI AI model gateway.

Requirements

  • Go ≥ 1.21
  • Zero external dependencies

Installation

go get github.com/aifiesta/meshapi-go-sdk@latest

Quick Start

import meshapi "github.com/aifiesta/meshapi-go-sdk"

client := meshapi.New(meshapi.Config{
    BaseURL: "https://api.meshapi.ai",
    Token:   "rsk_...",
})

model := "openai/gpt-4o-mini"
resp, err := client.Chat.Completions.Create(ctx, meshapi.ChatCompletionParams{
    Model:    &model,
    Messages: []meshapi.ChatMessage{{Role: "user", Content: "What is 2+2?"}},
})

Chat completions

// Non-streaming
resp, err := client.Chat.Completions.Create(ctx, meshapi.ChatCompletionParams{
    Model:    &model,
    Messages: []meshapi.ChatMessage{{Role: "user", Content: "Hello!"}},
})
fmt.Println(resp.Choices[0].Message.Content)

// Streaming
chunkCh, errCh := client.Chat.Completions.Stream(ctx, params)
for chunk := range chunkCh {
    if len(chunk.Choices) > 0 && chunk.Choices[0].Delta != nil {
        fmt.Print(*chunk.Choices[0].Delta.Content)
    }
}
if err := <-errCh; err != nil {
    log.Fatal(err)
}

Responses API (reasoning models)

respModel := "openai/o3-mini"
resp, _ := client.Responses.Create(ctx, meshapi.ResponsesParams{
    Model: &respModel,
    Input: "Solve for X: 2x + 5 = 15",
})

// List background response jobs, or fetch a persisted/background response by id.
// Synchronous create responses are not guaranteed to be retrievable via Get.
limit := 20
jobs, _ := client.Responses.List(ctx, meshapi.ResponsesListParams{Limit: &limit})
job, _ := client.Responses.Get(ctx, "resp_abc123")

Embeddings

embModel := "openai/text-embedding-3-small"
emb, _ := client.Embeddings.Create(ctx, meshapi.EmbeddingsParams{
    Model: &embModel,
    Input: []string{"The quick brown fox"},
})

Audio (TTS, STT, voices)

// Text-to-speech — returns []byte of raw audio
ttsModel := "sarvam/bulbul:v2"
voiceName := "meera"
audioBytes, err := client.Audio.Synthesize(ctx, meshapi.SpeechParams{
    Input: "Hello from MeshAPI.",
    Model: &ttsModel,
    Voice: &voiceName,
})
os.WriteFile("output.wav", audioBytes, 0644)

// Speech-to-text — send raw audio bytes with a filename hint
fileData, _ := os.ReadFile("audio.wav")
result, err := client.Audio.Transcribe(ctx, fileData, "audio.wav", meshapi.TranscriptionParams{
    Model: "sarvam/saaras:v3",
    // Optional: LanguageCode is model-specific (e.g. Sarvam expects "en-IN", not "en").
})
fmt.Println(result.Text)

// Translate audio to English via /v1/audio/transcriptions/translate
translateModel := "sarvam/saaras:v3"
translated, err := client.Audio.Translate(ctx, fileData, "audio.wav", &meshapi.TranscriptionTranslateParams{
    Model: &translateModel,
})
fmt.Println(translated.Text)

// Standalone audio translation via POST /v1/audio/translations
// (distinct endpoint from Translate above)
translated2, err := client.Audio.Translations(ctx, fileData, "audio.wav", meshapi.AudioTranslationParams{
    Model: "openai/whisper-large-v3",
})
fmt.Println(translated2.Text)

// List available voices
pageSize := 10
voices, err := client.Audio.ListVoices(ctx, &meshapi.ListVoicesParams{PageSize: &pageSize})

// Get a specific voice
voice, err := client.Audio.GetVoice(ctx, "voice-id")

Video generation

// Submit a video generation task
prompt := "A serene mountain lake at sunrise"
task, err := client.Videos.Generate(ctx, meshapi.VideoGenerationParams{
    Model: "byteplus/dreamina-seedance-2-0",
    Content: []meshapi.VideoContentItem{
        {Type: "text", Text: &prompt},
    },
})
fmt.Println("Task ID:", task.ID)

// Poll until complete
for {
    status, _ := client.Videos.Retrieve(ctx, task.ID)
    if status.Status == "succeeded" || status.Status == "failed" {
        break
    }
    time.Sleep(5 * time.Second)
}

// List past generation tasks
limit := 20
listing, err := client.Videos.List(ctx, meshapi.ListVideoGenerationsParams{Limit: &limit})
fmt.Printf("%d total tasks\n", listing.Total)

Image generation

imgModel := "openai/gpt-image-1"
imgN := 1
imgSize := "1024x1024"
img, _ := client.Images.Generate(ctx, meshapi.ImageGenerationParams{
    Model:  &imgModel,
    Prompt: "A watercolor of a fox in a snowy forest",
    N:      &imgN,
    Size:   &imgSize,
})

// Streaming
chunkCh, errCh := client.Images.Stream(ctx, params)
for chunk := range chunkCh { ... }

// Editing — Image is a base64/data-URL string (or meshapi.ImageRef);
// remote http(s) URLs are rejected by this endpoint.
editPrompt, editOp := "Replace the background with a beach at sunset", "edit"
edited, _ := client.Images.Edit(ctx, meshapi.ImageEditParams{
    Model:     "openai/gpt-image-1",
    Image:     "data:image/png;base64,<...>",
    Prompt:    &editPrompt,
    Operation: &editOp, // or inpaint / outpaint / mix / reframe / upscale / remove_background
})

Compare (multi-model)

compCh, errCh := client.Compare.Stream(ctx, meshapi.CompareParams{
    Models:   []string{"openai/gpt-4o-mini", "anthropic/claude-haiku-4.5"},
    Messages: []meshapi.ChatMessage{{Role: "user", Content: "Hello"}},
})
for event := range compCh { ... }

Batches

Batch jobs accept inline requests — no separate file upload step required.

batch, _ := client.Batches.Create(ctx, meshapi.CreateBatchParams{
    Requests: []meshapi.BatchRequestItem{
        {
            CustomID: "req-1",
            Body: map[string]interface{}{
                "model":    "openai/gpt-5-nano",
                "messages": []map[string]interface{}{{"role": "user", "content": "Hello"}},
            },
        },
    },
    Metadata: map[string]interface{}{"job": "my-batch"},
})

// Poll
got, _ := client.Batches.Get(ctx, batch.ID)
fmt.Println(got.Status)

// Cancel
client.Batches.Cancel(ctx, batch.ID)

RAG (Retrieval-Augmented Generation)

Upload files, embed them, and run vector search.

import "net/http"

// 1. Initialise upload — get a signed URL
upload, _ := client.RAG.InitUpload(ctx, meshapi.InitUploadRequest{
    FileName: "handbook.pdf",
    MimeType: "application/pdf",
})

// 2a. PUT file bytes to the signed URL yourself…
req, _ := http.NewRequestWithContext(ctx, http.MethodPut, upload.SignedURL, fileReader)
req.Header.Set("Content-Type", "application/pdf")
http.DefaultClient.Do(req)

// 2b. …or use the convenience wrapper that does both steps:
upload, _ = client.RAG.UploadFile(ctx, meshapi.UploadFileParams{
    FileName: "handbook.pdf",
    MimeType: "application/pdf",
    Content:  fileBytes,
})

// 3. Trigger embedding
client.RAG.Embed(ctx, meshapi.BulkEmbedRequest{
    FileIDs: []string{upload.FileID},
})

// 4. Poll until ready
for {
    s, _ := client.RAG.Get(ctx, upload.FileID)
    if s.EmbeddingStatus == "ready" { break }
    time.Sleep(3 * time.Second)
}

// 5. Search
topK := 5
results, _ := client.RAG.Search(ctx, meshapi.SearchRequest{
    Query: "onboarding process",
    TopK:  &topK,
})
for _, r := range results.Results {
    fmt.Printf("%.4f  %s\n", r.Score, r.Text)
}

// List files
limit := 50
list, _ := client.RAG.List(ctx, meshapi.ListRagFilesParams{Limit: &limit})

Realtime (Speech-to-Speech WebSocket)

session, err := client.Realtime.Connect(ctx, meshapi.RealtimeConnectParams{
    Model: "openai/gpt-4o-realtime-preview",
})
if err != nil {
    log.Fatal(err)
}
defer session.Close()

// Send a JSON event (GA session shape)
session.Send(ctx, map[string]any{
    "type": "session.update",
    "session": map[string]any{
        "type":              "realtime",
        "output_modalities": []string{"audio"},
        "instructions":      "You are a helpful assistant.",
        "audio": map[string]any{
            "input":  map[string]any{"format": map[string]any{"type": "audio/pcm", "rate": 24000}},
            "output": map[string]any{"format": map[string]any{"type": "audio/pcm", "rate": 24000}, "voice": "alloy"},
        },
    },
})

// Append input audio (PCM16 24kHz) — sent as base64 input_audio_buffer.append
session.SendAudio(ctx, pcmBytes)

// Receive frames one at a time
msg, err := session.Receive(ctx)
if err != nil {
    var re *meshapi.RealtimeError
    if errors.As(err, &re) {
        fmt.Println(re.Code) // "insufficient_quota", "idle_timeout", …
    }
}
fmt.Println(msg.Event["type"]) // "session.created", "response.done", …
if msg.Audio != nil { /* binary audio frame */ }

// Or use the channel-based pump
msgCh, errCh := session.Events(ctx)
for msg := range msgCh {
    fmt.Println(msg.Event["type"])
}
if err := <-errCh; err != nil {
    log.Fatal(err)
}

Auth is sent via Sec-WebSocket-Protocol: openai-realtime, Bearer <token>. The session is safe to send and receive from separate goroutines simultaneously. No external dependencies — the WebSocket client is implemented in the standard library.

Models

models, _ := client.Models.List(ctx, meshapi.ListModelsParams{})
free, _   := client.Models.Free(ctx)

// Paginated catalog search (DB-only, no model cost)
q, limit := "gpt", 10
page, _ := client.Models.Search(ctx, meshapi.ModelSearchParams{Q: &q, Limit: &limit})
fmt.Println(page.Total, page.Brands)

// Fetch one model's detail
gpt4o, _ := client.Models.Get(ctx, "openai/gpt-4o")

Moderations

res, _ := client.Moderations.Create(ctx, meshapi.ModerationParams{Input: "text to classify"})
if len(res.Results) > 0 && res.Results[0].Flagged {
    fmt.Println("flagged:", res.Results[0].Categories)
}

Gated server-side by WEB_SEARCH_ENABLED. Native-first with Tavily fallback; inspect res.Provider to see which engine served the request.

maxResults, includeAnswer := 5, true
res, _ := client.Web.Search(ctx, meshapi.WebSearchParams{
    Query:         "latest news on Mars rovers",
    MaxResults:    &maxResults,
    IncludeAnswer: &includeAnswer,
})
fmt.Println(res.Provider)
for _, hit := range res.Results {
    fmt.Println(hit.Title, hit.URL)
}

Router select

Gated server-side by AUTO_ROUTER_ENABLED. Returns the model the Auto Router would pick — without running inference.

sel, _ := client.Router.Select(ctx, meshapi.RouterSelectParams{
    Messages: []meshapi.ChatMessage{{Role: "user", Content: "Prove that 2+2=4."}},
})
fmt.Println(sel.Model, sel.AutoRouter.FallbackUsed)

Templates

tmpl, _ := client.Templates.Create(ctx, meshapi.CreateTemplateParams{Name: "my-tpl"})
client.Templates.Delete(ctx, tmpl.ID)

Error handling

resp, err := client.Chat.Completions.Create(ctx, params)
if err != nil {
    var svcErr *meshapi.MeshAPIError
    if errors.As(err, &svcErr) {
        fmt.Println(svcErr.Status)    // HTTP status
        fmt.Println(svcErr.Code)      // "unauthorized", "rate_limit_exceeded", …
        fmt.Println(svcErr.RequestID) // req_<ULID>
    }
}

Retry / backoff

Retries on 429/502/503/504 with exponential backoff (default 3 retries, 500 ms base, 30 s max, ±20% jitter). Respects Retry-After.

maxRetries := 5
client := meshapi.New(meshapi.Config{MaxRetries: &maxRetries})

Streams do not retry. On connection failure the error channel receives a MeshAPIError with Code="stream_interrupted".

Running tests

# Unit + contract tests (no server needed)
go test ./...

# Live tests (requires a running backend)
cd livetests
MESHAPI_TOKEN=rsk_... go test ./... -v -timeout 300s

Versioning

fmt.Println(meshapi.Version) // "0.1.12"

Documentation

Overview

Package meshapi is a Go client for the MeshAPI AI model gateway.

Quick start

client := meshapi.NewClient(meshapi.Config{
    BaseURL: "http://localhost:8000",
    Token:   "rsk_...",
})

model := "openai/gpt-4o-mini"
resp, err := client.Chat.Completions.Create(ctx, meshapi.ChatCompletionParams{
    Model:    &model,
    Messages: []meshapi.ChatMessage{{Role: "user", Content: "Hello!"}},
})

Package meshapi provides a typed Go client for the MeshAPI AI model gateway.

Index

Constants

View Source
const Version = "0.1.12"

Version is the current SDK version.

Variables

This section is empty.

Functions

This section is empty.

Types

type AudioOutputOptions added in v0.1.3

type AudioOutputOptions struct {
	Voice  *string `json:"voice,omitempty"`
	Format *string `json:"format,omitempty"`
}

type AudioResource added in v0.1.6

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

AudioResource provides access to /v1/audio/* endpoints.

func (*AudioResource) GetTranscription added in v0.1.6

func (r *AudioResource) GetTranscription(ctx context.Context, transcriptionID string) (map[string]any, error)

GetTranscription sends GET /v1/audio/transcriptions/{transcription_id}.

func (*AudioResource) GetVoice added in v0.1.6

func (r *AudioResource) GetVoice(ctx context.Context, voiceID string) (*Voice, error)

GetVoice sends GET /v1/audio/voices/{voice_id}.

func (*AudioResource) ListVoices added in v0.1.6

func (r *AudioResource) ListVoices(ctx context.Context, params *ListVoicesParams) (*VoicesResponse, error)

ListVoices sends GET /v1/audio/voices.

func (*AudioResource) Synthesize added in v0.1.6

func (r *AudioResource) Synthesize(ctx context.Context, params SpeechParams) ([]byte, error)

Synthesize sends POST /v1/audio/speech and returns raw audio bytes.

func (*AudioResource) Transcribe added in v0.1.6

func (r *AudioResource) Transcribe(ctx context.Context, fileData []byte, filename string, params TranscriptionParams) (*TranscriptionResponse, error)

Transcribe sends POST /v1/audio/transcriptions as a multipart upload.

func (*AudioResource) Translate added in v0.1.6

func (r *AudioResource) Translate(ctx context.Context, fileData []byte, filename string, params *TranscriptionTranslateParams) (*TranscriptionResponse, error)

Translate sends POST /v1/audio/transcriptions/translate as a multipart upload. Use Translations for the standalone POST /v1/audio/translations endpoint.

func (*AudioResource) Translations added in v0.1.8

func (r *AudioResource) Translations(ctx context.Context, fileData []byte, filename string, params AudioTranslationParams) (*TranscriptionResponse, error)

Translations sends POST /v1/audio/translations — the standalone audio translation endpoint (operationId: create_translation_v1_audio_translations_post). This is distinct from Translate (POST /v1/audio/transcriptions/translate). fileData is the raw audio bytes; filename is used for the Content-Disposition header. params.Model is required; prompt, response_format, and temperature are optional. Returns a TranscriptionResponse containing the translated text.

type AudioTranslationParams added in v0.1.8

type AudioTranslationParams struct {
	// Model is required — the translation model to use.
	Model          string   `json:"model"`
	Prompt         *string  `json:"prompt,omitempty"`
	ResponseFormat *string  `json:"response_format,omitempty"`
	Temperature    *float64 `json:"temperature,omitempty"`
}

AudioTranslationParams is the request body for POST /v1/audio/translations (standalone translation endpoint, distinct from /v1/audio/transcriptions/translate). Model and File (via fileData/filename in the method call) are required.

type AutoRouterMeta added in v0.1.8

type AutoRouterMeta struct {
	FallbackUsed   bool    `json:"fallback_used"`
	FallbackReason *string `json:"fallback_reason,omitempty"`
}

type BatchListResponse added in v0.1.3

type BatchListResponse struct {
	Object  string        `json:"object"`
	Data    []BatchObject `json:"data"`
	HasMore bool          `json:"has_more"`
	FirstID *string       `json:"first_id,omitempty"`
	LastID  *string       `json:"last_id,omitempty"`
}

type BatchObject added in v0.1.3

type BatchObject struct {
	ID               string                   `json:"id"`
	Object           *string                  `json:"object,omitempty"`
	Endpoint         *string                  `json:"endpoint,omitempty"`
	InputFileID      *string                  `json:"input_file_id,omitempty"`
	OutputFileID     *string                  `json:"output_file_id,omitempty"`
	ErrorFileID      *string                  `json:"error_file_id,omitempty"`
	Status           string                   `json:"status"`
	Model            *string                  `json:"model,omitempty"`
	Provider         *string                  `json:"provider,omitempty"`
	CreatedAt        *int64                   `json:"created_at,omitempty"`
	CompletedAt      *int64                   `json:"completed_at,omitempty"`
	ExpiresAt        *int64                   `json:"expires_at,omitempty"`
	UsageSynced      *bool                    `json:"usage_synced,omitempty"`
	CompletionWindow *string                  `json:"completion_window,omitempty"`
	RequestCounts    map[string]interface{}   `json:"request_counts,omitempty"`
	Metadata         map[string]interface{}   `json:"metadata,omitempty"`
	Results          []map[string]interface{} `json:"results,omitempty"`
	ErrorsDetail     []map[string]interface{} `json:"errors_detail,omitempty"`
}

type BatchRequestItem added in v0.1.3

type BatchRequestItem struct {
	CustomID string                 `json:"custom_id"`
	Method   string                 `json:"method,omitempty"`
	URL      string                 `json:"url,omitempty"`
	Body     map[string]interface{} `json:"body"`
}

type BatchesResource added in v0.1.3

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

func (*BatchesResource) Cancel added in v0.1.3

func (r *BatchesResource) Cancel(ctx context.Context, batchID string) (*BatchObject, error)

func (*BatchesResource) Create added in v0.1.3

func (*BatchesResource) Get added in v0.1.3

func (r *BatchesResource) Get(ctx context.Context, batchID string) (*BatchObject, error)

func (*BatchesResource) List added in v0.1.3

func (r *BatchesResource) List(ctx context.Context, after *string, limit *int) (*BatchListResponse, error)

type BuiltinTool added in v0.1.3

type BuiltinTool struct {
	Type string `json:"type"`
}

type BulkEmbedRequest added in v0.1.5

type BulkEmbedRequest struct {
	FileIDs  []string               `json:"file_ids"`
	Wait     *bool                  `json:"wait,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

BulkEmbedRequest triggers embedding jobs for one or more files.

type BulkEmbedResponse added in v0.1.5

type BulkEmbedResponse struct {
	Results []BulkEmbedResult `json:"results"`
}

BulkEmbedResponse is returned by POST /v1/files/embed.

type BulkEmbedResult added in v0.1.5

type BulkEmbedResult struct {
	FileID          string  `json:"file_id"`
	EmbeddingStatus string  `json:"embedding_status"`
	ChunkCount      *int    `json:"chunk_count,omitempty"`
	Error           *string `json:"error,omitempty"`
}

BulkEmbedResult is the per-file result from POST /v1/files/embed.

type ChatCompletionChoice

type ChatCompletionChoice struct {
	Index        int                    `json:"index"`
	Message      *ChatCompletionMessage `json:"message,omitempty"`
	FinishReason *string                `json:"finish_reason,omitempty"`
	Logprobs     interface{}            `json:"logprobs,omitempty"`
}

ChatCompletionChoice is one result choice in a non-streaming response.

type ChatCompletionChunk

type ChatCompletionChunk struct {
	ID      string                      `json:"id"`
	Object  string                      `json:"object"`
	Created int64                       `json:"created"`
	Model   string                      `json:"model"`
	Choices []ChatCompletionChunkChoice `json:"choices"`
	Usage   *UsageInfo                  `json:"usage,omitempty"`
	Cost    *string                     `json:"cost,omitempty"`
}

ChatCompletionChunk is a single SSE chunk in a streaming completion.

type ChatCompletionChunkChoice

type ChatCompletionChunkChoice struct {
	Index        int                       `json:"index"`
	Delta        *ChatCompletionChunkDelta `json:"delta,omitempty"`
	FinishReason *string                   `json:"finish_reason,omitempty"`
}

ChatCompletionChunkChoice is one choice in a streaming chunk.

type ChatCompletionChunkDelta

type ChatCompletionChunkDelta struct {
	Role      *string                `json:"role,omitempty"`
	Content   *string                `json:"content,omitempty"`
	ToolCalls []ToolCall             `json:"tool_calls,omitempty"`
	Audio     map[string]interface{} `json:"audio,omitempty"`
}

ChatCompletionChunkDelta is the partial content in a streaming chunk.

type ChatCompletionMessage

type ChatCompletionMessage struct {
	Role      string                 `json:"role"`
	Content   *string                `json:"content,omitempty"`
	ToolCalls []ToolCall             `json:"tool_calls,omitempty"`
	Audio     map[string]interface{} `json:"audio,omitempty"`
}

ChatCompletionMessage is a completed message in a non-streaming response.

type ChatCompletionParams

type ChatCompletionParams struct {
	Messages         []ChatMessage          `json:"messages"`
	Model            *string                `json:"model,omitempty"`
	Stream           *bool                  `json:"stream,omitempty"`
	Template         *string                `json:"template,omitempty"`
	Variables        map[string]string      `json:"variables,omitempty"`
	SessionID        *string                `json:"session_id,omitempty"`
	Temperature      *float64               `json:"temperature,omitempty"`
	MaxTokens        *int                   `json:"max_tokens,omitempty"`
	TopP             *float64               `json:"top_p,omitempty"`
	FrequencyPenalty *float64               `json:"frequency_penalty,omitempty"`
	PresencePenalty  *float64               `json:"presence_penalty,omitempty"`
	Stop             interface{}            `json:"stop,omitempty"` // string or []string
	Seed             *int                   `json:"seed,omitempty"`
	Tools            []Tool                 `json:"tools,omitempty"`
	ToolChoice       interface{}            `json:"tool_choice,omitempty"`
	ResponseFormat   map[string]interface{} `json:"response_format,omitempty"`
	Transforms       []string               `json:"transforms,omitempty"`
	Models           []string               `json:"models,omitempty"`
	User             *string                `json:"user,omitempty"`
	ReasoningEffort  *string                `json:"reasoning_effort,omitempty"` // "high" | "medium" | "low" | "none"
	Modality         *string                `json:"modality,omitempty"`
	Image            *ImageOptions          `json:"image,omitempty"`
	AsyncMode        *bool                  `json:"async_mode,omitempty"`
	Modalities       []string               `json:"modalities,omitempty"`
	Audio            *AudioOutputOptions    `json:"audio,omitempty"`
	// Cache enables prompt caching for this request (null = server default).
	Cache *bool `json:"cache,omitempty"`
	// Timeout overrides the server's upstream-provider timeout (default 300 s).
	// Set this for requests that may take longer than 5 minutes. This is
	// independent of the SDK-level TimeoutMs option on Config, which controls
	// the HTTP client timeout.
	Timeout *float64 `json:"timeout,omitempty"`
}

ChatCompletionParams is the request body for POST /v1/chat/completions.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID                string                 `json:"id"`
	Object            string                 `json:"object"`
	Created           int64                  `json:"created"`
	Model             string                 `json:"model"`
	Choices           []ChatCompletionChoice `json:"choices"`
	Usage             *UsageInfo             `json:"usage,omitempty"`
	SystemFingerprint *string                `json:"system_fingerprint,omitempty"`
}

ChatCompletionResponse is the full non-streaming response body.

type ChatMessage

type ChatMessage struct {
	Role             string                   `json:"role"`
	Content          interface{}              `json:"content,omitempty"` // string or []ContentPart
	Name             *string                  `json:"name,omitempty"`
	ToolCallID       *string                  `json:"tool_call_id,omitempty"`
	ToolCalls        []ToolCall               `json:"tool_calls,omitempty"`
	ReasoningDetails []map[string]interface{} `json:"reasoning_details,omitempty"`
}

ChatMessage represents a single message in the conversation.

type ChatResource

type ChatResource struct {
	Completions *CompletionsResource
}

ChatResource groups chat-related sub-resources.

type Client

type Client struct {
	Chat        *ChatResource
	Responses   *ResponsesResource
	Embeddings  *EmbeddingsResource
	Compare     *CompareResource
	Batches     *BatchesResource
	Models      *ModelsResource
	Templates   *TemplatesResource
	Images      *ImagesResource
	RAG         *RagResource
	Realtime    *RealtimeResource
	Audio       *AudioResource
	Videos      *VideosResource
	Moderations *ModerationsResource
	Web         *WebResource
	Router      *RouterResource
}

Client is the MeshAPI SDK client.

One instance = one auth realm. Use separate instances for different tokens:

inferenceClient := meshapi.New(meshapi.Config{Token: "rsk_..."})
mgmtClient      := meshapi.New(meshapi.Config{Token: "<jwt>"})

func New

func New(cfg Config) *Client

New creates a new MeshAPI client with the given configuration.

type CompareParams added in v0.1.3

type CompareParams struct {
	Models                 []string          `json:"models"`
	Messages               []ChatMessage     `json:"messages"`
	ModelOverrides         []ModelOverride   `json:"model_overrides,omitempty"`
	ComparisonModel        *string           `json:"comparison_model,omitempty"`
	ComparisonInstructions *string           `json:"comparison_instructions,omitempty"`
	Temperature            *float64          `json:"temperature,omitempty"`
	MaxTokens              *int              `json:"max_tokens,omitempty"`
	Cache                  *bool             `json:"cache,omitempty"`
	Stream                 *bool             `json:"stream,omitempty"`
	Template               *string           `json:"template,omitempty"`
	Variables              map[string]string `json:"variables,omitempty"`
	SkipComparison         *bool             `json:"skip_comparison,omitempty"`
}

type CompareResource added in v0.1.3

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

func (*CompareResource) Create added in v0.1.3

func (*CompareResource) Stream added in v0.1.3

func (r *CompareResource) Stream(ctx context.Context, params CompareParams) (<-chan CompareStreamEvent, <-chan error)

type CompareResponse added in v0.1.3

type CompareResponse struct {
	ComparisonID           string               `json:"comparison_id"`
	Object                 string               `json:"object"`
	Created                int64                `json:"created"`
	Models                 []string             `json:"models"`
	Results                []ModelCompareResult `json:"results"`
	Comparison             *string              `json:"comparison,omitempty"`
	ComparisonModel        *string              `json:"comparison_model,omitempty"`
	ComparisonUsage        *TokenUsage          `json:"comparison_usage,omitempty"`
	ComparisonFallbackUsed bool                 `json:"comparison_fallback_used"`
	TotalLatencyMs         int                  `json:"total_latency_ms"`
	Partial                bool                 `json:"partial"`
	SkipComparison         bool                 `json:"skip_comparison"`
}

type CompareStreamEvent added in v0.1.3

type CompareStreamEvent map[string]interface{}

type CompletionsResource

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

CompletionsResource handles POST /v1/chat/completions.

func (*CompletionsResource) Create

Create sends a non-streaming chat completion request and returns the full response.

func (*CompletionsResource) Stream

func (r *CompletionsResource) Stream(ctx context.Context, params ChatCompletionParams) (<-chan ChatCompletionChunk, <-chan error)

Stream opens a streaming chat completion. It returns two channels:

  • chunkCh: receives parsed ChatCompletionChunks until [DONE] or error
  • errCh: receives at most one error, then is closed

Both channels are always closed when the stream finishes. Callers must drain chunkCh before reading errCh, or use a select loop.

Streams are NEVER retried. On failure, catch the error from errCh and restart a new Stream call if reconnection is needed.

type Config

type Config struct {
	// BaseURL is the MeshAPI gateway base URL (required).
	BaseURL string
	// Token is the Bearer token for this auth realm (required).
	Token string
	// TimeoutMs is the request timeout in milliseconds (default 60_000).
	// For streaming requests this applies to TTFB only.
	TimeoutMs *int
	// MaxRetries is the number of retry attempts on retryable errors (default 3).
	MaxRetries *int
	// HTTPClient allows injecting a custom *http.Client (optional).
	HTTPClient *http.Client
}

Config holds the client configuration.

type ContentPart

type ContentPart struct {
	Type       string      `json:"type"`
	Text       *string     `json:"text,omitempty"`
	ImageURL   *ImageURL   `json:"image_url,omitempty"`
	InputAudio *InputAudio `json:"input_audio,omitempty"`
	VideoURL   *VideoURL   `json:"video_url,omitempty"`
	Fps        *string     `json:"fps,omitempty"`
}

ContentPart is one element of a multimodal message content array.

type CreateBatchParams added in v0.1.3

type CreateBatchParams struct {
	Requests         []BatchRequestItem     `json:"requests"`
	CompletionWindow *string                `json:"completion_window,omitempty"`
	Metadata         map[string]interface{} `json:"metadata,omitempty"`
}

type CreateTemplateParams

type CreateTemplateParams struct {
	Name        string                   `json:"name"`
	Description *string                  `json:"description,omitempty"`
	System      *string                  `json:"system,omitempty"`
	Messages    []map[string]interface{} `json:"messages,omitempty"`
	Model       *string                  `json:"model,omitempty"`
	Params      map[string]interface{}   `json:"params,omitempty"`
	Variables   []string                 `json:"variables,omitempty"`
	// TeamID scopes the template to a specific team (optional).
	TeamID *string `json:"team_id,omitempty"`
}

CreateTemplateParams is the request body for POST /v1/templates.

type CreateVideoGenerationResponse added in v0.1.6

type CreateVideoGenerationResponse struct {
	ID string `json:"id"`
}

CreateVideoGenerationResponse is the response from POST /v1/video/generations.

type EmbeddingItem added in v0.1.3

type EmbeddingItem struct {
	Object    string          `json:"object"`
	Index     int             `json:"index"`
	Embedding EmbeddingVector `json:"embedding"`
}

type EmbeddingVector added in v0.1.8

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

EmbeddingVector holds an embedding value that can be either a float array (encoding_format=float, the default) or a base64 string (encoding_format=base64). Use Floats() or Base64() to access the value.

func (*EmbeddingVector) Base64 added in v0.1.8

func (e *EmbeddingVector) Base64() string

Base64 returns the base64-encoded embedding string. Returns "" if the embedding is a float array.

func (*EmbeddingVector) Floats added in v0.1.8

func (e *EmbeddingVector) Floats() []float64

Floats returns the embedding as a float slice. Returns nil if the embedding is base64-encoded.

func (*EmbeddingVector) IsBase64 added in v0.1.8

func (e *EmbeddingVector) IsBase64() bool

IsBase64 reports whether this embedding was returned as a base64 string.

func (EmbeddingVector) MarshalJSON added in v0.1.8

func (e EmbeddingVector) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*EmbeddingVector) UnmarshalJSON added in v0.1.8

func (e *EmbeddingVector) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler. It accepts both a JSON array of floats and a JSON string (base64-encoded embedding).

type EmbeddingsParams added in v0.1.3

type EmbeddingsParams struct {
	Model           *string                `json:"model,omitempty"`
	Input           interface{}            `json:"input"` // string | []string | []int | [][]int | []MultimodalEmbeddingInput
	Dimensions      *int                   `json:"dimensions,omitempty"`
	EncodingFormat  *string                `json:"encoding_format,omitempty"` // "float" | "base64"
	InputType       *string                `json:"input_type,omitempty"`
	Provider        interface{}            `json:"provider,omitempty"`
	User            *string                `json:"user,omitempty"`
	Instructions    *string                `json:"instructions,omitempty"`
	SparseEmbedding map[string]interface{} `json:"sparse_embedding,omitempty"`
}

type EmbeddingsResource added in v0.1.3

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

func (*EmbeddingsResource) Create added in v0.1.3

type EmbeddingsResponse added in v0.1.3

type EmbeddingsResponse struct {
	Object string           `json:"object"`
	Data   []EmbeddingItem  `json:"data"`
	Model  string           `json:"model"`
	Usage  *EmbeddingsUsage `json:"usage,omitempty"`
}

type EmbeddingsUsage added in v0.1.3

type EmbeddingsUsage struct {
	PromptTokens *int `json:"prompt_tokens,omitempty"`
	TotalTokens  *int `json:"total_tokens,omitempty"`
}

type ImageEditParams added in v0.1.8

type ImageEditParams struct {
	Model           string      `json:"model"`
	Image           interface{} `json:"image"` // string (data-URL/base64) or ImageRef
	Prompt          *string     `json:"prompt,omitempty"`
	Operation       *string     `json:"operation,omitempty"` // edit|inpaint|outpaint|mix|reframe|upscale|remove_background
	Mask            interface{} `json:"mask,omitempty"`
	ReferenceImages interface{} `json:"reference_images,omitempty"` // []string or []ImageRef
	N               *int        `json:"n,omitempty"`
	Size            *string     `json:"size,omitempty"`
	ResponseFormat  *string     `json:"response_format,omitempty"`
	Background      *string     `json:"background,omitempty"`
	UpscaleFactor   *string     `json:"upscale_factor,omitempty"`
	QualityTier     *string     `json:"quality_tier,omitempty"`
	AspectRatio     *string     `json:"aspect_ratio,omitempty"`
	Resolution      *string     `json:"resolution,omitempty"`
	ExpandFactor    interface{} `json:"expand_factor,omitempty"` // string or float64
	MaskFeather     *int        `json:"mask_feather,omitempty"`
}

ImageEditParams is the JSON request body for POST /v1/images/edits. Image (and Mask / ReferenceImages) accept a base64/data-URL string or an ImageRef. Prompt is required for the "edit", "outpaint" and "mix" operations.

type ImageEmbeddingUrl added in v0.1.8

type ImageEmbeddingUrl struct {
	URL string `json:"url"`
}

ImageEmbeddingUrl holds a URL for a multimodal image embedding input.

type ImageGenerationChunk added in v0.1.3

type ImageGenerationChunk struct {
	ID      *string     `json:"id,omitempty"`
	Object  *string     `json:"object,omitempty"`
	Created int64       `json:"created"`
	Model   *string     `json:"model,omitempty"`
	Data    []ImageItem `json:"data"`
	Status  *string     `json:"status,omitempty"`
}

type ImageGenerationParams added in v0.1.3

type ImageGenerationParams struct {
	Prompt         string  `json:"prompt"`
	Model          *string `json:"model,omitempty"`
	N              *int    `json:"n,omitempty"`
	Size           *string `json:"size,omitempty"`
	Quality        *string `json:"quality,omitempty"`
	ResponseFormat *string `json:"response_format,omitempty"` // "url" | "b64_json"
	OutputFormat   *string `json:"output_format,omitempty"`   // "png" | "jpeg" | "webp"
	Stream         *bool   `json:"stream,omitempty"`
	// Additional spec fields
	AspectRatio                      *string                `json:"aspect_ratio,omitempty"`
	Resolution                       *string                `json:"resolution,omitempty"`
	OutputCompression                *int                   `json:"output_compression,omitempty"`          // 0..100
	Background                       *string                `json:"background,omitempty"`                  // "transparent"|"opaque"|"auto"
	Moderation                       *string                `json:"moderation,omitempty"`                  // "low"|"auto"
	PartialImages                    *int                   `json:"partial_images,omitempty"`              // 0..3
	Image                            interface{}            `json:"image,omitempty"`                       // string or []string
	Seed                             *int                   `json:"seed,omitempty"`                        // -1..2147483647
	SequentialImageGeneration        *string                `json:"sequential_image_generation,omitempty"` // "auto"|"disabled"
	SequentialImageGenerationOptions map[string]interface{} `json:"sequential_image_generation_options,omitempty"`
	GuidanceScale                    *float64               `json:"guidance_scale,omitempty"` // 1..10
	Watermark                        *bool                  `json:"watermark,omitempty"`
	OptimizePromptOptions            map[string]interface{} `json:"optimize_prompt_options,omitempty"`
}

type ImageGenerationResponse added in v0.1.3

type ImageGenerationResponse struct {
	Created      int64       `json:"created"`
	Data         []ImageItem `json:"data"`
	Background   *string     `json:"background,omitempty"`
	OutputFormat *string     `json:"output_format,omitempty"`
	Quality      *string     `json:"quality,omitempty"`
	Size         *string     `json:"size,omitempty"`
	Usage        *ImageUsage `json:"usage,omitempty"`
}

type ImageItem added in v0.1.3

type ImageItem struct {
	URL           *string `json:"url,omitempty"`
	B64JSON       *string `json:"b64_json,omitempty"`
	RevisedPrompt *string `json:"revised_prompt,omitempty"`
}

func (*ImageItem) Bytes added in v0.1.11

func (i *ImageItem) Bytes() ([]byte, error)

Bytes returns the raw image bytes regardless of how the provider returned them. It handles both B64JSON and a data: URI in URL (some models, e.g. openai/gpt-image-1, inline the image as a data URL rather than populating B64JSON). It returns an error for a remote http(s) URL (fetch it yourself) or when no image data is present.

type ImageOptions added in v0.1.3

type ImageOptions struct {
	N              *int    `json:"n,omitempty"`
	Size           *string `json:"size,omitempty"`
	Quality        *string `json:"quality,omitempty"`
	ResponseFormat *string `json:"response_format,omitempty"`
}

type ImageRef added in v0.1.8

type ImageRef struct {
	URL string `json:"url"`
}

ImageRef is an image reference for the edits endpoint: URL must be a data URL (data:image/<fmt>;base64,<b64>) or bare base64 — remote http(s) URLs are rejected. You may also pass the base64/data-URL string directly.

type ImageURL

type ImageURL struct {
	URL    string  `json:"url"`
	Detail *string `json:"detail,omitempty"`
}

ImageURL holds the URL and rendering detail for an image content part.

type ImageUsage added in v0.1.3

type ImageUsage struct {
	PromptTokens        int                    `json:"prompt_tokens"`
	CompletionTokens    int                    `json:"completion_tokens"`
	TotalTokens         int                    `json:"total_tokens"`
	InputTokensDetails  map[string]interface{} `json:"input_tokens_details,omitempty"`
	OutputTokensDetails map[string]interface{} `json:"output_tokens_details,omitempty"`
}

type ImagesResource added in v0.1.3

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

func (*ImagesResource) Edit added in v0.1.8

Edit edits a source image (JSON/base64 mode). Image must be a base64 or data:-URL string (or ImageRef) — remote http(s) URLs are rejected.

func (*ImagesResource) Generate added in v0.1.3

Generate sends a non-streaming image generation request and returns the full response.

func (*ImagesResource) Stream added in v0.1.3

func (r *ImagesResource) Stream(ctx context.Context, params ImageGenerationParams) (<-chan ImageGenerationChunk, <-chan error)

Stream opens a streaming image generation request. It returns two channels:

  • chunkCh: receives parsed ImageGenerationChunks until [DONE] or error
  • errCh: receives at most one error, then is closed

Both channels are always closed when the stream finishes. Callers must drain chunkCh before reading errCh, or use a select loop.

type InitUploadRequest added in v0.1.5

type InitUploadRequest struct {
	FileName string                 `json:"file_name"`
	MimeType string                 `json:"mime_type"`
	Embed    *bool                  `json:"embed,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

InitUploadRequest initialises a RAG file upload and returns a signed URL.

type InitUploadResponse added in v0.1.5

type InitUploadResponse struct {
	FileID    string `json:"file_id"`
	SignedURL string `json:"signed_url"`
	ExpiresAt string `json:"expires_at"`
}

InitUploadResponse is returned by POST /v1/files (RAG).

type InputAudio added in v0.1.3

type InputAudio struct {
	Data   *string `json:"data,omitempty"`
	URI    *string `json:"uri,omitempty"`
	URL    *string `json:"url,omitempty"`
	Format string  `json:"format"`
}

InputAudio holds an audio content part. One of Data, URI, or URL must be provided along with Format.

type ListModelsParams

type ListModelsParams struct {
	Free     *bool   // nil = no filter
	Type     *string // "text" | "embedding" | "image" | "audio" | "video"
	Provider *string // e.g. "openai", "amazon-bedrock", "vertex"
}

ListModelsParams holds optional query parameters for listing models.

type ListRagFilesParams added in v0.1.5

type ListRagFilesParams struct {
	Limit  *int `json:"limit,omitempty"`
	Offset *int `json:"offset,omitempty"`
}

ListRagFilesParams are the query parameters for GET /v1/files (RAG).

type ListVideoGenerationsParams added in v0.1.6

type ListVideoGenerationsParams struct {
	Status        *string `json:"status,omitempty"`
	Model         *string `json:"model,omitempty"`
	CreatedAfter  *string `json:"created_after,omitempty"`
	CreatedBefore *string `json:"created_before,omitempty"`
	Limit         *int    `json:"limit,omitempty"`
	Offset        *int    `json:"offset,omitempty"`
}

ListVideoGenerationsParams holds query parameters for GET /v1/video/generations.

type ListVoicesParams added in v0.1.6

type ListVoicesParams struct {
	NextPageToken     *string  `json:"next_page_token,omitempty"`
	PageSize          *int     `json:"page_size,omitempty"`
	Search            *string  `json:"search,omitempty"`
	Sort              *string  `json:"sort,omitempty"`
	SortDirection     *string  `json:"sort_direction,omitempty"`
	VoiceType         *string  `json:"voice_type,omitempty"`
	Category          *string  `json:"category,omitempty"`
	IncludeTotalCount *bool    `json:"include_total_count,omitempty"`
	VoiceIDs          []string `json:"voice_ids,omitempty"`
}

type MeshAPIError

type MeshAPIError struct {
	// Status is the HTTP status code (0 for stream/parse errors).
	Status int
	// Code is the machine-readable error code slug (e.g. "unauthorized").
	Code string
	// RequestID is the req_<ULID> tracing identifier from the response.
	RequestID string
	// Message is the human-readable error description.
	Message string
	// Details contains validation error details (non-nil on 422 responses).
	Details []interface{}
	// ProviderError contains upstream provider error details when available.
	ProviderError map[string]interface{}
	// RetryAfterSeconds is set on 429 responses.
	RetryAfterSeconds *int
}

MeshAPIError is returned when MeshAPI responds with a non-2xx status or sends an error frame mid-stream.

func (*MeshAPIError) Error

func (e *MeshAPIError) Error() string

type ModelCompareResult added in v0.1.3

type ModelCompareResult struct {
	Model        string                 `json:"model"`
	ResponseBody map[string]interface{} `json:"response_body,omitempty"`
	Content      *string                `json:"content,omitempty"`
	LatencyMs    int                    `json:"latency_ms"`
	Error        *string                `json:"error,omitempty"`
	ErrorCode    *string                `json:"error_code,omitempty"`
	Usage        *TokenUsage            `json:"usage,omitempty"`
	RequestID    string                 `json:"request_id"`
}

type ModelInfo

type ModelInfo struct {
	// Required fields
	ID                     string        `json:"id"`
	Name                   string        `json:"name"`
	ContextLength          *int          `json:"context_length,omitempty"`
	IsFree                 bool          `json:"is_free"`
	Pricing                *ModelPricing `json:"pricing,omitempty"`
	SupportsThinking       bool          `json:"supports_thinking"`
	SupportsCompletionsAPI bool          `json:"supports_completions_api"`
	SupportsResponsesAPI   bool          `json:"supports_responses_api"`
	ModelType              string        `json:"model_type"`
	InputModalities        []string      `json:"input_modalities,omitempty"`
	OutputModalities       []string      `json:"output_modalities,omitempty"`
	// Optional fields
	Brand                    *string `json:"brand,omitempty"`
	Provider                 *string `json:"provider,omitempty"`
	Description              *string `json:"description,omitempty"`
	SupportsRealtime         bool    `json:"supports_realtime"`
	SupportsEmbeddings       bool    `json:"supports_embeddings"`
	SupportsTools            bool    `json:"supports_tools"`
	SupportsStructuredOutput bool    `json:"supports_structured_output"`
	// SupportsSystemPrompt defaults to true in the spec (unlike the other
	// supports_* flags which default to false), so it is a pointer: nil means
	// the field was omitted and should be treated as true.
	SupportsSystemPrompt          *bool    `json:"supports_system_prompt,omitempty"`
	SupportsBatching              bool     `json:"supports_batching"`
	SupportsBackgroundResponse    bool     `json:"supports_background_response"`
	SupportsVideoGeneration       bool     `json:"supports_video_generation"`
	SupportsImageEdit             bool     `json:"supports_image_edit"`
	SupportsImageInpaint          bool     `json:"supports_image_inpaint"`
	SupportsImageOutpaint         bool     `json:"supports_image_outpaint"`
	SupportsImageMix              bool     `json:"supports_image_mix"`
	SupportsImageReframe          bool     `json:"supports_image_reframe"`
	SupportsImageUpscale          bool     `json:"supports_image_upscale"`
	SupportsImageRemoveBackground bool     `json:"supports_image_remove_background"`
	SupportsImageReference        bool     `json:"supports_image_reference"`
	ContextWindow                 *int     `json:"context_window,omitempty"`
	StandardContextThreshold      *int     `json:"standard_context_threshold,omitempty"`
	RealtimeSessionMaxTokens      *int     `json:"realtime_session_max_tokens,omitempty"`
	RealtimeMaxConcurrentPerOwner *int     `json:"realtime_max_concurrent_per_owner,omitempty"`
	IsComposite                   bool     `json:"is_composite"`
	CompositeModels               []string `json:"composite_models,omitempty"`
}

ModelInfo describes an available model.

type ModelOverride added in v0.1.3

type ModelOverride struct {
	Model        string   `json:"model"`
	Temperature  *float64 `json:"temperature,omitempty"`
	MaxTokens    *int     `json:"max_tokens,omitempty"`
	SystemPrompt *string  `json:"system_prompt,omitempty"`
}

type ModelPricing

type ModelPricing struct {
	// Required
	PromptUSDPer1K     *string `json:"prompt_usd_per_1k,omitempty"`
	CompletionUSDPer1K *string `json:"completion_usd_per_1k,omitempty"`
	// Optional
	PricingUnit                        *string `json:"pricing_unit,omitempty"`
	PromptUSDPer1M                     *string `json:"prompt_usd_per_1m,omitempty"`
	CompletionUSDPer1M                 *string `json:"completion_usd_per_1m,omitempty"`
	ImageOutputUSDPerImage             *string `json:"image_output_usd_per_image,omitempty"`
	RequestUSD                         *string `json:"request_usd,omitempty"`
	LongContextInputUSDPer1M           *string `json:"long_context_input_usd_per_1m,omitempty"`
	LongContextOutputUSDPer1M          *string `json:"long_context_output_usd_per_1m,omitempty"`
	CacheReadInputUSDPer1M             *string `json:"cache_read_input_usd_per_1m,omitempty"`
	CacheWriteInputUSDPer1M            *string `json:"cache_write_input_usd_per_1m,omitempty"`
	CacheReadAudioInputUSDPer1M        *string `json:"cache_read_audio_input_usd_per_1m,omitempty"`
	LongContextCacheReadInputUSDPer1M  *string `json:"long_context_cache_read_input_usd_per_1m,omitempty"`
	LongContextCacheWriteInputUSDPer1M *string `json:"long_context_cache_write_input_usd_per_1m,omitempty"`
	BatchInputUSDPer1M                 *string `json:"batch_input_usd_per_1m,omitempty"`
	BatchOutputUSDPer1M                *string `json:"batch_output_usd_per_1m,omitempty"`
	TrainingUSDPer1M                   *string `json:"training_usd_per_1m,omitempty"`
	FineTunedInputUSDPer1M             *string `json:"fine_tuned_input_usd_per_1m,omitempty"`
	FineTunedOutputUSDPer1M            *string `json:"fine_tuned_output_usd_per_1m,omitempty"`
	AudioInputUSDPer1M                 *string `json:"audio_input_usd_per_1m,omitempty"`
	AudioOutputUSDPer1M                *string `json:"audio_output_usd_per_1m,omitempty"`
	TranscriptionUSDPer1M              *string `json:"transcription_usd_per_1m,omitempty"`
	CachedAudioInputUSDPer1M           *string `json:"cached_audio_input_usd_per_1m,omitempty"`
	CachedTextInputUSDPer1M            *string `json:"cached_text_input_usd_per_1m,omitempty"`
	CacheHitUSDPer1M                   *string `json:"cache_hit_usd_per_1m,omitempty"`
	OutputWithAudioUSDPer1M            *string `json:"output_with_audio_usd_per_1m,omitempty"`
	OutputWithVideoUSDPer1M            *string `json:"output_with_video_usd_per_1m,omitempty"`
	ImageInputUSDPerImage              *string `json:"image_input_usd_per_image,omitempty"`
	ImageOutputSize                    *string `json:"image_output_size,omitempty"`
	EffectiveDate                      *string `json:"effective_date,omitempty"`
	DeprecatedDate                     *string `json:"deprecated_date,omitempty"`
	Notes                              *string `json:"notes,omitempty"`
	SourceURL                          *string `json:"source_url,omitempty"`
	DiscountPct                        *string `json:"discount_pct,omitempty"`
}

ModelPricing holds per-token pricing for a model. All values are strings per the spec — do not coerce to float.

type ModelSearchParams added in v0.1.8

type ModelSearchParams struct {
	Q              *string
	Free           *bool
	Discounted     *bool
	InputModality  []string
	OutputModality []string
	Brand          []string
	Sort           *string // "brand" | "name" | "id" | "context_length"
	Order          *string // "asc" | "desc"
	Limit          *int
	Offset         *int
}

ModelSearchParams holds query parameters for Models.Search. All fields are optional; leave a field nil/empty to omit it.

type ModelsPage added in v0.1.8

type ModelsPage struct {
	Items  []ModelInfo `json:"items"`
	Total  int         `json:"total"`
	Limit  int         `json:"limit"`
	Offset int         `json:"offset"`
	Brands []string    `json:"brands"`
}

type ModelsResource

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

ModelsResource provides access to the /v1/models endpoints.

func (*ModelsResource) Free

func (r *ModelsResource) Free(ctx context.Context) ([]ModelInfo, error)

Free returns only free-tier models.

func (*ModelsResource) Get added in v0.1.8

func (r *ModelsResource) Get(ctx context.Context, modelID string) (*ModelInfo, error)

Get returns a single model's detail by id (e.g. "openai/gpt-4o"). The modelID may contain slashes (which are preserved); other special characters are percent-encoded per segment.

func (*ModelsResource) List

func (r *ModelsResource) List(ctx context.Context, params ListModelsParams) ([]ModelInfo, error)

List returns all available models. Pass optional params to filter by free, type, or provider.

func (*ModelsResource) Paid

func (r *ModelsResource) Paid(ctx context.Context) ([]ModelInfo, error)

Paid returns only paid-tier models.

func (*ModelsResource) Search added in v0.1.8

func (r *ModelsResource) Search(ctx context.Context, params ModelSearchParams) (*ModelsPage, error)

Search returns a paginated, filtered page of the model catalog (DB-only).

type ModerationImageURL added in v0.1.8

type ModerationImageURL struct {
	URL string `json:"url"`
}

type ModerationInputItem added in v0.1.8

type ModerationInputItem struct {
	Type     string              `json:"type"` // "text" | "image_url"
	Text     *string             `json:"text,omitempty"`
	ImageURL *ModerationImageURL `json:"image_url,omitempty"`
}

type ModerationParams added in v0.1.8

type ModerationParams struct {
	Input interface{} `json:"input"`
	Model *string     `json:"model,omitempty"`
}

ModerationParams is the request body for POST /v1/moderations. Input is a string, []string, or []ModerationInputItem. Leave Model nil to use the server default ("omni-moderation-latest").

type ModerationResponse added in v0.1.8

type ModerationResponse struct {
	ID      string             `json:"id"`
	Model   string             `json:"model"`
	Results []ModerationResult `json:"results"`
}

type ModerationResult added in v0.1.8

type ModerationResult struct {
	Flagged        bool               `json:"flagged"`
	Categories     map[string]bool    `json:"categories"`
	CategoryScores map[string]float64 `json:"category_scores"`
}

type ModerationsResource added in v0.1.8

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

ModerationsResource provides access to POST /v1/moderations.

func (*ModerationsResource) Create added in v0.1.8

Create classifies the given input for policy violations.

type MultimodalEmbeddingInput added in v0.1.8

type MultimodalEmbeddingInput struct {
	Type     string             `json:"type"`
	Text     *string            `json:"text,omitempty"`
	ImageURL *ImageEmbeddingUrl `json:"image_url,omitempty"`
	VideoURL *VideoEmbeddingUrl `json:"video_url,omitempty"`
}

MultimodalEmbeddingInput is one element of a multimodal embeddings input array. Type is one of "text", "image_url", or "video_url".

type PronunciationDictionaryLocator added in v0.1.6

type PronunciationDictionaryLocator struct {
	PronunciationDictionaryID string `json:"pronunciation_dictionary_id"`
	VersionID                 string `json:"version_id"`
}

type ProviderPreferences added in v0.1.3

type ProviderPreferences struct {
	Order             []string `json:"order,omitempty"`
	AllowFallbacks    *bool    `json:"allow_fallbacks,omitempty"`
	RequireParameters *bool    `json:"require_parameters,omitempty"`
	DataCollection    *string  `json:"data_collection,omitempty"`
}

type RagFileListResponse added in v0.1.5

type RagFileListResponse struct {
	Files  []RagFileStatus `json:"files"`
	Total  int             `json:"total"`
	Limit  int             `json:"limit"`
	Offset int             `json:"offset"`
}

RagFileListResponse is returned by GET /v1/files (RAG).

type RagFileStatus added in v0.1.5

type RagFileStatus struct {
	FileID             string   `json:"file_id"`
	UploadStatus       string   `json:"upload_status"`
	FileName           string   `json:"file_name"`
	FileType           string   `json:"file_type"`
	MimeType           string   `json:"mime_type"`
	SizeBytes          *int64   `json:"size_bytes,omitempty"`
	AssetURL           *string  `json:"asset_url,omitempty"`
	SignedURL          *string  `json:"signed_url,omitempty"`
	SignedURLExpiresAt *string  `json:"signed_url_expires_at,omitempty"`
	EmbeddingStatus    string   `json:"embedding_status"`
	CreatedAt          string   `json:"created_at"`
	UpdatedAt          string   `json:"updated_at"`
	TotalTokens        *int64   `json:"total_tokens,omitempty"`
	TotalCostUSD       *float64 `json:"total_cost_usd,omitempty"`
	LastErrorCode      *string  `json:"last_error_code,omitempty"`
}

RagFileStatus represents the processing state of a RAG file.

type RagResource added in v0.1.5

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

RagResource provides access to the RAG /v1/files endpoints.

func (*RagResource) Embed added in v0.1.5

Embed enqueues embedding jobs for one or more files. Each file must have upload_status=ready and embedding_status=pending or failed.

func (*RagResource) Get added in v0.1.5

func (r *RagResource) Get(ctx context.Context, fileID string) (*RagFileStatus, error)

Get returns the current status of a single RAG file.

func (*RagResource) InitUpload added in v0.1.5

func (r *RagResource) InitUpload(ctx context.Context, params InitUploadRequest) (*InitUploadResponse, error)

InitUpload initialises a RAG file upload and returns a signed URL for the actual file content. After calling this, PUT the file bytes to SignedURL, then call Embed to trigger embedding.

func (*RagResource) List added in v0.1.5

List returns a paginated list of RAG files owned by the authenticated user.

func (*RagResource) Search added in v0.1.5

func (r *RagResource) Search(ctx context.Context, params SearchRequest) (*SearchResponse, error)

Search performs a vector similarity search over embedded files.

func (*RagResource) UploadFile added in v0.1.5

func (r *RagResource) UploadFile(ctx context.Context, params UploadFileParams) (*InitUploadResponse, error)

UploadFile is a convenience wrapper that calls InitUpload then PUTs the file content to the returned signed URL in one step. It returns the same InitUploadResponse so the caller has the FileID.

type RealtimeConnectParams added in v0.1.5

type RealtimeConnectParams struct {
	// Model is the realtime-capable model ID, e.g. "openai/gpt-4o-realtime-preview".
	Model string
}

RealtimeConnectParams holds parameters for opening a realtime session.

type RealtimeError added in v0.1.5

type RealtimeError struct {
	// Code is the snake_case error code, e.g. "invalid_api_key", "insufficient_quota".
	Code string `json:"code"`
	// Message is a human-readable description.
	Message string `json:"message"`
	// Param is the offending parameter, if any.
	Param string `json:"param,omitempty"`
	// RequestID is the server-assigned session request ID for log correlation.
	RequestID string `json:"request_id,omitempty"`
}

RealtimeError is delivered by the server inside a {"type":"error",...} frame before the socket is closed. It implements the error interface.

func (*RealtimeError) Error added in v0.1.5

func (e *RealtimeError) Error() string

type RealtimeMessage added in v0.1.5

type RealtimeMessage struct {
	// Text is the raw JSON string for text frames.
	Text string
	// Audio is the decoded raw audio bytes for output-audio delta events.
	Audio []byte
	// Event is the parsed JSON map for the server event.
	Event map[string]any
}

RealtimeMessage is a single frame received from the server.

Event holds the parsed JSON map for a server event. For output-audio delta events (response.output_audio.delta / response.audio.delta), Audio also carries the decoded raw audio bytes, so callers can check len(msg.Audio) > 0 while still inspecting msg.Event.

type RealtimeResource added in v0.1.5

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

RealtimeResource provides access to the MeshAPI WebSocket realtime endpoint.

Accessible as client.Realtime.

func (*RealtimeResource) Connect added in v0.1.5

Connect opens a WebSocket session to the realtime endpoint for the given model.

Authentication is delivered via the Sec-WebSocket-Protocol header following the wire contract: "openai-realtime, Bearer <token>".

The returned session is ready for bidirectional frame exchange immediately. Cancel ctx to abort the connection attempt; for an established session use session.Close().

type RealtimeSession added in v0.1.5

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

RealtimeSession is an active WebSocket session with the MeshAPI realtime endpoint.

Send and Receive may be called concurrently from separate goroutines. Close must be called exactly once when the session is no longer needed.

func (*RealtimeSession) Close added in v0.1.5

func (s *RealtimeSession) Close() error

Close closes the WebSocket connection with a normal closure. It acquires sendMu so that an in-progress Send or SendAudio is not racing with the close frame write. It is safe to call Close more than once.

func (*RealtimeSession) Events added in v0.1.5

func (s *RealtimeSession) Events(ctx context.Context) (<-chan RealtimeMessage, <-chan error)

Events starts a goroutine that pumps server frames into the returned channels.

msgCh closes when the session ends or ctx is done; errCh receives at most one terminal error. Drain msgCh before reading errCh.

func (*RealtimeSession) Receive added in v0.1.5

Receive reads the next frame from the server.

Returns *RealtimeError when the server delivers an error envelope ({"type":"error",...}). Returns io.EOF on a clean server-initiated close. Context cancellation or deadline interrupts an in-progress read.

func (*RealtimeSession) Send added in v0.1.5

func (s *RealtimeSession) Send(ctx context.Context, event any) error

Send marshals event as JSON and sends it to the server as a text frame.

func (*RealtimeSession) SendAudio added in v0.1.5

func (s *RealtimeSession) SendAudio(ctx context.Context, audio []byte) error

SendAudio appends raw PCM16 audio to the input buffer.

It is sent as a base64 input_audio_buffer.append text event — the realtime API does not accept binary WebSocket frames.

type ResponsesFunctionTool added in v0.1.3

type ResponsesFunctionTool struct {
	Type        string      `json:"type"`
	Name        string      `json:"name"`
	Description *string     `json:"description,omitempty"`
	Parameters  interface{} `json:"parameters,omitempty"`
	Strict      *bool       `json:"strict,omitempty"`
}

type ResponsesListItem added in v0.1.8

type ResponsesListItem struct {
	ID          string  `json:"id"`
	Object      *string `json:"object,omitempty"`
	Model       *string `json:"model,omitempty"`
	Provider    *string `json:"provider,omitempty"`
	Status      *string `json:"status,omitempty"`
	CreatedAt   *int64  `json:"created_at,omitempty"`
	CompletedAt *int64  `json:"completed_at,omitempty"`
	UsageSynced *bool   `json:"usage_synced,omitempty"`
}

type ResponsesListParams added in v0.1.8

type ResponsesListParams struct {
	After *string
	Limit *int
}

ResponsesListParams holds query parameters for Responses.List.

type ResponsesListResponse added in v0.1.8

type ResponsesListResponse struct {
	Object  *string             `json:"object,omitempty"`
	Data    []ResponsesListItem `json:"data"`
	HasMore bool                `json:"has_more"`
	FirstID *string             `json:"first_id,omitempty"`
	LastID  *string             `json:"last_id,omitempty"`
}

type ResponsesParams added in v0.1.3

type ResponsesParams struct {
	Model           *string                `json:"model,omitempty"`
	Input           interface{}            `json:"input"`
	Background      *bool                  `json:"background,omitempty"`
	Text            map[string]interface{} `json:"text,omitempty"`
	Template        *string                `json:"template,omitempty"`
	Variables       map[string]string      `json:"variables,omitempty"`
	SessionID       *string                `json:"session_id,omitempty"`
	Stream          *bool                  `json:"stream,omitempty"`
	MaxOutputTokens *int                   `json:"max_output_tokens,omitempty"`
	Temperature     *float64               `json:"temperature,omitempty"`
	TopP            *float64               `json:"top_p,omitempty"`
	Seed            *int                   `json:"seed,omitempty"`
	Reasoning       map[string]interface{} `json:"reasoning,omitempty"`
	Tools           []interface{}          `json:"tools,omitempty"`
	ToolChoice      interface{}            `json:"tool_choice,omitempty"`
	ResponseFormat  map[string]interface{} `json:"response_format,omitempty"`
	Plugins         []interface{}          `json:"plugins,omitempty"`
	User            *string                `json:"user,omitempty"`
	// Fields added in pass-2 audit — all optional/nullable per spec.
	// PreviousResponseID chains this response to a prior one for multi-turn.
	PreviousResponseID *string `json:"previous_response_id,omitempty"`
	// Instructions overrides the system-level instructions for this request.
	Instructions *string `json:"instructions,omitempty"`
	// Thinking is a free-form object controlling chain-of-thought (model-specific).
	Thinking map[string]interface{} `json:"thinking,omitempty"`
	// Caching is a free-form object with prompt-caching settings.
	Caching map[string]interface{} `json:"caching,omitempty"`
	// Store controls whether the response is persisted for later retrieval.
	Store *bool `json:"store,omitempty"`
	// Include lists additional output fields to return (model-specific).
	Include []interface{} `json:"include,omitempty"`
	// ExpireAt is a Unix timestamp after which the stored response may be deleted.
	ExpireAt *int64 `json:"expire_at,omitempty"`
	// MaxToolCalls limits the number of tool calls permitted (1..10).
	MaxToolCalls *int `json:"max_tool_calls,omitempty"`
	// ContextManagement is a free-form object for context window management.
	ContextManagement map[string]interface{} `json:"context_management,omitempty"`
	// Timeout overrides the server's upstream-provider timeout (default 300 s).
	Timeout *float64 `json:"timeout,omitempty"`
}

type ResponsesResource added in v0.1.3

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

func (*ResponsesResource) Create added in v0.1.3

func (*ResponsesResource) Get added in v0.1.8

func (r *ResponsesResource) Get(ctx context.Context, responseID string) (*ResponsesResponse, error)

Get fetches a background response job by id.

func (*ResponsesResource) List added in v0.1.8

List returns the caller's background response jobs (OpenAI list envelope).

func (*ResponsesResource) Stream added in v0.1.3

func (r *ResponsesResource) Stream(ctx context.Context, params ResponsesParams) (<-chan ResponsesStreamEvent, <-chan error)

type ResponsesResponse added in v0.1.3

type ResponsesResponse struct {
	ID     *string                `json:"id,omitempty"`
	Object *string                `json:"object,omitempty"`
	Model  *string                `json:"model,omitempty"`
	Output []interface{}          `json:"output,omitempty"`
	Usage  *ResponsesUsage        `json:"usage,omitempty"`
	Status *string                `json:"status,omitempty"`
	Extra  map[string]interface{} `json:"-"`
}

type ResponsesStreamEvent added in v0.1.3

type ResponsesStreamEvent map[string]interface{}

type ResponsesUsage added in v0.1.3

type ResponsesUsage struct {
	InputTokens             *int                   `json:"input_tokens,omitempty"`
	OutputTokens            *int                   `json:"output_tokens,omitempty"`
	TotalTokens             *int                   `json:"total_tokens,omitempty"`
	PromptTokens            *int                   `json:"prompt_tokens,omitempty"`
	CompletionTokens        *int                   `json:"completion_tokens,omitempty"`
	PromptTokensDetails     map[string]interface{} `json:"prompt_tokens_details,omitempty"`
	CompletionTokensDetails map[string]interface{} `json:"completion_tokens_details,omitempty"`
	ClassifierTokens        *int                   `json:"classifier_tokens,omitempty"`
}

type RouterResource added in v0.1.8

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

RouterResource provides access to POST /v1/router/select.

Select-only Auto Router: returns the model the Auto Router would pick for a prompt without running inference, so the caller can run inference on its own path. Gated server-side by AUTO_ROUTER_ENABLED. Fail-soft: on classification failure the router returns the configured default model with AutoRouterMeta.FallbackUsed = true rather than erroring.

func (*RouterResource) Select added in v0.1.8

Select returns the model the Auto Router would pick for the given messages.

type RouterSelectParams added in v0.1.8

type RouterSelectParams struct {
	Messages      []ChatMessage `json:"messages"`
	APIType       *string       `json:"api_type,omitempty"` // "completions" (default) | "responses" | "embeddings"
	ExcludeModels []string      `json:"exclude_models,omitempty"`
}

type RouterSelectResponse added in v0.1.8

type RouterSelectResponse struct {
	Model           string         `json:"model"`
	AutoRouter      AutoRouterMeta `json:"auto_router"`
	ReasoningEffort *string        `json:"reasoning_effort,omitempty"`
}

type SearchRequest added in v0.1.5

type SearchRequest struct {
	Query    string                 `json:"query"`
	TopK     *int                   `json:"top_k,omitempty"`
	FileIDs  []string               `json:"file_ids,omitempty"`
	Filter   map[string]interface{} `json:"filter,omitempty"`
	DateFrom *int64                 `json:"date_from,omitempty"`
	DateTo   *int64                 `json:"date_to,omitempty"`
}

SearchRequest is the body for POST /v1/files/search.

type SearchResponse added in v0.1.5

type SearchResponse struct {
	Results []SearchResult `json:"results"`
}

SearchResponse is returned by POST /v1/files/search.

type SearchResult added in v0.1.5

type SearchResult struct {
	Score      float64                `json:"score"`
	Text       string                 `json:"text"`
	ParentText string                 `json:"parent_text"`
	FileID     *string                `json:"file_id,omitempty"`
	FileName   *string                `json:"file_name,omitempty"`
	FileType   *string                `json:"file_type,omitempty"`
	MimeType   *string                `json:"mime_type,omitempty"`
	ChunkIndex *int                   `json:"chunk_index,omitempty"`
	CreatedAt  *int64                 `json:"created_at,omitempty"`
	Metadata   map[string]interface{} `json:"metadata"`
}

SearchResult is a single vector-search hit.

type SpeechParams added in v0.1.6

type SpeechParams struct {
	Input                           string                           `json:"input"`
	Model                           *string                          `json:"model,omitempty"`
	Voice                           *string                          `json:"voice,omitempty"`
	Stream                          *bool                            `json:"stream,omitempty"`
	ResponseFormat                  *string                          `json:"response_format,omitempty"`
	LanguageCode                    *string                          `json:"language_code,omitempty"`
	VoiceSettings                   *VoiceSettings                   `json:"voice_settings,omitempty"`
	PronunciationDictionaryLocators []PronunciationDictionaryLocator `json:"pronunciation_dictionary_locators,omitempty"`
	Seed                            *int                             `json:"seed,omitempty"`
	PreviousText                    *string                          `json:"previous_text,omitempty"`
	NextText                        *string                          `json:"next_text,omitempty"`
	PreviousRequestIDs              []string                         `json:"previous_request_ids,omitempty"`
	NextRequestIDs                  []string                         `json:"next_request_ids,omitempty"`
	ApplyTextNormalization          *string                          `json:"apply_text_normalization,omitempty"`
	ApplyLanguageTextNormalization  *bool                            `json:"apply_language_text_normalization,omitempty"`
	UsePvcAsIvc                     *bool                            `json:"use_pvc_as_ivc,omitempty"`
	EnableLogging                   *bool                            `json:"enable_logging,omitempty"`
	OptimizeStreamingLatency        *int                             `json:"optimize_streaming_latency,omitempty"`
	Speaker                         *string                          `json:"speaker,omitempty"`
	TargetLanguageCode              *string                          `json:"target_language_code,omitempty"`
	Pitch                           *float64                         `json:"pitch,omitempty"`
	Pace                            *float64                         `json:"pace,omitempty"`
	Loudness                        *float64                         `json:"loudness,omitempty"`
	SpeechSampleRate                *int                             `json:"speech_sample_rate,omitempty"`
	EnablePreprocessing             *bool                            `json:"enable_preprocessing,omitempty"`
}

type TemplateSummary

type TemplateSummary struct {
	ID          string                   `json:"id"`
	Name        string                   `json:"name"`
	Owner       *string                  `json:"owner"`
	IsGlobal    bool                     `json:"is_global"`
	Description *string                  `json:"description,omitempty"`
	System      *string                  `json:"system,omitempty"`
	Messages    []map[string]interface{} `json:"messages,omitempty"`
	Model       *string                  `json:"model,omitempty"`
	Params      map[string]interface{}   `json:"params,omitempty"`
	Variables   []string                 `json:"variables,omitempty"`
	CreatedAt   string                   `json:"created_at"`
	UpdatedAt   string                   `json:"updated_at"`
}

TemplateSummary is the response shape for all template operations.

type TemplatesResource

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

TemplatesResource provides access to the /v1/templates CRUD endpoints.

func (*TemplatesResource) Create

Create creates a new prompt template.

func (*TemplatesResource) Delete

func (r *TemplatesResource) Delete(ctx context.Context, id string) error

Delete deletes a template (returns nil on 204 No Content).

func (*TemplatesResource) Get

Get returns a single template by ID.

func (*TemplatesResource) List

List returns all templates owned by the authenticated user.

func (*TemplatesResource) Update

Update partially updates a template.

type TokenUsage added in v0.1.3

type TokenUsage struct {
	PromptTokens     *int `json:"prompt_tokens,omitempty"`
	CompletionTokens *int `json:"completion_tokens,omitempty"`
	TotalTokens      *int `json:"total_tokens,omitempty"`
}

type Tool

type Tool struct {
	Type     string       `json:"type"`
	Function ToolFunction `json:"function"`
}

Tool defines a callable function available to the model.

type ToolCall

type ToolCall struct {
	ID               string           `json:"id"`
	Type             string           `json:"type"`
	Function         ToolCallFunction `json:"function"`
	ThoughtSignature *string          `json:"thought_signature,omitempty"`
}

ToolCall represents a tool invocation in an assistant message.

type ToolCallFunction

type ToolCallFunction struct {
	Name      string `json:"name"`
	Arguments string `json:"arguments"`
}

ToolCallFunction holds the name and JSON-encoded arguments for a tool call.

type ToolChoice

type ToolChoice interface{}

ToolChoice controls model tool use. Use "auto", "none", "required", or ToolChoiceObject.

type ToolChoiceFunction

type ToolChoiceFunction struct {
	Name string `json:"name"`
}

ToolChoiceFunction names the function to call.

type ToolChoiceObject

type ToolChoiceObject struct {
	Type     string             `json:"type"`
	Function ToolChoiceFunction `json:"function"`
}

ToolChoiceObject selects a specific function.

type ToolFunction

type ToolFunction struct {
	Name        string      `json:"name"`
	Description *string     `json:"description,omitempty"`
	Parameters  interface{} `json:"parameters,omitempty"`
}

ToolFunction describes a callable function.

type TranscriptionParams added in v0.1.6

type TranscriptionParams struct {
	Model                 string   `json:"model"`
	LanguageCode          *string  `json:"language_code,omitempty"`
	TagAudioEvents        *bool    `json:"tag_audio_events,omitempty"`
	NumSpeakers           *int     `json:"num_speakers,omitempty"`
	TimestampsGranularity *string  `json:"timestamps_granularity,omitempty"`
	Diarize               *bool    `json:"diarize,omitempty"`
	DiarizationThreshold  *float64 `json:"diarization_threshold,omitempty"`
	AdditionalFormats     *string  `json:"additional_formats,omitempty"`
	FileFormat            *string  `json:"file_format,omitempty"`
	CloudStorageURL       *string  `json:"cloud_storage_url,omitempty"`
	SourceURL             *string  `json:"source_url,omitempty"`
	Webhook               *bool    `json:"webhook,omitempty"`
	WebhookID             *string  `json:"webhook_id,omitempty"`
	Temperature           *float64 `json:"temperature,omitempty"`
	Seed                  *int     `json:"seed,omitempty"`
	UseMultiChannel       *bool    `json:"use_multi_channel,omitempty"`
	WebhookMetadata       *string  `json:"webhook_metadata,omitempty"`
	EntityDetection       *string  `json:"entity_detection,omitempty"`
	NoVerbatim            *bool    `json:"no_verbatim,omitempty"`
	DetectSpeakerRoles    *bool    `json:"detect_speaker_roles,omitempty"`
	EntityRedaction       *string  `json:"entity_redaction,omitempty"`
	EntityRedactionMode   *string  `json:"entity_redaction_mode,omitempty"`
	Keyterms              []string `json:"keyterms,omitempty"`
	WithTimestamps        *bool    `json:"with_timestamps,omitempty"`
	DebugMode             *bool    `json:"debug_mode,omitempty"`
}

type TranscriptionResponse added in v0.1.6

type TranscriptionResponse struct {
	Text string `json:"text"`
}

type TranscriptionTranslateParams added in v0.1.6

type TranscriptionTranslateParams struct {
	Model  *string `json:"model,omitempty"`
	Prompt *string `json:"prompt,omitempty"`
}

type UpdateTemplateParams

type UpdateTemplateParams struct {
	Name        *string                  `json:"name,omitempty"`
	Description *string                  `json:"description,omitempty"`
	System      *string                  `json:"system,omitempty"`
	Messages    []map[string]interface{} `json:"messages,omitempty"`
	Model       *string                  `json:"model,omitempty"`
	Params      map[string]interface{}   `json:"params,omitempty"`
	Variables   []string                 `json:"variables,omitempty"`
}

UpdateTemplateParams is the request body for PATCH /v1/templates/{id}.

type UploadFileParams added in v0.1.5

type UploadFileParams struct {
	FileName string
	MimeType string
	Content  []byte
	Embed    *bool
	Metadata map[string]interface{}
}

UploadFileParams is used by RagResource.UploadFile — it combines the upload initialisation fields with the raw file Content to upload in one call.

type UsageInfo

type UsageInfo struct {
	PromptTokens               int                    `json:"prompt_tokens"`
	CompletionTokens           int                    `json:"completion_tokens"`
	TotalTokens                int                    `json:"total_tokens"`
	PromptTokensDetails        map[string]interface{} `json:"prompt_tokens_details,omitempty"`
	CompletionTokensDetails    map[string]interface{} `json:"completion_tokens_details,omitempty"`
	ClassifierPromptTokens     *int                   `json:"classifier_prompt_tokens,omitempty"`
	ClassifierCompletionTokens *int                   `json:"classifier_completion_tokens,omitempty"`
	ClassifierTokens           *int                   `json:"classifier_tokens,omitempty"`
}

UsageInfo holds token counts for a completion.

type VideoContentItem added in v0.1.6

type VideoContentItem struct {
	Type      string                 `json:"type"`
	Text      *string                `json:"text,omitempty"`
	ImageURL  map[string]interface{} `json:"image_url,omitempty"`
	VideoURL  map[string]interface{} `json:"video_url,omitempty"`
	AudioURL  map[string]interface{} `json:"audio_url,omitempty"`
	DraftTask map[string]interface{} `json:"draft_task,omitempty"`
	Role      *string                `json:"role,omitempty"`
}

VideoContentItem is a single item in the content array.

type VideoEmbeddingUrl added in v0.1.8

type VideoEmbeddingUrl struct {
	URL string `json:"url"`
}

VideoEmbeddingUrl holds a URL for a multimodal video embedding input.

type VideoGenerationParams added in v0.1.6

type VideoGenerationParams struct {
	Model                 string             `json:"model"`
	Content               []VideoContentItem `json:"content"`
	CallbackURL           *string            `json:"callback_url,omitempty"`
	ReturnLastFrame       *bool              `json:"return_last_frame,omitempty"`
	ServiceTier           *string            `json:"service_tier,omitempty"`
	ExecutionExpiresAfter *int               `json:"execution_expires_after,omitempty"`
	GenerateAudio         *bool              `json:"generate_audio,omitempty"`
	Draft                 *bool              `json:"draft,omitempty"`
	Resolution            *string            `json:"resolution,omitempty"`
	Ratio                 *string            `json:"ratio,omitempty"`
	Duration              *int               `json:"duration,omitempty"`
	Frames                *int               `json:"frames,omitempty"`
	Seed                  *int               `json:"seed,omitempty"`
	CameraFixed           *bool              `json:"camera_fixed,omitempty"`
	Watermark             *bool              `json:"watermark,omitempty"`
	SafetyIdentifier      *string            `json:"safety_identifier,omitempty"`
	Priority              *int               `json:"priority,omitempty"`
}

VideoGenerationParams is the request body for POST /v1/video/generations.

type VideoTaskContent added in v0.1.6

type VideoTaskContent struct {
	VideoURL     *string `json:"video_url,omitempty"`
	LastFrameURL *string `json:"last_frame_url,omitempty"`
}

VideoTaskContent holds the output URLs for a completed video task.

type VideoTaskError added in v0.1.6

type VideoTaskError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

VideoTaskError holds error details for a failed video task.

type VideoTaskListResponse added in v0.1.6

type VideoTaskListResponse struct {
	Object  string              `json:"object"`
	Data    []VideoTaskResponse `json:"data"`
	HasMore bool                `json:"has_more"`
	Total   int                 `json:"total"`
	Limit   int                 `json:"limit"`
	Offset  int                 `json:"offset"`
}

VideoTaskListResponse is the response from GET /v1/video/generations.

type VideoTaskResponse added in v0.1.6

type VideoTaskResponse struct {
	ID                    string            `json:"id"`
	Status                string            `json:"status"`
	Model                 *string           `json:"model,omitempty"`
	Error                 *VideoTaskError   `json:"error,omitempty"`
	CreatedAt             *int64            `json:"created_at,omitempty"`
	UpdatedAt             *int64            `json:"updated_at,omitempty"`
	Content               *VideoTaskContent `json:"content,omitempty"`
	Seed                  *int              `json:"seed,omitempty"`
	Resolution            *string           `json:"resolution,omitempty"`
	Ratio                 *string           `json:"ratio,omitempty"`
	Duration              *int              `json:"duration,omitempty"`
	Frames                *int              `json:"frames,omitempty"`
	FramesPerSecond       *int              `json:"framespersecond,omitempty"`
	GenerateAudio         *bool             `json:"generate_audio,omitempty"`
	SafetyIdentifier      *string           `json:"safety_identifier,omitempty"`
	Priority              *int              `json:"priority,omitempty"`
	Draft                 *bool             `json:"draft,omitempty"`
	DraftTaskID           *string           `json:"draft_task_id,omitempty"`
	ServiceTier           *string           `json:"service_tier,omitempty"`
	ExecutionExpiresAfter *int              `json:"execution_expires_after,omitempty"`
	Usage                 *VideoTaskUsage   `json:"usage,omitempty"`
}

VideoTaskResponse is the shape of a single video generation task.

type VideoTaskUsage added in v0.1.6

type VideoTaskUsage struct {
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

VideoTaskUsage holds token usage for a video task.

type VideoURL added in v0.1.8

type VideoURL struct {
	URL string `json:"url"`
}

VideoURL holds the URL for a video content part.

type VideosResource added in v0.1.6

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

VideosResource provides access to /v1/video/generations endpoints.

func (*VideosResource) Generate added in v0.1.6

Generate submits a video generation task (POST /v1/video/generations).

func (*VideosResource) List added in v0.1.6

List returns video generation tasks (GET /v1/video/generations).

func (*VideosResource) Retrieve added in v0.1.6

func (r *VideosResource) Retrieve(ctx context.Context, taskID string) (*VideoTaskResponse, error)

Retrieve fetches a single video generation task (GET /v1/video/generations/{task_id}).

type Voice added in v0.1.7

type Voice struct {
	VoiceID     string `json:"voice_id"`
	Name        string `json:"name"`
	Category    string `json:"category"`
	Description string `json:"description"`
	PreviewURL  string `json:"preview_url"`
	// Labels values are provider-defined and not always strings — decode as
	// arbitrary JSON so a numeric/bool/null label doesn't fail the whole request.
	Labels map[string]interface{} `json:"labels,omitempty"`
}

type VoiceSettings added in v0.1.6

type VoiceSettings struct {
	Stability       *float64 `json:"stability,omitempty"`
	SimilarityBoost *float64 `json:"similarity_boost,omitempty"`
	Style           *float64 `json:"style,omitempty"`
	UseSpeakerBoost *bool    `json:"use_speaker_boost,omitempty"`
	Speed           *float64 `json:"speed,omitempty"`
}

type VoicesResponse added in v0.1.7

type VoicesResponse struct {
	Voices []Voice `json:"voices"`
	// Pointers so an omitted has_more / total_count is distinguishable from a
	// real zero value (e.g. paginate while HasMore != nil && *HasMore).
	HasMore       *bool   `json:"has_more,omitempty"`
	TotalCount    *int    `json:"total_count,omitempty"`
	NextPageToken *string `json:"next_page_token"`
}

type WebResource added in v0.1.8

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

WebResource provides access to POST /v1/web/search.

Gated server-side by WEB_SEARCH_ENABLED; when disabled the endpoint returns an error rather than results. Failover between the native engine and Tavily is opaque — inspect WebSearchResponse.Provider to see which engine served the request.

func (*WebResource) Search added in v0.1.8

Search runs a live web search.

type WebSearchParams added in v0.1.8

type WebSearchParams struct {
	Query          string   `json:"query"`
	Model          *string  `json:"model,omitempty"`
	Provider       *string  `json:"provider,omitempty"`     // "native" | "tavily"
	MaxResults     *int     `json:"max_results,omitempty"`  // 1–20, server default 5
	SearchDepth    *string  `json:"search_depth,omitempty"` // "basic" | "advanced"
	IncludeDomains []string `json:"include_domains,omitempty"`
	ExcludeDomains []string `json:"exclude_domains,omitempty"`
	IncludeAnswer  *bool    `json:"include_answer,omitempty"`
}

type WebSearchResponse added in v0.1.8

type WebSearchResponse struct {
	Query   string                `json:"query"`
	Answer  *string               `json:"answer,omitempty"`
	Results []WebSearchResultItem `json:"results"`
	// Provider is "native" or "tavily" today; typed as string so an added
	// engine never breaks response decoding for existing SDK versions.
	Provider  string `json:"provider"`
	RequestID string `json:"request_id"`
}

type WebSearchResultItem added in v0.1.8

type WebSearchResultItem struct {
	Title         string   `json:"title"`
	URL           string   `json:"url"`
	Content       string   `json:"content"`
	Score         *float64 `json:"score,omitempty"`
	PublishedDate *string  `json:"published_date,omitempty"`
}

Jump to

Keyboard shortcuts

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