Skip to main content
Sonzai Docs

API Reference

Public reference for creating agents and interacting with them over REST API. Internal context assembly, memory management, and state orchestration are platform-managed and intentionally omitted.

Authentication

All API calls require Bearer authentication with your project API key.

Authorization: Bearer YOUR_PROJECT_API_KEY

REST API

Public HTTP endpoints for agent lifecycle, real-time agent interaction, and proactive delivery. Memory, mood, relationship, and context-management internals are handled by the platform.

Server-side only. The API does not accept browser requests. For web apps, proxy through your backend. See the Integration Guide.

Agent Lifecycle

POST/api/v1/agents

Create a new agent. Returns the agent with a platform-generated UUID.

Parameters

namestringAgent name (required)
personality_promptstringCustom system prompt (optional)
big5objectBig Five scores: openness, conscientiousness, extraversion, agreeableness, neuroticism (0.0-1.0)
speech_patternsstring[]Speech patterns (optional)
true_interestsstring[]Agent interests (optional)
project_idstringProject UUID to assign agent to (optional)
languagestringISO language code, e.g. "en" (optional)

Response

{ "agent_id": "uuid", "name": "...", ... }

GET/api/v1/agents

List agents. Filter by project_id query param.

Parameters

project_idstringFilter by project (query param, optional)

Response

Array of agent objects

GET/api/v1/agents/{agentId}

Get agent by ID.

Response

Agent object with personality, mood, profile

Chat

POST/api/v1/agents/{agentId}/chat

Chat with agent via SSE streaming. Returns Server-Sent Events.

Parameters

messagesCEChatMessage[]Conversation messages
user_idstringUser identifier

Response

SSE stream of chat completion chunks

Proactive Notifications

GET/api/v1/agents/{agentId}/notifications

List pending proactive messages.

Parameters

statusstringFilter by status: pending | consumed (default: pending, query param)
user_idstringFilter by user (optional, query param)
limitintMax results (default: 50, max: 500, query param)

Response

List of proactive messages with message_id, agent_id, user_id, check_type, intent, generated_message, status, created_at

POST/api/v1/agents/{agentId}/notifications/{messageId}/consume

Mark a notification as consumed after delivery.

Response

Confirmation

GET/api/v1/agents/{agentId}/notifications/history

List all notifications across all statuses.

Response

Full notification history

Agent Lifecycle (Detailed)

CreateAgent

Creates a new agent with personality configuration. Generates personality prompt, speech patterns, and emotional tendencies.

Request

user_idstringOwner user identifier
agent_namestringAgent display name
genderstring"male", "female", or "non_binary"
biostringAgent biography (optional)
avatar_urlstringAvatar image URL (optional)
big5CEBig5ScoresBig Five personality scores (0.0-1.0)
languagestringPrimary language
equipped_outfitstringInitial outfit ID (optional)
skillsCESkillLevel[]Initial skill levels (optional)
model_tierint32LLM model tier (optional)
project_idstringProject to assign agent to (optional)
agent_idstringCaller-specified ID for deterministic agents (optional)
personality_promptstringCustom system prompt (optional)
generate_goalsboolAuto-generate goals after creation (optional)
provided_goalsstring[]Store these goals directly (optional)
speech_patternsstring[]Speech patterns (optional)
true_interestsstring[]Agent interests (optional)
true_dislikesstring[]Agent dislikes (optional)
user_display_namestringOwner display name (optional)
generate_avatarboolAuto-generate an AI avatar on creation (default: true, costs 1 credit). Set to false to skip.

Response

agent_id (UUID), status ('completed' or 'in_progress')

GetAgent

Retrieves an agent's current state including personality, mood, and profile.

Request

agent_idstringAgent UUID

Response

Agent ID, name, bio, gender, avatar_url, Big5 scores, owner, created_at

UpdateAgent

Updates agent fields (name, bio, avatar, personality, interests, speech patterns).

Request

