# Send a message

> Send the diner's message to the AI waiter and stream the reply as server-sent events: text, dish cards and the turn's end.

Source: https://tamr.link/docs/api/chat

`POST https://tamr.link/api/v1/chat`

One diner message, up to 2,000 characters. The reply streams as server-sent events: `message` events carry `start`, `text` (a `delta` to append) or `card` (everything the card shows), then `done`. New event types and card kinds arrive within v1: skip what you don't know and keep showing the text. Draw only what a card says; never work out a total, a nutrition figure or a fit yourself. See [Build your own chat](https://tamr.link/docs/guides/custom-chat).

## Authentication

**Client API.** Send your publishable key in `x-tamr-key` and the diner's session in `x-tamr-session`, from [Start a session](https://tamr.link/docs/api/start-session). For a guest's session, also send its device id in `x-tamr-device`. A browser may call it only from an origin listed on the key.

## Headers

| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `x-tamr-device` | string | No | Guest sessions only: the device id the session was exchanged with. Matches `^[A-Za-z0-9_-]{8,128}$`. |
| `x-tamr-app` | string | No | Native apps only: the app's iOS bundle id or Android package name. A key used from an app it doesn't list is logged, never refused. Matches `^[A-Za-z][A-Za-z0-9_-]*(\.[A-Za-z0-9_-]+)+$`. |

## Request body

