meshapi

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 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@v0.1.6

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",
})

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
audioBytes, err := client.Audio.Synthesize(ctx, meshapi.SpeechParams{
    Input: "Hello from MeshAPI.",
    Model: "sarvam/bulbul:v2",
    Voice: strPtr("meera"),
})
os.WriteFile("output.wav", audioBytes, 0644)

// Speech-to-text — submit transcription job
fileData, _ := os.ReadFile("audio.wav")
lang := "en"
result, err := client.Audio.Transcribe(ctx, meshapi.TranscriptionParams{
    Model:    "sarvam/saaras:v3",
    File:     fileData,
    FileName: "audio.wav",
    Language: &lang,
})
fmt.Println(result.Text)

// Translate audio to English
translated, err := client.Audio.Translate(ctx, meshapi.TranscriptionParams{
    Model:    "sarvam/saaras:v3",
    File:     fileData,
    FileName: "audio.wav",
})
fmt.Println(translated.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
task, err := client.Videos.Generate(ctx, meshapi.VideoGenerationParams{
    Model: "byteplus/dreamina-seedance-2-0",
    Content: []meshapi.VideoContentItem{
        {Type: "text", Text: strPtr("A serene mountain lake at sunrise")},
    },
})
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 { ... }

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
list, _ := client.RAG.List(ctx, meshapi.ListRagFilesParams{Limit: intPtr(50)})

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
session.Send(ctx, map[string]any{
    "type":    "session.update",
    "session": map[string]any{"instructions": "You are a helpful assistant."},
})

// Send raw audio bytes
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)

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.0"

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.0"

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) (map[string]any, 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) (map[string]any, 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.

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"`
	Status       *string `json:"status,omitempty"`
	Model        *string `json:"model,omitempty"`
	Provider     *string `json:"provider,omitempty"`
	CreatedAt    *int64  `json:"created_at,omitempty"`
	CompletedAt  *int64  `json:"completed_at,omitempty"`
	UsageSynced  *bool   `json:"usage_synced,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"`
	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"`
	// 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"`
}

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
}

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"`
	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"`
}

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"`
}

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 interface{} `json:"embedding"`
}

type EmbeddingsParams added in v0.1.3

type EmbeddingsParams struct {
	Model          *string     `json:"model,omitempty"`
	Input          interface{} `json:"input"`
	Dimensions     *int        `json:"dimensions,omitempty"`
	EncodingFormat *string     `json:"encoding_format,omitempty"`
	InputType      *string     `json:"input_type,omitempty"`
	Provider       interface{} `json:"provider,omitempty"`
	User           *string     `json:"user,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"`
	TotalTokens  int `json:"total_tokens"`
}

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"`
	OutputFormat   *string `json:"output_format,omitempty"`
	Stream         *bool   `json:"stream,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"`
}

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 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) 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"`
	Format string `json:"format"`
}

type ListModelsParams

type ListModelsParams struct {
	Free *bool // nil = no filter
}

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 {
	ID                     string        `json:"id"`
	Name                   string        `json:"name"`
	ContextLength          *int          `json:"context_length,omitempty"`
	IsFree                 bool          `json:"is_free"`
	Pricing                *ModelPricing `json:"pricing,omitempty"`
	Description            *string       `json:"description,omitempty"`
	SupportsThinking       *bool         `json:"supports_thinking,omitempty"`
	SupportsCompletionsAPI *bool         `json:"supports_completions_api,omitempty"`
	SupportsResponsesAPI   *bool         `json:"supports_responses_api,omitempty"`
	ModelType              *string       `json:"model_type,omitempty"`
	InputModalities        []string      `json:"input_modalities,omitempty"`
	OutputModalities       []string      `json:"output_modalities,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 {
	PromptUSDPer1K               *string `json:"prompt_usd_per_1k,omitempty"`
	CompletionUSDPer1K           *string `json:"completion_usd_per_1k,omitempty"`
	ImageUSDPerImage             *string `json:"image_usd_per_image,omitempty"`
	DiscountPct                  *string `json:"discount_pct,omitempty"`
	PromptUSDPer1KDiscounted     *string `json:"prompt_usd_per_1k_discounted,omitempty"`
	CompletionUSDPer1KDiscounted *string `json:"completion_usd_per_1k_discounted,omitempty"`
}

ModelPricing holds per-token pricing for a model.

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) List

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

List returns all available models. Pass a non-nil Free pointer to filter.

func (*ModelsResource) Paid

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

Paid returns only paid-tier models.

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 raw bytes for binary audio frames.
	Audio []byte
	// Event is the parsed JSON map for text frames; nil for audio frames.
	Event map[string]any
}

RealtimeMessage is a single frame received from the server.

Exactly one of Text or Audio is non-empty per message.

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 sends raw audio bytes to the server as a binary frame.

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 ResponsesParams added in v0.1.3

type ResponsesParams struct {
	Model           *string                `json:"model,omitempty"`
	Input           interface{}            `json:"input"`
	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"`
	// 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) 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 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"`
}

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 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 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 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"`
}

Jump to

Keyboard shortcuts

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