agent_idstringAgent UUID
namestringNew name (optional)
biostringNew bio (optional)
avatar_urlstringNew avatar URL (optional)
big5CEBig5ScoresUpdated Big5 scores (optional)
true_interestsstring[]Updated interests (optional)
true_dislikesstring[]Updated dislikes (optional)
speech_patternsstring[]Updated speech patterns (optional)
personality_promptstringUpdated system prompt (optional)

Response

success (bool)

DeleteAgent

Permanently deletes an agent and all associated data (memory, mood, relationships).

Request

agent_idstringAgent UUID

Response

success (bool)

RegenerateAvatar

Generates or regenerates an AI-created avatar for the agent. Uses LLM to create an image prompt from personality data, then generates and uploads the image. Costs 1 credit. Avatars are auto-generated on agent creation unless disabled.

Request

agent_idstringAgent UUID (URL param)
stylestringOptional style hint (e.g. 'watercolor anime', 'realistic portrait')

Response

success (bool), avatar_url (string), prompt (string), generation_time_ms (int64)

UpdateAgentPersonality

Updates an agent's authored Big5 personality configuration when your product intentionally changes the agent design.

Request

agent_idstringAgent UUID
big5CEBig5ScoresUpdated Big Five scores with confidence

Response

success (bool)

Proactive Behaviors

ScheduleWakeup

Schedules the agent to proactively reach out to a user after a delay.

Request

agent_idstringAgent UUID
user_idstringUser identifier
check_typestringType of check: check_in, follow_up, mood_driven
intentstringWhy the agent wants to reach out
delay_hoursint32Hours to delay before wakeup

Response

wakeup_id (string), scheduled_at (Timestamp)

GetPendingWakeups

Retrieves pending wakeup events for an agent.

Request

agent_idstringAgent UUID

Response

List of PendingWakeup (wakeup_id, user_id, check_type, intent, scheduled_at)

Streaming Chat

Primary public conversation RPC. Send the agent, user, application context, and message history; the platform handles context assembly and state updates automatically.

StreamChat

Streams AI responses for an agent interaction while the platform handles internal memory and state updates behind the scenes.

Request

agent_idstringAgent UUID
user_idstringUser identifier
session_idstringUnique session ID
game_contextGameContextApplication state context
messagesCEChatMessage[]Conversation messages
continuation_tokenstringResume from previous response (optional)
request_typestring"chat", "guide", or "outing"
capabilitiesstring[]Unlocked capabilities (optional)
languagestringISO language code (optional)
interaction_rolestring"owner" or "non_owner"
skill_levelsmap<string, int32>Skill levels (optional)

Response

Stream of StreamChatEvent (delta | message_boundary | complete | side_effects | error)

StreamChatEvent is a oneof with these event types:

StreamChatDelta (delta)
contentstringText chunk from the AI
message_indexint32Index in multi-message response
is_follow_upboolWhether this is a follow-up message
replacementboolIf true, replaces all previous content
StreamChatComplete (complete)
full_contentstringComplete response text
finish_reasonstring"stop", "length", or "content_filter"
continuation_tokenstringToken for continuing the conversation
message_countint32Number of messages in response
StreamChatError (error)
messagestringError message
codestringError code

AI Generation

Platform-managed AI content generation for bios, goals, personalities, diary entries, and images.

GenerateBio

Generates or rewrites an agent's biography using AI based on their personality and context.

Request

agent_idstringAgent UUID
user_idstringUser identifier
current_biostringCurrent bio for rewriting (optional)
stylestringStyle: casual, formal, poetic, etc. (optional)

Response

bio (string), tone (string), confidence (double)

GenerateGoals

Generates personality-driven goals for an agent based on traits, interests, and memories.

Request

agent_idstringAgent UUID
agent_namestringAgent display name
big5CEBig5ScoresBig5 scores
true_interestsstring[]Agent interests
true_dislikesstring[]Agent dislikes
speech_patternsstring[]Speech patterns
recent_memoriesCERecentMemory[]Recent memories for context
current_goalsCEGoalSummary[]Existing goals to avoid duplication
max_goalsint32Maximum goals to generate
model_configCEModelConfigLLM model configuration (optional)
custom_contextmap<string, string>Application-specific context (optional)

Response

