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

# Voice Agents iOS SDK

> Add voice calls with your agent to a native iOS app in Swift with the FishAgent package

The `FishAgent` Swift package adds voice calls with your agent to a native iOS app. It behaves like the [Web SDK](https://docs.fish.audio/agents/deploy/web-sdk.md) and the [React Native SDK](https://docs.fish.audio/agents/deploy/react-native.md): the same session options, events, error codes, and end reasons. On top of the call, it handles the microphone permission and audio routing (loudspeaker, receiver, headsets).

It has no UI. You build the screen, and the SDK gives you the state to show.

> [!NOTE]
>
> Calls, the microphone, audio routes, reconnection, and calls in the background
> and with the screen locked were checked on an iPhone 12. Headsets, phone-call
> interruptions, and moving between Wi-Fi and cellular have not been checked
> yet.

> [card] [Authenticated sessions](https://docs.fish.audio/agents/deploy/authenticated-sessions.md)
>
> Create session tokens on your backend.

> [card] [Web SDK reference](https://docs.fish.audio/agents/deploy/web-sdk.md)
>
> Events, session options, and error codes.

> [card] [Source and example app](https://github.com/fishaudio/fish-agent-ios)
>
> The package and a one-screen example.

## Requirements

* **iOS 15 or later.**
* **Xcode 16.3 or later.** The SDK is built on LiveKit's Swift SDK, which needs Swift 6.1 tools.
* **Your own backend** to create session tokens, or a [public agent](#public-agent). Never ship an API key inside an app.
* **Tested with** LiveKit's Swift SDK 2.19.0 on an iPhone 12 with iOS 26.6 and an iPhone 16 simulator with iOS 18.5. Other versions may work but are untested.

## Install

Add the package in Xcode (**File > Add Package Dependencies**) with the repository's URL, or in `Package.swift`:

```swift Package.swift theme={null}
dependencies: [
    .package(url: "https://github.com/fishaudio/fish-agent-ios.git", from: "1.0.0"),
],
targets: [
    .target(name: "YourApp", dependencies: [.product(name: "FishAgent", package: "fish-agent-ios")]),
]
```

Add two things to your app's `Info.plist`:

* `NSMicrophoneUsageDescription`, the sentence iOS shows when it asks for the microphone. iOS ends an app that uses the microphone without it.
* The `audio` background mode (`UIBackgroundModes`), so a call continues in the background and with the screen locked.

## Quick start

```swift CallView.swift theme={null}
import FishAgent
import SwiftUI

struct CallView: View {
    @StateObject private var conversation = Conversation()

    var body: some View {
        VStack {
            Text(conversation.status.rawValue)
            ForEach(conversation.messages) { message in
                Text(message.text)
            }
            Button("Start call") {
                Task {
                    do {
                        let token = try SessionToken(json: try await fetchTokenFromYourBackend())
                        try await conversation.startSession(.sessionToken(token))
                    } catch is CancellationError {
                        // The user hung up while the call was starting.
                    } catch let error as FishAgentError {
                        showError(error.code.rawValue, error.message)
                    }
                }
            }
            Button("Hang up") {
                Task { try? await conversation.endSession() }
            }
        }
    }
}
```

`startSession` asks for the microphone permission if the user has not been asked yet. The [example app](https://github.com/fishaudio/fish-agent-ios/tree/main/Example) is one screen that does all of this.

## Start a session

An app starts a call in one of two ways, the same two the browser SDKs offer.

### From your backend (recommended)

When the user starts a call, the app asks your backend for a session token. The backend calls `POST /v1/agent/sessions` with your API key and returns the response unchanged. The endpoint is the same one web apps use; see [Authenticated sessions](https://docs.fish.audio/agents/deploy/authenticated-sessions.md) for backend examples.

Pass the response body to the SDK without picking fields out of it:

```swift theme={null}
let token = try SessionToken(json: responseBody)
try await conversation.startSession(.sessionToken(token))
```

Two things differ from the browser:

* **`localhost` is the phone, not your computer.** During development, use your computer's LAN address.
* **iOS blocks plain `http://`** unless the app allows it (`NSAllowsLocalNetworking` covers the local network). Serve the token endpoint over HTTPS in production.

### Public agent

An agent with [public access](https://docs.fish.audio/agents/deploy/public-agents.md) turned on takes sessions with just its id, with no API key and no backend:

```swift theme={null}
try await conversation.startSession(.agentId("YOUR_AGENT_ID"))
```

If the agent has **Restrict origins** on, the platform checks the request's `Origin` header against the agent's allowed origins. An app sends none, so pass one that is on the list:

```swift theme={null}
@_spi(Experimental) import FishAgent

try await conversation.startSession(.agentId("YOUR_AGENT_ID")) {
    $0.origin = "https://www.example.com"
}
```

Without it, a restricted agent answers `origin_forbidden`.

> [!WARNING]
>
> The `origin` option is experimental and may change in a minor release: a
> dedicated way for apps to identify themselves may replace it. It is only
> visible to a file that imports the SDK as `@_spi(Experimental) import
>     FishAgent`.

Anyone with the agent id can start sessions, billed to you. For a production app, especially one with signed-in users, prefer your backend: it decides who gets a token and can attribute sessions to your users. The React Native page says more about [what a public agent exposes](https://docs.fish.audio/agents/deploy/react-native.md#public-agent); all of it applies here.

## `Conversation`

One object for your app's calls, an `ObservableObject` on the main actor. It can make any number of calls, one at a time.

```swift theme={null}
Conversation(defaults: SessionOptions = .init(), options: ConversationOptions = .init())
```

| Member | Description |
| - | - |
| `status: ConversationStatus` | `idle` before the first call and after a failed start. Stays `ended` after a call until the next one starts |
| `mode: AgentMode` | What the agent is doing: listening, thinking, or speaking |
| `micMuted: Bool` | Whether the microphone is muted |
| `audioOutput: AudioOutputRoute` | The route that was asked for, not the device audio is playing on |
| `messages: [ChatMessage]` | The chat log of the current call, streaming entries included (`isFinal` is false while one is streaming). It stays after the call and is emptied when the next call starts |
| `endReason: EndReason?` | Why the last call ended |
| `events() -> AsyncStream<ConversationEvent>` | What happened. Each call returns a stream of its own; see [Events](#events) |
| `sessionId`, `isSpeaking` | The id of the current or last call's session, and whether `mode` is speaking |
| `transcript: [TranscriptSegment]` | Every transcript segment of the current or last call, in conversation order. A snapshot: later segments are not added to it |
| `startSession(_:configure:) async throws -> String` | Starts a call. Returns the session id once connected |
| `endSession() async throws` | Hangs up. Safe at any time |
| `setMicMuted(_:) async throws` | Mutes or unmutes the microphone |
| `sendUserMessage(_:audio:)` | Sends a typed message. The agent answers in text only unless `audio` is true |
| `sendUserActivity()`, `interrupt()` | Tells the agent the user is active (typing, for example), or stops the agent's current reply |
| `setAudioOutput(_:)` | `.auto`, `.speaker`, or `.earpiece`, during a call or before one |
| `registerClientTool(_:handler:)` | Registers a client tool for the current call and every later one |

The first six are `@Published`, so SwiftUI views update with them.

`SessionOptions` has the same fields as the Web SDK's [session options](https://docs.fish.audio/agents/deploy/web-sdk.md#options): `origin`, `serverUrl`, `language`, `timezone`, `context`, `overrides`, `dynamicVariables`, `endUserId`, `metadata`, `toolEvents`, `clientTools`, `clientToolTimeout`, and `microphone`. `clientToolTimeout` is a `TimeInterval` in seconds (15 by default) where the Web SDK counts milliseconds. `ConversationOptions` holds what the phone needs around calls: `audioOutput`.

The same rules as the other SDKs apply:

* A second `startSession` while one is on its way, or during a live call, joins that call.
* `endSession` during a start stops it where it is, before the microphone is captured if the call had not got that far: `startSession` throws `CancellationError`, and the session, if one was created, is closed.
* A failed start puts `status` back to `idle`.
* `sendUserMessage`, `sendUserActivity`, and `interrupt` do nothing when there is no call.
* The start belongs to the conversation. Cancelling the task that called `startSession` (a SwiftUI `.task` whose view went away, for example) stops the wait, not the call. Call `endSession` to hang up. Releasing the `Conversation` also ends its call.

### Events

`events()` carries the same events as the Web SDK's [event reference](https://docs.fish.audio/agents/deploy/web-sdk.md#events), as subclasses of `ConversationEvent`:

```swift theme={null}
for await event in conversation.events() {
    switch event {
    case let event as ConversationEvent.Message:
        append(event.role, event.text)
    case let event as ConversationEvent.Error:
        show(event.error)
    default:
        break
    }
}
```

Each call to `events()` makes a new stream, so several parts of your app can listen. Nothing is replayed: an event from before the stream was made is gone, so read state from the published properties. A consumer that falls more than 256 events behind loses the oldest ones. The streams end when the `Conversation` is released.

### One call per app

Only one call can run in a process at a time, whichever `Conversation` makes it. A second conversation's `startSession` throws `ConversationUsageError.callAlreadyActive` until the first call has ended. The audio session is shared by the whole process.

### Compatibility

What can gain members in a minor release is shaped so that your code already handles a member it does not know.

* **Events.** `ConversationEvent` is a class, and each kind of event is a subclass (`ConversationEvent.Message`, `ConversationEvent.ToolCallStarted`, and so on). A `switch` over events matches with `as` and has a `default`. An event can also gain a property.
* **End reasons, error codes, error stages, tool sources, and audio routes.** `EndReason`, `FishAgentError.Code`, `FishAgentError.Stage`, `ToolCallSource`, and `AudioOutputRoute` are structs with static members, not enums. Compare with the members (`reason == .userHangup`) and keep a `default`. Their `rawValue` is the text the API and the other SDKs use (`"user_hangup"`), which is also how this page writes them.

`ConversationStatus`, `AgentMode`, and `MessageRole` are enums. They are closed sets, and a minor release adds no case to them, so a `switch` over one of them needs no `default`.

A session token shows only its `sessionId`. The rest of it is how the SDK joins the call.

### What is left out

As in the React Native SDK, the browser-only members are not there: `startAudio`, `setOutputVolume`, `setInputDevice`, `setOutputDevice`, audio levels, and the screen wake lock. There is also no `getRoom()`: no LiveKit type appears in the SDK's API, so your app can move to a newer LiveKit 2.x without the SDK changing.

## Client tools

A [client tool](https://docs.fish.audio/agents/build/client-tools.md) is an async closure from the arguments to a result:

```swift theme={null}
var options = SessionOptions()
options.clientTools = [
    "get_cart": { _, _ in
        ["items": .number(Double(cart.items.count)), "total": .number(cart.total)]
    },
]
let conversation = Conversation(defaults: options)
```

Arguments and results are `JSONValue`, which can be written with literals. Returning `nil` sends no result. Throwing reports a failure to the agent. Handlers do not run on the main actor; mark the closure `@MainActor` to touch the UI.

## Audio

LiveKit configures, activates, and deactivates your app's audio session by itself as a call's audio starts and stops. The SDK does not touch activation. It states a route preference, and when the call ends it puts the session's category, mode, and options back to what your app had before the call. LiveKit leaves the call category behind, and other audio in your app would otherwise play quieter and ignore the silent switch.

During a call the session is `playAndRecord`, in video-chat mode on the speaker and voice-chat mode on the receiver. If your app plays other audio, expect its audio session to be reconfigured for the length of a call. The SDK does not activate the session again afterwards: an app that was playing starts its playback again itself.

## Troubleshooting

| Symptom | Cause and fix |
| - | - |
| The package does not resolve | Xcode is older than 16.3 |
| The app is ended when a call starts | `NSMicrophoneUsageDescription` is missing from `Info.plist` |
| `mic_permission_denied` | The user refused the microphone. iOS does not ask twice: send them to Settings |
| `ConversationUsageError.callAlreadyActive` | Only one call runs per app. End the other call, or use one `Conversation` for the app |
| A public agent fails with `origin_forbidden` | The agent restricts origins. Pass `origin`, matching one of its allowed origins exactly (scheme, host, and port) |
| The token request fails on an iPhone | `localhost` is the phone. Use your computer's LAN address, and allow local networking or use HTTPS. On the first run iOS also asks whether the app may reach the local network; until that is allowed, requests to it fail as if the phone were offline. Add `NSLocalNetworkUsageDescription` to explain the prompt |
| The call stops in the background | The `audio` background mode is missing from `Info.plist` |

## Going further

> [card] [React Native SDK](https://docs.fish.audio/agents/deploy/react-native.md)
>
> The same call in a React Native or Expo app.

> [card] [Client tools](https://docs.fish.audio/agents/build/client-tools.md)
>
> Let the agent call functions in your app.

> [card] [Authenticated sessions](https://docs.fish.audio/agents/deploy/authenticated-sessions.md)
>
> Create session tokens on your backend.

> [card] [Wire protocol](https://docs.fish.audio/agents/deploy/protocol.md)
>
> What the SDK speaks underneath.


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