A [ChatRequest](https://tamr.link/docs/api/schemas#chatrequest).

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `message` | string | Yes | 1 to 2,000 characters. |
| `conversationId` | string | No | 1 to 200 characters. |
| `branch` | string | No | An address: lower-case letters, digits and dashes. |
| `mode` | string | No | One of `dine_in`, `pickup`, `delivery`. |
| `table` | string | No | 1 to 40 characters. |
| `locale` | string | No | A language tag, such as `ar` or `en-GB`. |
| `restrictions` | object | No |  |
| `restrictions.avoidAllergens` | array of string | Yes | At most 10 items. Each: One of `gluten`, `dairy`, `egg`, `nuts`, `sesame`, `soy`, `fish`, `shellfish`, `peanut`, `mustard`. |
| `restrictions.keepDiets` | array of string | Yes | At most 8 items. Each: One of `vegan`, `vegetarian`, `gluten_free`, `halal`, `kosher`, `dairy_free`, `nut_free`, `keto`. |
| `cart` | array of object | No | At most 50 items. |
| `cart[].dishId` | string | Yes | 1 to 200 characters. |
| `cart[].variantId` | string | No | 1 to 200 characters. |
| `cart[].optionIds` | array of string | No | At most 20 items. 1 to 200 characters. |
| `cart[].quantity` | integer | Yes | 1 to 99. |
| `cart[].picks` | array of object | No | At most 120 items. |
| `cart[].picks[].pickId` | string | Yes | 1 to 200 characters. |
| `cart[].picks[].count` | integer | Yes | 1 to 20. |
| `goal` | object | No |  |
| `goal.mode` | string | Yes | One of `cutting`, `maintain`, `bulking`. |
| `goal.kcal` | integer | No | Calories for one meal: a ceiling when cutting or maintaining, a floor when bulking. 100 to 3,000. |
| `goal.proteinGrams` | integer | No | Grams of protein for one meal, always a floor. 5 to 300. |
| `takes` | array of string | No | At most 16 items. Matches `^[a-z][a-z_.]{0,47}$`. |
| `hide` | object | No |  |
| `hide.retailSuggestions` | boolean | No |  |
| `hide.loyalty` | boolean | No |  |
| `cardActions` | array of object | No | At most 6 items. |
| `cardActions[].tool` | `"offer_to_order"` | Yes |  |
| `cardActions[].offeredAt` | string | Yes | At most 40 characters. |
| `cardActions[].outcome` | `"added"` | Yes |  |
| `cardActions[].lines` | array of object | Yes | 1 to 8 items. |
| `cardActions[].lines[].dishId` | string | Yes | 1 to 200 characters. |
| `cardActions[].lines[].quantity` | integer | Yes | 1 to 99. |
| `cardActions[].lines[].size` | string or null | No | At most 80 characters. |

## Response

The reply streams as server-sent events (`text/event-stream`), each an `event:` line and a `data:` line of JSON.

| Event | `data` | What it says |
| --- | --- | --- |
| `message` | [ChatEvent](https://tamr.link/docs/api/schemas#chatevent) | A `start` (the conversation and message ids), a `text` (a `delta` to append) or a `card` (a card to draw). |
| `done` | [ChatDone](https://tamr.link/docs/api/schemas#chatdone) | How the turn ended. |
| `error` | any | The turn failed after it started. |

## Example

curl:

```bash
curl -N https://tamr.link/api/v1/chat \
  -H "x-tamr-key: $TAMR_APP_KEY" \
  -H "x-tamr-session: $TAMR_SESSION" \
  -H "content-type: application/json" \
  -d '{
  "message": "Something light without dairy?"
}'
```

Node:

```js
import { createClient } from "@tamr/api";

const tamr = createClient({ appKey: process.env.TAMR_APP_KEY });
// Sign the diner in first, with a token your backend signed (or a launch code).
await tamr.startSession({ token: dinerToken });

for await (const event of tamr.chat({ message: "Something light without dairy?" })) {
  if (event.event === "message" && event.data.type === "text") {
    process.stdout.write(event.data.delta);
  }
  if (event.event === "message" && event.data.type === "card") {
    console.log(event.data.card);
  }
}
```

Python:

```python
import os

import requests

API = "https://tamr.link/api/v1"
headers = {
    "x-tamr-key": os.environ["TAMR_APP_KEY"],
    "x-tamr-session": os.environ["TAMR_SESSION"],  # from POST /api/v1/sdk/session
}

with requests.post(
    f"{API}/chat",
    headers=headers,
    json={"message": "Something light without dairy?"},
    stream=True,
    timeout=60,
) as response:
    response.raise_for_status()
    # Server-sent events: an event: line, then a data: line of JSON.
    for line in response.iter_lines(decode_unicode=True):
        if line.startswith("data: "):
            print(line[len("data: "):])
```

## Example response

text/event-stream:

```text
event: message
data: {"type":"start","conversationId":"cmconv0001","messageId":"msg_01"}

event: message
data: {"type":"text","delta":"Try the grilled halloumi"}

event: message
data: {"type":"card","cardId":"call_01","card":{"kind":"dishes","layout":"carousel","framing":"Two light ones","dishes":[{"dishId":"cmdish0001","name":"Grilled halloumi","price":"1200","currency":"USD","imageUrl":"https://tamr.link/image-proxy/media/halloumi.webp","calories":420,"proteinGrams":24,"carbsGrams":8,"fatGrams":31,"allergens":["dairy"],"dietaryTags":["vegetarian"],"available":true,"externalId":"SKU-HALLOUMI"},{"dishId":"cmdish0002","name":"Mint lemonade","price":"400","currency":"USD","imageUrl":null,"calories":null,"proteinGrams":null,"carbsGrams":null,"fatGrams":null,"allergens":[],"dietaryTags":["vegan","a-tag-from-later"],"available":true,"externalId":null}]}}

event: done
data: {"finishReason":"stop"}
```

## Errors

Every error has the same body; switch on `data.code`. See [Errors and rate limits](https://tamr.link/docs/errors).

| `data.code` | Status | What to do |
| --- | --- | --- |
| `app_key_invalid` | 401 | The key is wrong, revoked or of another kind. Check it in the dashboard. |
| `sdk_disabled` | 403 | The SDK isn't switched on for this restaurant. Ask Tamr. |
| `origin_not_allowed` | 403 | A browser called from an origin the key doesn't list. Add the origin to the key. |
| `session_expired` | 401 | Start a new session with a fresh token or code, then send the call again once. |
| `invalid_request` | 400 | A field doesn't match the spec. The message says which. |
| `rate_limited` | 429 | Wait `retryAfter` seconds (also in the `Retry-After` header), then try again. |
| `message_rejected` | 422 | The message was refused (too long, or not about the restaurant). Show the message. |
| `menu_unavailable` | 404 | No published menu is served at that branch and service mode. |
| `not_found` | 404 | Not this diner's, or doesn't exist. The two read the same on purpose. |
| `test_limit_reached` | 429 | A test key's 50 conversations for the day are spent. Try again tomorrow, or use a live key. |
| `max_turns_reached` | 429 | The conversation is as long as it may be. Start a new one. |
| `after_hours_closed` | 503 | The location takes no conversations now. Show the message: the restaurant may have written it. |
| `waiter_resting` | 503 | The restaurant has paused its waiter. Show the message. |
| `unavailable` | 503 | Tamr can't serve this now. Try again later. |