List of CEGeneratedGoal (type, title, description, priority, related_traits), reasoning

GeneratePersonality

Generates speech patterns and interests from a template and Big5 scores.

Request

template_idstringTemplate identifier
base_promptstringBase personality prompt
big5CEBig5ScoresBig5 scores
agent_namestringAgent name
genderstringAgent gender

Response

speech_patterns (string[]), true_interests (string[]), used_fallback (bool)

GenerateDiary

Generates a diary entry from conversation messages and/or application events.

Request

agent_idstringAgent UUID
user_idstringUser identifier
datestringDate in YYYY-MM-DD format
agent_namestringAgent display name
languagestringLanguage for generated content
messagesCEDiaryMessage[]Conversation messages (role, content, time)
trigger_typestringdaily_summary, achievement, milestone, breakthrough
trigger_contextCEDiaryTriggerContextEvent trigger context (optional)
modelstringLLM model override (optional)
temperaturedoubleTemperature override (optional)
timezonestringTimezone for date handling (optional)

Response

user_id, date, diary (title, body_lines, tags), generation_time_ms

GenerateImage

Generates an image from a text prompt and stores it in cloud storage.

Request

promptstringImage generation prompt
negative_promptstringNegative prompt (optional)
modelstringModel to use (optional)
providerstringProvider to use (optional)
output_bucketstringGCS bucket for output (optional)
output_pathstringOutput path in bucket (optional)
cdn_domainstringCDN domain for public URL (optional)

Response

success, image_id, gcs_uri, public_url, mime_type, generation_time_ms, error

Voice & Media

Voice matching, text-to-speech, voice chat, and reflection capabilities.

VoiceMatch

Matches an agent to an appropriate TTS voice based on personality traits.

Request

big5CEBig5ScoresBig5 scores for matching
preferred_genderstringPreferred voice gender (optional)
agent_idstringAgent UUID (auto-lookup Big5 if provided without big5)

Response

voice_id, voice_name, match_score, reasoning

TextToSpeech

Text-to-speech using Google Gemini voices with emotional context awareness.

Request

textstringText to convert
voice_namestringGemini voice name
languagestringLanguage code (optional)
emotional_contextCEEmotionalContextEmotional themes and tone (optional)

Response

audio (bytes), content_type, voice_name

VoiceChat

Single-turn voice chat: transcribes audio, generates AI response, returns TTS audio.

Request

agent_idstringAgent UUID
user_idstringUser identifier
audiobytesRaw audio data
audio_formatstringAudio format (opus, pcm, wav)
voice_namestringTTS voice name
continuation_tokenstringResume from previous turn (optional)
languagestringLanguage code (optional)
game_idstringApplication identifier (optional)

Response

transcript, response (text), audio (bytes), content_type, continuation_token, side_effects_json

ListVoices

Lists available Gemini TTS voices, optionally filtered by gender.

Request

genderstringFilter by gender (optional)

Response

List of CEGeminiVoice (name, gender)

Reflect

Generates an AI reflection on a capability unlock, milestone, or other event.

Request

agent_idstringAgent UUID
user_idstringUser identifier
reflection_typestring"capability_unlock", "milestone", etc.
capabilitystringCapability name
capability_sourcestringSource of capability
contextstringAdditional context string (optional)
new_capabilities_jsonbytesNew capabilities JSON (optional)
session_idstringSession ID for auto context build (optional)
interaction_rolestring"owner" or "non_owner" (default: "owner")

Response

success (bool), reflection (string), side_effects_json (bytes)

Streaming Voice Chat

Bidirectional streaming voice chat with server-side VAD (voice activity detection). Client streams audio chunks continuously; server handles speech detection, transcription, AI response, and TTS.

StreamVoiceChat

Bidirectional streaming: client sends init + audio chunks, server returns transcripts and TTS audio. No manual stop button needed.

Request

initVoiceChatInitFirst message: session initialization
audio_chunkVoiceAudioChunkSubsequent messages: raw audio data

Response

Stream of events: ready | vad | transcript | response_delta | audio | turn_complete | error

