# Mobile apps

> Put a voice call with your agent, and a chat beside it, in your own iOS or Android app.

The mobile SDKs do in an app what `@aigently/web` does in a page ([Browser calls](/guides/browser-calls)):
your server starts a call and your app joins it, and a chat runs on the agent's own widget session.
The calls, the states and the rules are the same.

## Start the call on your server

**curl**

```sh
#!/bin/sh
# Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
curl -sS --fail-with-body -X POST "https://api.aigently.ai/v1/web-calls" \
  -H "Authorization: Bearer $AIGENTLY_API_KEY" \
  -H "Idempotency-Key: visit-20931" \
  --json '{
  "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
  "variables": {
    "first_name": "Sara"
  },
  "metadata": {
    "session": "S-20931"
  }
}'
```

**JavaScript**

```js
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
const response = await fetch("https://api.aigently.ai/v1/web-calls", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.AIGENTLY_API_KEY}`,
    "Content-Type": "application/json",
    "Idempotency-Key": "visit-20931",
  },
  body: JSON.stringify({
    "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
    "variables": {
      "first_name": "Sara"
    },
    "metadata": {
      "session": "S-20931"
    }
  }),
});
const answer = await response.json();
if (!response.ok) throw new Error(`${answer.code}: ${answer.detail}`);
console.log(answer);
```

**Python**

```python
# Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
# pip install httpx
import os

import httpx

response = httpx.post(
    "https://api.aigently.ai/v1/web-calls",
    headers={
        "Authorization": f"Bearer {os.environ['AIGENTLY_API_KEY']}",
        "Idempotency-Key": "visit-20931",
    },
    json={
        "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
        "variables": {
            "first_name": "Sara",
        },
        "metadata": {
            "session": "S-20931",
        },
    },
)
if response.is_error:
    raise SystemExit(response.text)
print(response.json())
```

**Go**

```go
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
)

func main() {
	payload := []byte(`{
  "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
  "variables": {
    "first_name": "Sara"
  },
  "metadata": {
    "session": "S-20931"
  }
}`)
	request, err := http.NewRequest("POST", "https://api.aigently.ai/v1/web-calls", bytes.NewReader(payload))
	if err != nil {
		panic(err)
	}
	request.Header.Set("Authorization", "Bearer "+os.Getenv("AIGENTLY_API_KEY"))
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Idempotency-Key", "visit-20931")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	body, _ := io.ReadAll(response.Body)
	if response.StatusCode >= 400 {
		fmt.Fprintln(os.Stderr, string(body))
		os.Exit(1)
	}
	fmt.Println(string(body))
}
```

**Java**

```java
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    public static void main(String[] args) throws Exception {
        String body = """
            {
              "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
              "variables": {
                "first_name": "Sara"
              },
              "metadata": {
                "session": "S-20931"
              }
            }
            """;
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.aigently.ai/v1/web-calls"))
            .header("Authorization", "Bearer " + System.getenv("AIGENTLY_API_KEY"))
            .header("Content-Type", "application/json")
            .header("Idempotency-Key", "visit-20931")
            .method("POST", HttpRequest.BodyPublishers.ofString(body))
            .build();
        // HTTP/1.1: on a plain-http address Java's default asks to upgrade, which not every
        // server allows.
        HttpClient client = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build();
        HttpResponse<String> response =
            client.send(request, HttpResponse.BodyHandlers.ofString());
        if (response.statusCode() >= 400) {
            System.err.println(response.body());
            System.exit(1);
        }
        System.out.println(response.body());
    }
}
```

**C#**

```csharp
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
using System.Net.Http.Headers;
using System.Text;

