Skip to main content

API Reference

Complete reference for the getpatter Python SDK.

Patter

The main SDK client class.

Constructor

ParameterTypeDefaultDescription
carrierTwilio | Telnyx | NoneNoneTelephony carrier instance. Reads credentials from env vars when arguments are omitted.
phone_numberstr""Phone number in E.164 format.
webhook_urlstr""Public hostname, no scheme.
tunnelCloudflareTunnel | Static | Ngrok | bool | NoneNoneTunnel directive. True is shorthand for CloudflareTunnel().
pricingdict | NoneNoneOverride default provider pricing. See Metrics & Cost Tracking.
persistbool | str | NoneNonePersistent dashboard history. None (default) → falls back to PATTER_LOG_DIR, then platform default — i.e. persistence is ON by default since 0.6.2. False force-off. True → platform default path. String → explicit path (~ expanded). See Configuration.

Methods

agent()

Pass engine=OpenAIRealtime(...), engine=OpenAIRealtime2(...), or engine=ElevenLabsConvAI(...) for end-to-end engines; omit engine= and pass stt=/tts= for pipeline mode.
ParameterTypeDefaultDescription
system_promptstrrequiredAgent instructions.
engineOpenAIRealtime | OpenAIRealtime2 | ElevenLabsConvAI | NoneNoneEnd-to-end voice runtime. Omit for pipeline mode.
sttSTTProvider | NoneNoneSTT instance for pipeline mode (e.g. DeepgramSTT()).
llmLLMProvider | NoneNoneLLM provider instance for pipeline mode (e.g. AnthropicLLM()). Mutually exclusive with on_message on serve(). Ignored when engine is set.
ttsTTSProvider | NoneNoneTTS instance for pipeline mode (e.g. ElevenLabsTTS()).
voicestr"alloy"TTS voice name (when engine doesn’t carry it).
modelstr"gpt-realtime-mini"AI model ID (when engine doesn’t carry it).
languagestr"en"BCP-47 language code.
first_messagestr""Greeting spoken at call start.
toolslist[Tool] | NoneNoneTool(...) instances for function calling.
variablesdict | NoneNoneDynamic {placeholder} variable substitutions.
guardrailslist[Guardrail] | NoneNoneGuardrail(...) instances applied to LLM output.
hooksPipelineHooks | NoneNonePipeline hooks for STT/TTS interception.
text_transformslist[Callable] | NoneNoneText transformation functions (pipeline mode).
vadVADProvider | NoneNoneVoice activity detection provider (pipeline mode).
audio_filterAudioFilter | NoneNoneAudio preprocessing filter (pipeline mode).
background_audioBackgroundAudioPlayer | NoneNoneBackground audio player (pipeline mode).
barge_in_threshold_msint300Barge-in hang-over window (ms). Set to 0 to disable.
aggressive_first_flushboolFalseEmit the first clause on a soft punctuation boundary (,, em/en-dash) once buffer ≥40 chars. Saves 200–500 ms TTFA. Hard-disabled when language starts with "it". Pipeline mode only.
disable_phone_preambleboolFalseDisable the phone-friendly preamble Patter prepends to system_prompt (no markdown / emojis / lists, numbers spelled out, replies kept short). Default False keeps the preamble on.
echo_cancellationboolFalsePipeline mode only. Instantiates an NlmsEchoCanceller per call so the agent’s own TTS bleed is removed from the inbound mic before VAD/STT. See Echo Cancellation.
mcp_serverslist | NoneNoneList of MCP server definitions exposed to the agent as tools. See MCP.
prewarm_first_messagebool | NoneNone (=False)Opt in to pre-rendering first_message TTS during the ringing window so playback starts instantly on pickup. Off by default in 0.6.2 — re-enable per agent when you’ve validated barge-in interaction.
Raises: ValueError if required credentials are missing or conflicting options are passed (e.g. both engine and stt/tts).

serve()

Start the embedded server. Blocks until stopped. local_recording enables carrier-neutral SDK-side recording: an interleaved stereo WAV (left = caller, right = agent, PCM16 16 kHz) written incrementally per call. Pass a directory string to choose the output directory. The final path is surfaced as recording_path in the on_call_end payload. Independent of the carrier-side recording flag. See Local Recording.

call()