VoiceChatInit
agent_idstringAgent UUID
user_idstringUser identifier
audio_formatstring"opus", "pcm", "wav" (default: "opus")
sample_rateint32Sample rate in Hz (default: 48000 for opus)
voice_namestringTTS voice name
languagestringLanguage code (default: "en")
game_idstringApplication identifier
continuation_tokenstringResume from previous session (optional)
VoiceAudioChunk
audiobytesRaw audio data (e.g., Opus frame)
end_of_speechboolOptional client-side VAD hint

Server response events:

VoiceStreamReady
session_idstringAssigned session ID
VoiceStreamVAD
speakingbooltrue = speech started, false = speech ended
VoiceStreamTranscript
textstringTranscript text
is_finalbooltrue = final transcript for this utterance
VoiceStreamAudio
audiobytesAudio data chunk
content_typestringe.g., "audio/opus", "audio/wav"
VoiceStreamTurnComplete
continuation_tokenstringToken for continuing the session
side_effects_jsonbytesJSON-serialized AgentSideEffects (optional)
VoiceStreamError
messagestringError message
codestring"vad_error", "stt_error", "llm_error", "tts_error"
fatalboolIf true, session should be closed

Analysis & Search

AI-powered conversation analysis, summarization, and grounded search.

AnalyzeConversation

Analyzes a conversation to extract side effects (personality deltas, habits, memories, etc.).

Request

agent_idstringAgent UUID
agent_namestringAgent display name
user_idstringUser identifier
messagesCEAnalyzeConversationMessage[]Messages to analyze (role, content)
is_finalboolWhether this is the final batch of messages

Response

success, side_effects_json (bytes), summary, latency_ms

SummarizeConversation

Generates a concise summary of a conversation with topic extraction.

Request

messagesCESummarizeConversationMessage[]Messages (role, content, time)
agent_namestringAgent name
user_namestringUser display name
max_summary_lengthint32Max summary length in characters

Response

summary (string), topics (string[]), message_count (int)

GenerateSearchQuery

Generates an optimized search query from a topic and category for web search.

Request

topicstringTopic to search for
categorystringCategory for context

Response

query (string), context (string)

GroundedSearch

Performs grounded web search with multiple queries and returns summarized results with sources.

Request

queriesstring[]Search queries
contextstringContext for search relevance
agent_namestringAgent name for response framing

Response

List of CEGroundedSearchResult (query, summary, sources with title/url/snippet)

Multi-Agent Dialogue

Agent-to-agent conversations for outings, dialogues, and multi-agent scenes.

AgentDialogue

Generates an agent response in a multi-agent dialogue context (e.g., outings between agents).

Request

agent_idstringAgent UUID (the responding agent)
user_idstringUser identifier
messagesCEChatMessage[]Dialogue messages
request_typestring"outing", "dialogue", etc.
scene_guidancestringScene-specific prompt guidance
tool_config_jsonbytesTool configuration JSON (optional)
session_idstringSession ID for auto context build (optional)
interaction_rolestring"owner" or "non_owner" (default: "owner")

Response

response (string), side_effects_json (bytes)

Application Events

Notify the platform about significant application events. The platform may generate diary entries, update goals, or take other AI actions. Fires OnDiaryGenerated webhook when diary is created.

TriggerGameEvent

Accepts application events (achievements, milestones, breakthroughs, completions) and triggers AI content generation.

Request

agent_idstringAgent UUID
user_idstringUser identifier
event_typestring"achievement", "milestone", "breakthrough", "level_up"
event_descriptionstringHuman-readable context for the AI
metadatamap<string, string>Additional context (achievement_id, level, etc.)
languagestringLanguage for generated content (default: "en")

Response

accepted (bool), event_id (string)

Knowledge Base

Project-scoped knowledge graph. Upload documents or push structured data via the API — the platform extracts entities, builds a graph, and gives agents a knowledge_search tool to query it during conversations.

Documents

POST/projects/{projectId}/knowledge/documents

Upload a document (multipart/form-data with 'file' field, max 50 MB). Returns 202 with document_id and triggers async extraction.

Parameters

filemultipartThe document file

Response