using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("AIGENTLY_API_KEY"));
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.aigently.ai/v1/web-calls")
{
    Content = new StringContent(
        """
        {
          "agent_id": "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
          "variables": {
            "first_name": "Sara"
          },
          "metadata": {
            "session": "S-20931"
          }
        }
        """,
        Encoding.UTF8,
        "application/json"),
};
request.Headers.Add("Idempotency-Key", "visit-20931");
var response = await client.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
    Console.Error.WriteLine(body);
    return 1;
}
Console.WriteLine(body);
return 0;
```

**PHP**

```php
<?php
// Start a browser call for your page. From your server, with a live key: give the page the url and token, and it joins with @aigently/web.
$curl = curl_init("https://api.aigently.ai/v1/web-calls");
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . getenv("AIGENTLY_API_KEY"),
        "Content-Type: application/json",
        "Idempotency-Key: visit-20931",
    ],
    CURLOPT_POSTFIELDS => json_encode([
        "agent_id" => "3c7d9e1f-5a2b-4c6d-8e0f-1a3b5c7d9e2f",
        "variables" => [
            "first_name" => "Sara",
        ],
        "metadata" => [
            "session" => "S-20931",
        ],
    ]),
]);
$body = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) >= 400) {
    fwrite(STDERR, $body . "\n");
    exit(1);
}
echo $body, "\n";
```

This is the same request as for a browser call. It needs `calls:write` and a **live key**, which
stays on your server: never put an API key in an app. The answer's `url` and `token` go to the app,
and the token joins this one call for 15 minutes.

## Join it from an iOS app

```swift
import Aigently

// Your own endpoint, which calls POST /v1/web-calls and returns url and token.
let credentials = try await yourServer.startCall()

let call = try await joinCall(credentials, handlers: CallHandlers(
    onState: { state in print(state) },
    onTranscript: { line in print(line.speaker, line.text) }
))
```

It needs iOS 13 or macOS 10.15, and Xcode 16.3 or later. Add `NSMicrophoneUsageDescription` to your
Info.plist: the first call asks for the microphone, and a person who refuses gets a call that ends
at once. For SwiftUI, `WebCallModel` holds a call as state and hangs up when it goes away.

## Join it from an Android app

```kotlin
import ai.aigently.*

// Your own endpoint, which calls POST /v1/web-calls and returns url and token.
val credentials = yourServer.startCall()

val call = joinCall(context, credentials, CallHandlers(
    onState = { state -> render(state) },
    onTranscript = { line -> show(line) },
))
```

It needs Android 5.0 (API 21) or later. Ask for `RECORD_AUDIO` before you join: a library cannot
show the permission prompt, and a call joined without it ends at once. For Compose,
`WebCallController` holds a call as state.

## What the call tells you

| State | What it means |
|---|---|
| connecting | Joining the call. |
| waiting | Joined; the agent is getting ready. |
| listening | The agent is listening. |
| thinking | The agent is working out what to say. |
| speaking | The agent is talking. |
| ended | The call is over. |

Each transcript line has a speaker, you or the agent, and grows while it is spoken, then arrives
once more as final. Keep the latest copy of each line by its id: `Transcript` does this on both
platforms. The agent's audio plays by itself.

## A chat

```swift
let chat = try await startChat(ChatOptions(
    agentId: "8a1f3c2e-…",
    publishableKey: "pk_…",
    origin: "https://www.aigently.ai"
))
let answer = try await chat.send("When do you open?")
```

```kotlin
val chat = startChat(ChatOptions(
    agentId = "8a1f3c2e-…",
    publishableKey = "pk_…",
    origin = "https://www.aigently.ai",
))
val answer = chat.send("When do you open?")
```

A chat uses the agent's **publishable key**, the one in your widget snippet. **An app names the site
it speaks for**: the platform opens a chat only for a domain listed under **Allow your domains** on
the agent's Connect tab, and it reads that domain from the request's `Origin` header, which a
browser sends and an app does not. Pass one of the listed domains, usually your own website's, as
`origin`. Values a person could type go in `variables`, as text. Values your server vouches for go in
a signed `identity` token, as for the [widget](/guides/widget-identity).

## Getting the SDKs

The mobile SDKs will be published with our other SDKs. Until then, a call works with any LiveKit
client: join `url` with `token`, publish the microphone, and play the agent's audio.
