> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kugelaudio.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Configuration

> SDK reference for configuring the KugelAudio client: client options, authentication modes, client lifecycle and closing, region selection and diagnostics.

## Client options

<CodeGroup>

```python Python
from kugelaudio import KugelAudio

# Simple setup
client = KugelAudio(api_key="your_api_key")

# With custom options
client = KugelAudio(
    api_key="your_api_key",                # Required: Your API key
    api_url="https://api.kugelaudio.com",  # Optional: API base URL
    tts_url=None,                          # Optional: separate TTS/WebSocket URL
    timeout=60.0,                          # Optional: Request timeout in seconds
    keepalive_ping_interval=20.0,          # Optional: WS ping interval; None disables
    region=None,                           # Optional: "eu", "us", or "global"
)
```

```typescript TypeScript
import { KugelAudio } from 'kugelaudio';

// Simple setup
const client = new KugelAudio({ apiKey: 'your_api_key' });

// With custom options
const configuredClient = new KugelAudio({
  apiKey: 'your_api_key',                // Required: Your API key
  apiUrl: 'https://api.kugelaudio.com',  // Optional: API base URL
  ttsUrl: undefined,                     // Optional: separate TTS/WebSocket URL
  timeout: 60000,                        // Optional: Request timeout in ms
  keepalivePingInterval: 20000,          // Optional: WS ping interval (ms); 0/null disables
  region: undefined,                     // Optional: 'eu', 'us', or 'global'
});
```

```java Java
import com.kugelaudio.sdk.KugelAudio;
import com.kugelaudio.sdk.KugelAudioOptions;
import java.time.Duration;

// Simple setup: reads the KUGELAUDIO_API_KEY environment variable
KugelAudio client = KugelAudio.fromEnv();

// Full configuration
KugelAudio configuredClient = new KugelAudio(
    KugelAudioOptions.builder("your_api_key")
        .apiUrl("https://api.kugelaudio.com")        // REST + WebSocket base URL
        .ttsUrl("https://api.kugelaudio.com")        // Optional: separate TTS/WebSocket URL
        .timeout(Duration.ofSeconds(60))             // HTTP calls and each generate()/stream() call
        .autoConnect(true)                           // Pre-connect WebSocket (default: true)
        .keepalivePingInterval(Duration.ofSeconds(20)) // WS ping interval; null disables
        .build()
);
```

```rust Rust
use std::time::Duration;

use kugelaudio::{KugelAudio, Region};

// Simple setup
let client = KugelAudio::new("your_api_key")?;

// With custom options
let configured_client = KugelAudio::builder("your_api_key")    // Required: your API key
    .api_url("https://api.kugelaudio.com")                      // Optional: API base URL
    .tts_url("https://api.kugelaudio.com")                      // Optional: separate TTS/WebSocket URL
    .timeout(Duration::from_secs(60))                           // Optional: request timeout
    .keepalive_ping_interval(Some(Duration::from_secs(20)))     // Optional: WS ping interval; None disables
    .region(Region::Eu)                                         // Optional: Eu, Us or Global
    .build()?;
```

```cpp C++
#include <chrono>

#include <kugelaudio/kugelaudio.hpp>

// Simple setup
kugelaudio::Client client{"your_api_key"};

// With custom options
kugelaudio::ClientOptions options;
options.api_key = "your_api_key";                         // Required: your API key
options.api_url = "https://api.kugelaudio.com";           // Optional: API base URL
options.tts_url = "https://api.kugelaudio.com";           // Optional: separate TTS/WebSocket URL
options.timeout = std::chrono::seconds(60);               // Optional: request timeout
options.keepalive_ping_interval = std::chrono::seconds(20); // Optional: WS ping interval; std::nullopt disables
options.region = kugelaudio::Region::EU;                  // Optional: EU, US or Global
kugelaudio::Client configured_client{options};
```

