Client SDKs

Python SDK

Install and configure the LMNT Python SDK with sync and async client support.

The LMNT Python SDK provides convenient access to the LMNT REST API from any Python application. It supports synchronous and asynchronous clients with streaming.

For per-method API documentation with code examples, see the API Reference. This page covers Python-specific SDK features and configuration.

Installation

pip install lmnt

Requirements

Python 3.10 or later is required.

Usage

import os
from lmnt import Lmnt
 
client = Lmnt(
    api_key=os.environ.get('LMNT_API_KEY'),  # This is the default and can be omitted
)
 
response = client.speech.generate(
    text='hello world.',
    voice='leah',
)

Consider using python-dotenv to add LMNT_API_KEY="my-lmnt-api-key" to your .env file so that your API key isn't stored in source control.

Async usage

Import AsyncLmnt instead of Lmnt and await each call:

import os
import asyncio
from lmnt import AsyncLmnt
 
client = AsyncLmnt(
    api_key=os.environ.get('LMNT_API_KEY'),
)
 
 
async def main() -> None:
    response = await client.speech.generate(
        text='hello world.',
        voice='leah',
    )
 
 
asyncio.run(main())

Functionality between the synchronous and asynchronous clients is otherwise identical.

Using aiohttp for better concurrency

By default, the async client uses httpx. For improved concurrency you can use aiohttp as the HTTP backend.

Install with the aiohttp extra:

pip install lmnt[aiohttp]

Then pass DefaultAioHttpClient() when constructing the client:

import asyncio
from lmnt import AsyncLmnt, DefaultAioHttpClient
 
 
async def main() -> None:
    async with AsyncLmnt(
        api_key='My API Key',
        http_client=DefaultAioHttpClient(),
    ) as client:
        response = await client.speech.generate(
            text='hello world.',
            voice='leah',
        )
 
 
asyncio.run(main())

Streaming responses

speech.generate returns audio bytes. To stream them as they're produced — instead of buffering the full response in memory — use with_streaming_response:

from lmnt import Lmnt
 
client = Lmnt()
 
with client.speech.with_streaming_response.generate(
    text='hello world.',
    voice='leah',
) as response:
    response.stream_to_file('hello.mp3')

The async client uses the same interface:

import asyncio
from lmnt import AsyncLmnt
 
client = AsyncLmnt()
 
 
async def main() -> None:
    async with client.speech.with_streaming_response.generate(
        text='hello world.',
        voice='leah',
    ) as response:
        await response.stream_to_file('hello.mp3')
 
 
asyncio.run(main())

The context manager is required so that the response is reliably closed.

File uploads

Request parameters that correspond to file uploads can be passed as bytes, a PathLike, or a tuple of (filename, contents, media_type).

from pathlib import Path
from lmnt import Lmnt
 
client = Lmnt()
 
client.voices.create(
    name='My Voice',
    files=[Path('sample1.wav'), Path('sample2.wav')],
    enhance=False,
)

The async client uses the same interface. If you pass a PathLike, the file contents are read asynchronously automatically.

Handling errors

When the library is unable to connect to the API (for example, a network issue or timeout), a subclass of lmnt.APIConnectionError is raised.

When the API returns a non-success status code (4xx or 5xx), a subclass of lmnt.APIStatusError is raised, with status_code and response properties.

All errors inherit from lmnt.APIError.

import lmnt
from lmnt import Lmnt
 
client = Lmnt()
 
try:
    client.speech.generate(
        text='hello world.',
        voice='leah',
    )
except lmnt.APIConnectionError as e:
    print('The server could not be reached')
    print(e.__cause__)  # an underlying Exception, likely raised within httpx
except lmnt.RateLimitError as e:
    print('A 429 status code was received; we should back off a bit.')
except lmnt.APIStatusError as e:
    print('Another non-200-range status code was received')
    print(e.status_code)
    print(e.response)

Error codes are as follows:

Status CodeError Type
400BadRequestError
401AuthenticationError
403PermissionDeniedError
404NotFoundError
422UnprocessableEntityError
429RateLimitError
>=500InternalServerError
N/AAPIConnectionError

