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

# Start calls with the Web SDK

> Start calls from a page with a public key, or with a call token your server gets with a secret key. Pass values, keep callers on one A/B version, ask for the microphone, and handle a call that can't start.

A call needs permission to start. The Web SDK gets it in one of two ways: with a **public key** in your page, or with a **call token** your server gets for each call.

## Public key or call token?

| | Public key in the page | Call token from your server |
| - | - | - |
| What you need | A public key (`pk_…`) | A secret key (`sk_…`) on your server, and an endpoint that returns a token |
| What the call runs | What the key's environment serves | What your server asks for: an environment, a version or a draft |
| Use it when | Your site calls one environment, which is most sites | You choose per call, or you only let signed-in users call |

Never put a secret key in a page. The SDK refuses one in a browser.

## With a public key

```javascript theme={null}
const agent = new HamsaVoiceAgent({ publicKey: "pk_..." });

agent.start({ agentId: "YOUR_AGENT_ID" });
```

`start()` gets a call token with the key and starts the call with it. The key can only start calls, in the one environment it was made for, so it's safe to leave in the page. Use the staging key on your staging site and the prod key on your live site.

A public key can't choose a version or an environment: `versionRef` and `environmentId` are refused with it.

## With a call token from your server

Your server asks Hamsa for a token with its secret key, and the page asks your server for one each time a call starts. A token starts one call and lasts about 30 seconds.

```javascript theme={null}
// Your server (Node.js), with the secret key in an environment variable
app.post("/hamsa/call-token", async (req, res) => {
  const reply = await fetch("https://api.tryhamsa.com/v1/voice-agents/call-token", {
    method: "POST",
    headers: {
      Authorization: `Token ${process.env.HAMSA_SECRET_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ voiceAgentId: "YOUR_AGENT_ID" }),
  });
  res.json((await reply.json()).data); // { callToken, expiresAt, resolved }
});
```

```javascript theme={null}
// Your page, holding no key
const agent = new HamsaVoiceAgent();

agent.start({
  agentId: "YOUR_AGENT_ID",
  callToken: () =>
    fetch("/hamsa/call-token", { method: "POST" })
      .then((r) => r.json())
      .then((d) => d.callToken),
});
```

* `/hamsa/call-token` is your own endpoint, not Hamsa's. Protect it the way you protect the rest of your app, for example by letting only signed-in users call it.
* Pass a function, as above, rather than a token you fetched earlier. The SDK calls it as the call starts, so the token is still fresh.
* `callToken` also takes the token itself, if the page already has one.
* With no `environmentId` or `versionRef`, the call runs what prod serves.

What your server can send when it asks for the token:

| Field | What it does |
| - | - |
| `voiceAgentId` | Required. The agent to call. |
| `environmentId` | Run what that environment serves. |
| `versionRef` | Run a version: a version ID, `draft`, or `draft:<draftId>`. |
| `callerKey` | Keep the caller on one side of an A/B test (see below). |
| `isChatOnly` | `true` for a [chat](https://docs.tryhamsa.com/developers/sdks/web-sdk/chat.md). |

The token decides the agent, version and environment, so the page doesn't send `versionRef` or `environmentId` next to it. See [Create a call token](https://docs.tryhamsa.com/api-reference/endpoint/create-call-token.md) for the full API.

## Pass values to the agent

`params` fill the agent's [variables](https://docs.tryhamsa.com/agents/variables/dynamic-variables.md). Each key is a variable name: letters, digits and underscores, not starting with a digit.

```javascript theme={null}
agent.start({
  agentId: "YOUR_AGENT_ID",
  params: { customer_name: "Sara", order_id: "A-1042" },
});
```

## Keep a caller on one version during an A/B test

While an agent's prod runs an [A/B test](https://docs.tryhamsa.com/agents/release/ab-tests.md), each call gets a version by weight. Phone callers stay on one side by their number. A web call has no number, so pass `callerKey`: an ID for the person that stays the same across visits, such as your own user ID (1 to 200 characters, never a secret).

```javascript theme={null}
agent.start({
  agentId: "YOUR_AGENT_ID",
  callerKey: currentUser.id,
});
```

Without it, each web call is assigned on its own. With call tokens, send `callerKey` to your server's token request too.

## Ask for the microphone first

Ask for the microphone before you start the call, so you can explain what to do if the visitor says no:

```javascript theme={null}
async function microphoneAllowed() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    stream.getTracks().forEach((track) => track.stop()); // the SDK opens its own
    return true;
  } catch {
    return false;
  }
}

button.addEventListener("click", async () => {
  if (!(await microphoneAllowed())) {
    status.textContent = "Allow the microphone in your browser to talk to us.";
    return;
  }
  agent.start({ agentId: "YOUR_AGENT_ID" });
});
```

If you don't, and the visitor refuses the microphone, the call still connects without their voice and `error` fires. End it with `agent.end()`.

A [chat](https://docs.tryhamsa.com/developers/sdks/web-sdk/chat.md) never asks for the microphone.

## If a call fails to start

If Hamsa refuses the call, `error` fires with a `HamsaApiError`. It has a `message` that says what to do, plus:

| Field | What it is |
| - | - |
| `messageKey` | Which refusal it is (below). |
| `status` | The HTTP status. |
| `params` | Details, such as `params.environment` with `EnvironmentNotDeployed`. |
| `retryAfter` | Seconds to wait, with `ApiKeyRateLimited`. |

| `messageKey` | What it means |
| - | - |
| `EnvironmentNotDeployed` | The key's environment runs nothing for this agent yet. Publish a version there. |
| `KeyNotForAgent` | The key is limited to other agents. |
| `ApiKeyRateLimited` | Too many calls started with this key in a minute. Wait `retryAfter` seconds. |
| `KeyRotated` | The key's value was replaced. Use the current one from the API keys page. |
| `PublicKeyFixedEnvironment` | `versionRef` or `environmentId` was passed with a public key. |
| `CallTokenSessionOnly` | This key can't start calls from a page. Use a public key. |
| `CallTokenInvalid` | The token was already used or expired. Get a new one for each call. |
| `CallTokenRequired` | An older API key asked for a version or an environment. Use a public key, or a call token. |

```javascript theme={null}
import { HamsaApiError } from "@hamsa-ai/voice-agents-sdk";

agent.on("error", (error) => {
  if (error instanceof HamsaApiError && error.messageKey === "ApiKeyRateLimited") {
    status.textContent = `Busy. Try again in ${error.retryAfter ?? 30} seconds.`;
    return;
  }
  status.textContent = error.message;
});
```

Other problems arrive the same way as a plain `Error`: the network, your `callToken` function failing or returning nothing, or a `callerKey` that isn't 1 to 200 characters.

With no `error` listener, `start()` rejects instead, so `try { await agent.start(...) } catch (error) { ... }` works too.

Mistakes in your code throw straight away from `new HamsaVoiceAgent(...)`: a secret key in a browser, a `publicKey` that doesn't start with `pk_`, or a public key passed where an older API key goes.

## Let the agent use your page

The agent can call functions in your page during the call, such as reading the cart or opening a product. Pass them in `tools` with `voiceEnablement: true`. See [Web tools](https://docs.tryhamsa.com/agents/tools/web-tools.md).

## Related

> [card] [API keys](https://docs.tryhamsa.com/overview/create-api-keys.md)
>
> Create public and secret keys, and limit them to agents and domains.

> [card] [During a call](https://docs.tryhamsa.com/developers/sdks/web-sdk/during-a-call.md)
>
> End, pause, mute and more once the call has started.


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