```dart Dart
import 'package:kugelaudio/kugelaudio.dart';

// Simple setup
final client = KugelAudio(apiKey: 'your_api_key');

// With custom options
final configuredClient = KugelAudio(
  apiKey: 'your_api_key',                         // Required: your API key
  apiUrl: 'https://api.kugelaudio.com',           // Optional: API base URL
  ttsUrl: null,                                   // Optional: separate TTS/WebSocket URL
  timeout: const Duration(seconds: 60),           // Optional: request timeout
  keepalivePingInterval: const Duration(seconds: 20), // Optional: WS ping interval; null disables
  region: null,                                   // Optional: Region.eu, Region.us or Region.global
);
```

</CodeGroup>

<Tabs>
<Tab title="Python">

| Parameter | Type | Default | Description |
|---|---|---|---|
| `api_key` | `str` | required | Your API key. A `eu-`, `us-`, or `global-` prefix selects the region; the SDK strips it before authenticating. |
| `api_url` | `str \| None` | `https://api.kugelaudio.com` | API base URL. For self-hosted deployments, see [On-Premise Deployment](/guides/self-hosted). |
| `tts_url` | `str \| None` | same as `api_url` | TTS server URL for WebSocket streaming. |
| `timeout` | `float` | `60.0` | HTTP request timeout in seconds. |
| `keepalive_ping_interval` | `float \| None` | `20.0` | Seconds between WebSocket ping frames on the pooled connection to prevent idle timeouts. Set to `None` to disable. |
| `region` | `str \| None` | `None` | `"eu"`, `"us"`, or `"global"`. `"eu"` selects the direct EU endpoint; the other values use the default geo-routed endpoint. |

</Tab>
<Tab title="TypeScript">

| Option | Type | Default | Description |
|---|---|---|---|
| `apiKey` | `string` | required | API key or JWT token. A `eu-`, `us-`, or `global-` prefix selects the region; the SDK strips it before authenticating. |
| `apiUrl` | `string` | `https://api.kugelaudio.com` | API base URL. For self-hosted deployments, see [On-Premise Deployment](/guides/self-hosted). |
| `ttsUrl` | `string` | same as `apiUrl` | TTS server URL for WebSocket streaming. |
| `timeout` | `number` | `60000` | HTTP request and WebSocket opening timeout in milliseconds. Does not limit audio duration on an established socket. |
| `keepalivePingInterval` | `number \| null` | `20000` | Milliseconds between WebSocket ping frames on the pooled connection. Set to `0` or `null` to disable. Node only; ignored in browsers. |
| `region` | `Region` | none | `'eu'`, `'us'`, or `'global'`. `'eu'` selects the direct EU endpoint; the other values use the default geo-routed endpoint. |
| `isToken` | `boolean` | `false` | Treat `apiKey` as a JWT user token. |
| `orgId` | `number` | none | Organisation to bill usage against. Required for token auth to record usage. |