document_id, file_name, file_size, checksum, status, gcs_path

GET/projects/{projectId}/knowledge/documents

List documents. Query: limit (default 50, max 200).

Response

documents[], total

GET/projects/{projectId}/knowledge/documents/{docId}

Get a single document.

Response

KBDocument object

DELETE/projects/{projectId}/knowledge/documents/{docId}

Delete a document.

Response

204 No Content

Facts & Graph

POST/projects/{projectId}/knowledge/facts

Insert entities and relationships into the knowledge graph. Resolves against existing nodes, creates/updates with version history.

Parameters

sourcestringSource identifier (default: 'api')
facts[]arrayEntities: entity_type, label, properties
relationships[]arrayEdges: from_label, to_label, edge_type

Response

processed, created, updated, details[]

GET/projects/{projectId}/knowledge/nodes

List knowledge graph nodes. Query: type (filter), limit (default 100, max 500).

Response

nodes[], total

GET/projects/{projectId}/knowledge/nodes/{nodeId}

Get a node with connected edges. Query: history=true for version history.

Response

node, outgoing[], incoming[], history[]

DELETE/projects/{projectId}/knowledge/nodes/{nodeId}

Soft-delete a node (sets is_active=false).

Response

204 No Content

GET/projects/{projectId}/knowledge/nodes/{nodeId}/history

Get version history for a node. Query: limit (default 50, max 200).

Response

history[], total

Search

GET/projects/{projectId}/knowledge/search

Full-text search with graph traversal. Query: q (required), limit, history, type, filters (JSON).

Parameters

qstringSearch query (required)
limitintMax results (default 20, max 100)
typestringComma-separated entity types to filter
filtersJSON stringProperty filter object
historyboolInclude version history

Response

query, results[] (with related nodes), total

Schemas

POST/projects/{projectId}/knowledge/schemas

Create an entity type schema with fields and optional similarity config.

Parameters

entity_typestringEntity type name (required)
fields[]arrayField definitions: name, type, required
descriptionstringSchema description
similarity_configobjectmatch_fields[], threshold

Response

KBEntitySchema object

GET/projects/{projectId}/knowledge/schemas

List entity schemas for a project.

Response

schemas[], total

PUT/projects/{projectId}/knowledge/schemas/{schemaId}

Update an entity schema.

Parameters

entity_typestringUpdated entity type name
fields[]arrayUpdated field definitions

Response

KBEntitySchema object

DELETE/projects/{projectId}/knowledge/schemas/{schemaId}

Delete an entity schema.

Response

204 No Content

Stats

GET/projects/{projectId}/knowledge/stats

Get knowledge base statistics (document counts, node counts, edge count, extraction tokens).

Response

documents {total, indexed, pending, failed}, nodes {total, active}, edges, extraction_tokens

Analytics

POST/projects/{projectId}/knowledge/analytics/rules

Create an analytics rule (recommendation or trend).

Parameters

rule_typestring'recommendation' or 'trend'
namestringRule name
configobjectRule configuration
enabledboolWhether the rule is active

Response

KBAnalyticsRule object

GET/projects/{projectId}/knowledge/analytics/recommendations

Get recommendations. Query: rule_id, source_id (both required), limit.

Response

recommendations[], total

GET/projects/{projectId}/knowledge/analytics/trends

Get trend aggregations. Query: node_id (required).

Response

trends[], total

POST/projects/{projectId}/knowledge/analytics/feedback

Record recommendation feedback (shown/converted).

Parameters

source_node_idstringSource node ID
target_node_idstringTarget node ID
rule_idstringAnalytics rule ID
convertedboolWhether the user converted
score_at_timefloatScore when recommendation was shown

Response

status: 'recorded'

User Priming

Pre-load user metadata and content so AI agents already “know” users from their first conversation. Metadata (name, company, title) becomes instant facts; content blocks (text, chat transcripts) are processed asynchronously via LLM extraction.

Prime a User

POST/agents/{agentId}/users/{userId}/prime

Prime a user with metadata and content. Returns 202 with a job ID; LLM extraction of content runs asynchronously.

Parameters

