sonzai

package module
v1.12.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 18 Imported by: 0

README

Sonzai Go SDK

Go Reference Go Report Card

The official Go SDK for the Sonzai Character Engine API. Build AI characters with persistent memory, evolving personality, and real-time voice.

Zero dependencies. Uses only the Go standard library.

Documentation

Full API documentation is available at sonz.ai/docs.

See the api reference for a complete list of methods and types.

Installation

import (
    sonzai "github.com/sonz-ai/sonzai-go" // imported as sonzai
)
go get github.com/sonz-ai/sonzai-go@v1.0.0

Getting Started

package main

import (
    "context"
    "fmt"

    sonzai "github.com/sonz-ai/sonzai-go"
)

func main() {
    client := sonzai.NewClient("my-api-key") // defaults to os.LookupEnv("SONZAI_API_KEY")

    // Stream a chat response
    err := client.Agents.ChatStream(
        context.Background(),
        "agent-id",
        sonzai.ChatOptions{
            Messages: []sonzai.ChatMessage{{Role: "user", Content: "Hello!"}},
            UserID:   "user-123",
        },
        func(event sonzai.ChatStreamEvent) error {
            fmt.Print(event.Content())
            return nil
        },
    )
    if err != nil {
        panic(err)
    }
}

See the examples directory for more.

Requirements

This library requires Go 1.22 or later.

Contributing

See CONTRIBUTING.md for guidelines.

License

MIT - see LICENSE for details.

Documentation

Overview

Package sonzai provides a Go SDK for the Sonzai Character Engine API.

Usage:

client := sonzai.NewClient("your-api-key")

// Chat with an agent
resp, err := client.Agents.Chat(ctx, "agent-id", sonzai.ChatOptions{
    Messages: []sonzai.ChatMessage{{Role: "user", Content: "Hello!"}},
})

// Stream chat
err := client.Agents.ChatStream(ctx, "agent-id", opts, func(event sonzai.ChatStreamEvent) error {
    fmt.Print(event.Content())
    return nil
})

// Evaluate agent quality
result, err := client.Eval.Evaluate(ctx, "agent-id", eval.EvaluateOptions{...})

Package sonzai provides the official Go SDK for the Sonzai Character Engine API.

The SDK enables you to build AI characters with persistent memory, evolving personality, and proactive behaviors. It requires zero external dependencies and uses only the Go standard library.

Getting Started

Create a client with your API key:

client := sonzai.NewClient("sk-your-api-key")

Or use the SONZAI_API_KEY environment variable:

client := sonzai.NewClient("")

Chat

Send messages and receive streaming or aggregated responses:

// Non-streaming
resp, err := client.Agents.Chat(ctx, "agent-id", sonzai.ChatOptions{
    Messages: []sonzai.ChatMessage{{Role: "user", Content: "Hello!"}},
    UserID:   "user-123",
})

// Streaming
err := client.Agents.ChatStream(ctx, "agent-id", opts, func(event sonzai.ChatStreamEvent) error {
    fmt.Print(event.Content())
    return nil
})

Resources

The client exposes the following resource groups:

  • client.Agents — Chat, context engine data, and agent-scoped operations
  • client.Agents.Memory — Memory tree, search, and timeline
  • client.Agents.Personality — Personality profile and evolution history
  • client.Agents.Sessions — Session lifecycle and tool configuration
  • client.Agents.Instances — Agent instance CRUD and reset
  • client.Agents.Notifications — Proactive notification management
  • client.Agents.CustomState — Arbitrary key-value state storage
  • client.Agents.Image — Image generation
  • client.Eval — Evaluation, simulation, and benchmarking (separate sub-package)
  • client.Eval.Templates — Evaluation template CRUD
  • client.Eval.Runs — Evaluation run management

Error Handling

The SDK returns typed errors for different failure scenarios:

resp, err := client.Agents.Chat(ctx, "agent-id", opts)
if err != nil {
    var authErr *sonzai.AuthenticationError
    if errors.As(err, &authErr) {
        log.Fatal("Invalid API key")
    }
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidSignature = errors.New("sonzai: webhook signature is invalid")
	ErrTimestampExpired = errors.New("sonzai: webhook timestamp is outside tolerance")
	ErrMissingSignature = errors.New("sonzai: missing or empty signature header")
	ErrInvalidSecret    = errors.New("sonzai: invalid or empty webhook secret")
)

Sentinel errors for webhook signature verification.

Functions

func VerifyWebhookSignature added in v1.0.2

func VerifyWebhookSignature(payload []byte, sigHeader, secret string) error

VerifyWebhookSignature verifies a Sonzai webhook payload signature using the default timestamp tolerance of 5 minutes.

Usage in a webhook handler:

body, _ := io.ReadAll(r.Body)
sig := r.Header.Get("Sonzai-Signature")
if err := sonzai.VerifyWebhookSignature(body, sig, webhookSecret); err != nil {
    http.Error(w, "Invalid signature", 401)
    return
}

func VerifyWebhookSignatureWithTolerance added in v1.0.2

func VerifyWebhookSignatureWithTolerance(payload []byte, sigHeader, secret string, tolerance time.Duration) error

VerifyWebhookSignatureWithTolerance verifies a Sonzai webhook payload signature with a custom timestamp tolerance. Set tolerance to 0 to skip timestamp checking.

The signature header format is: t={unix_timestamp},v1={hex_hmac_sha256} Multiple signatures may be present (comma-separated v1= values) to support secret rotation.

Types

type Agent

type Agent struct {
	AgentID           string   `json:"agent_id"`
	Name              string   `json:"name"`
	Bio               string   `json:"bio,omitempty"`
	Gender            string   `json:"gender,omitempty"`
	AvatarURL         string   `json:"avatar_url,omitempty"`
	Status            string   `json:"status,omitempty"`
	PersonalityPrompt string   `json:"personality_prompt,omitempty"`
	SpeechPatterns    []string `json:"speech_patterns,omitempty"`
	TrueInterests     []string `json:"true_interests,omitempty"`
	TrueDislikes      []string `json:"true_dislikes,omitempty"`
	CreatedAt         string   `json:"created_at,omitempty"`
}

Agent represents an agent returned from the API.

type AgentInstance

