Python types
Type index for cosmo-ai-sdk — credentials, model blocks, tools, session payloads, and every enum's members.
This page is the type index for the Python SDK; the client, agent, and session objects are documented on RealtimeClient (Python), audio I/O on Audio (Python). Unless a row says otherwise, every name here is a root import: from cosmo_ai import .... The submodules cosmo_ai.tools, cosmo_ai.skills, cosmo_ai.hooks, cosmo_ai.mcp, and cosmo_ai.audio carry the deeper surfaces noted below.
from cosmo_ai import RealtimeClient, TokenSource, AudioConfig, ThinkingLevel
from cosmo_ai import GeminiModel
from cosmo_ai.tools import ClientToolJob
client = RealtimeClient(token=TokenSource.endpoint("https://your-backend.example.com/token"))
agent = client.agent(
model=GeminiModel(thinking_level=ThinkingLevel.LOW),
audio=AudioConfig(output=False),
)Token sources
A TokenSource is the credential shape for distributed apps: it fetches a fresh minted token, caches it, and re-fetches when less than 60 seconds of life remain; a session start rejected with HTTP 401 drops the cache. Pass one as token= to RealtimeClient.
| Name | Description |
|---|---|
TokenSource.endpoint(url, *, headers=None) | Classmethod. POSTs url (empty JSON body) and reads {jwt, expires_at} — the wire shape of POST /api/v1/external/auth/token, so a backend that forwards a mint response qualifies (the serialized expiresAt spelling is accepted too). url must be absolute https (http only for localhost) — CredentialsError with code INSECURE_BASE_URL otherwise. Failures raise TokenSourceError; on a rejection its server_code is the server's slug when the body parses, http_<status> otherwise. |
TokenSource.custom(fetch_token) | Classmethod. A source backed by your own async callable — full control over transport and auth. Resolves with a MintedToken (the shape mint_token returns); an empty jwt raises TokenSourceError with code fetcher_failed. |
HeadersInput | Mapping[str, str], or a callable returning one (sync or awaitable) — the headers= argument to endpoint(), resolved per fetch. From cosmo_ai.token_source. |
FetchToken | Callable[[], Awaitable[MintedToken]] — the custom() fetcher type. From cosmo_ai.token_source. |
Credential resolution
A zero-argument RealtimeClient() resolves a credential itself. The environment variables involved:
| Variable | Role |
|---|---|
COSMO_API_KEY | Wins when set (non-empty). |
COSMO_CREDENTIALS_FILE | Relocates the credentials file — the CI/container knob. Default ~/.cosmo/credentials. |
COSMO_PROFILE | Selects the profile in the file; default default. A named profile that doesn't exist is an error, never a silent fallback. |
COSMO_BASE_URL | The API origin (https required except localhost). A file credential carries its own base_url, which outranks this; a conflict raises CredentialsError with code BASE_URL_MISMATCH. |
The CredentialsError family reports what went wrong, on the shared .code / .message shape:
| Error | .code | When |
|---|---|---|
CredentialsError | NO_CREDENTIAL / PROFILE_NOT_FOUND | Nothing resolved, or the named profile is missing. |
CredentialsError | FILE_INVALID | The file is unreadable or malformed. |
CredentialsError | EXPIRED | The stored key's expires_at has passed. |
CredentialsError | BASE_URL_MISMATCH | The file's base_url conflicts with COSMO_BASE_URL. |
CredentialsError | CONFLICTING_CREDENTIALS / API_KEY_IN_TOKEN_SLOT / INSECURE_BASE_URL | The credential was supplied in a way the SDK refuses to send. |
Model
model= takes a model id or provider alias as a plain string, or one provider-discriminated block. A knob only exists on the provider that honors it, and the block names the provider itself — the provider tag defaults to the class's value and always serializes, so you never write it — meaning a model that disagrees with its knobs is unrepresentable. All five classes are root imports.
| Class | provider | Knobs |
|---|---|---|
GeminiModel | "gemini" | model_id, temperature (0.0–2.0), max_output_tokens (1–32768), thinking_level (ThinkingLevel), include_thoughts, tool_response_policy, tool_response_overrides, turn_detection (unset or "cosmo_vad" = Cosmo's semantic detection; "server_vad" = silence-window detection), end_of_speech_sensitivity ("low" / "high"), silence_duration_ms (0–5000), prefix_padding_ms (0–5000) — the last three are read only with "server_vad" — and cosmo_vad (CosmoVadConfig: pause_ms / prefix_ms / max_hold_ms, each 0–5000) tuning the semantic detector. |
OpenAIModel | "openai" | model_id, turn_detection ("server_vad" / "semantic_vad"), eagerness (semantic_vad only), silence_duration_ms and prefix_padding_ms (0–5000, server_vad only). Sampling and token limits are pinned by the provider. |
OpenAIMiniModel | "openai_mini" | model_id; no other knobs — the same API on a faster, cheaper tier, equally untunable today. |
OpenAILiveModel | "openai_live" | model_id, plus the knobs of the backend Responses model GPT Live delegates tool calls and reasoning to: responses_model, responses_instructions (defaults to the agent's own), reasoning_effort (OpenAILiveReasoningEffort), verbosity (OpenAILiveVerbosity), tool_choice (OpenAILiveToolChoice), parallel_tool_calls, max_output_tokens (16–32768), service_tier (OpenAILiveServiceTier), and delegation (OpenAILiveDelegation: responses / client / cosmo) — who does the work the voice model hands off; under client and cosmo the responses_* knobs are unused, the agent declares no tools, and the session emits a delegation-created event. GPT Live is full-duplex and owns its turn-taking, so it has no detector knobs; it is audio-only, so video and screen frames are ignored on it. |
GrokModel | "grok" | model_id, turn_detection ("server_vad", the only detector Grok offers), silence_duration_ms and prefix_padding_ms (0–5000), reasoning_effort (GrokReasoningEffort: HIGH — Grok’s own default, deliberate answers at multi-second latency — or NONE, answering immediately), speed (0.7–1.5 playback-rate multiplier), and idle_timeout_ms (0–120000; the server re-engages the user after this much post-response silence, re-arming each response). Sampling and token limits are pinned by the provider. |
model_id pins the concrete model within the block's provider; leave it unset to run that provider's default, and a model_id belonging to another provider is rejected at session start. RealtimeModel, the union alias that annotates the model= parameter, is also a root import — as is RealtimeModelBlock for the block alone.
ThinkingLevel (Gemini only): MINIMAL / LOW / MEDIUM / HIGH (wire values minimal, low, medium, high).
GrokReasoningEffort (Grok only): HIGH / NONE (wire values high, none).
OpenAILiveReasoningEffort (GPT Live only): MINIMAL / LOW / MEDIUM / HIGH (wire values minimal, low, medium, high). OpenAILiveVerbosity: LOW / MEDIUM / HIGH. OpenAILiveToolChoice: AUTO / REQUIRED / NONE. OpenAILiveServiceTier: AUTO / DEFAULT / FLEX / PRIORITY. All four are root imports.
Tool types
The tools= parameter type is Sequence[AgentTool] — a plain union of the authorable tool classes. WebSearchTool, ExamineImageTool, DetectObjectsTool, PointAtObjectTool, and EndCallTool are zero-config server-tool opt-ins (each carries only its kind; unknown fields are a validation error), all root imports. The deeper authoring surface lives in cosmo_ai.tools:
| Name | Import | Description |
|---|---|---|
PointAtObjectTool | cosmo_ai | Opt-in to the server-executed object locator that returns points (kind="point_at_object"). |
ClientTool | cosmo_ai.tools | The raw client-tool spec the @tool decorator lowers to: name (max 64 chars, ^[a-z][a-z0-9_]{2,63}$), description (max 2048), parameters (JSON Schema, restricted dialect), handler. |
BackgroundClientTool | cosmo_ai.tools | Long-running variant — same wire shape; its handler receives the args and a ClientToolJob instead of returning a result. |
ClientToolJob | cosmo_ai.tools | Handle for one background tool call: job_id, tool_name, acked, and the coroutines ack(note=""), complete(*, result=None, summary=None), fail(*, error). All three terminal calls are idempotent once delivered; result payloads cap at 8 KiB and terminal text at 2048 chars. |
AgentTool | cosmo_ai | The union: ClientTool | WebSearchTool | ExamineImageTool | DetectObjectsTool | PointAtObjectTool | EndCallTool | ScreenLocateTool | SpeakerLogTool. |
Session and event types
Supporting types carried on session state and events:
| Name | Shape / members |
|---|---|
DisconnectReason | Enum: CLIENT_ENDED, CLIENT_CLOSED, HANDSHAKE_FAILED, SERVER_ENDED, TRANSPORT_ERROR (values client_ended, …). Carried on SessionState.disconnect_reason and SessionEndContext.reason. |
RejectedTool | name, reason — one entry of ReadyEvent.rejected_tools: a tool that was valid but unavailable here, dropped so the session can run. |
ResolvedAgent | name, tools (list of tool names) — ReadyEvent.agent when the session launched a catalog agent: which stored agent resolved and what it runs with. None for inline agents. Informational only — the server runs the stored config regardless. |
SessionHandle | The return of RealtimeAgent.start(): awaitable and an async context manager, either form yielding the started RealtimeSession. Created by the SDK; exists as a name so wrapping code can annotate it. |
ErrorCode | Enum, all 7 members: AUTH_FAILED, WORKSPACE_FORBIDDEN, VOICE_DISABLED, UPSTREAM_DISCONNECT, INTERNAL_ERROR, INVALID_MESSAGE, VERSION_MISMATCH (wire values are the lowercase slugs). The code on a ErrorEvent event. |
SessionStartTimings | Server-side session-start phase breakdown in ms: version_check_ms, project_check_ms, provider_resolve_ms, db_insert_ms, mint_tokens_ms, dispatch_ms, total_ms, and optional resolve_ms. Read it off session.connect_timings.server_timings. |
TranscriptRole | USER / ASSISTANT (values user/assistant; the wire's uppercase spellings are accepted on decode). |
TranscriptItem | id, role (TranscriptRole), text, is_final — one coalesced turn in session.transcript and on TranscriptUpdatedEvent.items. Frozen; id is a stable render key, and an item never changes once is_final is True. |
InterruptionSensitivity | DEFAULT / HIGH / LOW. |
Verification and telephony types
Types resolved by client.verify(), client.mint_token(), and session.dial():
| Name | Shape |
|---|---|
CredentialInfo | credential (CredentialKind), workspace (WorkspaceInfo | None — present for an API key, None for a minted token), scopes, can_start_sessions, realtime_voice_available, external_user_id. |
CredentialKind | Enum: API_KEY ("api_key"), USER_TOKEN ("user_token"). |
WorkspaceInfo | name, slug — the workspace a credential is bound to. |
MintedToken | jwt, expires_at (datetime), token_id (the revocation handle — keep it server-side). |
DialResult | dial_id (UUID) — the dial is queued, not connected; progress arrives as session events. |
Gemini tool response policies
GeminiToolResponsePolicy(behavior="non_blocking", scheduling="when_idle") lets a tool run while the agent continues speaking. Set GeminiModel.tool_response_policy for the default and tool_response_overrides for a mapping from declared tool names to replacement policies. The default remains blocking. Scheduling accepts when_idle (answer after current speech), silent (absorb without speaking), or interrupt (interrupt speech to answer).
from cosmo_ai import GeminiModel, GeminiToolResponsePolicy
model = GeminiModel(
model_id="gemini-3.8-live",
tool_response_overrides={
"lookup": GeminiToolResponsePolicy(behavior="non_blocking", scheduling="when_idle"),
},
)gemini-3.8-live-extended-thinking defaults to non-blocking tools, accepts low, medium or high thinking, and rejects minimal, blocking policies and explicit scheduling. An utterance can finish while the model is still thinking. Use non-blocking tools for independent lookups; keep actions that must finish before further speech blocking on standard Gemini Live. Existing background job tools keep their separate acknowledgement and completion contract.