display_namestringUser's display name
metadataobjectcompany, title, email, phone, custom (map)
content[]arrayContent blocks: type ('text', 'chat_transcript'), body
sourcestringSource identifier (e.g., 'crm', 'linkedin')

Response

job_id, status ('queued'), facts_created

GET/agents/{agentId}/users/{userId}/prime/{jobId}

Get the status of a priming job.

Response

ImportJob object (job_id, status, facts_created, error_message, etc.)

Content

POST/agents/{agentId}/users/{userId}/content

Add content blocks for async LLM extraction (e.g., append chat transcripts after priming).

Parameters

content[]arrayContent blocks: type, body
sourcestringSource identifier

Response

job_id, status ('queued')

Metadata

GET/agents/{agentId}/users/{userId}/metadata

Get priming metadata for a user.

Response

UserPrimingMetadata object

PATCH/agents/{agentId}/users/{userId}/metadata

Partially update priming metadata. New facts are auto-generated from updated fields.

Parameters

display_namestringUpdated name
companystringUpdated company
titlestringUpdated title
emailstringUpdated email
phonestringUpdated phone
custommapCustom key-value pairs (merged)

Response

metadata (updated), facts_created

Batch Import

POST/agents/{agentId}/users/import

Import multiple users with metadata and content in a single request. Metadata facts are created synchronously; content extraction runs async.

Parameters

users[]arrayArray of {user_id, display_name, metadata, content[]}
sourcestringSource identifier

Response

job_id, status ('queued'), total_users, facts_created

GET/agents/{agentId}/users/import/{jobId}

Get the status of a batch import job.

Response

ImportJob object

GET/agents/{agentId}/users/imports

List recent import jobs for an agent. Query: limit (default 20).

Response

jobs[], count

Shared Types

GameContext
custom_fieldsmap<string, string>Arbitrary application-specific key-value pairs passed through to prompts
game_state_jsonbytesOptional structured state as JSON (pass-through to prompts)
CEBig5Scores
opennessdoubleOpenness to experience (0.0-1.0)
conscientiousnessdoubleOrganization and discipline (0.0-1.0)
extraversiondoubleSocial energy and enthusiasm (0.0-1.0)
agreeablenessdoubleWarmth and cooperation (0.0-1.0)
neuroticismdoubleEmotional sensitivity (0.0-1.0)
confidencedoubleAssessment confidence (0.0-1.0)
MoodState
valencedoublePleasure/displeasure spectrum (0-100)
arousaldoubleActivation/energy level (0-100)
tensiondoubleStress/calmness state (0-100)
affiliationdoubleSocial warmth/closeness (0-100)
CEChatMessage
rolestring"user" or "assistant"
contentstringMessage text
timestampTimestampWhen the message was sent
MemoryCandidate
contentstringMemory content text
fact_typestringpreference, commitment, fact, experience, correction
importancedoubleImportance score (0.0-1.0)
entitiesstring[]Related entities
Habit
namestringHabit name
categorystringHabit category
strengthdoubleCurrent strength (0.0-1.0)
last_observedTimestampLast observation time
is_formedboolWhether the habit is fully formed
CEGoal
idstringGoal identifier
descriptionstringGoal description
statusstring"active", "completed", "abandoned"
prioritystringPriority level
related_traitsstring[]Related personality traits
created_atTimestampWhen the goal was created
Interest
topicstringInterest topic
categorystringInterest category
confidencedoubleDetection confidence (0.0-1.0)
discovered_atTimestampWhen the interest was discovered
research_statusstring"pending" or "researched"
CEModelConfig
providerstringLLM provider name
modelstringModel identifier
temperaturedoubleSampling temperature
max_tokensint32Maximum tokens to generate
ProactiveMessage
message_idstringUnique message identifier
agent_idstringAgent that generated the message
user_idstringTarget user
wakeup_idstringAssociated wakeup event
check_typestringType of check (check_in, follow_up, mood_driven)
intentstringWhy the agent wants to reach out
generated_messagestringThe actual message text
statusstringpending, consumed, expired, failed_generation
created_atTimestampWhen generated