Retries

Certain errors are automatically retried twice by default, with a short exponential backoff. Connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default.

Use the max_retries option to configure or disable this:

from lmnt import Lmnt
 
# Configure the default for all requests:
client = Lmnt(
    max_retries=0,  # default is 2
)
 
# Or, configure per-request:
client.with_options(max_retries=5).speech.generate(
    text='hello world.',
    voice='leah',
)

Timeouts

By default, requests time out after 1 minute. Configure this with the timeout option, which accepts a float or an httpx.Timeout:

import httpx
from lmnt import Lmnt
 
# Configure the default for all requests:
client = Lmnt(
    timeout=20.0,  # 20 seconds (default is 1 minute)
)
 
# More granular control:
client = Lmnt(
    timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)
 
# Override per-request:
client.with_options(timeout=5.0).speech.generate(
    text='hello world.',
    voice='leah',
)

On timeout, an APITimeoutError is thrown. Requests that time out are retried twice by default.

Type system

Nested request parameters are TypedDicts. Responses are Pydantic models which provide helper methods for serializing back into JSON (.to_json()) or a dictionary (.to_dict()).

Typed requests and responses provide autocomplete and documentation within your editor. To see type errors in VS Code, set python.analysis.typeCheckingMode to basic.

Handling null vs missing fields

In an API response, a field may be explicitly null or missing entirely; in either case, its value is None. You can differentiate the two with .model_fields_set:

if response.my_field is None:
    if 'my_field' not in response.model_fields_set:
        print('field was not in the response')
    else:
        print('field was null')

Advanced usage

Accessing raw response data (e.g., headers)

The "raw" response from httpx can be accessed by prefixing .with_raw_response. to any HTTP method call:

from lmnt import Lmnt
 
client = Lmnt()
response = client.speech.with_raw_response.generate(
    text='hello world.',
    voice='leah',
)
print(response.headers.get('X-My-Header'))
 
speech = response.parse()  # the object that `speech.generate()` would have returned
print(speech)

Logging

The SDK uses the standard library logging module.

Enable logging by setting the LMNT_LOG environment variable:

export LMNT_LOG=info

Use debug for more verbose output.

Making custom/undocumented requests

This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.

Undocumented endpoints

To make requests to undocumented endpoints, use client.get, client.post, and other HTTP verbs. Client options like retries are still respected.

import httpx
 
response = client.post(
    '/foo',
    cast_to=httpx.Response,
    body={'my_param': True},
)
 
print(response.headers.get('x-foo'))

Undocumented request params

Use the extra_query, extra_body, and extra_headers request options to send additional parameters.

Undocumented response properties

To access undocumented response properties, read fields like response.unknown_prop. The full extra-fields dict is available as response.model_extra.

Configuring the HTTP client

You can override the httpx client — useful for proxies, custom transports, and other advanced configuration:

import httpx
from lmnt import Lmnt, DefaultHttpxClient
 
client = Lmnt(
    # Or use the `LMNT_BASE_URL` env var
    base_url='http://my.test.server.example.com:8083',
    http_client=DefaultHttpxClient(
        proxy='http://my.test.proxy.example.com',
        transport=httpx.HTTPTransport(local_address='0.0.0.0'),
    ),
)

You can also customize per-request:

client.with_options(http_client=DefaultHttpxClient(...))

Managing HTTP resources

By default the library closes underlying HTTP connections whenever the client is garbage collected. You can manually close the client with .close() or use a context manager:

from lmnt import Lmnt
 
with Lmnt() as client:
    # make requests here
    ...
 
# HTTP client is now closed

Semantic versioning

This package generally follows SemVer, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes that only affect static types, without breaking runtime behavior.
  2. Changes to library internals which are technically public but not intended or documented for external use.
  3. Changes that we don't expect to impact the vast majority of users in practice.

Determining the installed version

If you've upgraded but aren't seeing new features, your environment is likely still using an older version. Check at runtime with:

import lmnt
 
print(lmnt.__version__)

Additional resources