> ## 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.

# My First Agent

> Build a browser voice agent in about 10 minutes: a Vite page with a Start button, a tiny Node.js backend that mints ws-tickets so the API key stays off the page, status and a live transcript

This guide walks you through building your first voice agent in under 10 minutes. You will create a web page with a single button that starts a conversation, shows the agent's status, and displays the transcript in real time.

## What you will build

A web page with:

* A **Start** button that requests microphone permission and connects to Lokutor
* A **status indicator** that shows whether the agent is listening, thinking, or speaking
* A **transcript panel** that displays what the user said and what the agent replied

## Prerequisites

* An API key from [app.lokutor.com](https://app.lokutor.com)
* A modern browser with microphone support (Chrome, Firefox, Edge, Safari)
* Node.js 22 or later

## Step 1: Create the project

```bash theme={null}
npm create vite@latest my-first-agent -- --template vanilla-ts
cd my-first-agent
npm install @lokutor/sdk
```

The API key never goes into the page. A small backend exchanges it for a short-lived ticket, and the page asks the backend for one each time it connects ([Secure browser setup](https://docs.lokutor.com/guides/secure-browser-setup.md)).

Create `server.mjs` next to `package.json`:

```javascript theme={null}
// server.mjs: run with LOKUTOR_API_KEY=sk_... node server.mjs
import http from 'node:http';

http.createServer(async (req, res) => {
  if (req.method !== 'POST' || req.url !== '/api/lokutor-ticket') {
    res.writeHead(404).end();
    return;
  }
  // In a real app, check the user's session here before minting a ticket.
  const r = await fetch('https://api.lokutor.com/ws-ticket', {
    method: 'POST',
    headers: { Authorization: `Bearer ${process.env.LOKUTOR_API_KEY}` },
  });
  res.writeHead(r.ok ? 200 : 502, { 'Content-Type': 'application/json' });
  res.end(await r.text()); // {"ticket":"wst_…","expires_in":600}
}).listen(3001);
```

Create `vite.config.ts` so the page can reach it during development:

```typescript theme={null}
import { defineConfig } from 'vite';

export default defineConfig({
  server: { proxy: { '/api': 'http://localhost:3001' } },
});
```

## Step 2: Write the HTML

Replace `index.html` with:

```html theme={null}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>My First Agent</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 600px; margin: 40px auto; padding: 0 20px; }
    #status { font-weight: bold; padding: 8px 16px; border-radius: 8px; display: inline-block; margin-bottom: 16px; }
    .listening { background: #dbeafe; color: #1e40af; }
    .thinking { background: #fef3c7; color: #92400e; }
    .speaking { background: #d1fae5; color: #065f46; }
    .disconnected { background: #f3f4f6; color: #6b7280; }
    #transcript { border: 1px solid #e5e7eb; border-radius: 8px; padding: 16px; min-height: 200px; }
    .message { margin-bottom: 12px; }
    .user { color: #1e40af; }
    .agent { color: #065f46; }
    button { padding: 12px 24px; font-size: 16px; cursor: pointer; border-radius: 8px; border: none; background: #9e4851; color: white; }
    button:disabled { opacity: 0.5; cursor: not-allowed; }
  </style>
</head>
<body>
  <h1>My First Agent</h1>
  <button id="start">Start Conversation</button>
  <div id="status" class="disconnected">Disconnected</div>
  <div id="transcript"></div>
  <script type="module" src="/src/main.ts"></script>
</body>
</html>
```

## Step 3: Write the agent logic

Replace `src/main.ts` with:

```typescript theme={null}
import { VoiceAgentClient, VoiceStyle, Language } from '@lokutor/sdk';

const startBtn = document.getElementById('start') as HTMLButtonElement;
const statusEl = document.getElementById('status') as HTMLDivElement;
const transcriptEl = document.getElementById('transcript') as HTMLDivElement;

async function getTicket(): Promise<string> {
  const res = await fetch('/api/lokutor-ticket', { method: 'POST' });
  if (!res.ok) throw new Error('Could not get a ticket');
  return (await res.json()).ticket;
}

const client = new VoiceAgentClient({
  auth: getTicket, // called before every connect and reconnect
  prompt: 'You are a helpful and friendly AI assistant. Keep your answers short and conversational.',
  voice: VoiceStyle.F1,
  language: Language.ENGLISH,
});

client.on('transcription', (text: string) => {
  addMessage('user', text);
});

client.on('response', (text: string) => {
  addMessage('agent', text);
});

client.on('status', (status: string) => {
  statusEl.textContent = status;
  statusEl.className = status;
});

client.on('error', (error: any) => {
  console.error('Agent error:', error);
  statusEl.textContent = 'Error';
  statusEl.className = 'disconnected';
});

startBtn.addEventListener('click', async () => {
  startBtn.disabled = true;
  startBtn.textContent = 'Connecting...';

  try {
    await client.startManaged();
    startBtn.textContent = 'Connected';
  } catch (err) {
    console.error('Failed to start:', err);
    startBtn.disabled = false;
    startBtn.textContent = 'Start Conversation';
  }
});

function addMessage(role: 'user' | 'agent', text: string) {
  const div = document.createElement('div');
  div.className = `message ${role}`;
  div.textContent = role === 'user' ? `You: ${text}` : `Agent: ${text}`;
  transcriptEl.appendChild(div);
  transcriptEl.scrollTop = transcriptEl.scrollHeight;
}
```

## Step 4: Run it

In one terminal:

```bash theme={null}
LOKUTOR_API_KEY=sk_your_key_here node server.mjs
```

In another:

```bash theme={null}
npm run dev
```

Open `http://localhost:5173` in your browser, click **Start Conversation**, and speak into your microphone.

## How it works

1. `startManaged()` requests microphone permission, calls `getTicket()`, and opens a WebSocket to Lokutor with the ticket
2. The SDK sends your configuration (prompt, voice, language) to the server
3. When you speak, the SDK streams microphone audio to the server
4. The server cleans the audio, detects the end of your turn, transcribes it, asks the language model, and streams the spoken reply back
5. The SDK plays the audio and emits events for transcription, response, and status

## Next steps

* Run an agent you built in the dashboard instead: replace `prompt`, `voice` and `language` with `agentId: 'your-agent-id'`. See [Voice Agent](https://docs.lokutor.com/sdk/agent.md#running-a-dashboard-agent).
* Give your agent **tools** so it can fetch data from your systems. See [Tool Calling](https://docs.lokutor.com/sdk/tool-calling.md).
* Handle **interruptions**. See [Handling Interruptions](https://docs.lokutor.com/guides/handling-barge-in.md).
* Put the agent on a **phone number**. See [Phone agent quickstart](https://docs.lokutor.com/guides/phone-agent-quickstart.md).
* Understand where the **latency** goes. See [Latency](https://docs.lokutor.com/guides/latency-optimization.md).

More examples are in the SDK repository: [github.com/lokutor-ai/lokutor-sdk](https://github.com/lokutor-ai/lokutor-sdk) (`js/examples`).


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