---
name: behavr
description: Add persistent visual memory to an app with the BEHAVR API. Use when users upload screenshots, receipts, product photos, photos of documents or short videos and the app must answer questions about them later.
---

If you fetched this page through a tool that summarizes, download the raw file with curl and read it fully before writing code.

# BEHAVR setup guide for AI coding agents

BEHAVR is a visual memory API. `remember()` stores an image or video. `ask()` answers questions about everything stored. No vector database, vision pipeline or embedding code is needed.

This guide covers images and video and matches `behavr-sdk` 0.4.0. Follow the steps below in order. Do not invent function names or options. Only use what is listed here.

## When to use BEHAVR

Use it when the app lets users upload images, screenshots, receipts, product photos, photos of documents or short videos, and later needs to answer questions about them ("What was the invoice total?", "What did the customer upload?").

## When NOT to use BEHAVR

- The app only needs memory of text conversations. A text-memory tool fits better.
- The files are PDFs or other non-image documents. PDF is not supported (the API returns 422). Convert pages to images first.
- The images are small, low resolution or mostly tiny text. See Limits.

## Step 1. Get an API key

Ask the developer to create a key at https://behavr.in (Free plan: 50 images per month; video needs Starter or above). Never invent or hardcode a key.

Store it as an environment variable:

```
BEHAVR_API_KEY=their_key_here
```

Add `.env` to `.gitignore` if it is not already there. Never commit the key.

## Step 2. Install

Requires Node.js 18 or newer.

```bash
npm install behavr-sdk
```

## Step 3. Create the client

Keep the API key on the server side only. Never put it in browser code.

```ts
import { BehavrClient } from "behavr-sdk";

const behavr = new BehavrClient({ apiKey: process.env.BEHAVR_API_KEY! });
```

CommonJS also works: `const { BehavrClient } = require("behavr-sdk");`

## Step 4. Remember files where users upload

Find the place in the app where a user uploads a file, and call `remember()` there.

```ts
const remembered = await behavr.remember({
  file: uploadedFile,          // file path string, Buffer, { buffer, filename }, or Blob/File
  externalUserId: user.id,     // required if the app has more than one end user
  retainImage: false,          // optional, see below
});
// returns { memoryId, status, summary }, plus warnings (e.g. ["low_resolution"]) when the API sends any
```

`remember()` returns as soon as the file is uploaded, before processing finishes. `status` is usually `"queued"` at that point. Processing continues in the background, so the memory is not searchable yet (see "Processing is asynchronous").

Supported files:

- Images: JPG/JPEG, PNG, HEIC, WEBP.
- Video: MP4, MOV, AVI, MKV, WEBM. Requires a Starter plan or above (not included in Free). Duration: min 10 seconds, max 65 minutes.
- PDF is not supported.
- Max file size 500 MB (images and videos).

Videos use the same `remember()` call and return the same response shape. They take longer than images to process and become searchable.

### retainImage (optional)

Off by default. Without it, the uploaded photo is deleted after analysis and only the thumbnail and extracted text are kept. With `retainImage: true`, BEHAVR keeps a copy of the original photo that you can fetch later with `getOriginal()`.

- Photos only. Sending `retainImage: true` with a video fails with a 422 (`RETAIN_IMAGE_PHOTOS_ONLY`).
- JPEG, PNG and WebP originals are kept. Other formats (including HEIC) are analysed as usual, but the original is not kept.
- Retained uploads are limited to 25 MB (larger fails with a 413).
- Metadata such as EXIF (including GPS location) is stripped from the kept copy.
- Only turn it on if the app needs the original later. The developer is responsible for getting end users' consent before uploading their images and before turning on `retainImage`, and for deleting their memories when they ask.

### Scoping

Optional fields on `remember()`, `ask()` and `list()`: `externalUserId`, `clientId`, `agentId`. If `clientId` or `agentId` is omitted, BEHAVR uses `"default"`.