type AgentInstance struct {
	InstanceID  string `json:"instance_id"`
	AgentID     string `json:"agent_id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Status      string `json:"status"`
	IsDefault   bool   `json:"is_default"`
	CreatedAt   string `json:"created_at,omitempty"`
	UpdatedAt   string `json:"updated_at,omitempty"`
}

AgentInstance represents an agent instance.

type AgentToolCapabilities added in v1.0.1

type AgentToolCapabilities struct {
	WebSearch       bool `json:"web_search"`
	RememberName    bool `json:"remember_name"`
	ImageGeneration bool `json:"image_generation"`
}

AgentToolCapabilities specifies which built-in tools to enable for an agent.

type AgentsResource

type AgentsResource struct {
	Memory        *MemoryResource
	Personality   *PersonalityResource
	Sessions      *SessionsResource
	Instances     *InstancesResource
	Notifications *NotificationsResource
	CustomState   *CustomStateResource
	Image         *ImageResource
	Voice         *VoiceResource
	Wakeups       *WakeupResource
	Generation    *GenerationResource
	// contains filtered or unexported fields
}

AgentsResource provides agent-scoped operations.

func (*AgentsResource) Chat

func (a *AgentsResource) Chat(ctx context.Context, agentID string, opts ChatOptions) (*ChatResponse, error)

Chat sends a chat message and returns the aggregated response.

func (*AgentsResource) ChatStream

func (a *AgentsResource) ChatStream(ctx context.Context, agentID string, opts ChatOptions, callback func(ChatStreamEvent) error) error

ChatStream sends a chat message and calls the callback for each streaming event.

func (*AgentsResource) ChatStreamChannel added in v1.0.1

func (a *AgentsResource) ChatStreamChannel(ctx context.Context, agentID string, opts ChatOptions) (<-chan ChatStreamEvent, <-chan error)

ChatStreamChannel sends a chat message and returns a channel of streaming events. The channel is closed when the stream ends or the context is cancelled.

func (*AgentsResource) Create

func (a *AgentsResource) Create(ctx context.Context, opts CreateAgentOptions) (*Agent, error)

Create creates a new agent.

func (*AgentsResource) Delete

func (a *AgentsResource) Delete(ctx context.Context, agentID string) error

Delete deletes an agent.

func (*AgentsResource) Dialogue

func (a *AgentsResource) Dialogue(ctx context.Context, agentID string, opts DialogueOptions) (*DialogueResponse, error)

Dialogue initiates a dialogue with an agent.

func (*AgentsResource) Get

func (a *AgentsResource) Get(ctx context.Context, agentID string) (*Agent, error)

Get returns an agent by ID.

func (*AgentsResource) GetDiary

func (a *AgentsResource) GetDiary(ctx context.Context, agentID string, userID, instanceID string) (map[string]interface{}, error)

GetDiary returns diary entries for an agent.

func (*AgentsResource) GetGoals

func (a *AgentsResource) GetGoals(ctx context.Context, agentID string, userID, instanceID string) (map[string]interface{}, error)

GetGoals returns goal data for an agent.

func (*AgentsResource) GetHabits

func (a *AgentsResource) GetHabits(ctx context.Context, agentID string, userID, instanceID string) (map[string]interface{}, error)

GetHabits returns habit data for an agent.

func (*AgentsResource) GetInterests

func (a *AgentsResource) GetInterests(ctx context.Context, agentID string, userID, instanceID string) (map[string]interface{}, error)

GetInterests returns interest data for an agent.

func (*AgentsResource) GetMood

func (a *AgentsResource) GetMood(ctx context.Context, agentID string, userID, instanceID string) (map[string]interface{}, error)

GetMood returns the current mood for an agent.

func (*AgentsResource) GetMoodAggregate

func (a *AgentsResource) GetMoodAggregate(ctx context.Context, agentID string, userID, instanceID string) (map[string]interface{}, error)

GetMoodAggregate returns aggregated mood statistics for an agent.

func (*AgentsResource) GetMoodHistory

func (a *AgentsResource) GetMoodHistory(ctx context.Context, agentID string, userID, instanceID string) (map[string]interface{}, error)

GetMoodHistory returns mood history for an agent.

func (*AgentsResource) GetRelationships

func (a *AgentsResource) GetRelationships(ctx context.Context, agentID string, userID, instanceID string) (map[string]interface{}, error)

GetRelationships returns relationship data for an agent.

func (*AgentsResource) GetUsers

func (a *AgentsResource) GetUsers(ctx context.Context, agentID string) (map[string]interface{}, error)

GetUsers returns users for an agent.

func (*AgentsResource) TriggerEvent

func (a *AgentsResource) TriggerEvent(ctx context.Context, agentID string, opts TriggerEventOptions) (*TriggerEventResponse, error)

TriggerEvent triggers a game event / activity for an agent.

func (*AgentsResource) Update

func (a *AgentsResource) Update(ctx context.Context, agentID string, opts UpdateAgentOptions) (*Agent, error)

Update updates an agent's profile.

func (*AgentsResource) UpdatePersonality added in v1.0.1

func (a *AgentsResource) UpdatePersonality(ctx context.Context, agentID string, opts UpdatePersonalityOptions) (*UpdatePersonalityResponse, error)

UpdatePersonality updates an agent's Big5 personality scores.

type AtomicFact

type AtomicFact struct {
	FactID       string  `json:"fact_id"`
	AgentID      string  `json:"agent_id"`
	UserID       string  `json:"user_id"`
	NodeID       string  `json:"node_id"`
	AtomicText   string  `json:"atomic_text"`
	FactType     string  `json:"fact_type"`
	Importance   float64 `json:"importance"`
	SupersedesID string  `json:"supersedes_id"`
	SessionID    string  `json:"session_id"`
	CreatedAt    string  `json:"created_at,omitempty"`
}

AtomicFact represents a single atomic fact stored in memory.

type AuthenticationError

type AuthenticationError struct{ SonzaiError }

AuthenticationError is returned when the API key is invalid or missing.

type BadRequestError

type BadRequestError struct{ SonzaiError }

BadRequestError is returned when the request is invalid.

type Big5

type Big5 struct {
	Openness          Big5Trait `json:"openness"`
	Conscientiousness Big5Trait `json:"conscientiousness"`
	Extraversion      Big5Trait `json:"extraversion"`
	Agreeableness     Big5Trait `json:"agreeableness"`
	Neuroticism       Big5Trait `json:"neuroticism"`
}

Big5 represents the Big Five personality model.

type Big5Scores

type Big5Scores struct {
	Openness          float64 `json:"openness"`
	Conscientiousness float64 `json:"conscientiousness"`
	Extraversion      float64 `json:"extraversion"`
	Agreeableness     float64 `json:"agreeableness"`
	Neuroticism       float64 `json:"neuroticism"`
	Confidence        float64 `json:"confidence,omitempty"`
}

Big5Scores represents raw Big5 personality scores for updates (0-100 scale).

type Big5Trait

type Big5Trait struct {
	Score      float64 `json:"score"`
	Percentile int     `json:"percentile"`
	Confidence float64 `json:"confidence,omitempty"`
}

Big5Trait represents a single Big Five personality trait.

type ChatChoice

type ChatChoice struct {
	Delta        map[string]string `json:"delta"`
	FinishReason *string           `json:"finish_reason"`
	Index        int               `json:"index"`
}

ChatChoice represents a single choice in a streaming response.

type ChatMessage

type ChatMessage struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

ChatMessage represents a single message in a conversation.

type ChatOptions

type ChatOptions struct {
	Messages             []ChatMessage          `json:"messages"`
	UserID               string                 `json:"user_id,omitempty"`
	UserDisplayName      string                 `json:"user_display_name,omitempty"`
	SessionID            string                 `json:"session_id,omitempty"`
	InstanceID           string                 `json:"instance_id,omitempty"`
	Provider             string                 `json:"provider,omitempty"`
	Model                string                 `json:"model,omitempty"`
	ContinuationToken    string                 `json:"continuation_token,omitempty"`
	AiServiceCookie      string                 `json:"ai_service_cookie,omitempty"`
	RequestType          string                 `json:"request_type,omitempty"`
	Language             string                 `json:"language,omitempty"`
	CompiledSystemPrompt string                 `json:"compiled_system_prompt,omitempty"`
	InteractionRole      string                 `json:"interaction_role,omitempty"`
	Timezone             string                 `json:"timezone,omitempty"`
	ToolCapabilities     *AgentToolCapabilities `json:"tool_capabilities,omitempty"`
	ToolDefinitions      []ToolDefinition       `json:"tool_definitions,omitempty"`
}

ChatOptions configures a chat request.

type ChatResponse

type ChatResponse struct {
	Content   string     `json:"content"`
	SessionID string     `json:"session_id"`
	Usage     *ChatUsage `json:"usage,omitempty"`
}

ChatResponse is the aggregated result of a non-streaming chat call.

type ChatStreamEvent

type ChatStreamEvent struct {
	Choices []ChatChoice              `json:"choices,omitempty"`
	Usage   *ChatUsage                `json:"usage,omitempty"`
	Type    string                    `json:"type,omitempty"`
	Data    map[string]interface{}    `json:"data,omitempty"`
	Error   *struct{ Message string } `json:"error,omitempty"`

	// Rich event fields (populated based on Type)
	MessageIndex      int             `json:"message_index,omitempty"`
	IsFollowUp        bool            `json:"is_follow_up,omitempty"`
	Replacement       bool            `json:"replacement,omitempty"`
	FullContent       string          `json:"full_content,omitempty"`
	FinishReason      string          `json:"finish_reason,omitempty"`
	ContinuationToken string          `json:"continuation_token,omitempty"`
	ResponseCookie    string          `json:"response_cookie,omitempty"`
	MessageCount      int             `json:"message_count,omitempty"`
	SideEffectsJSON   json.RawMessage `json:"side_effects,omitempty"`
	EnrichedContext   json.RawMessage `json:"enriched_context,omitempty"`
	BuildDurationMs   int64           `json:"build_duration_ms,omitempty"`
	UsedFastPath      bool            `json:"used_fast_path,omitempty"`
	ErrorMessage      string          `json:"error_message,omitempty"`
	ErrorCode         string          `json:"error_code,omitempty"`
	IsTokenError      bool            `json:"is_token_error,omitempty"`
}

ChatStreamEvent represents a single SSE event from the chat stream.

func (*ChatStreamEvent) Content

func (e *ChatStreamEvent) Content() string

Content returns the text content from the first choice delta, or from the Data["content"] field for rich events.

func (*ChatStreamEvent) IsFinished

func (e *ChatStreamEvent) IsFinished() bool

IsFinished returns true if the stream has finished.

type ChatUsage

type ChatUsage struct {
	PromptTokens     int `json:"promptTokens"`
	CompletionTokens int `json:"completionTokens"`
	TotalTokens      int `json:"totalTokens"`
}

ChatUsage represents token usage for a chat completion.

type Client

type Client struct {
	// Agents provides chat, memory, personality, and other agent-scoped operations.
	Agents *AgentsResource

	// Eval provides evaluation, simulation, and benchmarking operations.
	Eval *eval.Client

	// Voices provides the global voice catalog.
	Voices *VoicesResource

	// Webhooks provides webhook registration and management.
	Webhooks *WebhooksResource
	// contains filtered or unexported fields
}

Client is the Sonzai Character Engine API client.

func NewClient

func NewClient(apiKey string, opts ...ClientOption) *Client

NewClient creates a new Sonzai client with the given API key. If apiKey is empty, it falls back to the SONZAI_API_KEY environment variable.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures the Sonzai client.

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL sets the API base URL.

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout sets the HTTP request timeout.

type CreateAgentOptions

type CreateAgentOptions struct {
	AgentID                      string                    `json:"agent_id,omitempty"`
	UserID                       string                    `json:"user_id,omitempty"`
	UserDisplayName              string                    `json:"user_display_name,omitempty"`
	Name                         string                    `json:"name"`
	Gender                       string                    `json:"gender,omitempty"`
	Bio                          string                    `json:"bio,omitempty"`
	AvatarURL                    string                    `json:"avatar_url,omitempty"`
	ProjectID                    string                    `json:"project_id,omitempty"`
	PersonalityPrompt            string                    `json:"personality_prompt,omitempty"`
	SpeechPatterns               []string                  `json:"speech_patterns,omitempty"`
	TrueInterests                []string                  `json:"true_interests,omitempty"`
	TrueDislikes                 []string                  `json:"true_dislikes,omitempty"`
	PrimaryTraits                []string                  `json:"primary_traits,omitempty"`
	Big5                         *Big5Scores               `json:"big5,omitempty"`
	Dimensions                   *SDKPersonalityDimensions `json:"dimensions,omitempty"`
	Preferences                  map[string]string         `json:"preferences,omitempty"`
	Behaviors                    map[string]string         `json:"behaviors,omitempty"`
	ToolCapabilities             *AgentToolCapabilities    `json:"tool_capabilities,omitempty"`
	Language                     string                    `json:"language,omitempty"`
	SeedMemories                 []SeedMemory              `json:"seed_memories,omitempty"`
	LoreContext                  map[string]interface{}    `json:"lore_generation_context,omitempty"`
	GenerateOriginStory          bool                      `json:"generate_origin_story,omitempty"`
	GeneratePersonalizedMemories bool                      `json:"generate_personalized_memories,omitempty"`
}

CreateAgentOptions configures an agent creation request.

type CustomState

type CustomState struct {
	StateID     string      `json:"state_id"`
	AgentID     string      `json:"agent_id"`
	Scope       string      `json:"scope"`
	Key         string      `json:"key"`
	Value       interface{} `json:"value"`
	ContentType string      `json:"content_type"`
	UserID      string      `json:"user_id,omitempty"`
	InstanceID  string      `json:"instance_id,omitempty"`
	CreatedAt   string      `json:"created_at,omitempty"`
	UpdatedAt   string      `json:"updated_at,omitempty"`
}

CustomState represents a custom state entry.

type CustomStateCreateOptions

type CustomStateCreateOptions struct {
	Key         string      `json:"key"`
	Value       interface{} `json:"value"`
	Scope       string      `json:"scope,omitempty"`        // "global" (default), "user", or "instance"
	ContentType string      `json:"content_type,omitempty"` // "text" (default), "json", or "binary"
	UserID      string      `json:"user_id,omitempty"`      // required if scope is "user"
	InstanceID  string      `json:"instance_id,omitempty"`
}

CustomStateCreateOptions configures a custom state creation request.

type CustomStateListOptions

type CustomStateListOptions struct {
	Scope      string // "global", "user", or "instance"
	UserID     string
	InstanceID string
}

CustomStateListOptions configures a custom state list request.

type CustomStateListResponse

type CustomStateListResponse struct {
	States []CustomState `json:"states"`
}

CustomStateListResponse is the response from listing custom states.

type CustomStateResource

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

CustomStateResource provides custom state operations for an agent.

func (*CustomStateResource) Create

Create creates a new custom state.

func (*CustomStateResource) Delete

func (c *CustomStateResource) Delete(ctx context.Context, agentID, stateID string) error

Delete deletes a custom state.

func (*CustomStateResource) List

List returns custom states for an agent.

func (*CustomStateResource) Update

func (c *CustomStateResource) Update(ctx context.Context, agentID, stateID string, opts CustomStateUpdateOptions) (*CustomState, error)

Update updates a custom state.

type CustomStateUpdateOptions

type CustomStateUpdateOptions struct {
	Value       interface{} `json:"value"`
	ContentType string      `json:"content_type,omitempty"`
}

CustomStateUpdateOptions configures a custom state update request.

type DeliveryAttemptsResponse added in v1.0.2

type DeliveryAttemptsResponse struct {
	Attempts []WebhookDeliveryAttempt `json:"attempts"`
}

DeliveryAttemptsResponse is the response from listing delivery attempts.

type DialogueMessage

type DialogueMessage struct {
	MessageID string `json:"message_id"`
	AgentID   string `json:"agent_id"`
	Role      string `json:"role"`
	Content   string `json:"content"`
}

DialogueMessage represents a single message in a dialogue.

type DialogueOptions

type DialogueOptions struct {
	UserID              string          `json:"user_id,omitempty"`
	EnrichedContextJSON json.RawMessage `json:"enriched_context,omitempty"`
	Messages            []ChatMessage   `json:"messages,omitempty"`
	RequestType         string          `json:"request_type,omitempty"`
	SceneGuidance       string          `json:"scene_guidance,omitempty"`
	ToolConfigJSON      json.RawMessage `json:"tool_config,omitempty"`
	InstanceID          string          `json:"instance_id,omitempty"`
}

DialogueOptions configures a dialogue request.

type DialogueResponse

type DialogueResponse struct {
	Response        string          `json:"response"`
	SideEffectsJSON json.RawMessage `json:"side_effects,omitempty"`
}

DialogueResponse is the response from a dialogue.

type EmotionalContext added in v1.0.1

type EmotionalContext struct {
	Themes []string `json:"themes,omitempty"`
	Tone   string   `json:"tone,omitempty"`
}

EmotionalContext provides emotional hints for TTS generation.

type EntityContext

type EntityContext struct {
	Name        string `json:"name,omitempty"`
	Personality string `json:"personality,omitempty"`
}

EntityContext provides agent identity for voice sessions.

type Fact

type Fact struct {
	FactID          string   `json:"fact_id"`
	AgentID         string   `json:"agent_id"`
	UserID          string   `json:"user_id,omitempty"`
	Content         string   `json:"content"`
	Category        string   `json:"category"` // "relationship", "preference", "event", "interest"
	Confidence      float64  `json:"confidence"`
	MentionCount    int      `json:"mention_count"`
	CreatedAt       string   `json:"created_at,omitempty"`
	LastMentionedAt string   `json:"last_mentioned_at,omitempty"`
	ContextExamples []string `json:"context_examples,omitempty"`
}

Fact represents a single extracted fact from agent memory.

type FactListOptions

type FactListOptions struct {
	UserID   string
	Category string // "relationship", "preference", "event", "interest"
	Limit    int
	Offset   int
}

FactListOptions configures a fact listing request.

type FactListResponse

type FactListResponse struct {
	Facts      []Fact `json:"facts"`
	TotalCount int    `json:"total_count"`
	HasMore    bool   `json:"has_more"`
}

FactListResponse is the response from listing facts.

type GenerateBioOptions

type GenerateBioOptions struct {
	Name                string          `json:"name,omitempty"`
	Gender              string          `json:"gender,omitempty"`
	Description         string          `json:"description,omitempty"`
	UserID              string          `json:"user_id,omitempty"`
	EnrichedContextJSON json.RawMessage `json:"enriched_context_json,omitempty"`
	CurrentBio          string          `json:"current_bio,omitempty"`
	Style               string          `json:"style,omitempty"`
	InstanceID          string          `json:"instance_id,omitempty"`
}

GenerateBioOptions configures a bio generation request.

type GenerateBioResponse

type GenerateBioResponse struct {
	Bio        string  `json:"bio"`
	Tone       string  `json:"tone,omitempty"`
	Confidence float64 `json:"confidence,omitempty"`
}

GenerateBioResponse is the response from bio generation.

type GenerateCharacterOptions

type GenerateCharacterOptions struct {
	Name        string   `json:"name"`
	Gender      string   `json:"gender,omitempty"`
	Description string   `json:"description,omitempty"`
	Fields      []string `json:"fields,omitempty"`
}

GenerateCharacterOptions configures a character generation request.

type GenerateCharacterResponse

type GenerateCharacterResponse struct {
	Bio               string                     `json:"bio"`
	PersonalityPrompt string                     `json:"personality_prompt"`
	Big5              *Big5Scores                `json:"big5,omitempty"`
	SpeechPatterns    []string                   `json:"speech_patterns,omitempty"`
	TrueInterests     []string                   `json:"true_interests,omitempty"`
	TrueDislikes      []string                   `json:"true_dislikes,omitempty"`
	PrimaryTraits     []string                   `json:"primary_traits,omitempty"`
	Dimensions        *SDKPersonalityDimensions  `json:"dimensions,omitempty"`
	Preferences       *SDKInteractionPreferences `json:"preferences,omitempty"`
	Behaviors         *SDKBehavioralTraits       `json:"behaviors,omitempty"`
}

GenerateCharacterResponse is the response from character generation.

type GenerateSeedMemoriesOptions

type GenerateSeedMemoriesOptions struct {
	UserID                       string                 `json:"user_id,omitempty"`
	AgentName                    string                 `json:"agentName,omitempty"`
	Big5                         *Big5Scores            `json:"big5,omitempty"`
	PersonalityPrompt            string                 `json:"personalityPrompt,omitempty"`
	GuideSummary                 string                 `json:"guide_summary,omitempty"`
	TrueInterests                []string               `json:"trueInterests,omitempty"`
	TrueDislikes                 []string               `json:"trueDislikes,omitempty"`
	SpeechPatterns               []string               `json:"speechPatterns,omitempty"`
	CreatorDisplayName           string                 `json:"creatorDisplayName,omitempty"`
	StaticLoreMemories           []SeedMemory           `json:"staticLoreMemories,omitempty"`
	LoreGenerationContext        *LoreGenerationContext `json:"loreGenerationContext,omitempty"`
	IdentityMemoryTemplates      []IdentityMemory       `json:"identityMemoryTemplates,omitempty"`
	GenerateOriginStory          bool                   `json:"generateOriginStory,omitempty"`
	GeneratePersonalizedMemories bool                   `json:"generatePersonalizedMemories,omitempty"`
	ModelConfig                  *ModelConfig           `json:"model_config,omitempty"`
	StoreMemories                bool                   `json:"store_memories,omitempty"`
}

GenerateSeedMemoriesOptions configures a seed memory generation request. Field names use camelCase to match the Platform API.

type GenerateSeedMemoriesResponse

type GenerateSeedMemoriesResponse struct {
	Memories       []SeedMemory `json:"memories"`
	MemoriesStored int32        `json:"memories_stored,omitempty"`
}

GenerateSeedMemoriesResponse is the response from seed memory generation.

type GenerationResource

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

GenerationResource provides AI content generation operations.

func (*GenerationResource) GenerateBio

func (g *GenerationResource) GenerateBio(ctx context.Context, agentID string, opts GenerateBioOptions) (*GenerateBioResponse, error)

GenerateBio generates a bio for an agent using AI.

func (*GenerationResource) GenerateCharacter

GenerateCharacter generates a full character profile from a description.

func (*GenerationResource) GenerateSeedMemories

GenerateSeedMemories generates seed memories for an agent using AI.

func (*GenerationResource) SeedMemories added in v1.0.1

func (g *GenerationResource) SeedMemories(ctx context.Context, agentID string, opts SeedMemoriesOptions) (*SeedMemoriesResponse, error)

SeedMemories bulk imports initial memories for an agent during setup.

type IdentityMemory

type IdentityMemory struct {
	Template   string   `json:"template"`
	FactType   string   `json:"factType,omitempty"`
	Importance float64  `json:"importance,omitempty"`
	Entities   []string `json:"entities,omitempty"`
}

IdentityMemory represents a template for identity memory generation.

type ImageGenerateOptions

type ImageGenerateOptions struct {
	Prompt         string `json:"prompt"`
	NegativePrompt string `json:"negative_prompt,omitempty"`
	Model          string `json:"model,omitempty"`
	Provider       string `json:"provider,omitempty"`
	OutputBucket   string `json:"output_bucket,omitempty"`
	OutputPath     string `json:"output_path,omitempty"`
}

ImageGenerateOptions configures an image generation request.

type ImageGenerateResponse

type ImageGenerateResponse struct {
	ImageID          string `json:"image_id"`
	URL              string `json:"public_url"`
	MimeType         string `json:"mime_type"`
	GenerationTimeMs int    `json:"generation_time_ms"`
}

ImageGenerateResponse is the response from image generation.

type ImageResource

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

ImageResource provides image generation operations for an agent.

func (*ImageResource) Generate

Generate creates an image using the agent's context.

type InstanceListResponse

type InstanceListResponse struct {
	Instances []AgentInstance `json:"instances"`
}

InstanceListResponse is the response from listing instances.

type InstancesResource

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

InstancesResource provides agent instance operations.

func (*InstancesResource) Create

func (i *InstancesResource) Create(ctx context.Context, agentID, name, description string) (*AgentInstance, error)

Create creates a new agent instance.

func (*InstancesResource) Delete

func (i *InstancesResource) Delete(ctx context.Context, agentID, instanceID string) error

Delete deletes an instance.

func (*InstancesResource) Get

func (i *InstancesResource) Get(ctx context.Context, agentID, instanceID string) (*AgentInstance, error)

Get returns a specific instance.

func (*InstancesResource) List

List returns all instances for an agent.

func (*InstancesResource) Reset

func (i *InstancesResource) Reset(ctx context.Context, agentID, instanceID string) (*AgentInstance, error)

Reset resets an instance (clears all context data).

type InternalServerError

type InternalServerError struct{ SonzaiError }

InternalServerError is returned when the server returns a 5xx error.

type LoreGenerationContext added in v1.0.1

type LoreGenerationContext struct {
	WorldDescription         string            `json:"worldDescription"`
	EntityTerminology        map[string]string `json:"entityTerminology,omitempty"`
	OriginPromptInstructions string            `json:"originPromptInstructions,omitempty"`
}

LoreGenerationContext provides world context for LLM-based lore generation.

type MemoryListOptions

type MemoryListOptions struct {
	UserID          string
	InstanceID      string
	ParentID        string
	IncludeContents bool
	Limit           int
}

MemoryListOptions configures a memory list request.

type MemoryNode

type MemoryNode struct {
	NodeID     string  `json:"node_id"`
	AgentID    string  `json:"agent_id"`
	UserID     string  `json:"user_id"`
	ParentID   string  `json:"parent_id"`
	Title      string  `json:"title"`
	Summary    string  `json:"summary"`
	Importance float64 `json:"importance"`
	CreatedAt  string  `json:"created_at,omitempty"`
	UpdatedAt  string  `json:"updated_at,omitempty"`
}

MemoryNode represents a node in the memory tree.

type MemoryResetOptions

type MemoryResetOptions struct {
	UserID     string // scope to single user; empty = reset all
	InstanceID string // scope to single instance
}

MemoryResetOptions configures a memory reset request.

type MemoryResetResponse

type MemoryResetResponse struct {
	AgentID              string `json:"agent_id"`
	UserID               string `json:"user_id,omitempty"`
	Status               string `json:"status"`
	FactsDeleted         int    `json:"facts_deleted"`
	RelationshipsDeleted int    `json:"relationships_deleted"`
}

MemoryResetResponse is the response from resetting memory.

type MemoryResource

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

MemoryResource provides memory operations for an agent.

func (*MemoryResource) List

func (m *MemoryResource) List(ctx context.Context, agentID string, opts *MemoryListOptions) (*MemoryResponse, error)

List returns the memory tree for an agent.

func (*MemoryResource) ListFacts

func (m *MemoryResource) ListFacts(ctx context.Context, agentID string, opts *FactListOptions) (*FactListResponse, error)

ListFacts returns atomic facts for an agent, optionally filtered by category.

func (*MemoryResource) Reset

Reset deletes all memory for an agent, optionally scoped to a single user.

func (*MemoryResource) Search

Search searches agent memories.

func (*MemoryResource) Timeline

Timeline returns the memory timeline for an agent.

type MemoryResponse

type MemoryResponse struct {
	Nodes    []MemoryNode            `json:"nodes"`
	Contents map[string][]AtomicFact `json:"contents"`
}

MemoryResponse is the response from the memory list endpoint.

type MemorySearchOptions

type MemorySearchOptions struct {
	Query      string
	InstanceID string
	Limit      int
}

MemorySearchOptions configures a memory search request.

type MemorySearchResponse

type MemorySearchResponse struct {
	Results []MemorySearchResult `json:"results"`
}

MemorySearchResponse is the response from the memory search endpoint.

type MemorySearchResult

type MemorySearchResult struct {
	FactID   string  `json:"fact_id"`
	Content  string  `json:"content"`
	FactType string  `json:"fact_type"`
	Score    float64 `json:"score"`
}

MemorySearchResult represents a single search result.

type MemoryTimelineOptions

type MemoryTimelineOptions struct {
	UserID     string
	InstanceID string
	Start      string
	End        string
}

MemoryTimelineOptions configures a memory timeline request.

type MemoryTimelineResponse

type MemoryTimelineResponse struct {
	Sessions   []TimelineSession `json:"sessions"`
	TotalFacts int               `json:"total_facts"`
}

MemoryTimelineResponse is the response from the memory timeline endpoint.

type ModelConfig added in v1.0.1

type ModelConfig struct {
	Provider    string  `json:"provider"`
	Model       string  `json:"model"`
	Temperature float64 `json:"temperature"`
	MaxTokens   int32   `json:"max_tokens"`
}

ModelConfig specifies LLM provider and model settings.

type NotFoundError

type NotFoundError struct{ SonzaiError }

NotFoundError is returned when the requested resource is not found.

type Notification

type Notification struct {
	MessageID        string `json:"message_id"`
	AgentID          string `json:"agent_id"`
	UserID           string `json:"user_id"`
	WakeupID         string `json:"wakeup_id"`
	CheckType        string `json:"check_type"`
	Intent           string `json:"intent"`
	GeneratedMessage string `json:"generated_message"`
	Status           string `json:"status"`
	ConsumedAt       string `json:"consumed_at,omitempty"`
	CreatedAt        string `json:"created_at,omitempty"`
}

Notification represents a proactive notification.

type NotificationListOptions

type NotificationListOptions struct {
	Status string
	UserID string
	Limit  int
}

NotificationListOptions configures a notification list request.

type NotificationListResponse

type NotificationListResponse struct {
	Notifications []Notification `json:"notifications"`
}

NotificationListResponse is the response from listing notifications.

type NotificationsResource

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

NotificationsResource provides notification operations for an agent.

func (*NotificationsResource) Consume

func (n *NotificationsResource) Consume(ctx context.Context, agentID, messageID string) (*SessionResponse, error)

Consume marks a notification as consumed.

func (*NotificationsResource) History

func (n *NotificationsResource) History(ctx context.Context, agentID string, limit int) (*NotificationListResponse, error)

History returns notification history.

func (*NotificationsResource) List

List returns notifications for an agent.

type PermissionDeniedError

type PermissionDeniedError struct{ SonzaiError }

PermissionDeniedError is returned when the API key lacks permission.

type PersonalityBehaviors

type PersonalityBehaviors struct {
	Proactivity string `json:"proactivity"`
	Reliability string `json:"reliability"`
	Humor       string `json:"humor"`
}

PersonalityBehaviors represents behavioral traits.

type PersonalityDelta

type PersonalityDelta struct {
	DeltaID   string `json:"delta_id"`
	Change    string `json:"change"`
	Reason    string `json:"reason"`
	CreatedAt string `json:"created_at,omitempty"`
}

PersonalityDelta represents a personality evolution event.

type PersonalityDimensions

type PersonalityDimensions struct {
	Warmth         int `json:"warmth"`
	Energy         int `json:"energy"`
	Openness       int `json:"openness"`
	EmotionalDepth int `json:"emotional_depth"`
	Playfulness    int `json:"playfulness"`
	Supportiveness int `json:"supportiveness"`
	Curiosity      int `json:"curiosity"`
	Wisdom         int `json:"wisdom"`
}

PersonalityDimensions represents personality dimension scores (1-10).

type PersonalityGetOptions

type PersonalityGetOptions struct {
	HistoryLimit int
	Since        string
}

PersonalityGetOptions configures a personality get request.

type PersonalityPreferences

type PersonalityPreferences struct {
	Pace                string `json:"pace"`
	Formality           string `json:"formality"`
	HumorStyle          string `json:"humor_style"`
	EmotionalExpression string `json:"emotional_expression"`
}

PersonalityPreferences represents interaction preferences.

type PersonalityProfile

type PersonalityProfile struct {
	AgentID             string                 `json:"agent_id"`
	Name                string                 `json:"name"`
	Gender              string                 `json:"gender"`
	Bio                 string                 `json:"bio"`
	AvatarURL           string                 `json:"avatar_url"`
	PersonalityPrompt   string                 `json:"personality_prompt"`
	SpeechPatterns      []string               `json:"speech_patterns"`
	TrueInterests       []string               `json:"true_interests"`
	TrueDislikes        []string               `json:"true_dislikes"`
	PrimaryTraits       []string               `json:"primary_traits"`
	Temperature         float64                `json:"temperature"`
	Big5                Big5                   `json:"big5"`
	Dimensions          PersonalityDimensions  `json:"dimensions"`
	Preferences         PersonalityPreferences `json:"preferences"`
	Behaviors           PersonalityBehaviors   `json:"behaviors"`
	EmotionalTendencies map[string]float64     `json:"emotional_tendencies"`
	CreatedAt           string                 `json:"created_at,omitempty"`
}

PersonalityProfile represents the full personality profile.

type PersonalityResource

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

PersonalityResource provides personality operations for an agent.

func (*PersonalityResource) Get

Get returns the personality profile and evolution history.

func (*PersonalityResource) Update

Update updates the personality Big5 scores for an agent.

type PersonalityResponse

type PersonalityResponse struct {
	Profile   PersonalityProfile `json:"profile"`
	Evolution []PersonalityDelta `json:"evolution"`
}

PersonalityResponse is the response from the personality endpoint.

type PersonalityUpdateOptions

type PersonalityUpdateOptions struct {
	Big5             *Big5Scores `json:"big5"`
	AssessmentMethod string      `json:"assessment_method,omitempty"` // "quiz", "conversation", "llm_analysis"
	TotalExchanges   int         `json:"total_exchanges,omitempty"`
}

PersonalityUpdateOptions configures a personality update request.

type PersonalityUpdateResponse

type PersonalityUpdateResponse struct {
	AgentID string `json:"agent_id"`
	Status  string `json:"status"`
}

PersonalityUpdateResponse is the response from updating personality.

type RateLimitError

type RateLimitError struct{ SonzaiError }

RateLimitError is returned when rate limit is exceeded.

type SDKBehavioralTraits added in v1.0.1

type SDKBehavioralTraits struct {
	ResponseLength    string `json:"response_length"`
	QuestionFrequency string `json:"question_frequency"`
	EmpathyStyle      string `json:"empathy_style"`
	ConflictApproach  string `json:"conflict_approach"`
}

SDKBehavioralTraits contains behavioral response patterns.

type SDKInteractionPreferences added in v1.0.1

type SDKInteractionPreferences struct {
	ConversationPace    string `json:"conversation_pace"`
	Formality           string `json:"formality"`
	HumorStyle          string `json:"humor_style"`
	EmotionalExpression string `json:"emotional_expression"`
}

SDKInteractionPreferences contains conversation style preferences.

type SDKPersonalityDimensions added in v1.0.1

type SDKPersonalityDimensions struct {
	Intellect       float64 `json:"intellect"`
	Aesthetic       float64 `json:"aesthetic"`
	Industriousness float64 `json:"industriousness"`
	Orderliness     float64 `json:"orderliness"`
	Enthusiasm      float64 `json:"enthusiasm"`
	Assertiveness   float64 `json:"assertiveness"`
	Compassion      float64 `json:"compassion"`
	Politeness      float64 `json:"politeness"`
	Withdrawal      float64 `json:"withdrawal"`
	Volatility      float64 `json:"volatility"`
}

SDKPersonalityDimensions contains BFAS personality aspect scores (0-100 scale).

type ScheduleWakeupOptions

type ScheduleWakeupOptions struct {
	UserID           string `json:"user_id"`
	ScheduledAt      string `json:"scheduled_at"` // RFC3339 timestamp
	CheckType        string `json:"check_type"`   // "birthday", "occasion", "recurring_event", "interest_check", "general"
	Intent           string `json:"intent,omitempty"`
	Occasion         string `json:"occasion,omitempty"`
	InterestTopic    string `json:"interest_topic,omitempty"`
	EventDescription string `json:"event_description,omitempty"`
}

ScheduleWakeupOptions configures a wakeup scheduling request.

type ScheduledWakeup

type ScheduledWakeup struct {
	WakeupID         string `json:"wakeup_id"`
	AgentID          string `json:"agent_id"`
	UserID           string `json:"user_id"`
	ScheduledAt      string `json:"scheduled_at"`
	CheckType        string `json:"check_type"`
	Status           string `json:"status"`
	Intent           string `json:"intent,omitempty"`
	LastTopic        string `json:"last_topic,omitempty"`
	EventDescription string `json:"event_description,omitempty"`
	Occasion         string `json:"occasion,omitempty"`
	InterestTopic    string `json:"interest_topic,omitempty"`
	ExecutedAt       string `json:"executed_at,omitempty"`
	CreatedAt        string `json:"created_at,omitempty"`
}

ScheduledWakeup represents a scheduled wakeup.

type SeedMemoriesOptions added in v1.0.1

type SeedMemoriesOptions struct {
	UserID     string       `json:"user_id"`
	Memories   []SeedMemory `json:"memories"`
	InstanceID string       `json:"instance_id,omitempty"`
}

SeedMemoriesOptions configures a bulk memory seeding request.

type SeedMemoriesResponse added in v1.0.1

type SeedMemoriesResponse struct {
	MemoriesCreated int32 `json:"memories_created"`
}

SeedMemoriesResponse is the response from memory seeding.

type SeedMemory

type SeedMemory struct {
	Content    string   `json:"content"`
	FactType   string   `json:"fact_type,omitempty"`
	Importance float64  `json:"importance,omitempty"`
	Entities   []string `json:"entities,omitempty"`
}

SeedMemory represents a memory to seed during agent creation.

type SessionEndOptions

type SessionEndOptions struct {
	UserID          string        `json:"user_id"`
	SessionID       string        `json:"session_id"`
	InstanceID      string        `json:"instance_id,omitempty"`
	TotalMessages   int           `json:"total_messages,omitempty"`
	DurationSeconds int           `json:"duration_seconds,omitempty"`
	Messages        []ChatMessage `json:"messages,omitempty"`
}

SessionEndOptions configures a session end request.

type SessionResponse

type SessionResponse struct {
	Success bool `json:"success"`
}

SessionResponse is the response from session start/end.

type SessionStartOptions

type SessionStartOptions struct {
	UserID     string `json:"user_id"`
	SessionID  string `json:"session_id"`
	InstanceID string `json:"instance_id,omitempty"`
}

SessionStartOptions configures a session start request.

type SessionToolsOptions

type SessionToolsOptions struct {
	Tools []ToolDefinition `json:"tools"`
}

SessionToolsOptions configures tools for a session.

type SessionsResource

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

SessionsResource provides session lifecycle operations.

func (*SessionsResource) End

End concludes a chat session.

func (*SessionsResource) SetTools

func (s *SessionsResource) SetTools(ctx context.Context, agentID, sessionID string, opts SessionToolsOptions) (*SessionResponse, error)

SetTools configures the tools available for a session. The Platform API expects a raw JSON array as the request body.

func (*SessionsResource) Start

Start begins a chat session.

type SonzaiError

type SonzaiError struct {
	StatusCode int
	Message    string
}

SonzaiError is the base error type for all SDK errors.

func (*SonzaiError) Error

func (e *SonzaiError) Error() string

type TTSOptions

type TTSOptions struct {
	Text             string            `json:"text"`
	VoiceName        string            `json:"voice_name,omitempty"`
	Language         string            `json:"language,omitempty"`
	EmotionalContext *EmotionalContext `json:"emotional_context,omitempty"`
}

TTSOptions configures a text-to-speech request.

type TTSResponse

type TTSResponse struct {
	Audio       string `json:"audio"` // base64-encoded audio
	ContentType string `json:"content_type"`
	VoiceName   string `json:"voice_name,omitempty"`
	DurationMs  int    `json:"duration_ms,omitempty"`
}

TTSResponse is the response from text-to-speech.

type TimelineSession

type TimelineSession struct {
	SessionID   string       `json:"session_id"`
	Facts       []AtomicFact `json:"facts"`
	FirstFactAt string       `json:"first_fact_at,omitempty"`
	LastFactAt  string       `json:"last_fact_at,omitempty"`
	FactCount   int          `json:"fact_count"`
}

TimelineSession represents a session in the memory timeline.

type ToolDefinition

type ToolDefinition struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Parameters  map[string]interface{} `json:"parameters,omitempty"`
}

ToolDefinition defines an external tool available during a session.

type TriggerEventOptions

type TriggerEventOptions struct {
	UserID           string            `json:"user_id"`
	EventType        string            `json:"event_type"`                  // e.g., "achievement", "milestone", "level_up"
	EventDescription string            `json:"event_description,omitempty"` // Human-readable context for the AI
	Metadata         map[string]string `json:"metadata,omitempty"`
	Language         string            `json:"language,omitempty"`
	InstanceID       string            `json:"instance_id,omitempty"`
}

TriggerEventOptions configures an event trigger request.

type TriggerEventResponse

type TriggerEventResponse struct {
	Accepted bool   `json:"accepted"`
	EventID  string `json:"event_id"`
}

TriggerEventResponse is the response from triggering an event.

type UpdateAgentOptions

type UpdateAgentOptions struct {
	Name              string                    `json:"name,omitempty"`
	Bio               string                    `json:"bio,omitempty"`
	AvatarURL         string                    `json:"avatar_url,omitempty"`
	PersonalityPrompt string                    `json:"personality_prompt,omitempty"`
	SpeechPatterns    []string                  `json:"speech_patterns,omitempty"`
	TrueInterests     []string                  `json:"true_interests,omitempty"`
	TrueDislikes      []string                  `json:"true_dislikes,omitempty"`
	Big5              *Big5Scores               `json:"big5,omitempty"`
	Dimensions        *SDKPersonalityDimensions `json:"dimensions,omitempty"`
	ToolCapabilities  *AgentToolCapabilities    `json:"tool_capabilities,omitempty"`
}

UpdateAgentOptions configures an agent profile update request.

type UpdatePersonalityOptions added in v1.0.1

type UpdatePersonalityOptions struct {
	Big5       *Big5Scores               `json:"big5"`
	Dimensions *SDKPersonalityDimensions `json:"dimensions,omitempty"`
}

UpdatePersonalityOptions configures a personality update request.

type UpdatePersonalityResponse added in v1.0.1

type UpdatePersonalityResponse struct {
	Success bool `json:"success"`
}

UpdatePersonalityResponse is the response from updating personality.

type Voice

type Voice struct {
	VoiceID        string `json:"voice_id"`
	VoiceName      string `json:"voice_name"`
	Gender         string `json:"gender"`
	Tier           int    `json:"tier"`
	Provider       string `json:"provider"`
	Language       string `json:"language"`
	Accent         string `json:"accent,omitempty"`
	AgeProfile     string `json:"age_profile,omitempty"`
	Description    string `json:"description,omitempty"`
	SampleAudioURL string `json:"sample_audio_url,omitempty"`
	Availability   string `json:"availability"`
}

Voice represents an available voice in the catalog.

type VoiceChatOptions

type VoiceChatOptions struct {
	UserID            string `json:"user_id,omitempty"`
	Audio             string `json:"audio"`                  // base64-encoded audio
	AudioFormat       string `json:"audio_format,omitempty"` // "webm", "wav", etc.
	VoiceName         string `json:"voice_name,omitempty"`
	ContinuationToken string `json:"continuation_token,omitempty"`
	Language          string `json:"language,omitempty"`
}

VoiceChatOptions configures a single-turn voice chat request.

type VoiceChatResponse

type VoiceChatResponse struct {
	Transcript        string `json:"transcript"`
	Response          string `json:"response"`
	Audio             string `json:"audio"` // base64-encoded
	ContentType       string `json:"content_type"`
	ContinuationToken string `json:"continuation_token,omitempty"`
}

VoiceChatResponse is the response from single-turn voice chat.

type VoiceListOptions

type VoiceListOptions struct {
	Tier     int
	Gender   string
	Language string
	Limit    int
	Offset   int
}

VoiceListOptions configures a voice listing request.

type VoiceListResponse

type VoiceListResponse struct {
	Voices     []Voice `json:"voices"`
	TotalCount int     `json:"total_count"`
	HasMore    bool    `json:"has_more"`
}

VoiceListResponse is the response from listing voices.

type VoiceMatchOptions

type VoiceMatchOptions struct {
	Big5            *Big5Scores `json:"big5,omitempty"`
	PreferredGender string      `json:"preferred_gender,omitempty"`
}

VoiceMatchOptions configures a voice matching request.

type VoiceMatchResponse

type VoiceMatchResponse struct {
	VoiceID    string  `json:"voice_id"`
	VoiceName  string  `json:"voice_name"`
	MatchScore float64 `json:"match_score"`
	Reasoning  string  `json:"reasoning,omitempty"`
}

VoiceMatchResponse is the response from voice matching.

type VoiceResource

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

VoiceResource provides per-agent voice operations.

func (*VoiceResource) Chat

Chat performs a single-turn voice chat: send audio, receive text + audio response.

func (*VoiceResource) GetToken

func (v *VoiceResource) GetToken(ctx context.Context, agentID string, opts VoiceTokenOptions) (*VoiceStreamToken, error)

GetVoiceToken obtains a short-lived token for WebSocket voice streaming. The token expires in 60 seconds and is single-use.

func (*VoiceResource) Match

Match finds the best matching voice for an agent based on personality and preferences.

func (*VoiceResource) Stream

func (v *VoiceResource) Stream(ctx context.Context, token *VoiceStreamToken) (*VoiceStream, error)

Stream opens a bidirectional WebSocket for real-time voice chat. The token should be obtained from GetToken. After connecting, the session is authenticated automatically and a "ready" event is sent.

Usage:

token, _ := client.Agents.Voice.GetToken(ctx, agentID, opts)
stream, _ := client.Agents.Voice.Stream(ctx, token)
defer stream.Close()

// Send audio chunks
stream.SendAudio(audioBytes)

// Signal end of speech (or let server detect silence)
stream.EndOfSpeech()

// Receive events
for {
    event, err := stream.Recv()
    if err == io.EOF { break }
    switch event.Type {
    case "transcript": fmt.Println("User:", event.Text)
    case "response_delta": fmt.Print(event.Text)
    case "audio": playAudio(event.Audio)
    case "turn_complete": // ready for next turn
    }
}

func (*VoiceResource) TTS

func (v *VoiceResource) TTS(ctx context.Context, agentID string, opts TTSOptions) (*TTSResponse, error)

TTS converts text to speech using the agent's voice.

type VoiceStream

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

VoiceStream is a bidirectional WebSocket connection for real-time voice chat. Send audio with SendAudio, signal end-of-speech with EndOfSpeech, and receive events with Recv.

func (*VoiceStream) Close

func (s *VoiceStream) Close() error

Close closes the voice stream.

func (*VoiceStream) Configure

func (s *VoiceStream) Configure(audioFormat, voiceName, language string) error

Configure sends a config message to change audio format, voice, or language mid-session without reconnecting.

func (*VoiceStream) EndOfSpeech

func (s *VoiceStream) EndOfSpeech() error

EndOfSpeech signals the server that the user has finished speaking, triggering immediate processing without waiting for silence detection.

func (*VoiceStream) Recv

func (s *VoiceStream) Recv() (*VoiceStreamEvent, error)

Recv reads the next event from the voice stream. Returns io.EOF when the connection is closed.

func (*VoiceStream) SendAudio

func (s *VoiceStream) SendAudio(audio []byte) error

SendAudio sends a binary audio chunk to the server.

type VoiceStreamConfig

type VoiceStreamConfig struct {
	AgentID     string `json:"agent_id"`
	VoiceName   string `json:"voice_name,omitempty"`
	Language    string `json:"language,omitempty"`
	AudioFormat string `json:"audio_format,omitempty"` // "webm", "ogg", etc. Default: "audio/webm;codecs=opus"
}

VoiceStreamConfig configures a voice streaming session.

type VoiceStreamEvent

type VoiceStreamEvent struct {
	// Type is the event type: "ready", "vad", "transcript", "response_delta",
	// "turn_complete", "error", or "audio" (binary audio data).
	Type string `json:"type"`

	// SessionID is set on "ready" events.
	SessionID string `json:"session_id,omitempty"`

	// Speaking is set on "vad" events.
	Speaking *bool `json:"speaking,omitempty"`

	// Text is set on "transcript" and "response_delta" events.
	Text string `json:"text,omitempty"`

	// ContinuationToken is set on "turn_complete" events.
	ContinuationToken string `json:"continuation_token,omitempty"`

	// ContentType is set on "turn_complete" events (audio MIME type).
	ContentType string `json:"content_type,omitempty"`

	// Error is set on "error" events.
	Error     string `json:"error,omitempty"`
	ErrorCode string `json:"error_code,omitempty"`

	// Audio is set on "audio" events (raw binary TTS audio data).
	Audio []byte `json:"-"`
}

VoiceStreamEvent represents a server event from the voice stream.

type VoiceStreamToken

type VoiceStreamToken struct {
	WSURL     string `json:"wsUrl"`
	AuthToken string `json:"authToken"`
}

VoiceStreamToken represents the token needed to establish a voice WebSocket.

type VoiceTokenOptions

type VoiceTokenOptions struct {
	VoiceName     string         `json:"voiceName,omitempty"`
	Language      string         `json:"language,omitempty"`
	EntityContext *EntityContext `json:"entityContext,omitempty"`
}

VoiceTokenOptions configures a voice WebSocket token request.

type VoicesResource

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

VoicesResource provides global voice catalog operations.

func (*VoicesResource) List

List returns available voices from the catalog.

type WakeupResource

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

WakeupResource provides wakeup scheduling operations for an agent.

func (*WakeupResource) Schedule

func (w *WakeupResource) Schedule(ctx context.Context, agentID string, opts ScheduleWakeupOptions) (*ScheduledWakeup, error)

Schedule creates a new scheduled wakeup for the agent.

type WebhookDeliveryAttempt added in v1.0.2

type WebhookDeliveryAttempt struct {
	AttemptID     string `json:"attempt_id"`
	EventType     string `json:"event_type"`
	WebhookURL    string `json:"webhook_url"`
	ResponseCode  int    `json:"response_code"`
	ResponseBody  string `json:"response_body,omitempty"`
	ErrorMessage  string `json:"error_message,omitempty"`
	DurationMs    int    `json:"duration_ms"`
	AttemptNumber int    `json:"attempt_number"`
	Status        string `json:"status"`
	CreatedAt     string `json:"created_at"`
}

WebhookDeliveryAttempt represents a single webhook delivery attempt.

type WebhookEndpoint added in v1.0.2

type WebhookEndpoint struct {
	EventType  string `json:"event_type"`
	WebhookURL string `json:"webhook_url"`
	AuthHeader string `json:"auth_header,omitempty"`
}

WebhookEndpoint represents a registered webhook.

type WebhookListResponse added in v1.0.2

type WebhookListResponse struct {
	Webhooks []WebhookEndpoint `json:"webhooks"`
}

WebhookListResponse is the response from listing webhooks.

type WebhookRegisterOptions added in v1.0.2

type WebhookRegisterOptions struct {
	WebhookURL string `json:"webhook_url"`
	AuthHeader string `json:"auth_header,omitempty"`
}

WebhookRegisterOptions configures a webhook registration request.

type WebhookRegisterResponse added in v1.0.2

type WebhookRegisterResponse struct {
	Success       bool   `json:"success"`
	SigningSecret string `json:"signing_secret,omitempty"`
}

WebhookRegisterResponse is the response from registering a webhook. SigningSecret is only populated on first registration (creation), not updates.

type WebhooksResource added in v1.0.2

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

WebhooksResource provides webhook management operations.

func (*WebhooksResource) Delete added in v1.0.2

func (w *WebhooksResource) Delete(ctx context.Context, eventType string) error

Delete removes a webhook for an event type.

func (*WebhooksResource) List added in v1.0.2

List returns all registered webhooks.

func (*WebhooksResource) ListDeliveryAttempts added in v1.0.2

func (w *WebhooksResource) ListDeliveryAttempts(ctx context.Context, eventType string) (*DeliveryAttemptsResponse, error)

ListDeliveryAttempts returns recent delivery attempts for a specific event type.

func (*WebhooksResource) Register added in v1.0.2

Register registers (or updates) a webhook URL for an event type. Returns a WebhookRegisterResponse which includes the signing secret on first registration. The signing secret is only returned once at creation time.

Event types include: "on_wakeup_ready", "on_diary_generated", "on_personality_updated", "on_recurring_event_due", etc.

func (*WebhooksResource) RotateSecret added in v1.0.2

func (w *WebhooksResource) RotateSecret(ctx context.Context, eventType string) (*WebhookRegisterResponse, error)

RotateSecret generates a new signing secret for a webhook event type. The new secret is returned in the response and is only shown once.

Directories

Path Synopsis
Package eval provides evaluation, simulation, and benchmarking operations for the Sonzai Character Engine API.
Package eval provides evaluation, simulation, and benchmarking operations for the Sonzai Character Engine API.
examples
agent-lifecycle command
Example: create an agent, chat with it, then clean up.
Example: create an agent, chat with it, then clean up.
chat command
Example: streaming chat with a Sonzai agent.
Example: streaming chat with a Sonzai agent.
evaluation command
Example: run a simulation and evaluate agent quality.
Example: run a simulation and evaluate agent quality.
memory command
Example: search and browse an agent's memory tree.
Example: search and browse an agent's memory tree.
voice command
Example: match a voice to an agent and generate speech.
Example: match a voice to an agent and generate speech.
internal
ws
Package ws provides a minimal WebSocket client using only the Go standard library.
Package ws provides a minimal WebSocket client using only the Go standard library.

Jump to

Keyboard shortcuts

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