Python SDK
Install the Python SDK from PyPI. The methods below require SDK 0.6.8 and a matching CLI/gateway version.
Install
Python 3.10 or newer is required. All supported platforms use the same pure Python wheel:
python -m pip install edgespeakThe SDK discovers the CLI automatically and requires CLI >= 0.6.8 with edgespeak-sdk-v2 support (edgespeak.MIN_CLI_VERSION). Compatible installations are reused without a network check. Missing or incompatible installations trigger the official stable installer, followed by another compatibility check. Installation requires network access and uses a separate directory under ~/.edgespeak/sdk/, preserving existing CLI entries and PATH; it has a separate 20-minute timeout. If the official CLI or installer release still lacks SDK support, startup reports a clear error. Models and native engines are not included in the Python package. Automatic installation supports macOS Apple Silicon, Linux x86_64 and Windows x64.
Transcribe and align
import os
from edgespeak import EdgeSpeak
with EdgeSpeak(api_key=os.environ["EDGESPEAK_API_KEY"]) as client:
transcript = client.transcribe("meeting.wav", language="en", diarize=True)
alignment = client.align("speech.wav", text="The exact words spoken.", language="en")
print(transcript["text"])
print(alignment)The SDK starts its own CLI service on a random loopback port. It uses the highest compatible CLI version it finds; pass cli_path= to pin a specific executable, which is checked the same way and never falls back to discovery or installation. client.cli_path and client.cli_version report the CLI that was started. Without an account API key, the CLI uses its existing local activation flow.
Speaker analysis
with EdgeSpeak() as client:
turns = client.diarize("meeting.wav", num_speakers=2)
first = client.speaker_embedding("alice.wav")
second = client.speaker_embedding("bob.wav")
comparison = client.speaker_similarity(first["data"][0]["embedding"], second["data"][0]["embedding"])The methods return the gateway JSON objects. See transcription and speaker analysis and alignment for response fields. Audio timestamps are in seconds. Alignment requires the words actually spoken, not a translation.
Account API KEY
Open the separate API KEY page from the account menu to name and create a key. Copy the full key when it appears; the list only retains its prefix. Choose its validity period and revoke keys you no longer use.
Pass the key as api_key, or set EDGESPEAK_API_KEY and let EdgeSpeak() read it. The SDK translates the account credential for its CLI internally. For an attached gateway, pass its separate token as gateway_key; these examples use EDGESPEAK_GATEWAY_KEY. Account keys use the account’s existing device and usage limits. They do not provide website login or offline authorization.
SDK and desktop sessions on the same machine share a device slot. Closing the SDK or revoking a key does not remove the device. Remove an unused machine in the account page’s device management to free its slot. Account keys remain valid after a password reset until they expire or you revoke them.
The SDK passes the account key through the child environment, not command-line arguments. The CLI keeps session credentials in memory while preserving the existing desktop identity and shared usage ledger. Revocation rejects subsequent server requests; previously issued credentials last at most five minutes. Already-running inference is not interrupted.
Service ownership
Prefer a with block. close() is idempotent and releases the service started by that client. Garbage collection has a cleanup fallback, but its timing is not guaranteed. The service also watches its parent’s input pipe so it can exit if Python terminates unexpectedly.
A service that does not finish shutdown is forcibly stopped. A closed HTTP port alone does not prove native workers have exited. Windows process cleanup and inference-loaded process cleanup must pass release validation before this development SDK is published.
Create a new client in each worker process. Prefer Python multiprocessing’s spawn mode; a forked child must not use its parent’s client.
Attach to a running gateway
with EdgeSpeak(
base_url="http://127.0.0.1:1118/v1",
gateway_key=os.environ["EDGESPEAK_GATEWAY_KEY"],
) as client:
result = client.transcribe("meeting.wav")An attached client never stops the external service. Do not pass an account api_key in this mode. Remote URLs require HTTPS. Redirects, environment proxies, and environment CA overrides are disabled.
Errors and timeouts
EdgeSpeakError exposes code and status_code; server error text is not echoed. RuntimeStartError indicates CLI launch or handshake failure. The default request timeout is 600 seconds per HTTP I/O phase, not a total job deadline. startup_timeout defaults to 30 seconds. A request timeout does not prove server-side inference has stopped.
Speech methods
Methods return the API JSON unchanged (models() additionally annotates it with capability groups), except transcribe(response_format="text"), which returns a string. Times are in seconds. See the audio API, alignment API, and text API for model requirements and parameter constraints.
| Method | Options and behavior |
|---|---|
transcribe(audio, ...) | model, language, diarize, response_format, prompt, timestamp_granularities, word_timestamp_enabled, candidates, semantic_sentence_enabled, min_chars, max_chars, start_margin, end_margin, stream |
align(audio, ...) | text or text_file, text_format, model, language, search_effort, threshold, start + end, protected_terms, text_normalization, audio_track, audio_channel, semantic_sentence_enabled, min_chars, max_chars, start_margin, end_margin, word_boundaries ("auto" or "input", see word-level timing), progress |
segment(text, ...) | Plain text or segments, threshold, paragraph_threshold, min_chars, max_chars, start_margin, end_margin, options |
diarize(audio, ...) | Independent speaker turns; optional num_speakers from 1 to 32 |
speaker_embedding(audio, ...) | One path or a list of paths; optional model; batch results retain input order |
speaker_similarity(a, b, ...) | Two embeddings produced by the same model; optional model |
diarize=True selects diarized_json in transcription. It cannot be combined with another response format. Speaker-count selection belongs to diarize(): the transcription and alignment APIs do not accept num_speakers. The alignment API does not currently perform speaker diarization.
Reference files and alignment
with EdgeSpeak() as client:
aligned = client.align(
"speech.wav", text_file="captions.ass", language="en",
search_effort="auto", semantic_sentence_enabled=True,
min_chars=10, max_chars=80,
)
from_json = client.align(
"speech.wav", text={"segments": [{"text": "The exact words spoken."}]}
)text_file reads a local UTF-8 file (optional BOM, up to 64 MiB). Supported extensions are .txt, .json, .srt, .ass, and .ssa; text_format can override the extension. JSON accepts the API caption structure with segments[].text (or a top-level text fallback). To pass subtitle contents directly, use text=contents, text_format="srt" (or json, ass, ssa). Supply exactly one of text and text_file.
The SDK uploads file contents, never a local text_path. The CLI's shared parser extracts spoken text, discards existing subtitle timing, and ignores ASS styles, comments, and drawing commands. Alignment computes new timing from the audio. This requires the CLI/API 0.6.8 text_format support.
Semantic sentences and paragraphs
with EdgeSpeak() as client:
sentences = client.segment("First sentence. A second sentence.", max_chars=80)
paragraphs = client.segment("A longer passage.", paragraph_threshold=0.6)
transcript = client.transcribe("meeting.wav", diarize=True)
captions = client.segment(segments=transcript["segments"], min_chars=10, max_chars=80)Plain-text mode produces sentences. Timed-segment mode retains timing and speaker information through the API's resegmentation behavior. Paragraph mode accepts plain text only and cannot be combined with timed segments, length limits, or margins. semantic_sentence_enabled=True also enables sentence segmentation directly during transcription or alignment; omitted settings inherit runtime defaults.
Progress and streaming
with EdgeSpeak() as client:
with client.align("speech.wav", text="The exact words spoken.", progress=True) as events:
for event in events:
print(event)Alignment yields progress/stage events followed by the final alignment object. A progress value of 1 is not the final result. transcribe(stream=True) yields SSE events and currently requires an attached desktop gateway; the headless CLI does not support streaming transcription. Streaming transcription requires response_format="json" and does not support diarization or timestamp granularities. The API rejects incompatible combinations.
Use a stream context manager when stopping early. Closing the client also closes its streams. A connection that ends without a terminal event raises EdgeSpeakError with code incomplete_stream. Closing a stream releases the connection and upload files, but does not guarantee cancellation of inference already running.
Runnable examples
The Python SDK examples cover transcription, alignment, semantic sentences/paragraphs, timed captions, speaker turns, batch embeddings, and similarity. Run each file with --help for its options. Use --base-url to attach to a gateway; otherwise the example starts and closes its own CLI service.
python sdk/python/examples/transcribe.py meeting.wav --diarize --semantic
python sdk/python/examples/align.py speech.wav --text-file captions.srt --progress
python sdk/python/examples/segment.py --text "First sentence. Another sentence." --max-chars 80
python sdk/python/examples/segment.py --segments-file transcript.json --max-chars 80
python sdk/python/examples/speakers.py meeting.wav alice.wav bob.wav --num-speakers 2A key may be set to Never expires. This removes the key expiry date only; account entitlement, subscription usage limits, online authorization, and revocation still apply. Temporary authorization credentials remain limited to five minutes.
The SDK preserves the gateway's error.code as exception.code. Use exception.reason to distinguish api_key_expired, api_key_revoked, and usage_exhausted. Quota errors expose a validated exception.resets_at when the server supplies the next reset time; the existing gateway code remains license_required for that response. No arbitrary server message is echoed.
Each API KEY shares the account subscription allowance and its billing period with desktop usage. Creating or switching keys does not reset usage. The next subscription period restores its allowance according to the account plan.
Additional gateway methods
New SDK method names follow the existing HTTP paths. These client additions do not create new HTTP endpoints. Existing methods such as segment() retain their names.
| Method | Existing HTTP endpoint |
|---|---|
text_normalizations(text, language=..., mode="tn") | POST /v1/text/normalizations |
health() / usage(refresh=False) | GET /v1/health / GET /v1/usage |
models() / models_running() / models_downloads() | GET /v1/models, /v1/models/running, /v1/models/downloads |
models_load(model) / models_unload(model) | POST /v1/models/load, /v1/models/unload |
models_download(model) / models_download_cancel(model) | POST /v1/models/download, /v1/models/download/cancel |
chat_completions(messages, model=...) | POST /v1/chat/completions |
responses(input, model=...) | POST /v1/responses |
messages(messages, model=..., max_tokens=...) | POST /v1/messages |
tokenize(content, model=...) | POST /v1/tokenize |
Normalization supports TN (written → spoken) and ITN (spoken → written). Top-level text preserves the input; converted text is in alternatives[i].text. Spans use UTF-8 byte offsets into the original text. Use slice_utf8 instead of Python string slicing:
from edgespeak import EdgeSpeak, slice_utf8
with EdgeSpeak() as client:
result = client.text_normalizations("There are 25 items.", language="en", top_k=1)
print(result["alternatives"][0]["text"])
for span in result["alternatives"][0]["spans"]:
print(slice_utf8(result["text"], span["start_byte"], span["end_byte"]))top_k is 1–16; omission inherits the gateway default. classes is an optional non-empty allow-list. See the text API for supported languages, classes and response fields. Normalization and segmentation use the gateway account's text allowance, without an additional SDK deduction. Queries preserve null for unlimited allowance.
Generation returns protocol JSON by default, or a closeable EventStream with stream=True. Chat completes at [DONE] (including usage after finish_reason), Responses at response.completed, and Messages at message_stop; one content block stopping is not the end of the message. Stream errors, incomplete Responses and truncated streams raise EdgeSpeakError. Use with or close() when stopping early; this does not promise to cancel inference or undo consumed usage. Responses already yielded before an incomplete event remain available to the caller; a non-stream incomplete response raises without returning its partial result.
messages() sends anthropic-version (default 2023-06-01); override it with anthropic_version and optionally supply anthropic_beta. Other protocol extensions go in options, which cannot override any explicitly named field, even when that argument was omitted. Model-supported structured image inputs are accepted for text generation; there is no image-generation API.
tokenize() returns a JSON object or a bare integer token array, depending on the provider. For a provider schema other than content, omit content and supply its fields in options. Raw token counts exclude chat-template additions. EdgeSpeak does not deduct inference allowance for tokenization; an external provider may apply its own charges. Model lifecycle calls are explicit operations: queries never start a download, and download/cancel responses describe a job rather than guarantee completion.
All additions retain the same owned/attached authorization rules. Missing APIs on an older gateway produce an explicit compatibility error; unknown models retain their model-specific errors. Speech synthesis, voice management and speech-example SDK methods are deferred. Realtime WebSocket and MCP remain separate protocols; no Python session client is added here.
Models by capability
models() now adds a groups field to its existing Models result (SDK 0.6.9), organizing the live gateway catalog by capability; object and data remain unchanged. The same method is available on AsyncEdgeSpeak with await.
with EdgeSpeak() as client:
catalog = client.models()
groups = catalog["groups"]
for capability, group in groups.items():
print(capability, group["description"])
for model in group["models"]:
print(model["id"], model.get("installed"), model.get("default_for", []))Groups cover transcription, alignment, speaker diarization, speaker embeddings/similarity, speech synthesis, text generation/tokenization, segmentation, normalization and audio upsampling, when advertised. Each group includes title, description, supported_endpoints, sdk_methods and models. A multi-capability model appears in each applicable group. Each model retains the gateway's complete metadata and exact public ID; there is no SDK-maintained model list. Unknown or omitted capabilities remain visible under other.
installed=True: the gateway reports the model installed; this does not mean it is currently loaded or every request is authorized.installed=False: the gateway reports it not installed. Missinginstalledmeans unknown, not false.default_forandsupported_endpointsdescribe each model, not every model in the group. Use the returned public ID, such asEdgeSpeak/Lattice-2-Flash, intranscribe(model=...); speaker selection usesdiarize(model=...)ortranscribe(diarization_model=...)on a supporting gateway.models()only callsGET /v1/models; it does not load or download models. The original gateway records remain indata; grouping and descriptions are SDK annotations. An owned client may start/install the CLI as usual.models_running()reports runtime state. Speech synthesis may be advertised by HTTP even though this SDK has no convenience method for it; itssdk_methodsis empty.
Runnable examples: python examples/models.py --base-url http://127.0.0.1:1118/v1 and python examples/async_models.py --base-url http://127.0.0.1:1118/v1; add --json for complete metadata.