- If the app has more than one end user, always pass `externalUserId`. Without it, `ask()` searches every memory stored under that `clientId` and users get mixed together. A memory saved without `externalUserId` does not appear when you filter by a user later.
- `clientId` is a filter, not an access boundary. `ask()` and `list()` only read memories stored under the `clientId` you pass. It is controlled by your server and is not a separate credential. Never take `clientId` or `externalUserId` from untrusted client input.
- `getOriginal()` and `deleteMemory()` are scoped to the API key, not to `clientId`. They act on any memory under the key, whatever its `clientId`, `agentId` or `externalUserId`. Before calling them, check on your server that the caller owns the memory (for example, store `memoryId` next to your own user id when `remember()` returns).

## Step 5. Ask questions

```ts
const { answer, sources, sourceDetails } = await behavr.ask({
  question: "What did the customer upload?",
  externalUserId: user.id,     // same scope used in remember()
});
// returns { answer, sources, sourceDetails }, plus warnings and lowResolutionSources when the API sends them
```

- `sources`: every memory id that was in context for the answer, not only the ones it used.
- `sourceDetails`: up to 3 memories the answer says it used, as reported by the model. It may be incomplete, and is `[]` when there are none. Each entry is `{ memoryId, title, createdAt, category, snippet, hasOriginal, lowResolution }`.

Use the same `clientId`, `agentId` and `externalUserId` values in `ask()` that were used in `remember()`.

To list stored memories: `await behavr.list({ externalUserId, limit, status })` returns `{ memories, total }`. Each memory has `memoryId`, `title`, `category`, `thumbnailUrl`, `createdAt`, `sourceType`, `hasOriginal` (fields can be missing). `limit` defaults to 20 (max 100). `status` defaults to `"completed"`; pass `"failed"` or `"all"` to see others.

## Important: processing is asynchronous

`remember()` returns before processing finishes. BEHAVR then processes the file in the background. `ask()` only searches memories that have finished processing. If you ask too early, the answer says there are no completed captures yet.

Do not use a fixed sleep. Poll `list()` until the new `memoryId` shows up as completed, with a timeout:

```ts
async function waitUntilReady(memoryId: string, externalUserId?: string, timeoutMs = 90000) {
  const start = Date.now();
  while (Date.now() - start < timeoutMs) {
    const { memories } = await behavr.list({ externalUserId, status: "completed", limit: 100 });
    if (memories.some((m) => m.memoryId === memoryId)) return true;
    await new Promise((r) => setTimeout(r, 3000));
  }
  return false; // not ready yet, or it failed: check list({ status: "failed" })
}

const { memoryId } = await behavr.remember({ file: uploadedFile, externalUserId });
const ready = await waitUntilReady(memoryId, externalUserId);
```

Photos are usually ready in about 10-15 seconds; videos take longer. Treat that as a guide, not a guarantee: still poll `list()` rather than sleeping for a fixed time, and give videos a longer timeout. In UI, show a "processing" state instead of asking immediately after upload.

## Optional: fetch a retained original

Only works for memories uploaded with `retainImage: true` (`hasOriginal` is `true`).

```ts
const { url, expiresAt, expiresIn } = await behavr.getOriginal(memoryId, {
  expiresIn: 300, // optional, whole seconds; the API clamps it to 60-3600 (default 900)
});
```

`url` is a short-lived signed link. Anyone with it can download the file until it expires, so do not log it, store it or send it to anyone except the user who owns the photo. Check ownership first (see Scoping).

## Optional: delete a memory

```ts
const { memoryId: id, deleted, deletedMemories, deletedFiles } = await behavr.deleteMemory(memoryId);
```

Deletes one memory and the data BEHAVR derived from it, including its thumbnail and any retained original. Copies outside BEHAVR's live storage (such as infrastructure backups) are not covered by this call. Check ownership first (see Scoping).

- Deleting the same memory twice throws `MemoryNotFoundError`.
- A memory that is still processing can't be deleted yet: this throws `MemoryProcessingError` (409). Retry once it has completed or failed.
- A 500 with `err.code === "deletion_incomplete"` means the memory is already hidden but not fully removed. Repeat the call. The SDK does not retry on its own.

