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

# Unity API Reference

> Every public type, field, property, event and method of the Lokutor package for Unity 0.2.0: LokutorAgent, LokutorLipSync, LokutorVoice, VoiceAgentClient, TTSClient, STTClient, SpeechToTextClient, LokutorSession and their helpers.

Version 0.2.0, Unity 2021.3 or newer, namespace `Lokutor`. Install it as in
[Unity: introduction](https://docs.lokutor.com/sdks/unity/introduction.md). The names match the [JavaScript](https://docs.lokutor.com/sdks/javascript/reference.md) and
[Python](https://docs.lokutor.com/sdks/python/reference.md) SDKs; the [parity table](https://docs.lokutor.com/guides/game-engines.md#the-same-sdk-everywhere) puts the four
side by side.

The components (`LokutorAgent`, `LokutorLipSync`, `LokutorVoice`, `LokutorAudioManager`) raise their events on the main
thread. Everything else is plain C# without `UnityEngine`, and raises its events when you call `Update()`.

| | Types |
| :- | :- |
| **Components** | [`LokutorAgent`](#lokutoragent), [`LokutorLipSync`](#lokutorlipsync), [`LokutorVoice`](#lokutorvoice), [`LokutorAudioManager`](#lokutoraudiomanager) |
| **Actions** | [`AgentAction`](#agentaction), [`ActionParam`](#actionparam), [`ParamType`](#paramtype), [`ActionArgs`](#actionargs), [`LokutorActionBinding`](#lokutoractionbinding) |
| **Conversations** | [`VoiceAgentClient`](#voiceagentclient), [`ToolDefinition`](#tooldefinition), [`ToolCall`](#toolcall), [`TranscriptLine`](#transcriptline), [`CustomLLMConfig`](#customllmconfig), [`LlmRequest`](#llmrequest), [`LlmReply`](#llmreply), [`IAudioManager`](#iaudiomanager), [`LokutorSession`](#lokutorsession), [`SessionOptions`](#sessionoptions), [`AgentState`](#agentstate), [`MicMode`](#micmode) |
| **Speech** | [`TTSClient`](#ttsclient), [`SynthesizeOptions`](#synthesizeoptions), [`TTSResult`](#ttsresult), [`STTClient`](#sttclient), [`TranscribeOptions`](#transcribeoptions), [`TranscribeResult`](#transcriberesult), [`TranscribeSegment`](#transcribesegment), [`SpeechToTextClient`](#speechtotextclient), [`VoiceLines`](#voicelines), [`VoiceLine`](#voiceline), [`SayOptions`](#sayoptions) |
| **Lip sync** | [`Viseme`](#viseme), [`LipSync`](#lipsync), [`MouthRig`](#mouthrig), [`Shape`](#mouthrig), [`MouthRigKind`](#mouthrigkind), [`LokutorVisemeShape`](#lokutorvisemeshape), [`LokutorVisemeSprite`](#lokutorvisemesprite), [`MouthShape`](#mouthshape), [`VisemeMark`](#visememark) |
| **Audio** | [`LokutorMicrophone`](#lokutormicrophone), [`LokutorVoicePlayer`](#lokutorvoiceplayer), [`PlaybackBuffer`](#playbackbuffer), [`LokutorAudio`](#lokutoraudio), [`StreamResampler`](#streamresampler), [`StreamingResampler`](#streamingresampler), [`Pcm16`](#pcm16) |
| **API and errors** | [`LokutorApi`](#lokutorapi), [`VoiceInfo`](#voiceinfo), [`LanguageInfo`](#languageinfo), [`ModelInfo`](#modelinfo), [`ServerConfig`](#serverconfig), [`HealthStatus`](#healthstatus), [`LokutorError`](#lokutorerror), [`LokutorException`](#lokutorexception), [`EventPump`](#eventpump), [`MiniJson`](#minijson), [`LokutorTextEvent`](#lokutortextevent), [`LokutorStateEvent`](#lokutorstateevent) |

## Components

### `LokutorAgent`

`class LokutorAgent : MonoBehaviour`

A component (**Lokutor > Lokutor Agent**, needs an AudioSource). Makes a character a voice agent: it listens through the microphone, answers in its own voice from where it stands (3D audio), moves its mouth, and calls your game's functions ("actions") when the conversation calls for it.

**Account** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `apiKey` | `string` | `""` | Your Lokutor API key (dashboard > API keys). Fine while prototyping; a shipped game should use `TicketProvider` so the key stays on your server. Empty: `LokutorAgent.DefaultApiKey`, then the `LOKUTOR_API_KEY` environment variable. |
| `agentId` | `string` | `""` | Optional: the id of an agent built in the Lokutor dashboard. Its persona, voice and language are used unless set below. |

**Character** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `persona` | `string` | `"You are a friendly villager in a fantasy town. Answer in one or two short sentences."` | Who the character is, what it knows and how it talks. |
| `contextHeading` | `string` | `"Right now in the game:"` | The line above what `SetContext` tells the character. Write it in the language of the persona. |
| `voice` | `string` | `"F1"` | F1-F5 (female) or M1-M5 (male), or a voice id from the Lokutor dashboard. |
| `language` | `string` | `"en"` | en, es, fr, pt, ca, gl, eu... or auto: the character follows the language the player speaks. |
| `pitch` | `float` | — | Shifts the voice up or down: small creatures, giants. -12 to 12. |
| `startOnAwake` | `bool` | `true` | Start talking as soon as the scene starts. Off: call `StartConversation()` (e.g. when the player walks up). |
| `spatialVoice` | `bool` | `true` | The voice comes from the character's position (3D). Off: heard the same everywhere (2D). |
| `autoReconnect` | `bool` | `true` | Open the connection again when it drops. The character does not remember what came before. |

**Microphone** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `micMode` | `MicMode` | `MicMode.Always` | `Always`: the microphone is open and the server detects turns. `PushToTalk`: heard only while the key is held. `Off`: no microphone; the character hears only `FeedMicrophone()`. |
| `pushToTalkKey` | `KeyCode` | `KeyCode.T` | Held to talk in PushToTalk mode (old Input Manager). With the new Input System use `pushToTalkAction` or call `SetTalking()`. |
| `pushToTalkAction` | `UnityEngine.InputSystem.InputActionReference` | — | Held to talk in PushToTalk mode. Only with the Input System package. |
| `microphoneDevice` | `string` | `""` | Empty: the default microphone. |
| `muteMicWhileSpeaking` | `bool` | `true` | Mutes the microphone while the character talks, so speakers can't make it interrupt itself, and while any other `LokutorAgent` or `LokutorVoice` does, so that it does not answer them. Turn off when players use headphones and should be able to interrupt. |
| `actionFiller` | `bool` | `false` | The server has the character say "One moment" or the like while an action runs, or what the model wrote before it. Off: it says nothing until its answer. |
| `speakBeforeActions` | `bool` | `true` | What it begins to say before it calls an action is heard. Turn it off with an action that it must call before it answers ("how funny that was"): the model can write its plan there. |

**Lip sync (optional)** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `lipSync` | `LokutorLipSync` | — | Empty: the Lokutor Lip Sync on this object, under it or above it; without one, a new one, which finds by itself the faces whose mouth it knows, or uses the fields below. |
| `face` | `SkinnedMeshRenderer` | — | A face mesh, when it is not under this object. |
| `mouthBlendShape` | `string` | `""` | Its mouth-open blend shape, when its names are not recognised. |
| `jaw` | `Transform` | — | Or a jaw bone, rotated around its local X axis. |
| `jawMaxAngle` | `float` | `12f` | How far the jaw turns at its widest, in degrees. |
| `mouthGain` | `float` | `1.5f` | Loudness multiplier of a mouth without visemes. 0.2 to 5. |

**Game actions the character can use** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `actions` | `List<LokutorActionBinding>` | `new List<LokutorActionBinding>()` | Actions the character can use, wired to methods in the Inspector. |

**Events** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `onPlayerSaid` | `LokutorTextEvent` | `new LokutorTextEvent()` | What the player said, once the turn is over. |
| `onCharacterSaid` | `LokutorTextEvent` | `new LokutorTextEvent()` | What the character is about to say. `LokutorApi.StripTags(text)` takes out `[laugh]` and the like for subtitles. |
| `onCharacterInterrupted` | `LokutorTextEvent` | `new LokutorTextEvent()` | The player cut the character off: what they heard. |
| `onStateChanged` | `LokutorStateEvent` | `new LokutorStateEvent()` | The conversation moved to another [`AgentState`](#agentstate). |
| `onConversationEnded` | `LokutorTextEvent` | `new LokutorTextEvent()` | The conversation is over: why. |
| `onReconnecting` | `UnityEvent` | `new UnityEvent()` | The connection dropped and is being opened again. |
| `onReconnected` | `UnityEvent` | `new UnityEvent()` | It is open again, in a fresh conversation. |

**From code**

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `DefaultApiKey` | `string` | — | Used by every agent whose apiKey field is empty. Set it once from code if you prefer. Static. |
| `TicketProvider` | `Func<Task<string>>` | — | For a shipped game: returns a short-lived ticket from **your** server, which calls `POST https://api.lokutor.com/ws-ticket` with the API key. Set before `StartConversation()`; called on the main thread, before every connection. |
| `Llm` | `CustomLLMConfig` | — | Your own OpenAI-compatible language model. Set before `StartConversation()`. |
| `OnLlmRequest` | `Func<LlmRequest, LlmReply, Task<string>>` | — | Your own language model, running in the game: return the reply, or write it with `reply.Chunk`. Set before `StartConversation()`. |
| `url` | `string` | `LokutorApi.VoiceAgentUrl` | The voice agent endpoint. Change it for a local server or a proxy. |
| `Session` | `LokutorSession` | — | The session underneath (events, raw audio). Null until `StartConversation()`. Read only. |
| `Player` | `LokutorVoicePlayer` | — | The voice's player. Read only. |
| `Mic` | `LokutorMicrophone` | — | The microphone. Read only. |
| `Muted` | `bool` | — | The player has muted their microphone. |
| `State` | `AgentState` | — | What the conversation is doing now. Read only. |
| `MouthOpen` | `float` | — | How open the mouth should be right now, 0 to 1 (already follows the audio you hear). Read only. |
| `HeardSeconds` | `float` | — | How much of the current reply has been heard, in seconds: the clock viseme times are read against. Read only. |
| `VoiceLevel` | `float` | — | Loudness of the character's voice right now (RMS). Read only. |
| `IsSpeaking` | `bool` | — | The character's voice is being heard. Read only. |

**Events**

| Event | Raised when |
| :- | :- |
| `Action<string> PlayerSaidPartial` | The player's words while they are still talking. |
| `Action<string, ActionArgs, string> ActionCalled` | An action ran: name, arguments, result. |
| `Action<IReadOnlyList<Viseme>> VisemesReceived` | Mouth shapes of the reply, as they arrive. |
| `Action<float[], int> VoicePlayed` | The voice as it is given to the AudioSource (samples, rate): for a character that another character listens to. The array is reused. |
| `Action<int> SessionLimit` | The server announced how many seconds this session may still run. |
| `Action<LokutorError> Error` | Something failed, as a [`LokutorError`](#lokutorerror). |

#### `LokutorAgent AddAction(string name, string description, Func<ActionArgs, string> handler, params ActionParam[] parameters)`

Lets the character call a game function. Works before or during a conversation. The handler runs on the main thread and returns a short sentence saying what happened.

#### `LokutorAgent AddActionAsync(string name, string description, Func<ActionArgs, Task<string>> handler, params ActionParam[] parameters)`

An action that takes a while (a walk, a web request): the character waits for the result.

#### `LokutorAgent AddAction(AgentAction action)`

The same, from an [`AgentAction`](#agentaction).

#### `void RemoveAction(string name)`

The character can no longer call it.

#### `void StartConversation()`

Opens the conversation: the character greets the player and starts listening.

#### `void StopConversation()`

Ends the conversation and releases the microphone.

#### `void SetPersona(string newPersona)`

Changes who the character is, mid-conversation.

#### `void SetContext(string key, string value)`

Tells the character something about the game right now (`"Time left"`, `"20 seconds"`), without rewriting its persona. Null takes it out. Changes in the same quarter second are sent together. A dashboard agent needs a `persona` for this: its own prompt cannot be extended from the game.

#### `void SetVoice(string newVoice)`

Changes the voice, mid-conversation.

#### `void SetLanguage(string newLanguage)`

Changes the language, mid-conversation. `"auto"`: the character follows the language the player speaks.

#### `void SetPitch(float newPitch)`

Shifts the voice up or down, mid-conversation.

#### `void ResetConversation()`

Forgets the conversation so far (the character starts fresh).

#### `List<TranscriptLine> GetTranscript()`

The conversation so far, or the last one.

#### `void SetTalking(bool talking)`

Push-to-talk from any input: true while the player holds the button.

#### `void FeedMicrophone(float[] samples, int offset, int count, int sampleRate)`

What the character hears, when it does not come from the microphone (`MicMode.Off`): mono samples at any rate.

### `LokutorLipSync`

`class LokutorLipSync : MonoBehaviour`

A component (**Lokutor > Lokutor Lip Sync**). Moves a mouth with a voice: blend shapes, a jaw, or 2D drawings. LokutorAgent and LokutorVoice feed it; or feed it yourself with `PushVisemes` and `Advance`. See [Lip sync](https://docs.lokutor.com/sdks/unity/lip-sync.md).

**Blend shapes** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `faces` | `List<SkinnedMeshRenderer>` | `new List<SkinnedMeshRenderer>()` | The meshes whose mouth moves: usually the face, plus teeth or tongue if they have the shapes too. Empty: every mesh under this object whose mouth is recognised. |
| `mapping` | `List<LokutorVisemeShape>` | `new List<LokutorVisemeShape>()` | Your rig, when its names are not recognised (Oculus, Ready Player Me and VRChat visemes, VRM and VRoid, ARKit, or a mouth-open shape). |

**Jaw** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `jaw` | `Transform` | — | A jaw bone (or head part), rotated around its local X axis. |
| `jawMaxAngle` | `float` | `12f` | How far the jaw turns at its widest, in degrees. |

**2D** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `mouthSprite` | `SpriteRenderer` | — | A sprite whose drawing changes with the mouth. |
| `mouthSprites` | `Sprite[]` | `new Sprite[0]` | 0 closed, 1 slightly open, 2 open, 3 round (if there are that many). |
| `visemeSprites` | `List<LokutorVisemeSprite>` | `new List<LokutorVisemeSprite>()` | Or a drawing for each viseme; the ones missing use sil's. |

**Feel** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `intensity` | `float` | `1f` | How far the mouth opens. |
| `lead` | `float` | `0.05f` | Seconds the mouth leads the sound: people open before they speak. |
| `blend` | `float` | `0.07f` | Seconds over which one shape melts into the next. 0.05 is crisp and cartoonish, 0.12 soft. |
| `loudness` | `float` | `0.35f` | How much quiet speech closes the mouth. |
| `steppedFps` | `float` | — | Steps per second of the mouth, for a hand-drawn look (12 = animation on twos). 0 = smooth. |
| `gain` | `float` | `1.5f` | Loudness multiplier for mouths that follow the loudness (no visemes). |

**Events** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `onVisemeChanged` | `LokutorTextEvent` | `new LokutorTextEvent()` | The mouth changed shape: its name. |

**From code**

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Core` | `LipSync` | — | The mouth's timeline, without the engine. Read only. |
| `Weights` | `float[]` | — | Weight of each of the 15 visemes right now, in `LokutorApi.Visemes` order. Read only. |
| `Current` | `string` | — | The strongest one. Read only. |
| `MouthOpen` | `float` | — | How open the mouth is, 0 to 1. Read only. |
| `HasVisemes` | `bool` | — | Whether the voice being heard has visemes. Without them the mouth follows the loudness. Read only. |
| `Rig` | `MouthRigKind` | — | Which kind of mouth was found. Read only. |

#### `void Bind()`

Finds the mouth. Done by itself the first time; call it after changing faces or mapping.

#### `void PushVisemes(IEnumerable<Viseme> list)`

The visemes of the reply being heard, as they arrive.

#### `void Clear()`

A new reply, or silence: the mouth closes.

#### `void Advance(float heard, float level, bool speaking, float delta)`

One frame of the mouth. `heard` is how much of the reply has been heard, in seconds; `level` its loudness (RMS); `speaking` whether it is playing at all. Called for you by LokutorAgent and LokutorVoice.

#### `void Apply()`

Puts the mouth's shape on the face. Done by itself every frame.

#### `Sprite MouthSprite()`

The drawing of the mouth's shape, for a UI Image or a material of yours. Null when there are none.

### `LokutorVoice`

`class LokutorVoice : MonoBehaviour`

A component (**Lokutor > Lokutor Voice**, needs an AudioSource). Says written lines (barks, narration, tutorials) in a character's voice, from its place in the world, moving its mouth. Lines are kept on disk, so each is made once; they can also ship with the game and need no network at all. See [Speech](https://docs.lokutor.com/sdks/unity/speech.md).

**In the Inspector**

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `apiKey` | `string` | `""` | Your Lokutor API key. Empty: `LokutorAgent.DefaultApiKey`, then the `LOKUTOR_API_KEY` environment variable. A shipped game should ship its lines, or use `TicketProvider`. |
| `voice` | `string` | `"F1"` | F1-F5 (female) or M1-M5 (male), or a voice id from the Lokutor dashboard. |
| `language` | `string` | `"en"` | The language of its lines. |
| `spatialVoice` | `bool` | `true` | The voice comes from the character's position (3D). Off: heard the same everywhere (2D). |
| `mutesMicrophones` | `bool` | `true` | Agents do not listen while this voice is heard (see `muteMicWhileSpeaking`). Off for a voice too far away to reach the player's microphone. |
| `keepLines` | `bool` | `true` | Keep lines on disk (`persistentDataPath/lokutor_voices`), so each is made only once. |
| `shippedLines` | `string` | `"LokutorVoices"` | The folder, inside a Resources folder, of the lines that ship with the game (see `SaveLinesTo`). |
| `lipSync` | `LokutorLipSync` | — | Empty: the Lokutor Lip Sync on this object, under it or above it, or a new one that finds the mouth by itself. |

**Events** (in the Inspector)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `onLineStarted` | `LokutorTextEvent` | `new LokutorTextEvent()` | A line is being heard. |
| `onLineFinished` | `LokutorTextEvent` | `new LokutorTextEvent()` | It has been heard to the end, or was stopped. |

**From code**

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `TicketProvider` | `Func<Task<string>>` | — | For a shipped game: returns a short-lived ticket from **your** server. |
| `url` | `string` | `LokutorApi.TTSUrl` | The text-to-speech endpoint. |
| `Lines` | `VoiceLines` | — | The queue of lines, without the engine. Read only. |
| `Player` | `LokutorVoicePlayer` | — | The voice's player. Read only. |
| `IsSpeaking` | `bool` | — | A line is being said. Read only. |
| `MouthOpen` | `float` | — | How open the mouth is, 0 to 1. Read only. |
| `HeardSeconds` | `float` | — | How much of the line has been heard, in seconds. Read only. |

**Events**

| Event | Raised when |
| :- | :- |
| `Action<LokutorError> Error` | A line could not be made, as a [`LokutorError`](#lokutorerror). |

#### `Task<bool> Say(string text, SayOptions options = null)`

Says a line; awaited, returns when it has been heard (`true`) or could not be said (`false`). Lines wait for each other, unless `options.Interrupt`.

#### `void SayLine(string text)`

The same for a UnityEvent or a coroutine's fire and forget.

#### `IEnumerator SayAndWait(string text, SayOptions options = null)`

For coroutines: `yield return voice.SayAndWait("...");`

#### `void Stop()`

Stops at once and forgets the lines waiting.

#### `Task PreloadLines(IEnumerable<string> texts, SayOptions options = null)`

Makes lines before they are needed, so they start at once.

#### `bool HasLine(string text, SayOptions options = null)`

Whether a line is on disk or ships with the game.

#### `Task SaveLinesTo(string folder, IEnumerable<string> texts, SayOptions options = null)`

Writes lines into a folder of the project, so they ship with the game and need no network or key: in the editor, `SaveLinesTo("Assets/Resources/LokutorVoices", lines)`.

### `LokutorAudioManager`

`class LokutorAudioManager : MonoBehaviour, IAudioManager`

A component (**Lokutor > Lokutor Audio Manager**, needs an AudioSource): Unity's microphone and speakers for the clients of the SDK. A whole conversation with VoiceAgentClient, or dictation with SpeechToTextClient, without a LokutorAgent.

**In the Inspector**

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `microphoneDevice` | `string` | `""` | Empty: the default microphone. |

**From code**

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Playback` | `PlaybackBuffer` | — | The voice waiting to be played. Read only. |
| `Mic` | `LokutorMicrophone` | — | The microphone. Read only. |
| `Muted` | `bool` | — | The microphone is muted. |

#### `Task<bool> StartManaged(VoiceAgentClient voiceAgent)`

Connects the client with this microphone and speaker, and raises its events on the main thread.

#### `Task<bool> StartManaged(SpeechToTextClient speechToText)`

Connects the client with this microphone, and raises its events on the main thread.

#### `bool StartMicrophone(Action<float[], int, int> handler)`

As [`IAudioManager`](#iaudiomanager).

#### `void StopMicrophone()`

As `IAudioManager`.

#### `void PlayAudio(byte[] pcm16, int sampleRate)`

As `IAudioManager`.

#### `void StopPlayback()`

As `IAudioManager`.

#### `float GetAmplitude()`

The microphone's loudness, 0 to 1.

## Actions

### `AgentAction`

`class AgentAction`

A game function the character can decide to call: open a door, give an item, start a quest. The handler returns a short sentence that tells the character what happened ("Gave the iron sword. The player now has 5 gold."), which it uses to answer. See [Actions](https://docs.lokutor.com/sdks/unity/actions.md).

```csharp theme={null}
new AgentAction(string name, string description, Func<ActionArgs, string> handler, params ActionParam[] parameters)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Name` | `string` | — | What the character calls it. Read only. |
| `Description` | `string` | — | When to use it. Read only. |
| `Parameters` | `IReadOnlyList<ActionParam>` | — | Its arguments. Read only. |

#### `static AgentAction Async(string name, string description, Func<ActionArgs, Task<string>> handler, params ActionParam[] parameters)`

An action that takes a while: the character waits for the result.

#### `ToolDefinition ToTool()`

The definition the language model sees.

### `ActionParam`

`class ActionParam`

One argument an action takes, e.g. `new ActionParam("item", "Which item to give")`.

```csharp theme={null}
new ActionParam(string name, string description, ParamType type = ParamType.String, bool required = true, params string[] choices)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Name` | `string` | — | The argument's name. Read only. |
| `Description` | `string` | — | What it is, in plain words. Read only. |
| `Type` | `ParamType` | — | Its type. Read only. |
| `Required` | `bool` | — | Whether the character must give it. Read only. |
| `Choices` | `string[]` | — | If set, the model may only pick one of these values. Read only. |

### `ParamType`

The type of one action parameter, as the language model sees it. Values: `String`, `Number`, `Integer`, `Boolean`.

### `ActionArgs`

`class ActionArgs`

The arguments the character chose when it called an action.

```csharp theme={null}
new ActionArgs(string json)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Json` | `string` | — | All of them, as a JSON object. Read only. |

#### `bool Has(string name)`

Whether the character gave this argument.

#### `string GetString(string name, string fallback = "")`

An argument as text.

#### `double GetNumber(string name, double fallback = 0)`

An argument as a number.

#### `int GetInt(string name, int fallback = 0)`

An argument as a whole number.

#### `bool GetBool(string name, bool fallback = false)`

An argument as true or false.

### `LokutorActionBinding`

`class LokutorActionBinding`

A game action set up in the Inspector: the character calls it, onCalled runs.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `name` | `string` | `"open_gate"` | What the character calls it, e.g. open\_gate. Letters, digits and \_ only. |
| `description` | `string` | `"Opens the town gate for the player."` | When the character should use it, in plain words. |
| `reply` | `string` | `"The gate is now open."` | What the character is told happened, so it can say so. |
| `onCalled` | `UnityEvent` | `new UnityEvent()` | What happens in the game. |

## Conversations

### `VoiceAgentClient`

`class VoiceAgentClient : EventPump, IDisposable`

A voice conversation over `/ws/agent`, with the same options, methods and events as `VoiceAgentClient` in the JavaScript and Python SDKs. It does not need Unity. Call its `Update()` every frame: that is when its events are raised.

For a character in a scene use LokutorAgent, which adds the microphone, the 3D voice, lip sync and actions on top of this.

```csharp theme={null}
new VoiceAgentClient()
new VoiceAgentClient(string apiKey, string prompt = null, string voice = null, string language = null)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `ApiKey` | `string` | — | An API key, or a `wst_` ticket. Fine while prototyping; a shipped game should set `Auth`. |
| `Auth` | `Func<Task<string>>` | — | Called before every connect and reconnect for the credential to use: have it ask your server for a ticket (`POST https://api.lokutor.com/ws-ticket`). |
| `AgentId` | `string` | — | An agent from the dashboard. Then voice, language and prompt are sent only if you set them. |
| `ServerUrl` | `string` | `LokutorApi.VoiceAgentUrl` | The voice agent endpoint. |
| `Prompt` | `string` | — | The system prompt. |
| `Voice` | `string` | — | Null: `F1`, or the dashboard agent's. |
| `Language` | `string` | — | `"auto"` or `""`: the agent follows the player's language. Null: `en`, or the dashboard agent's. |
| `Pitch` | `float` | — | Shifts the voice up or down. |
| `Tools` | `List<ToolDefinition>` | `new List<ToolDefinition>()` | Functions the agent may call. |
| `WantVisemes` | `bool` | — | Ask for mouth shapes. |
| `Llm` | `CustomLLMConfig` | — | Your own OpenAI-compatible endpoint. |
| `OnLlmRequest` | `Func<LlmRequest, LlmReply, Task<string>>` | — | Your model runs in the game: return the reply, or write it with `reply.Chunk(text)` as it is produced and return null. |
| `LlmTools` | `string` | `"auto"` | `"none"`: the agent's tools are not sent to `OnLlmRequest`. |
| `AutoReconnect` | `bool` | `true` | Open the connection again when it drops (2 s, 4 s, 8 s, 10 s, 10 s). |
| `MaxReconnectAttempts` | `int` | `5` | Attempts before giving up. |
| `ConnectTimeout` | `TimeSpan` | `TimeSpan.FromSeconds(15)` | How long to wait for the connection. |
| `UserAgent` | `string` | `"lokutor-csharp/" + LokutorApi.Version` | Sent when connecting. |
| `Generation` | `int` | — | The reply being spoken. Grows by one with each reply of a session. Read only. |
| `SessionId` | `string` | — | The server's id of this session. Read only. |
| `PlaybackRate` | `int` | — | Rate of the agent's audio, announced by the server. Read only. |
| `InputRate` | `int` | — | Rate the server expects of the microphone. Read only. |
| `Connected` | `bool` | — | The session is open. Read only. |
| `LastError` | `LokutorError` | — | Why the last connection failed. Read only. |

**Events**

| Event | Raised when |
| :- | :- |
| `Action<string> Transcription` | A final line of player speech. |
| `Action<string> TranscriptionPartial` | The player's words while they are still talking. Not kept in `GetTranscript()`. |
| `Action<string> Response` | What the agent is about to say. |
| `Action<byte[], int> Audio` | The agent's voice (16-bit PCM, mono, at PlaybackRate) and its generation. Audio of superseded replies never gets here. |
| `Action<IReadOnlyList<Viseme>, int> Visemes` | Mouth shapes of the reply, and its generation. |
| `Action<string> Status` | `connected`, `listening`, `thinking`, `speaking`, `interrupted`, acknowledgements, and the client's own `reconnecting` and `disconnected`. |
| `Action<LokutorError> Error` | Something failed, as a [`LokutorError`](#lokutorerror). |
| `Action<ToolCall> ToolCall` | The agent wants a function called. Answer with `SubmitToolResult(call.CallId, result)`. |
| `Action<int> GenerationStarted` | A new reply has begun: whatever was queued of the previous one must not be played. |
| `Action<string, string> TranscriptTruncated` | The player cut the agent off: what they heard, and the whole line. |
| `Action<string, string> TranscriptRevised` | The player's paused sentence and its continuation became one line: the new text, and the one it replaces. |
| `Action<float, string> SessionLimit` | How many seconds this session may still run, when the server sets a limit, and why. |
| `Action Reconnected` | A dropped connection was opened again. It is a new server session: the agent does not remember the old one. |
| `Action<int, string> Ended` | The server ended the session on purpose (close code, reason); no reconnection follows. |

#### `Task<bool> ConnectAsync()`

Opens the session and sends the configuration. `false` if it could not: the reason is raised as `Error` and kept in `LastError`.

#### `void Disconnect()`

Ends the session and releases the microphone.

#### `Task DisconnectAsync()`

The same, awaited.

#### `void Dispose()`

Ends the session and releases everything.

#### `Task<bool> StartManagedAsync(IAudioManager audio)`

Runs the microphone and the speaker too: a whole conversation in one call.

#### `bool ToggleMute()`

Mutes or unmutes the managed microphone; returns whether it is now muted.

#### `float GetAmplitude()`

The managed microphone's loudness, 0 to 1.

#### `void SendAudio(byte[] pcm16)`

Microphone audio: 16-bit PCM, 16 kHz, mono. Keep sending it (silence too): the server measures pauses in it.

#### `void SendAudioFloat(float[] samples, int rate)`

The same from float samples at any rate.

#### `void SendAudioFloat(float[] samples, int offset, int count, int rate)`

The same from part of an array.

#### `void UpdatePrompt(string prompt)`

Replaces the prompt, mid-session.

#### `void UpdateVoice(string voice)`

Changes the voice, mid-session.

#### `void UpdateLanguage(string language)`

Changes the language, mid-session.

#### `void UpdateTools(IEnumerable<ToolDefinition> tools)`

Replaces the tools, mid-session.

#### `void UpdatePitch(float pitch)`

Shifts the voice's pitch for the rest of the session.

#### `void UpdateVisemes(bool enabled)`

Asks for visemes, or stops asking, from the next reply on.

#### `void Reset()`

Clears the conversation: the agent starts fresh.

#### `void SubmitToolResult(string callId, object result)`

Answers a `ToolCall` with a string, or anything JSON can carry.

#### `List<TranscriptLine> GetTranscript()`

The conversation so far.

#### `string GetTranscriptText()`

The same as text, a line each.

#### `static Task<List<VoiceInfo>> GetVoicesAsync(string baseUrl = LokutorApi.VoiceAgentUrl)`

As [`LokutorApi.GetVoicesAsync`](#lokutorapi).

#### `static Task<List<LanguageInfo>> GetLanguagesAsync(string baseUrl = LokutorApi.VoiceAgentUrl)`

As `LokutorApi.GetLanguagesAsync`.

#### `static Task<List<ModelInfo>> GetModelsAsync(string baseUrl = LokutorApi.VoiceAgentUrl)`

As `LokutorApi.GetModelsAsync`.

#### `static Task<ServerConfig> GetConfigAsync(string baseUrl = LokutorApi.VoiceAgentUrl)`

As `LokutorApi.GetConfigAsync`.

#### `static Task<Dictionary<string, object>> GetStatusAsync(string baseUrl = LokutorApi.VoiceAgentUrl)`

As `LokutorApi.GetStatusAsync`.

#### `static Task<HealthStatus> GetHealthAsync(string baseUrl = LokutorApi.VoiceAgentUrl)`

As `LokutorApi.GetHealthAsync`.

### `ToolDefinition`

`class ToolDefinition`

A function the agent may call (OpenAI format).

```csharp theme={null}
new ToolDefinition()
new ToolDefinition(string name, string description, Dictionary<string, object> parameters = null)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Name` | `string` | — | The function's name. |
| `Description` | `string` | — | When to use it. |
| `Parameters` | `Dictionary<string, object>` | — | A JSON schema: `{"type": "object", "properties": {...}, "required": [...]}`. |

### `ToolCall`

`class ToolCall`

The agent wants a function called. Answer with `SubmitToolResult(CallId, result)`.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Name` | `string` | — | The function. |
| `Arguments` | `string` | — | A JSON object. |
| `CallId` | `string` | — | Give it back with the result. |

### `TranscriptLine`

`class TranscriptLine`

A line of the conversation.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Role` | `string` | — | `"user"` or `"agent"`. |
| `Text` | `string` | — | What was said. |
| `Timestamp` | `long` | — | Unix time in milliseconds. |

### `CustomLLMConfig`

`class CustomLLMConfig`

Your own OpenAI-compatible endpoint.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `BaseUrl` | `string` | — | The endpoint, up to `/v1`. |
| `ApiKey` | `string` | — | Its key. |
| `Model` | `string` | — | The model's name. |
| `Headers` | `Dictionary<string, string>` | — | Sent with every request. |
| `Tools` | `string` | — | `"auto"` or `"none"`. |
| `SpeculativeLlm` | `bool?` | — | See [Bring your own LLM](https://docs.lokutor.com/guides/bring-your-own-llm.md). |

### `LlmRequest`

`class LlmRequest`

One turn for a model that runs in the game: the conversation so far (OpenAI chat messages) and the agent's tools.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `RequestId` | `string` | — | The turn's id. |
| `Messages` | `List<Dictionary<string, object>>` | `new List<Dictionary<string, object>>()` | The conversation so far, as OpenAI chat messages. |
| `Tools` | `List<Dictionary<string, object>>` | `new List<Dictionary<string, object>>()` | The agent's tools. |

### `LlmReply`

`class LlmReply`

The reply of your own model to one LlmRequest. Stop when Cancelled turns true: the player spoke over it.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Cancelled` | `bool` | — | The player spoke over the reply: stop. Read only. |
| `Token` | `CancellationToken` | — | The same, for your own requests. Read only. |

#### `void Chunk(string text)`

More text. Lokutor starts speaking at the first sentence.

#### `void ToolCall(string name, object arguments, string callId = "")`

One of the agent's tools to call. Arguments: a JSON string, or anything JSON can carry.

#### `void Done()`

The reply is complete. Returning from the handler does it for you.

#### `void Fail(string message)`

The model failed: the agent is told so.

### `IAudioManager`

`interface IAudioManager`

A microphone and a speaker for a managed conversation (AudioManager in the JavaScript SDK). LokutorAudioManager is Unity's.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Muted` | `bool` | — | The microphone is muted. |

#### `bool StartMicrophone(Action<float[], int, int> onAudio)`

Captures: mono samples, how many, and their rate. False when there is no microphone.

#### `void StopMicrophone()`

Releases it.

#### `void PlayAudio(byte[] pcm16, int sampleRate)`

Queues voice (16-bit PCM, mono).

#### `void StopPlayback()`

Stops at once and forgets what was queued.

#### `float GetAmplitude()`

The microphone's loudness, 0 to 1.

### `LokutorSession`

`class LokutorSession : IDisposable`

One voice conversation with one character, without the engine, on top of VoiceAgentClient. It knows what the character is doing, keeps its voice until the engine plays it, runs the game's actions, and decides when the microphone is open. LokutorAgent is a thin layer on top; use the session in an engine that is not Unity.

```csharp theme={null}
new LokutorSession(SessionOptions options)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `DefaultPlaybackRate` | `int` | `LokutorApi.OutputRate` | Until the server announces another. Constant. |
| `DefaultInputRate` | `int` | `LokutorApi.InputRate` | Until the server announces another. Constant. |
| `MuteMicWhileSpeaking` | `bool` | — | See `SessionOptions.MuteMicWhileSpeaking`; it can change at any time. |
| `ActionFiller` | `bool` | — | See `SessionOptions.ActionFiller`; it can change at any time. |
| `SpeakBeforeActions` | `bool` | — | See `SessionOptions.SpeakBeforeActions`; it can change at any time. |
| `OthersAudible` | `Func<bool>` | `null` | Other voices of the game that would reach the microphone: with `MuteMicWhileSpeaking`, it is muted while this is true. `LokutorAgent` sets it. |
| `Client` | `VoiceAgentClient` | — | The layer underneath, for what the session does not cover. Read only. |
| `Playback` | `PlaybackBuffer` | — | The character's voice. Pull from it in your audio callback at `PlaybackRate`. Read only. |
| `PlaybackRate` | `int` | — | Rate of the character's voice. Read only. |
| `InputRate` | `int` | — | Rate the server expects of the microphone. Read only. |
| `State` | `AgentState` | — | What the conversation is doing now. Read only. |
| `IsConnected` | `bool` | — | The session is open. Read only. |
| `SessionId` | `string` | — | The server's id of this session. Read only. |
| `MouthOpen` | `float` | — | Loudness of the character's voice right now, 0 to 1: drive a mouth or jaw with it. Read only. |
| `HeardSeconds` | `float` | — | How much of the current reply has been heard, in seconds: the clock for visemes. Read only. |
| `IsSpeaking` | `bool` | — | The character's voice is being heard (not its background sound). Read only. |

**Events**

| Event | Raised when |
| :- | :- |
| `Action<AgentState> StateChanged` | The conversation moved to another state. |
| `Action<string> PlayerSaid` | What the player said, once the turn is over. |
| `Action<string> PlayerSaidPartial` | The player's words while they are still talking. |
| `Action<string> AgentSaid` | What the character is about to say. `LokutorApi.StripTags` takes out `[laugh]` and the like for subtitles. |
| `Action<string> AgentInterrupted` | The player cut the character off; this is what they actually heard. |
| `Action<string, ActionArgs, string> ActionCalled` | An action ran (after its handler returned): name, arguments, result. |
| `Action VoiceCleared` | A new reply begins, or the one being spoken was cut: a mouth should close. |
| `Action<IReadOnlyList<Viseme>> Visemes` | Mouth shapes of the reply, as they arrive. |
| `Action<IReadOnlyList<VisemeMark>> VisemesReceived` | The same with the names of version 0.1. |
| `Action<LokutorError> Error` | Something failed, as a [`LokutorError`](#lokutorerror). |
| `Action<int> SessionLimit` | The server announced how many seconds this session may still run. |
| `Action Reconnecting` | The connection dropped and is being opened again. |
| `Action Reconnected` | It is open again, in a fresh conversation. |
| `Action<string> Disconnected` | The conversation is over: why. |

#### `LokutorSession AddAction(AgentAction action)`

Lets the character call a game function. Works before or during a conversation.

#### `LokutorSession AddAction(string name, string description, Func<ActionArgs, string> handler, params ActionParam[] parameters)`

The same, in one call.

#### `LokutorSession AddActionAsync(string name, string description, Func<ActionArgs, Task<string>> handler, params ActionParam[] parameters)`

An action that takes a while: the character waits for the result.

#### `void RemoveAction(string name)`

The character can no longer call it.

#### `void RefreshActions()`

Sends the list of actions again. AddAction and RemoveAction do it for you.

#### `Task ConnectAsync(CancellationToken cancel = default)`

Opens the conversation. Throws an `IOException` when it cannot; its inner exception is a `LokutorException` with the error.

#### `static string ConfigLanguage(string language, bool dashboardAgent)`

The language to send at connect, or null to send none.

#### `void SetPersona(string persona)`

Changes who the character is, mid-conversation.

#### `void SetContext(string key, string value)`

Tells the character something about the game right now (`"Time left"`, `"20 seconds"`), without rewriting its persona. Null takes it out. Changes in the same quarter second are sent together, by `Update()`. A dashboard agent needs a `Persona` for this: its own prompt cannot be extended from the game.

#### `void SetVoice(string voice)`

Changes the voice.

#### `void SetLanguage(string language)`

"auto": the character follows the language the player speaks.

#### `void SetPitch(float pitch)`

Shifts the voice up or down.

#### `void ResetConversation()`

Forgets the conversation so far (the character starts fresh).

#### `List<TranscriptLine> GetTranscript()`

The conversation so far.

#### `void SendMicrophone(float[] samples, int offset, int count, int sampleRate)`

Sends microphone audio (mono floats, any sample rate) to the character. Call it with whatever the engine captured since last frame; resampling and framing are handled here. Keep calling it with silence (zeros) when the player is quiet: the server hears pauses as end of turn.

#### `void SendPcm16(byte[] pcm16At16k)`

Sends 16 kHz mono PCM16 as is (e.g. a recorded line).

#### `void SetVoiceAudibleUntil(DateTime utc)`

Tells the session when the voice the engine has already taken from `Playback` will have finished coming out of the speakers (its own buffers and output latency included), so the microphone stays muted until then. Engines that do not call it get EchoTailMs after their last read, which is enough when they read close to real time.

#### `void Update()`

Call once per frame from the game's main thread. Delivers queued events, runs action handlers, and moves the state from Speaking back to Ready once the voice has played out.

#### `Task DisconnectAsync()`

Ends the conversation.

#### `void Dispose()`

Ends the conversation and releases everything.

### `SessionOptions`

`class SessionOptions`

The options of a `LokutorSession`.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `ApiKey` | `string` | — | Your Lokutor API key. Fine for prototypes; a shipped game should use `TicketProvider`. |
| `TicketProvider` | `Func<Task<string>>` | — | Returns a short-lived ticket minted by **your** backend (`POST https://api.lokutor.com/ws-ticket` with the API key), so the key never ships inside the game. Called before every connect, on the thread that calls `ConnectAsync`, or `Update` when a dropped connection is opened again. |
| `AgentId` | `string` | — | An agent built in the Lokutor dashboard. Persona, voice and language then default to it. |
| `Persona` | `string` | — | Who the character is and how it talks (the system prompt). |
| `ContextHeading` | `string` | `"Right now in the game:"` | The line above what `SetContext` tells the character. Write it in the language of the persona. |
| `Voice` | `string` | — | `F1`-`F5`, `M1`-`M5`, or a voice id from `GET /voices`. |
| `Language` | `string` | — | `en`, `es`, `fr`, `pt`, `ca`, `gl`, `eu`... or `"auto"` (or `""`): the character answers in the language the player speaks. Null: the default (`en`; a dashboard agent keeps its own). |
| `Pitch` | `float` | — | Shifts the voice up or down: small creatures, giants. |
| `Visemes` | `bool` | `true` | Receive the mouth shapes of the voice, for lip sync. |
| `Llm` | `CustomLLMConfig` | — | Your own OpenAI-compatible language model. |
| `OnLlmRequest` | `Func<LlmRequest, LlmReply, Task<string>>` | — | Your own language model, running in the game (see VoiceAgentClient.OnLlmRequest). |
| `AutoReconnect` | `bool` | `true` | Open the connection again when it drops. The character does not remember what came before. |
| `MuteMicWhileSpeaking` | `bool` | `true` | Send silence instead of the microphone while the character's voice is playing, so laptop speakers do not make it interrupt itself. Turn off with headphones to let players interrupt. |
| `ActionFiller` | `bool` | `false` | The server has the character say "One moment" or the like while an action runs, or what the model wrote before it. False: it says nothing until its answer. |
| `SpeakBeforeActions` | `bool` | `true` | What it begins to say before it calls an action is heard. Turn it off with an action that it must call before it answers ("how funny that was"): the model can write its plan there. |
| `EchoTailMs` | `int` | `300` | How long the microphone stays muted after the voice has finished playing: the room's echo still reaches it for a moment. |
| `Url` | `string` | `LokutorApi.VoiceAgentUrl` | The voice agent endpoint. |
| `UserAgent` | `string` | `"lokutor-game-sdk/" + LokutorApi.Version` | Sent when connecting. |
| `ConnectTimeout` | `TimeSpan` | `TimeSpan.FromSeconds(15)` | How long to wait for the connection. |
| `Dispatcher` | `Action<Action>` | — | How events reach your code. Null (the default): they are queued and delivered when you call `LokutorSession.Update`, i.e. on your game's main thread. |

### `AgentState`

What the conversation is doing. Values: `Disconnected`, `Connecting`, `Ready`, `PlayerTalking`, `Thinking`, `Speaking`.

### `MicMode`

When the character hears the player. Values: `Always`, `PushToTalk`, `Off`.

## Speech

### `TTSClient`

`class TTSClient : IDisposable`

Text to speech over `/ws/tts`, as `TTSClient` in the JavaScript and Python SDKs. For a character that says written lines use LokutorVoice, which plays them and moves the mouth.

```csharp theme={null}
new TTSClient(string apiKey = null)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `ApiKey` | `string` | — | An API key, or a `wst_` ticket. |
| `Auth` | `Func<Task<string>>` | — | Called for the credential: a ticket from your server, in a shipped game. |
| `ServerUrl` | `string` | `LokutorApi.TTSUrl` | The text-to-speech endpoint. |
| `UserAgent` | `string` | `"lokutor-csharp/" + LokutorApi.Version` | Sent when connecting. |
| `KeepOpen` | `TimeSpan` | `TimeSpan.FromSeconds(8)` | Keep the connection open this long after a request, so the next one skips the handshake. It counts as a session. |
| `ConnectTimeout` | `TimeSpan` | `TimeSpan.FromSeconds(15)` | How long to wait for the connection. |
| `FirstAudioTimeout` | `TimeSpan` | `TimeSpan.FromSeconds(30)` | How long to wait for the first audio. |
| `StallTimeout` | `TimeSpan` | `TimeSpan.FromSeconds(15)` | How long to wait between chunks afterwards. |

#### `Task<TTSResult> SynthesizeAsync(string text, SynthesizeOptions options = null, CancellationToken cancel = default)`

Speaks a text; done when all of it has arrived. The callbacks in the options run as it is generated, on the thread that called this (in Unity, the main one). Requests run one after another.

#### `void Cancel()`

Stops the request being spoken and forgets the ones waiting.

#### `void Close()`

Cancels, and closes the connection.

#### `void Dispose()`

The same as `Close()`.

### `SynthesizeOptions`

`class SynthesizeOptions`

The options of one request.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Voice` | `string` | `"F1"` | `F1`-`F5`, `M1`-`M5`, or a voice id from the dashboard. |
| `Language` | `string` | `"en"` | The language of the text. |
| `Visemes` | `bool` | — | Ask for mouth shapes. |
| `Speed` | `float?` | — | Sent only when set, as `Steps` and `Temperature`. The server's defaults are what production is tuned for. |
| `Steps` | `int?` | — | See [Text to speech](https://docs.lokutor.com/sdk/tts.md). |
| `Temperature` | `float?` | — | See [Text to speech](https://docs.lokutor.com/sdk/tts.md). |
| `DictionaryIds` | `List<string>` | — | Your [pronunciation](https://docs.lokutor.com/api-reference/pronunciation.md) dictionaries. |
| `Pronunciations` | `Dictionary<string, string>` | — | Word to how to say it. |
| `OnAudio` | `Action<byte[]>` | — | 16-bit PCM, 44.1 kHz, mono, as it is generated. |
| `OnVisemes` | `Action<IReadOnlyList<Viseme>>` | — | Times are from the request's first sample. |
| `OnTTFB` | `Action<int>` | — | Milliseconds until the first audio. |
| `OnError` | `Action<LokutorError>` | — | Why it failed. |

### `TTSResult`

`class TTSResult`

What came of it.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Ok` | `bool` | — | It worked. Read only. |
| `Audio` | `byte[]` | `new byte[0]` | 16-bit PCM, mono, at SampleRate. |
| `SampleRate` | `int` | `LokutorApi.OutputRate` | Rate of `Audio`. |
| `Visemes` | `List<Viseme>` | `new List<Viseme>()` | Mouth shapes, if asked for. |
| `Error` | `LokutorError` | — | Why it did not, or null. |
| `Seconds` | `float` | — | How long the audio lasts. Read only. |

### `STTClient`

`class STTClient`

Transcribes one complete recording (`POST /stt/transcribe`), as `STTClient` in the JavaScript and Python SDKs. For speech as it happens use SpeechToTextClient.

```csharp theme={null}
new STTClient(string apiKey = null)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `ApiKey` | `string` | — | An API key, or a `wst_` ticket. |
| `Auth` | `Func<Task<string>>` | — | Called for the credential. |
| `ServerUrl` | `string` | `LokutorApi.STTUrl` | The API's address: only its host is used. |

#### `Task<TranscribeResult> TranscribeAsync(byte[] audio, TranscribeOptions options = null, CancellationToken cancel = default)`

Audio is 16-bit PCM mono (set SampleRate if it is not 16 kHz) or a whole WAV file's bytes.

### `TranscribeOptions`

`class TranscribeOptions`

The options of one transcription.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `SampleRate` | `int` | — | Rate of raw PCM (16000 if not set). A WAV carries its own. |
| `Format` | `string` | — | `"pcm16"` or `"wav"`. Not set: found from the bytes. |
| `Language` | `string` | — | The language spoken. |
| `Keyterms` | `List<string>` | — | Names and terms to write your way when what is heard is close. |

### `TranscribeResult`

`class TranscribeResult`

What came of it.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Ok` | `bool` | — | It worked. Read only. |
| `Text` | `string` | `""` | What was said. |
| `Engine` | `string` | `""` | The recogniser used. |
| `Language` | `string` | `""` | The language of the transcript. |
| `LatencyMs` | `float` | — | How long it took, in milliseconds. |
| `DurationSeconds` | `float` | — | How long the audio lasts. |
| `SampleRate` | `int` | — | Rate of the audio. |
| `Segments` | `List<TranscribeSegment>` | `new List<TranscribeSegment>()` | The transcript in pieces, with times. |
| `Error` | `LokutorError` | — | Why it failed, or null. |

### `TranscribeSegment`

`class TranscribeSegment`

A piece of the transcript.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Text` | `string` | — | What was said. |
| `Start` | `float` | — | When it starts, in seconds. |
| `End` | `float` | — | When it ends. |
| `Duration` | `float` | — | How long it lasts. |

### `SpeechToTextClient`

`class SpeechToTextClient : EventPump, IDisposable`

Speech to text as the player talks, over `/ws/stt`: voice commands, dictation, captions. No language model and no voice. As `SpeechToTextClient` in the JavaScript SDK. Call its `Update()` every frame, or start it with LokutorAudioManager.

```csharp theme={null}
new SpeechToTextClient(string apiKey = null)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `ApiKey` | `string` | — | An API key, or a `wst_` ticket. |
| `Auth` | `Func<Task<string>>` | — | Called for the credential. |
| `ServerUrl` | `string` | `LokutorApi.STTUrl` | The live transcription endpoint. |
| `Language` | `string` | `"en"` | The language spoken. |
| `Vad` | `string` | `"silero"` | How speech is detected: `"silero"` (default) or `"rms"`. |
| `Keyterms` | `List<string>` | — | Names and terms to write your way when what is heard is close. |
| `ConnectTimeout` | `TimeSpan` | `TimeSpan.FromSeconds(15)` | How long to wait for the connection. |
| `UserAgent` | `string` | `"lokutor-csharp/" + LokutorApi.Version` | Sent when connecting. |
| `Connected` | `bool` | — | The session is open. Read only. |

**Events**

| Event | Raised when |
| :- | :- |
| `Action<string> PartialTranscript` | The best guess so far, while the player talks. |
| `Action<string> FinalTranscript` | The player finished a sentence. |
| `Action<LokutorError> Error` | Something failed, as a [`LokutorError`](#lokutorerror). |
| `Action<string> StatusChange` | `connecting`, `connected`, `disconnected`. |

#### `Task<bool> ConnectAsync(IAudioManager audio = null)`

Connects, and with an audio manager (LokutorAudioManager in Unity) starts listening. Without one, send the audio yourself.

#### `void Disconnect()`

Ends the session and releases the microphone.

#### `void Dispose()`

The same.

#### `void SendAudio(byte[] pcm16)`

16-bit PCM, 16 kHz, mono. Keep sending silence: the end of an utterance is measured in it.

#### `void SendAudioFloat(float[] samples, int offset, int count, int rate)`

The same from float samples at any rate.

#### `void EndUtterance()`

Finishes whatever is being said now.

### `VoiceLines`

`class VoiceLines`

Says lines one after another through a `PlaybackBuffer`, and keeps them.

```csharp theme={null}
new VoiceLines(TTSClient tts, PlaybackBuffer playback, LipSync lipSync)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Voice` | `string` | `"F1"` | The voice of its lines. |
| `Language` | `string` | `"en"` | The language of its lines. |
| `Load` | `Func<string, VoiceLine>` | — | Where lines come from before the network: from disk, from the game's own files. By key; null when it is not there. |
| `Store` | `Action<string, VoiceLine>` | — | Where they are kept. |
| `Tts` | `TTSClient` | — | The client underneath. Read only. |
| `Playback` | `PlaybackBuffer` | — | The voice waiting to be played. Read only. |
| `LipSync` | `LipSync` | — | The mouth it moves. Read only. |
| `Current` | `string` | — | The line being said, or `""`. Read only. |
| `IsSpeaking` | `bool` | — | A line is being said. Read only. |

**Events**

| Event | Raised when |
| :- | :- |
| `Action<string> LineStarted` | A line is being heard. |
| `Action<string> LineFinished` | It has been heard to the end, or was stopped. |
| `Action<LokutorError> Error` | A line could not be made. |

#### `Task<bool> SayAsync(string text, SayOptions options = null)`

Says a line. The task ends when it has been heard (`true`) or could not be said (`false`). Lines wait for each other.

#### `void Stop()`

Stops at once and forgets the lines waiting.

#### `void Update()`

Call once per frame, on the thread `SayAsync` is called from.

#### `Task PreloadAsync(IEnumerable<string> lines, SayOptions options = null)`

Fetches lines before they are needed, so they start at once and, once kept, work without a network.

#### `Task SaveAsync(Action<string, VoiceLine> store, IEnumerable<string> lines, SayOptions options = null)`

The same, into a place of your choice (the game's own files): `store(key, line)`.

#### `bool HasLine(string text, SayOptions options = null)`

Whether a line is already kept.

### `VoiceLine`

`class VoiceLine`

A line as it is kept: the voice and its mouth shapes.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `SampleRate` | `int` | `LokutorApi.OutputRate` | Rate of `Audio`. |
| `Audio` | `byte[]` | `new byte[0]` | 16-bit PCM, mono. |
| `Visemes` | `List<Viseme>` | `new List<Viseme>()` | Its mouth shapes. |

#### `static string KeyFor(string voice, string language, string text)`

The name a line is kept under: the same voice, language and words give the same one.

#### `byte[] ToBytes()`

The line as a file.

#### `static VoiceLine FromBytes(byte[] bytes)`

Null when the bytes are not a line.

### `SayOptions`

`class SayOptions`

The options of one line.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Voice` | `string` | — | Null: the character's. |
| `Language` | `string` | — | Null: the character's. |
| `Interrupt` | `bool` | — | Say it now, dropping what is being said. |

## Lip sync

### `Viseme`

`struct Viseme`

One mouth shape of a reply: V its id (0-14) and C its name in LokutorApi.Visemes, T when it starts and D how long it lasts, in seconds from the reply's first sample.

```csharp theme={null}
new Viseme(int v, float t, float d)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `V` | `int` | — | Its id, 0 to 14. |
| `C` | `string` | — | Its name in `LokutorApi.Visemes`. |
| `T` | `float` | — | When it starts, in seconds from the reply's first sample. |
| `D` | `float` | — | How long it lasts, in seconds. |

### `LipSync`

`class LipSync`

The shape of a mouth over time. Give it the visemes of a reply and, every frame, how much of the reply has been heard: it answers with the weight of each of the 15 shapes. Without visemes it follows the loudness.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Intensity` | `float` | `1f` | How far the mouth opens. |
| `Lead` | `float` | `0.05f` | Seconds the mouth leads the sound: people open before they speak. |
| `Blend` | `float` | `0.07f` | Seconds over which one shape melts into the next. 0.05 is crisp and cartoonish, 0.12 soft. |
| `Loudness` | `float` | `0.35f` | How much quiet speech closes the mouth, 0 to 1. |
| `SteppedFps` | `float` | — | Steps per second of the mouth, for a hand-drawn look (12 = animation on twos). 0 = smooth. |
| `Gain` | `float` | `1.5f` | Loudness multiplier for mouths that follow the loudness (no visemes). |
| `Weights` | `float[]` | — | Weight of each of the 15 visemes right now, in `LokutorApi.Visemes` order. Read only. |
| `Current` | `string` | — | The strongest one. Read only. |
| `MouthOpen` | `float` | — | How open the mouth is, 0 to 1. Read only. |
| `HasVisemes` | `bool` | — | Whether the voice being heard has visemes. Read only. |
| `Openness` | `IReadOnlyList<float>` | — | How open each viseme is, for jaws and mouth-open shapes. Static. |

**Events**

| Event | Raised when |
| :- | :- |
| `Action<string> VisemeChanged` | The mouth changed shape: its name in `LokutorApi.Visemes`. |

#### `void PushVisemes(IEnumerable<Viseme> list)`

The visemes of the reply being heard, as they arrive.

#### `void Clear()`

A new reply, or silence: the mouth closes.

#### `bool Advance(float heard, float level, bool speaking, float delta)`

One frame of the mouth. `heard` is how much of the reply has been heard, in seconds; `level` its loudness (RMS); `speaking` whether it is playing at all. `false`: nothing changed (a stepped mouth holds its pose).

#### `int SpriteFrame(int count)`

The frame of a set of mouth drawings: 0 closed, 1 slightly open, 2 open, 3 round (if there are that many).

### `MouthRig`

`class MouthRig`

Which blend shapes of a face make each viseme. They are found by name: the 15 visemes of Oculus, Ready Player Me and VRChat (viseme\_PP, viseme\_aa...), VRM (aa ih ou ee oh) and the A I U E O of VRoid and MMD-style rigs, ARKit (jawOpen, mouthFunnel...), or a single mouth-open shape. Or write your own mapping.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Kind` | `MouthRigKind` | — | Which kind of mouth was found. Read only. |
| `Shapes` | `List<Shape>` | — | The blend shapes that move. Read only. |

#### `static MouthRig Find(IReadOnlyList<string> names, IReadOnlyDictionary<string, Dictionary<string, float>> mapping = null)`

Finds the mouth in a list of blend shape names (their order gives the indices). `mapping`, if not empty, is used instead of the usual names: viseme name to blend shape name to weight, 0 to 1.

### `MouthRig.Shape`

`struct Shape`

One blend shape that moves: its index, and how much of it each viseme takes.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Index` | `int` | — | The blend shape's index. |
| `PerViseme` | `float[]` | — | How much of it each viseme takes. |

#### `float Weight(float[] visemes, float intensity)`

Its weight for these viseme weights, 0 to 1 (a little more with a high intensity).

### `MouthRigKind`

The kinds of mouth LipSync finds in a face. Values: `None`, `Visemes`, `Vrm`, `ArKit`, `MouthOpen`, `Custom`.

### `LokutorVisemeShape`

`class LokutorVisemeShape`

One blend shape of one viseme, for rigs whose names are not recognised.

```csharp theme={null}
new LokutorVisemeShape()
new LokutorVisemeShape(string viseme, string blendShape, float weight = 1f)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `viseme` | `string` | `"aa"` | `sil PP FF TH DD kk CH SS nn RR aa E ih oh ou` |
| `blendShape` | `string` | `""` | The blend shape's name. |
| `weight` | `float` | `1f` | How much of it, 0 to 1. |

### `LokutorVisemeSprite`

`class LokutorVisemeSprite`

The drawing of one viseme.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `viseme` | `string` | `"aa"` | `sil PP FF TH DD kk CH SS nn RR aa E ih oh ou` |
| `sprite` | `Sprite` | — | Its drawing. |

### `MouthShape`

A mouth shape, coarse enough to map onto any sprite set. LipSync uses the 15 visemes themselves. Values: `Rest`, `A`, `E`, `I`, `O`, `U`, `MBP`, `FV`, `L`, `S`, `Other`.

### `VisemeMark`

`struct VisemeMark`

A viseme with the names it had before 0.2. `Viseme` is what LipSync takes.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Time` | `float` | — | When it starts, in seconds. |
| `Duration` | `float` | — | How long it lasts. |
| `Id` | `int` | — | Its id, 0-14. |
| `Name` | `string` | — | Its name in LokutorApi.Visemes. |
| `Char` | `char` | — | The first letter of its name. |
| `Shape` | `MouthShape` | — | Its coarse shape. |

#### `static MouthShape ShapeFor(char c)`

The mouth of a letter.

## Audio

### `LokutorMicrophone`

`class LokutorMicrophone : IDisposable`

The microphone, in mono blocks as they arrive. LokutorAgent and LokutorAudioManager have one each.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Muted` | `bool` | — | Silence is handed over instead of sound: a conversation's microphone must not simply stop, its pauses are measured in it. |
| `Level` | `float` | — | Loudness of the last block, 0 to 1. Read only. |
| `IsRunning` | `bool` | — | Capturing. Read only. |
| `Rate` | `int` | — | Rate of what it captures. Read only. |

#### `bool Start(string deviceName = null)`

False (and a warning in the console) without a microphone, or when it cannot be opened.

#### `void Stop()`

Releases it.

#### `void Dispose()`

The same as `Stop()`.

#### `void Update(Action<float[], int, int> onAudio)`

Call once per frame: hands over what has arrived (samples, how many, rate). The array is reused.

### `LokutorVoicePlayer`

`class LokutorVoicePlayer : IDisposable`

Plays a voice through an AudioSource as it arrives, and tells its buffer how much of it has been heard. LokutorAgent, LokutorVoice and LokutorAudioManager have one each.

```csharp theme={null}
new LokutorVoicePlayer(AudioSource source, PlaybackBuffer buffer)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Source` | `AudioSource` | — | The AudioSource it plays through. Read only. |
| `Buffer` | `PlaybackBuffer` | — | The voice it plays. Read only. |
| `AudibleUntilUtc` | `DateTime` | — | When the voice written so far will have come out of the speakers (the mixer's delay included). Read only. |

**Events**

| Event | Raised when |
| :- | :- |
| `Action<float[], int> VoicePlayed` | The voice just given to the AudioSource, as it is: for a character that another character listens to. The array is reused. |

#### `void Update()`

Call once per frame.

#### `void Stop()`

Silence, and lets go of the clip. `Update()` starts again.

#### `void Dispose()`

Stops for good.

### `PlaybackBuffer`

`class PlaybackBuffer`

A voice, waiting to be played. Network threads write; the engine reads at `SampleRate`, a little ahead of what it is playing. Silence is returned when it runs dry, so the engine can keep a looping source going for the whole conversation.

It also keeps the clock lip sync runs on: the engine says how much of what it read has come out (`MarkPlayed`), and `HeardSeconds` is how much of the current reply has been heard.

```csharp theme={null}
new PlaybackBuffer(int sampleRate, int initialSeconds = 20)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `SampleRate` | `int` | — | Rate of the voice. Read only. |
| `BufferedSeconds` | `float` | — | Seconds of audio waiting to be read. Read only. |
| `IsPlaying` | `bool` | — | Audio is waiting to be read. Read only. |
| `IsAudible` | `bool` | — | The voice is not over: some waits to be read, or was read and has not come out yet. Read only. |
| `Level` | `float` | — | Loudness of the most recently read block (RMS scaled to roughly 0 to 1). Read only. |
| `LastVoiceReadUtc` | `DateTime` | — | When the engine last read some of the voice (UTC). Read only. |
| `TotalRead` | `long` | — | Samples read since the buffer was made, silence included. Read only. |
| `Clears` | `int` | — | Grows with every `Clear()`, so an engine knows that what it read before one is not to be played. Read only. |
| `HeardSeconds` | `float` | — | How much of the current reply has been heard, in seconds: the clock viseme times are read against. Read only. |
| `HeardLevel` | `float` | — | Loudness (RMS) of what is being heard right now; 0 when nothing is. Read only. |

#### `void MarkPlayed(long samples)`

How many of the samples read so far (`TotalRead`) have come out of the speakers. An engine that never says is taken to play what it reads at once.

#### `void Write(float[] samples)`

More voice.

#### `int Read(float[] dst, int offset, int n)`

Fills `dst` (mono) with queued audio, then silence.

#### `void Clear()`

Drops everything queued (the caller interrupted, or a newer reply began) and counts from 0 again.

### `LokutorAudio`

`class LokutorAudio`

Audio helpers, named as in the JavaScript and Python SDKs.

#### `static float[] Pcm16ToFloat32(byte[] pcm)`

16-bit PCM to floats, -1 to 1.

#### `static byte[] Float32ToPcm16(float[] samples)`

Floats to 16-bit PCM, clipped.

#### `static float CalculateRMS(float[] samples)`

Loudness (root mean square).

#### `static float CalculateRMS(float[] samples, int offset, int count)`

The same of part of an array.

#### `static float[] NormalizeAudio(float[] samples, float targetPeak = 0.95f)`

The same audio, scaled so its loudest sample is `targetPeak`.

#### `static float[] Resample(float[] samples, int fromRate, int toRate)`

A whole recording at another rate.

#### `static byte[] WavBytes(byte[] pcm, int rate)`

A whole PCM16 mono recording as a WAV file's bytes.

### `StreamResampler`

`class StreamResampler`

Streaming mono resampler. Keeps its phase across calls, so audio can be pushed in chunks of any size (a game engine hands the microphone over in whatever blocks it has). Downsampling averages the input over each output step, which is enough anti-aliasing for speech going to a recogniser; upsampling interpolates linearly.

```csharp theme={null}
new StreamResampler(int inputRate, int outputRate)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `InputRate` | `int` | — | Rate of the input. Read only. |
| `OutputRate` | `int` | — | Rate of the output. Read only. |

#### `float[] Process(float[] input)`

The next block, resampled.

#### `float[] Process(float[] input, int offset, int count)`

The same from part of an array.

#### `void Reset()`

Forgets the phase: the next block starts a new stream.

### `StreamingResampler`

`class StreamingResampler : StreamResampler`

The name `StreamResampler` had before 0.2.

```csharp theme={null}
new StreamingResampler(int inputRate, int outputRate)
```

### `Pcm16`

`class Pcm16`

PCM16 little-endian helpers.

#### `static byte[] FromFloat(float[] samples, int offset, int count)`

Floats to 16-bit PCM.

#### `static float[] ToFloat(byte[] bytes)`

16-bit PCM to floats.

## API and errors

### `LokutorApi`

`class LokutorApi`

Constants and helpers shared by the whole package, and the API's public [discovery](https://docs.lokutor.com/sdk/discovery.md) endpoints, which need no key. (A class cannot be called `Lokutor` inside its namespace.)

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Version` | `string` | `"0.2.0"` | The version of the package. Constant. |
| `VoiceAgentUrl` | `string` | `"wss://api.lokutor.com/ws/agent"` | The voice agent endpoint. Constant. |
| `TTSUrl` | `string` | `"wss://api.lokutor.com/ws/tts"` | The text-to-speech endpoint. Constant. |
| `STTUrl` | `string` | `"wss://api.lokutor.com/ws/stt"` | The live transcription endpoint. Constant. |
| `InputRate` | `int` | `16000` | Rate of the audio the API takes (16-bit PCM, mono). Constant. |
| `OutputRate` | `int` | `44100` | Rate of the audio the API sends (16-bit PCM, mono). Constant. |
| `AutoLanguage` | `string` | `"auto"` | Pass as a voice agent's language so the character follows the language the player speaks. Constant. |
| `Voices` | `IReadOnlyList<string>` | — | Voice slots, `F1` to `M5`: each is a native speaker of the language in use. `GetVoicesAsync` has the live list. Static. |
| `Languages` | `IReadOnlyDictionary<string, string>` | — | Languages the API documents for SDKs: code to name. `GetLanguagesAsync` has the live list. Static. |
| `Visemes` | `IReadOnlyList<string>` | — | The 15 mouth shapes, by id. Viseme events carry the id (`V`) and the name (`C`). Static. |
| `ReconnectableCloseCodes` | `IReadOnlyCollection<int>` | — | Close codes after which a session is opened again: the connection dropped or the server went away. Every other close is the server ending the session on purpose. Static. |

#### `static string LanguageToWire(string language)`

The value the protocol carries for a language: `"auto"` and `""` are both `""` (follow the player).

#### `static string StripTags(string text)`

A line without the [expression tags](https://docs.lokutor.com/api-reference/expression-tags.md) the voice performs (`[laugh]`, `[sad]`...), for subtitles.

#### `static int VisemeId(string name)`

The id (0-14) of a viseme name, whatever its case; 0 (closed) for an unknown one.

#### `static string HttpOrigin(string url)`

`ws://host/path` becomes `http://host`.

#### `static Task<List<VoiceInfo>> GetVoicesAsync(string baseUrl = VoiceAgentUrl)`

Voices the API offers.

#### `static Task<List<LanguageInfo>> GetLanguagesAsync(string baseUrl = VoiceAgentUrl)`

Languages the API offers.

#### `static Task<List<ModelInfo>> GetModelsAsync(string baseUrl = VoiceAgentUrl)`

Speech models.

#### `static Task<ServerConfig> GetConfigAsync(string baseUrl = VoiceAgentUrl)`

Request limits and defaults.

#### `static Task<Dictionary<string, object>> GetStatusAsync(string baseUrl = VoiceAgentUrl)`

Runtime status of the service, as the API reports it.

#### `static Task<HealthStatus> GetHealthAsync(string baseUrl = VoiceAgentUrl)`

Whether the service is ready to take requests.

### `VoiceInfo`

`class VoiceInfo`

A voice the API offers.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Id` | `string` | — | Give it as a voice. |
| `Name` | `string` | — | Its name. |
| `Gender` | `string` | — | Its gender. |
| `Languages` | `List<string>` | `new List<string>()` | The languages it speaks. |

### `LanguageInfo`

`class LanguageInfo`

A language the API offers.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Code` | `string` | — | Give it as a language. |
| `Name` | `string` | — | Its name. |

### `ModelInfo`

`class ModelInfo`

A speech model.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Name` | `string` | — | Its name. |
| `Description` | `string` | — | What it is. |
| `IsDefault` | `bool` | — | The one used when none is named. |

### `ServerConfig`

`class ServerConfig`

Request limits and defaults.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `MaxTextLength` | `int` | — | The longest text of one request. |
| `MinSteps` | `int` | — | Limits of `Steps`. |
| `MaxSteps` | `int` | — | Limits of `Steps`. |
| `SampleRate` | `int` | — | Rate of the audio it sends. |
| `Channels` | `int` | — | 1: mono. |
| `MinSpeed` | `double` | — | Limits of `Speed`. |
| `MaxSpeed` | `double` | — | Limits of `Speed`. |

### `HealthStatus`

`class HealthStatus`

Whether the service is ready.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Ready` | `bool` | — | It can take requests. |
| `Status` | `string` | — | What the service says. |

### `LokutorError`

`class LokutorError`

An error from the API or the SDK. `Code` is one of the [error codes](https://docs.lokutor.com/api-reference/errors.md), the same as in the JavaScript and Python SDKs.

```csharp theme={null}
new LokutorError(string code, string message, string detail = "", bool? retryable = null)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Code` | `string` | — | One of the [error codes](https://docs.lokutor.com/api-reference/errors.md). Read only. |
| `Message` | `string` | — | What happened, in a sentence. Read only. |
| `Detail` | `string` | — | More, if the server said it. Read only. |
| `Retryable` | `bool` | — | Whether the same request can work later. Servers say so; otherwise it follows from the code. Read only. |

#### `static LokutorError FromServer(object data)`

From a server's error payload: `{code, message, detail, retryable}`, or a plain string.

### `LokutorException`

`class LokutorException : Exception`

A LokutorError thrown, by the calls that have no other way to report one.

```csharp theme={null}
new LokutorException(LokutorError error, Exception inner = null)
```

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Error` | `LokutorError` | — | The error. Read only. |

### `EventPump`

`class EventPump`

Delivers events on your game's thread: they are queued as the network brings them and raised when you call `Update`, once per frame. `VoiceAgentClient` and `SpeechToTextClient` are one.

| Member | Type | Default | Description |
| :- | :- | :- | :- |
| `Dispatcher` | `Action<Action>` | — | Null (the default): events wait for `Update()`. |

#### `void Update()`

Call once per frame from the game's main thread.

### `MiniJson`

`class MiniJson`

The JSON reader and writer the package uses, so it needs no other.

#### `static object Parse(string json)`

A JSON text as dictionaries, lists, strings, numbers, booleans and null.

#### `static string Serialize(object value)`

The opposite.

### `LokutorTextEvent`

`class LokutorTextEvent : UnityEvent<string>`

A UnityEvent with a text.

### `LokutorStateEvent`

`class LokutorStateEvent : UnityEvent<AgentState>`

A UnityEvent with the conversation's state.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.