Make an outbound call. Keyword arguments are snake_case — e.g. machine_detection=, ring_timeout=, on_machine_detection= (the latter was renamed from on_machine in 0.6.2; the callback receives a MachineDetectionResult not a raw dict). machine_detection defaults to True since 0.6.2 — on Twilio Patter uses MachineDetection=DetectMessageEnd + Async AMD so there is no answer-latency penalty on human pickups. Pass machine_detection=False to skip per-call AMD billing for known destinations. ring_timeout defaults to 25 seconds, the production-recommended value. Pass 60 for legacy carrier-default parity, or None to omit the parameter entirely (carrier picks its own default).

test()

Start an interactive terminal test session. Simulates a phone call without telephony, STT, or TTS — pure text input/output. See Test Mode.

disconnect()

Disconnect from Patter. Stops the embedded server.

Carriers

Twilio

Telnyx


Engines

OpenAIRealtime

OpenAIRealtime2

Selects the GA Realtime API. Separate marker from OpenAIRealtime because the GA endpoint speaks a different session.update wire shape. See Engines › OpenAIRealtime2.

ElevenLabsConvAI


STT classes

All classes accept api_key: str | None = None and fall back to the provider’s standard env var. See the STT page for full constructor signatures.

TTS classes

All classes accept api_key: str | None = None and fall back to the provider’s standard env var. See the TTS page for full constructor signatures.

LLM providers

All classes accept api_key: str | None = None and fall back to the provider’s standard env var (GoogleLLM prefers GEMINI_API_KEY, falls back to GOOGLE_API_KEY). See the LLM page for full constructor signatures and tool-calling semantics. Pass an instance via phone.agent(llm=...) for pipeline mode. llm= is mutually exclusive with on_message on serve() and is ignored when engine= is set.

Tunnels

ClassBehavior
CloudflareTunnel()Auto-start a Cloudflare Quick Tunnel via the local cloudflared binary.
Static(hostname=...)Use an existing public hostname (user-managed tunnel, e.g. ngrok).
Ngrok(hostname=...)Use an existing ngrok hostname (you run ngrok http 8000 yourself). Same behavior as Static(hostname=...) with an ngrok-friendly name.
tunnel=True on Patter(...) is shorthand for tunnel=CloudflareTunnel().

Tools & Guardrails

Tool

Either handler or webhook_url must be provided. tool(...) is a factory that doubles as a decorator — see Tools.

Guardrail

See Guardrails.

Data Classes

All data classes are frozen (immutable) dataclasses.

Agent

provider is a closed string literal — "openai_realtime", "openai_realtime_2", "elevenlabs_convai", or "pipeline". It is normally derived from engine / stt+tts and rarely set by hand.

CallEvent

IncomingMessage

STTConfig / TTSConfig

Internal config dataclasses produced when you pass an STT/TTS instance to phone.agent(). You rarely need to construct these directly.

CallControl

Passed as the second argument to on_message handlers. Allows dynamic call management:

CallMetrics / CostBreakdown / LatencyBreakdown / TurnMetrics

See Metrics & Cost Tracking.

Exceptions

Every Patter exception carries a stable, machine-readable ErrorCode on its code attribute. Branch on the code instead of class-name strings:

ErrorCode values

CodeRaised when
CONFIGInvalid constructor args, missing required env var, frozen-config violation.
CONNECTIONWebSocket connect failure, HTTP 5xx from a provider, network error.
AUTHProvider rejected our credentials (HTTP 401/403, invalid signature).
TIMEOUTProvider response, voicemail post, or other awaited operation timed out.
RATE_LIMITProvider returned HTTP 429.
WEBHOOK_VERIFICATIONTwilio / Telnyx / Plivo webhook signature verification failed.
INPUT_VALIDATIONCaller passed a malformed phone number, tool arg, etc.
PROVIDER_ERRORGeneric catch-all for unexpected upstream provider failures.
PROVISIONPhone number provisioning, webhook configuration, or carrier setup failed.
INTERNALAssertion failed / unexpected internal state. Likely a Patter bug.
ErrorCode is a StrEnum — values compare equal to their string form, so exc.code == "AUTH" also works for backward-compatible callers.

Audio helpers

HelperPurpose
builtin_clip_path(name: str) -> PathResolve the on-disk path for a built-in BuiltinAudioClip (hold music, dial tones, hangup chimes) so callers can preload or copy them.
select_sound_from_list(sounds, *, rng=None) -> strPick one entry from a list of sound paths/IDs deterministically (or randomly when rng is provided). Useful for randomised hold music.
resample_24k_to_16k(pcm: bytes) -> bytesOne-shot 24 kHz → 16 kHz PCM resampler. Mirrors the helper Patter uses internally for OpenAI TTS chunks; exported for callers who need to do the same conversion outside the streaming loop.

Top-level exports