## Error handling

Failed requests throw `BehavrApiError` (or a subclass of it). Use `err.status` and `err.code` (a machine-readable code when the API sends one). `err.message` includes the API's message when there is one, otherwise a generic text such as "Failed to remember file." The raw response body is in `err.payload`.

Typed subclasses, all caught by `instanceof BehavrApiError`:

| Class | Status | `code` | Thrown by |
|---|---|---|---|
| `MemoryNotFoundError` | 404 | `memory_not_found` | `getOriginal`, `deleteMemory` |
| `OriginalNotAvailableError` | 404 | `original_not_available` | `getOriginal` |
| `OriginalPendingError` | 409 | `original_pending` | `getOriginal` |
| `MemoryProcessingError` | 409 | `memory_processing` | `deleteMemory` |

Anything else (for example `deletion_incomplete`, or a 503 `original_temporarily_unavailable`) is a plain `BehavrApiError` with `code` set.

```ts
import { BehavrApiError, OriginalPendingError, OriginalNotAvailableError } from "behavr-sdk";

try {
  const { url } = await behavr.getOriginal(memoryId);
} catch (err) {
  if (err instanceof OriginalPendingError) {
    // still being processed; try again shortly
  } else if (err instanceof OriginalNotAvailableError) {
    // no original was kept for this memory
  } else if (err instanceof BehavrApiError) {
    console.error(err.status, err.code, err.message);
  } else {
    throw err;
  }
}
```

| Status | Meaning |
|---|---|
| 401 | API key missing or invalid. Check `BEHAVR_API_KEY`. |
| 403 | The key is fine, but the plan limit is reached (monthly image limit) or the subscription expired. Do not regenerate the key. Show the message to the developer. |
| 404 | `getOriginal` / `deleteMemory`: no such memory under this key (or already deleted), or no retained original. |
| 409 | `getOriginal`: original still processing. `deleteMemory`: memory still processing. |
| 413 | File is larger than 500 MB, or larger than 25 MB with `retainImage: true`. |
| 422 | Unsupported file type (for example PDF), missing question, a reserved `clientId`, or `retainImage: true` with a video. |
| 429 | Rate limit. Wait and retry once, using the `Retry-After` header if present. Do not retry in a loop. |
| 500 | `deletion_incomplete` from `deleteMemory`: repeat the call. |

The SDK never retries requests on its own.

## Limits (be honest with the developer)

- Best results with images 640px or larger. Smaller images are accepted, but very small text can be read wrongly. Small images may be flagged, and an answer may end with a note that some sources are low resolution. If you see that note, tell the developer instead of presenting the answer as certain.
- Processing is asynchronous (see above).
- Video: Starter plan or above, 10 seconds to 65 minutes, up to 5 video uploads per hour per account. Video takes longer to process than images.
- Free plan: 50 images per month, no video. Paid plans: Starter $29, Pro $99. Details at https://behavr.in.

## Step 6. Verify the setup

After adding the code, run one test:

1. Call `remember()` with one clear test image (at least 640px).
2. Wait until it is ready with `waitUntilReady()` (or poll `list()`).
3. Call `ask()` with a question about that image.
4. Check that `answer` is sensible. Do not rely on `sources` to prove which file was used: it lists the memories given to the model as context, not only the ones the answer cites. `sourceDetails` is the model's own report and may be incomplete.

Tell the developer which files you changed and where `remember()` and `ask()` were added.

## Using BEHAVR through MCP instead

There is an MCP server, `behavr-mcp` on npm, for using BEHAVR from an AI tool directly instead of inside app code. It runs locally over stdio. It has setup instructions for Claude Code. Its Cursor config is untested, and hosted tools that cannot run local servers will not work with it. For app code, use the SDK above.

## Links

- Website and API keys: https://behavr.in
- SDK: https://www.npmjs.com/package/behavr-sdk
- MCP server: https://www.npmjs.com/package/behavr-mcp