The full `KugelAudioOptions` interface is in [Types and errors](/sdks/types#client-options).

</Tab>
<Tab title="Java">

| Builder method | Type | Default | Description |
|---|---|---|---|
| `builder(apiKey)` | `String` | required | API key or token. A `eu-`, `us-`, or `global-` prefix selects the region; the SDK strips it before authenticating. |
| `.apiUrl(...)` | `String` | `https://api.kugelaudio.com` | REST + WebSocket base URL. For self-hosted deployments, see [On-Premise Deployment](/guides/self-hosted). |
| `.ttsUrl(...)` | `String` | same as `apiUrl` | Separate TTS server URL for WebSocket streaming. |
| `.region(Region)` | `Region` | none | `Region.EU`, `Region.US`, or `Region.GLOBAL`. `Region.EU` selects the direct EU endpoint. |
| `.timeout(Duration)` | `Duration` | 60 s | Timeout for HTTP calls and for each complete `generate()` or `stream()` request. A generation that runs longer throws `ConnectionException("Request timed out")`; raise it for long texts. |
| `.autoConnect(boolean)` | `boolean` | `true` | Pre-open the WebSocket at construction. |
| `.keepalivePingInterval(Duration)` | `Duration` | 20 s | WebSocket ping interval to prevent idle timeouts. Pass `null` to disable. |
| `.token()` | none | none | Treat the key as a JWT user token. |
| `.orgId(int)` | `int` | none | Organisation to bill usage against (required for token auth). |

`KugelAudio.fromEnv()` builds a client from the `KUGELAUDIO_API_KEY` environment
variable and throws a `ValidationException` when it is not set.

</Tab>
<Tab title="Rust">

| Builder method | Type | Default | Description |
|---|---|---|---|
| `KugelAudio::builder(api_key)` | `impl Into<String>` | required | Your API key. A `eu-`, `us-`, or `global-` prefix selects the region; the SDK strips it before authenticating. `KugelAudio::new(api_key)` builds a client with every default. |
| `.api_url(...)` | `impl Into<String>` | `https://api.kugelaudio.com` | API base URL. For self-hosted deployments, see [On-Premise Deployment](/guides/self-hosted). |
| `.tts_url(...)` | `impl Into<String>` | same as `api_url` | TTS server URL for WebSocket streaming. |
| `.region(Region)` | `Region` | none | `Region::Eu`, `Region::Us`, or `Region::Global`. `Region::Eu` selects the direct EU endpoint; the other values use the default geo-routed endpoint. |
| `.timeout(Duration)` | `Duration` | 60 s | HTTP request timeout and WebSocket opening timeout. |
| `.keepalive_ping_interval(Option<Duration>)` | `Option<Duration>` | 20 s | WebSocket ping interval of the pooled connection. `None` disables it. |
| `.telemetry(bool)` | `bool` | on for the hosted API | [SDK diagnostics](/sdks/telemetry). |
| `.build()` | | | Returns `kugelaudio::Result<KugelAudio>`; a missing key is an `Error::Validation`. |

`KugelAudio` is cheap to clone and safe to share between tasks; clones share one
connection pool.

</Tab>
<Tab title="C++">

| `ClientOptions` field | Type | Default | Description |
|---|---|---|---|
| `api_key` | `std::string` | required | Your API key. A `eu-`, `us-`, or `global-` prefix selects the region; the SDK strips it before authenticating. `Client{api_key}` builds a client with every default. |
| `api_url` | `std::optional<std::string>` | `https://api.kugelaudio.com` | API base URL. For self-hosted deployments, see [On-Premise Deployment](/guides/self-hosted). |
| `tts_url` | `std::optional<std::string>` | same as `api_url` | TTS server URL for WebSocket streaming. |
| `region` | `std::optional<Region>` | none | `Region::EU`, `Region::US`, or `Region::Global`. `Region::EU` selects the direct EU endpoint. |
| `timeout` | `std::chrono::milliseconds` | 60 s | HTTP request timeout, WebSocket handshake timeout, and the longest wait for the next frame of a one-shot stream. |
| `keepalive_ping_interval` | `std::optional<std::chrono::seconds>` | 20 s | WebSocket ping interval of the pooled connection. `std::nullopt` disables it. |
| `telemetry` | `std::optional<bool>` | on for the hosted API | [SDK diagnostics](/sdks/telemetry). |
| `log_handler` | `LogHandler` | writes warnings to `std::cerr` | Receives SDK log messages with their `LogLevel`. |

A `Client` and its resources are thread-safe; share one client.

</Tab>
<Tab title="Dart">

| Parameter | Type | Default | Description |
|---|---|---|---|
| `apiKey` | `String` | required | Your API key. A `eu-`, `us-`, or `global-` prefix selects the region; the SDK strips it before authenticating. |
| `apiUrl` | `String?` | `https://api.kugelaudio.com` | API base URL. For self-hosted deployments, see [On-Premise Deployment](/guides/self-hosted). |
| `ttsUrl` | `String?` | same as `apiUrl` | TTS server URL for WebSocket streaming. |
| `region` | `Region?` | `null` | `Region.eu`, `Region.us`, or `Region.global`. `Region.eu` selects the direct EU endpoint. |
| `timeout` | `Duration` | 60 s | HTTP request timeout and WebSocket opening timeout. |
| `keepalivePingInterval` | `Duration?` | 20 s | WebSocket ping interval of long-lived sockets; `null` disables it. Not used in the browser, which sends its own pings. |
| `telemetry` | `bool?` | on for the hosted API | [SDK diagnostics](/sdks/telemetry). |
| `httpClient` | `http.Client?` | a new `http.Client` | Replaces the HTTP client; `close()` closes it. |
| `webSocketConnector` | `WebSocketConnector?` | the platform's | Replaces how WebSockets are opened. |

</Tab>
</Tabs>

When several are set, the API URL wins over the region, and the region wins over an
API-key prefix.

## Authentication modes

Most integrations pass a project-scoped API key. For user-token scenarios, set the
matching flag and bill usage to an organisation. For browser WebSockets, use a
short-lived user JWT from your authentication flow with `isToken: true`. The
JavaScript SDK still accepts API keys for legacy browser WebSockets and warns
once when that deprecated authentication is used.

<CodeGroup>

```python Python
# Not available in the Python SDK: it authenticates with API keys only.
```

```typescript TypeScript
// JWT user token: bill usage to an organisation
const user = new KugelAudio({ apiKey: jwt, isToken: true, orgId: 1253 });
```

```java Java
// JWT user token: bill usage to an organisation
KugelAudio user = new KugelAudio(
    KugelAudioOptions.builder(jwt).token().orgId(1253).build()
);
```

```rust Rust
// Not available in the Rust SDK: it authenticates with API keys only.
```

```cpp C++
// Not available in the C++ SDK: it authenticates with API keys only.
```

```dart Dart
// Not available in the Dart SDK: it authenticates with API keys only.
```

</CodeGroup>

In TypeScript the active mode is readable from getters: `client.isToken`,
`client.orgId`, plus `client.apiKey`, `client.ttsUrl`, and
`client.keepalivePingInterval`. In Java the resolved mode is available via
`options.getAuthMode()` (`AuthMode.API_KEY` or `AuthMode.TOKEN`).

## Client lifecycle

<CodeGroup>

```python Python
client = await KugelAudio.create(api_key="your_api_key")
print(client.is_connected())      # True once the pooled async socket is open
await client.aclose()             # Release HTTP + WebSocket resources

# KugelAudio is also a context manager, so resources are released automatically
with KugelAudio(api_key="your_api_key") as client:
    audio = client.tts.generate(text="Hello!", model_id="kugel-3.5", voice_id=1071)
    audio.save("output.wav")
```

```typescript TypeScript
await client.connect();            // Pre-open the WebSocket
console.log(client.isConnected()); // true once open
client.close();                    // Release the WebSocket + pending pings
```

```java Java
// KugelAudio is AutoCloseable, so try-with-resources releases it automatically
try (KugelAudio client = KugelAudio.fromEnv()) {
    client.connect();                          // Block until the WebSocket is open
    System.out.println(client.isConnected());  // true once open
    // ... generate, stream ...
}                                              // close(): releases HTTP + WebSocket resources
```

```rust Rust
let client = KugelAudio::new("your_api_key")?;
client.tts().connect(None).await?;           // Pre-open the WebSocket (None: kugel-3.5)
println!("{}", client.tts().is_connected()); // true once open
client.close().await;                        // Release the WebSocket + deliver pending reports
```

```cpp C++
{
  kugelaudio::Client client{"your_api_key"};
  client.connect();                           // Block until the WebSocket is open
  std::cout << client.is_connected() << '\n'; // 1 once open
  // ... generate, stream ...
}  // The destructor calls close(): releases the WebSocket + delivers pending reports
```

```dart Dart
final client = await KugelAudio.create(apiKey: 'your_api_key'); // Pre-opens the WebSocket
print(client.tts.isConnected);  // true once open
await client.close();           // Release HTTP + WebSocket resources + pending reports
```

</CodeGroup>

<Tabs>
<Tab title="Python">

`KugelAudio.create()` accepts the same options as the constructor plus
`model` (default `"kugel-3.5"`), the model the pooled socket is opened for.

The async pre-connection methods are also exposed on the TTS resource as
`client.tts.connect_async()` and `client.tts.is_connected()`. The synchronous
`connect()` method exists, but synchronous `generate()` and `stream()` run on
their own event-loop thread and do not reuse that socket. Use
`streaming_session_sync()` when a synchronous application needs a persistent
streaming connection.

`stream_async()` reuses the pooled socket by default. Pass
`reuse_connection=False` to open a fresh connection for that call.

</Tab>
<Tab title="TypeScript">

In Node.js, the pooled WebSocket and its keepalive timer keep the process
alive until you call `client.close()`.

</Tab>
<Tab title="Java">

The constructor starts the WebSocket connection in the background unless
`.autoConnect(false)` is set; `KugelAudio.createConnected(options)` waits for it.
See [Pre-connecting for low latency](/sdks/quickstart#pre-connecting-for-low-latency).

</Tab>
<Tab title="Rust">

`client.tts().connect(Some("kugel-3"))` opens the pooled socket for another model.
Call `client.close().await` before your program exits: it closes the pooled socket
and delivers pending diagnostics, waiting at most one second. Sessions are closed by
their own `close()`.

</Tab>
<Tab title="C++">

`client.connect(model_id)` opens the pooled socket for another model (default
`"kugel-3.5"`). `close()` is idempotent; the destructor calls it. Sessions keep the
client's internals alive, so a session may outlive the `Client` that created it.

</Tab>
<Tab title="Dart">

`KugelAudio.create()` accepts the same arguments as the constructor plus `modelId`
(default `"kugel-3.5"`), the model the pooled socket is opened for. On an existing
client, `client.tts.connect()` does the same. Sessions are closed by their own
`close()`.

</Tab>
</Tabs>

## Region selection

Pin traffic to the direct EU endpoint when needed. See the [EU endpoint guide](/guides/regions) for details.

<CodeGroup>

```python Python
# Option 1: prefix your API key
client = KugelAudio(api_key="eu-ka_your_api_key")

# Option 2: explicit region parameter
client = KugelAudio(api_key="ka_your_api_key", region="eu")
```

```typescript TypeScript
// Option 1: prefix your API key
const client = new KugelAudio({ apiKey: 'eu-ka_your_api_key' });

// Option 2: explicit region parameter
const explicitEuClient = new KugelAudio({ apiKey: 'ka_your_api_key', region: 'eu' });
```

```java Java
// Option 1: prefix your API key (the prefix is stripped before authentication)
KugelAudio client = new KugelAudio(
    KugelAudioOptions.builder("eu-ka_your_api_key").build()
);

// Option 2: explicit region
KugelAudio explicitEuClient = new KugelAudio(
    KugelAudioOptions.builder("ka_your_api_key")
        .region(Region.EU)
        .build()
);
```

```rust Rust
// Option 1: prefix your API key (the prefix is stripped before authentication)
let client = KugelAudio::new("eu-ka_your_api_key")?;

// Option 2: explicit region
let explicit_eu_client = KugelAudio::builder("ka_your_api_key")
    .region(Region::Eu)
    .build()?;
```

```cpp C++
// Option 1: prefix your API key (the prefix is stripped before authentication)
kugelaudio::Client client{"eu-ka_your_api_key"};

// Option 2: explicit region
kugelaudio::ClientOptions options;
options.api_key = "ka_your_api_key";
options.region = kugelaudio::Region::EU;
kugelaudio::Client explicit_eu_client{options};
```

```dart Dart
// Option 1: prefix your API key (the prefix is stripped before authentication)
final client = KugelAudio(apiKey: 'eu-ka_your_api_key');

// Option 2: explicit region
final explicitEuClient = KugelAudio(apiKey: 'ka_your_api_key', region: Region.eu);
```

</CodeGroup>

The key prefix is an SDK convenience: the SDK removes it and routes to the EU
host. Raw HTTP or WebSocket clients call `https://api.eu.kugelaudio.com` with
the key without the prefix.

## Diagnostics

The SDKs report their own connection and streaming failures back to KugelAudio so
we can see problems that never reach our servers. They never send your text,
audio or credentials. See [SDK Diagnostics](/sdks/telemetry) for the full field
list and the opt-out.

## Next steps

- [Generate speech](/sdks/generate): one-shot generation and parameters
- [Streaming](/sdks/streaming): streaming sessions and barge-in
