Skip to content

Python SDK · pyai-sdk v0.4.0

Natural speech, a few lines of Python.

Stream Speak and transcribe recordings with Hear through one reusable client.

Receive audio as it arrives with speech_stream.
Reuse pooled connections across synthesis and transcription requests.
Leave the Hear language hint unset for automatic detection.

From download to working audio

Python 3.10+. A PyAI key. The starter writes speech.wav; add --transcribe call.wav to transcribe your own recording.

Terminal · macOS / Linux
curl -fSL https://pyai.com/starters/pyai-python.tar.gz -o pyai-python.tar.gz
tar -xzf pyai-python.tar.gz
cd pyai-python
python3 -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
cp .env.example .env
# Fill in .env, then export its values in this shell:
set -a
. ./.env
set +a
python main.py

Edit the downloaded .env before running. Keep it out of Git. On Windows, use WSL for these shell commands.

What happens when you run it?

The starter measures first received bytes, not speaker playback latency. Feed PCM chunks to your audio sink for live playback.

Take it into your application

Choose a voice from the API catalog and check its language coverage. Reuse clients, consume streaming audio immediately, and cancel interrupted responses. PCM, WAV and G.711 stream; MP3 and Opus are buffered.

The complete entry point

This is the same file included in the download. Copy it here, or get the full project with its dependency and environment files.

main.py
"""Stream Speak to a WAV, then optionally transcribe a local recording."""
import argparse
from contextlib import closing
import os
from pathlib import Path
import time
import wave

from pyai import PyAI


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--text", default="Hello! Your PyAI voice integration is ready.")
    parser.add_argument("--transcribe", type=Path)
    args = parser.parse_args()
    started = time.perf_counter()
    received = 0
    with PyAI(api_key=os.environ["PYAI_API_KEY"]) as client:
        # Reuse this client in your application; do not recreate it per chunk.
        with wave.open("speech.wav", "wb") as audio:
            audio.setparams((1, 2, 24000, 0, "NONE", "not compressed"))
            with closing(client.audio.speech_stream(
                input=args.text,
                voice=os.getenv("PYAI_VOICE", "stock_emma_en_gb"),
                response_format="pcm", sample_rate=24000,
            )) as chunks:
                for chunk in chunks:
                    if not received:
                        print(f"First audio bytes: {(time.perf_counter() - started) * 1000:.0f} ms")
                    # A live player can consume each chunk here instead.
                    audio.writeframesraw(chunk)
                    received += len(chunk)
        if not received:
            raise RuntimeError("Speak returned no audio")
        print(f"Saved speech.wav ({received} PCM bytes)")
        if args.transcribe:
            with args.transcribe.open("rb") as recording:
                result = client.audio.transcriptions.create(
                    file=recording, filename=args.transcribe.name,
                )  # Omit the language hint for automatic detection.
            print(result["text"])


if __name__ == "__main__":
    main()

Build with Python in your coding agent

Install Node.js 22+ and your coding agent first. Connect PyAI’s MCP server, then ask it to call get_started. For a sandbox test, ask it to call create_sandbox_key once. Keep live credentials in your environment.

Codex · terminal
codex mcp add pyai -- npx -y @pyai/mcp@0.2.0
Claude Code · terminal
claude mcp add --transport stdio --scope project pyai -- npx -y @pyai/mcp@0.2.0
Cursor · .cursor/mcp.json
{
  "mcpServers": {
    "pyai": {
      "type": "stdio",
      "command": "npx",
      "args": [
        "-y",
        "@pyai/mcp@0.2.0"
      ]
    }
  }
}

Merge the pyai entry into your existing mcpServers configuration. Enable it in Cursor’s MCP settings.

Paste into your coding agent
Read https://pyai.com/skill.md and https://pyai.com/sdks/python.md.
Use the matching starter to add PyAI voice to this project.
Keep credentials in environment variables. Run a short synthetic
audio test and report the result and any missing credentials.
Do not place a phone call or send a message unless I ask.

Want a reusable local skill? Copy the Codex and Claude Code skill install commands. Any tool that reads Markdown can use skill.md.

Python SDK questions

What is included in the download?

The Python starter includes its complete entry point, pinned PyAI package version, dependency manifest, environment template, and run instructions.

What do I need before running it?

A PyAI key. The starter writes speech.wav; add --transcribe call.wav to transcribe your own recording.

Can I use this with Cursor, Codex or Claude Code?

Yes. Connect the PyAI MCP server and give your agent the Python Markdown guide. It includes the complete starter source and setup commands.

How do I test streaming performance?

Measure first received audio and playback readiness separately in your application. Network location, load, text, and voice affect timing. Playing the saved file does not measure streaming latency.

← Explore all SDKs