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

# Atlaso SDK

> Attach a user to each request, read what memory did, and save or delete facts, with the OpenAI client you already use.

The Atlaso SDK is optional. Your OpenAI client keeps making the model calls; the
SDK adds three things around it:

* **A user on each request**, never on a shared client, so one user's memory
  cannot reach another user.
* **A receipt for each call**: which memories went into the prompt, and the cost
  as a decimal string, or a reason when the cost is not known.
* **The [Memory API](https://docs.atlaso.ai/gateway/memory-api.md)** as methods: save, list, delete and
  erase, each with a clear outcome and safe retries.

It sends no separate telemetry requests. When the gateway lists your client line for
retirement, the library logs each distinct notice once by default. It never adds a
request field you did not set.

## Install

> [tab] TypeScript
>
> ```bash theme={null}
> npm install atlaso openai
> ```
>
> No runtime dependencies. Node 18 or newer, Bun or Deno, on your server.

> [tab] Python
>
> ```bash theme={null}
> pip install atlaso openai
> ```
>
> One dependency, `httpx`. Python 3.9 to 3.13.

Create a **Use only** key whose memory is for **Each user of my app** (see
[Keys](https://docs.atlaso.ai/gateway/keys.md)) and set it as `ATLASO_KEY` on your server, the same
variable the [Quickstart](https://docs.atlaso.ai/gateway/quickstart.md) uses. The SDK reads only that variable.

```bash theme={null}
export ATLASO_KEY='sk-at-...'
```

There is no variable for the address: pass `baseURL`
(TypeScript) or `base_url` (Python) in code, so a changed environment can never
send your users' IDs somewhere else.

## One shared client, a user per request

For each request, after your own sign-in check, call `forUser` (TypeScript) or
`for_user` (Python), then `openai()` on the result. It returns a cheap copy of
one shared OpenAI client with that user attached. The Atlaso object builds the
shared client on first use and reuses it, so every copy shares its connections;
the shared client never carries a user. In TypeScript, pass the OpenAI class
once: `new Atlaso({ OpenAI })`. `anthropic()` does the same for Anthropic.

### Example 1: first memory call

> [tab] Python
>
> ```python theme={null}
> from atlaso import Atlaso
>
> atlaso = Atlaso()                      # reads ATLASO_KEY
> user = atlaso.for_user("demo-user-42")   # one per request
>
> user.memory.add("My demo project is named Lantern and its launch day is Tuesday.")
> reply = user.openai().chat.completions.create(
>     model="openai/gpt-6.1-terra",
>     messages=[{"role": "user", "content": "What is my demo project called?"}],
> )
> print(reply.choices[0].message.content)
> ```

> [tab] TypeScript
>
> Save as `first.mjs` and run `node first.mjs` (Node 18 or newer):
>
> ```typescript theme={null}
> import OpenAI from "openai";
> import { Atlaso } from "atlaso";
>
> const atlaso = new Atlaso({ OpenAI });        // reads ATLASO_KEY
> const user = atlaso.forUser("demo-user-42");    // one per request
>
> await user.memory.add("My demo project is named Lantern and its launch day is Tuesday.");
> const reply = await user.openai().chat.completions.create({
>   model: "openai/gpt-6.1-terra",
>   messages: [{ role: "user", content: "What is my demo project called?" }],
> });
> console.log(reply.choices[0].message.content);
> ```

The question does not contain the fact. Atlaso recalls it for `demo-user-42`
and adds it to the prompt. The save retries an uncertain send by itself; see
[When a save is uncertain](#when-a-save-is-uncertain) for the rare case it
still cannot tell.

### See which memories the reply used

Ask for the raw response and read its receipt: the IDs of the facts put into
the prompt, and the cost.

> [tab] Python
>
> ```python theme={null}
> raw = user.openai().chat.completions.with_raw_response.create(
>     model="openai/gpt-6.1-terra",
>     messages=[{"role": "user", "content": "What is my demo project called?"}],
> )
> first = atlaso.read_receipt(raw)
> print(first.receipt.memory.memory_ids if first.receipt.memory else [])   # the saved fact's ID
> print(first.receipt.cost)                # state "known" and usd, the cost as a decimal string
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> const first = atlaso.readReceipt(
>   await user.openai().chat.completions.create({
>     model: "openai/gpt-6.1-terra",
>     messages: [{ role: "user", content: "What is my demo project called?" }],
>   }).withResponse(),
> );
> console.log(first.receipt.memory?.memoryIds);   // the saved fact's ID
> console.log(first.receipt.cost);                // state "known" and usd, the cost as a decimal string
> ```

[Example 3](#example-3-which-memories-a-reply-used) shows every receipt field.

### The safe pattern in a server

> [tab] Python
>
> ```python theme={null}
> def answer(user_id: str, question: str) -> str:
>     scoped = atlaso.for_user(user_id).openai()   # made for this request only
>     reply = scoped.chat.completions.create(
>         model="openai/gpt-6.1-terra",
>         messages=[{"role": "user", "content": question}],
>     )
>     return reply.choices[0].message.content
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> export async function answer(userId: string, question: string) {
>   const scoped = atlaso.forUser(userId).openai();   // made for this request only
>   const reply = await scoped.chat.completions.create({
>     model: "openai/gpt-6.1-terra",
>     messages: [{ role: "user", content: question }],
>   });
>   return reply.choices[0].message.content;
> }
> ```

### Bring your own client

To use an OpenAI client you configured yourself (your own timeouts, retries or
HTTP client), build it once from `client_options()` (Python) or
`clientOptions()` (TypeScript), without a user, and pass it per request:
`user.client(openai)`, or the same call as `user.openai(openai)`. Anthropic clients
go to `user.anthropic(client)`, built from `anthropic_options()` /
`anthropicOptions()`.

> [tab] Python
>
> ```python theme={null}
> from openai import OpenAI
>
> openai = OpenAI(**atlaso.client_options(), timeout=20)   # shared, no user on it
> reply = user.client(openai).chat.completions.create(
>     model="openai/gpt-6.1-terra",
>     messages=[{"role": "user", "content": "What is my demo project called?"}],
> )
> print(reply.choices[0].message.content)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> const openai = new OpenAI({ ...atlaso.clientOptions(), timeout: 20_000 });   // shared, no user on it
> const own = await user.client(openai).chat.completions.create({
>   model: "openai/gpt-6.1-terra",
>   messages: [{ role: "user", content: "What is my demo project called?" }],
> });
> console.log(own.choices[0].message.content);
> ```

> [!WARNING]
>
> **The dangerous pattern: a user on a shared client.** A client built once with
> an `x-atlaso-user` default header sends every request, for every user, as that
> user: one user's facts reach everyone. `client()` refuses such a client with a
> `ConfigurationError` whose code is `shared_client_has_user`. It also refuses a
> client that does not point at Atlaso (`client_not_gateway`), so a user ID is
> never sent to another service.

> [tab] Python
>
> ```python theme={null}
> from openai import OpenAI
>
> # Don't: this client would send every request as demo-user-42.
> shared_options = atlaso.client_options()
> shared_options["default_headers"] = {"x-atlaso-user": "demo-user-42"}
> shared = OpenAI(**shared_options)
> atlaso.for_user("demo-user-43").client(shared)   # raises shared_client_has_user
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> // Don't: this client would send every request as demo-user-42.
> const shared = new OpenAI({
>   ...atlaso.clientOptions(),
>   defaultHeaders: { "x-atlaso-user": "demo-user-42" },
> });
> atlaso.forUser("demo-user-43").client(shared);   // throws shared_client_has_user
> ```

If a framework gives you no client to copy, pass the user's headers on each
call instead: `user.headers()` returns `x-atlaso-user`, the optional library name/version header, and any options you set on
the scope (`memory`, `tags`, `sessionId` or `session_id`). The
[framework recipes](https://docs.atlaso.ai/gateway/framework-recipes.md) show this for each framework.

## Use it for yourself

Building something just for you? On the **API keys** page, create a key whose
**Memory for** is **Me** and export it as `ATLASO_KEY`. `atlaso.openai()` returns
the shared OpenAI client with no user on it, and its calls use your own memory:
the same facts your Atlaso tools save.

> [tab] Python
>
> ```python theme={null}
> from atlaso import Atlaso
>
> atlaso = Atlaso()   # a key whose memory is for "Me"
> reply = atlaso.openai().chat.completions.create(
>     model="openai/gpt-6.1-terra",
>     messages=[{"role": "user", "content": "Which units do I prefer?"}],
> )
> print(reply.choices[0].message.content)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import OpenAI from "openai";
> import { Atlaso } from "atlaso";
>
> const atlaso = new Atlaso({ OpenAI });   // a key whose memory is for "Me"
> const reply = await atlaso.openai().chat.completions.create({
>   model: "openai/gpt-6.1-terra",
>   messages: [{ role: "user", content: "Which units do I prefer?" }],
> });
> console.log(reply.choices[0].message.content);
> ```

`atlaso.anthropic()` does the same for Anthropic.

`atlaso.memory` saves, lists and deletes your own facts from code. It works with
the same **Me** key, as long as the key's memory is not **Off**:

> [tab] Python
>
> ```python theme={null}
> from atlaso import Atlaso
>
> atlaso = Atlaso()   # a key whose memory is for "Me"
> atlaso.memory.add("I prefer metric units.")
> fact = atlaso.memory.list().page().data[0]
> atlaso.memory.delete(fact.id)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Atlaso } from "atlaso";
>
> const atlaso = new Atlaso();   // a key whose memory is for "Me"
> await atlaso.memory.add("I prefer metric units.");
> const fact = (await atlaso.memory.list().page()).data[0];
> await atlaso.memory.delete(fact.id);
> ```

`atlaso.memory` also has `search`, `update` and `add_many` (`addMany` in
TypeScript), with the same results, retries and idempotency keys as
`user.memory`. A delete forgets the fact everywhere, your Atlaso tools included.
There is no erase: a key never deletes all of your memories at once, so use
**Delete all memories** on the dashboard for that. Every save, edit and delete
appears on the dashboard's Activity and Memory pages: rows from the SDK show an
"SDK" tag and direct web requests show "API". See
[Your own memory](https://docs.atlaso.ai/gateway/memory-api.md#your-own-memory).

With a key whose memory is for **Each user of my app**, a call without a user
goes out with no memory (the library logs a one-time notice that names
`for_user(id).openai()`), and `atlaso.memory` answers `memory_scope_per_user`.
With a **Me** key, do not use `for_user(id)`: a call that names a user is refused
with 403 `memory_scope_owner` and costs nothing, so your own memory never answers
for someone else.

## Model-name suggestions

Type a model ID for suggestions; new model strings still work. `ModelName`
offers the callable canonical IDs in the catalog at this library's release. TypeScript uses a literal union plus `string & {}`; Python uses
`Union[KnownModelName, str]`. Future names and strings loaded from configuration
still type-check and pass through unchanged. These suggestions do not validate a
request. For typo checking against this release, opt into `KnownModelName`.

Suggestions include live chat models from the main catalog and provider files.
Hidden rows, dedicated-only deployments and unsupported model kinds are excluded.
Models requiring account approval remain listed; availability depends on your key.
Constants list canonical IDs, not aliases or upstream-only names. Update the
library to refresh suggestions, or use a new model string immediately.

The AI SDK's `chat()` and `responses()` helpers and browser-token model lists use
these suggestions. Routing helpers accept provider names, not model names. Scoped
OpenAI and Anthropic clients retain their vendor types; use an annotated variable
or a generated constant with them:

```typescript theme={null}
import OpenAI from "openai";
import { Atlaso, type ModelName } from "atlaso";

const atlaso = new Atlaso({ OpenAI });
const model: ModelName = "openai/gpt-6.1-terra"; // suggestions appear as you type the ID
await atlaso.forUser("u1").openai().chat.completions.create({
  model, messages: [{ role: "user", content: "Hello" }],
});
```

```python theme={null}
from atlaso import Atlaso, ModelName

atlaso = Atlaso()
model: ModelName = "openai/gpt-6.1-terra"  # suggestions appear as you type the ID
atlaso.for_user("u1").openai().chat.completions.create(
    model=model, messages=[{"role": "user", "content": "Hello"}],
)
```

Python completion is checked against the Pyright language server; both mypy and
Pyright accept a plain `str` for `ModelName`. Pyright 1.1.408 offers the names
in annotated variables and function arguments, but not inside a nested
browser-token dictionary/list literal; annotate the model variable first there.
Mypy checks types but does not itself
provide editor completion. `KnownModelName` rejects unknown names in both checkers.

With `KnownModelName` in Python, mypy lists every known name (about 500) when a
string is not one of them. The start of that message shows the file, the line
and the string you typed: fix that string, or check a name at runtime with
`name in KNOWN_MODEL_NAMES`.

## Shared memory

Write a fact once for every app user in the key's project. Shared methods live
on `atlaso`, not on a user scope. Use a server key for a project with **Each
user of my app**. Shared routes refuse `x-atlaso-user` and browser tokens.

> [tab] Python
>
> ```python theme={null}
> from atlaso import Atlaso
>
> atlaso = Atlaso()  # server key; reads ATLASO_KEY
> saved = atlaso.shared.add("Support hours are 9am to 6pm IST, Monday to Friday.")
> if saved.outcome == "added":
>     raw = atlaso.for_user("u1").openai().chat.completions.with_raw_response.create(
>         model="openai/gpt-4o-mini",
>         messages=[{"role": "user", "content": "What are the support hours?"}],
>     )
>     memory = atlaso.read_receipt(raw).receipt.memory
>     print(memory.shared_ids if memory else [])
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Atlaso } from "atlaso";
> import OpenAI from "openai";
>
> const atlaso = new Atlaso({ OpenAI }); // server key; reads ATLASO_KEY
> const saved = await atlaso.shared.add("Support hours are 9am to 6pm IST, Monday to Friday.");
> if (saved.outcome === "added") {
>   const raw = await atlaso.forUser("u1").openai().chat.completions.create({
>     model: "openai/gpt-4o-mini",
>     messages: [{ role: "user", content: "What are the support hours?" }],
>   }).withResponse();
>   console.log(atlaso.readReceipt(raw).receipt.memory?.sharedIds);
> }
> ```

`add` sends an automatic idempotency key, or the one you pass as
`idempotencyKey` (TypeScript) or `idempotency_key` (Python). If you pass your
own key, make it random: a key derived from the text makes the stored key a keyed
hash of that text (the SDK's automatic keys are already random). A timeout or other
uncertain add returns `unknown` with the key it used; the SDK does not
automatically retry it. To resend safely, call `add` again with the same text
and that key within 24 hours: if the first add was saved, you get the same
fact back. If that fact was deleted, or all shared facts were deleted, the resend
returns `409 fact_replaced` with `replaced_by` null and saves nothing, also
when the first add ended in `unknown` or an error.
`delete` and `deleteAll()` (`delete_all()` in Python) can return
`pending`; call `resume()` to finish. Shared facts are limited to 1,000 per project.

Shared methods return their own types: `SharedFact` (`id`, `text`, `source`,
`createdAt` / `created_at`; no app-user label), `SharedAddResult` and
`SharedPage`, whose `total` is the project's shared fact count on every page
(null / `None` only if the gateway did not say). A per-user model call can
include at most three shared facts; the receipt reports their IDs in
`memory.sharedIds` (TypeScript) or `memory.shared_ids` (Python). See
[Shared memory](https://docs.atlaso.ai/gateway/memory.md#shared-memory-for-a-project).

Three codes refuse shared memory to something other than a server key:

| Code | Raised by | When |
| - | - | - |
| `shared_needs_server_key` | The SDK, before sending | You read `atlaso.shared` on a client made with a browser token. Nothing is sent. |
| `browser_token_not_allowed` | The gateway, HTTP 403 | A browser token reaches a shared route directly. The gateway's browser-token check refuses it before any shared check. |
| `shared_write_forbidden` | The gateway, HTTP 403 | Any other credential that is not a server key reaches the shared memory check. |

Owner-memory keys get `memory_scope_owner` and keys without a project get
`shared_needs_project`. See [Errors](https://docs.atlaso.ai/gateway/errors.md#shared_write_forbidden).

### Delete every shared fact

`deleteAll()` permanently deletes every shared fact in this key's project.
Python calls this method `delete_all()`. Run it only when you intend to remove
all of the project's shared facts. It leaves app users' own facts intact.

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Atlaso } from "atlaso";
>
> const atlaso = new Atlaso();
> console.log((await atlaso.shared.deleteAll()).outcome);
> ```

> [tab] Python
>
> ```python theme={null}
> from atlaso import Atlaso
>
> atlaso = Atlaso()
> print(atlaso.shared.delete_all().outcome)
> ```

Shared facts follow the same rule. After you delete a shared fact, or delete
all shared facts, a resend of the earlier add with the same key returns
`409 fact_replaced` with `replaced_by` null for the rest of that key's 24 hours,
and the fact does not come back. To add it again on purpose, call `add` with a
new key.

## Example 2: save, list and delete

> [tab] Python
>
> ```python theme={null}
> saved = user.memory.add("Prefers metric units")
> if saved.outcome == "unknown":
>     saved = user.memory.add("Prefers metric units", idempotency_key=saved.idempotency_key)  # same key, safe resend
>
> for memory in user.memory.list():   # newest first; pages for you
>     print(memory.id, memory.text)
>
> if saved.outcome == "added":
>     deleted = user.memory.delete(saved.memory.id)
>     print(deleted.outcome)        # "deleted", "already_gone" or "pending"
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> const saved = await user.memory.add("Prefers metric units");
> if (saved.outcome === "unknown") {
>   await user.memory.add("Prefers metric units", { idempotencyKey: saved.idempotencyKey }); // same key, safe resend
> }
>
> for await (const memory of user.memory.list()) {   // newest first; pages for you
>   console.log(memory.id, memory.text);
> }
>
> if (saved.outcome === "added") {
>   const deleted = await user.memory.delete(saved.memory.id);
>   console.log(deleted.outcome);   // "deleted", "already_gone" or "pending"
> }
> ```

| Call | Outcome | What it means |
| - | - | - |
| `add` | `added` | Saved. `memory` holds the stored fact. Its text can differ from what you sent, because recognised passwords, API keys and tokens are blacked out before storage. Other details, such as card or ID numbers, are saved as typed. |
| `add` | `unknown` | No clear answer. Reuse its `idempotency_key` (`idempotencyKey`) with the same text within 24 hours; `safe_to_repeat` (`safeToRepeat`) is true only with that same key. |
| `add` | `rejected` | Nothing was saved because an erase of this user is still running (`reason` is `erase_in_progress`). `safe_to_repeat` is true: add it again once the erase has finished. |
| `delete` | `deleted` / `already_gone` | Done. `already_gone` means the ID was not there. |
| `delete`, `erase` | `pending` | The server is still deleting. Call `resume()` to resend; it is safe. |
| `erase` | `erased` | Every fact of this user in this key's project is gone. It is not an account-wide deletion. See [Erase a user](#erase-a-user). |

In Python each outcome is its own type, so `if saved.outcome == "added": saved.memory.id`
type-checks under `mypy --strict`, as the TypeScript union does.

`list` pages for you. If the fact you paged from is deleted meanwhile, it raises
`CursorInvalidError` instead of quietly starting again. Delete and erase wait for
a pending deletion up to your timeout (30 seconds by default; set `waitMs` or
`wait=` per call).

### When a save is uncertain

An unknown add may still finish. Resend the same text with its returned
`idempotency_key` or `idempotencyKey` within 24 hours. The SDK uses the same key
on its own retries. A new key can create a second fact.

## Example 3: which memories a reply used

Pass a raw response to `read_receipt()` (Python) or `readReceipt()` (TypeScript)
to get the receipt. In TypeScript use `.withResponse()`; in Python use `.with_raw_response`.

> [tab] Python
>
> ```python theme={null}
> raw = user.openai().chat.completions.with_raw_response.create(
>     model="openai/gpt-6.1-terra",
>     messages=[{"role": "user", "content": "What day does my project launch?"}],
> )
> tracked = atlaso.read_receipt(raw)
> print(tracked.data.choices[0].message.content)
> print(tracked.receipt.memory.memory_ids if tracked.receipt.memory else [])   # put into this prompt
> print(tracked.receipt.cost)                # state "known" and usd, the cost as a decimal string
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> const tracked = atlaso.readReceipt(
>   await user.openai().chat.completions.create({
>     model: "openai/gpt-6.1-terra",
>     messages: [{ role: "user", content: "What day does my project launch?" }],
>   }).withResponse(),
> );
> console.log(tracked.data.choices[0].message.content);
> console.log(tracked.receipt.memory?.memoryIds);   // put into this prompt
> console.log(tracked.receipt.cost);                // state "known" and usd, the cost as a decimal string
> ```

A receipt gives the IDs of the facts in the prompt, not their text. To show the
text, list the user's memories and match the IDs:

> [tab] Python
>
> ```python theme={null}
> used = tracked.receipt.memory.memory_ids if tracked.receipt.memory else []
> for memory in user.memory.list():
>     if memory.id in used:
>         print(memory.text)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> const used = new Set(tracked.receipt.memory?.memoryIds ?? []);
> for await (const memory of user.memory.list()) {
>   if (used.has(memory.id)) console.log(memory.text);
> }
> ```

A fact deleted since the call cannot be recovered: its ID stays in the receipt,
but its text is gone.

The receipt is plain data. Python names are shown; TypeScript uses camelCase.

| Field | Meaning |
| - | - |
| `memory.status` | `used`, `none`, `off`, `skipped` (see `memory.reason`) or `bypass`. |
| `memory.memory_ids` | IDs of the facts put into this request's prompt. This shows what the model saw, not proof that it used them. |
| `memory.memories_in_prompt` | How many facts were put into this request's prompt, or `null` when the header value is invalid. Not facts saved. |
| `memory.gateway_overhead_ms` | Atlaso's time before the provider call. |
| `cost` | `state` is `known` (with `usd` as a decimal string such as `"0.000010"`), `pending` while a stream runs, or `unknown` with `why`. Unknown cost is never shown as zero. |
| `cache` | Cache read and write token counts, when the provider reports them. |
| `ignored_params`, `tags_dropped` | Settings the model ignored and [tags](https://docs.atlaso.ai/gateway/tags.md) that were not recorded. The call still ran. |
| `stream_state` | `not_stream`, `open`, `complete`, `interrupted`, `errored` or `aborted`. |
| `request_id`, `call_id` | For support and for finding the call in Activity. |

`read_receipt()` / `readReceipt()` only reads. It never changes the reply or a chunk. Responses calls work
the same way through `responses.create`; their receipt kind is `responses`.

## Example 4: streaming cost is your choice

A stream carries its cost only when you ask for usage. The SDK never turns it on
for you, because that would change your request. With the tapped client shown
below, a completed stream without usage has cost `unknown` with `why` set to
`usage_not_requested`; Activity still records the cost.

> [tab] Python
>
> ```python theme={null}
> raw = user.openai().chat.completions.with_raw_response.create(
>     model="openai/gpt-6.1-terra",
>     messages=[{"role": "user", "content": "Say hello."}],
>     stream=True,
>     stream_options={"include_usage": True},   # your choice
> )
> tracked = atlaso.read_receipt(raw)
> for chunk in tracked.stream:   # your client's own chunks, unchanged
>     if chunk.choices:
>         print(chunk.choices[0].delta.content or "", end="")
> print()
> print(tracked.receipt.cost)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> const streamed = atlaso.readReceipt(
>   await user.openai().chat.completions.create({
>     model: "openai/gpt-6.1-terra",
>     messages: [{ role: "user", content: "Say hello." }],
>     stream: true,
>     stream_options: { include_usage: true },   // your choice
>   }).withResponse(),
> );
> console.log(streamed.receipt.memory?.memoryIds);   // known before the first token
> let streamedText = "";
> for await (const chunk of streamed.stream) {       // your client's own chunks, unchanged
>   streamedText += chunk.choices[0]?.delta?.content ?? "";
> }
> console.log(streamedText);
> console.log((await streamed.done).cost);
> ```

For streaming, use `user.openai()` (or `user.client(openai)`) as above: its transport tap observes
the terminal marker. The `user.headers()` path only attaches request headers;
it cannot install that tap. If a stream read through that path has no usage or
`atlaso` chunk, the receipt reports `interrupted` with `provider_unknown`, even
when a finish reason was seen. It cannot prove completion or recover the cost.

Read the stream through `tracked.stream`, not the raw stream, or the receipt
cannot see the end. Keep the chunk that has no `choices`: it carries the usage.
`done` in TypeScript resolves when the stream ends for any reason and never
rejects; in Python the receipt is final once the loop ends. If you stop early,
call `close()` (Python) and the receipt says `aborted`.

## Example 5: the AI SDK

A Next.js route with `streamText`, and the memory receipt sent to `useChat`.
See [AI SDK](https://docs.atlaso.ai/gateway/ai-sdk.md) for the adapter.

```typescript theme={null}
// app/api/chat/route.ts
import { streamText, convertToModelMessages, type UIMessage } from "ai";
import { createAtlaso } from "atlaso/ai-sdk";

const atlaso = createAtlaso();   // no user here

export async function POST(req: Request) {
  const userId = await requireUserId(req);   // your sign-in check
  const { messages } = (await req.json()) as { messages: UIMessage[] };
  const result = streamText({
    model: atlaso.forUser(userId).chat("openai/gpt-6.1-terra"),   // fresh per request
    messages: await convertToModelMessages(messages),
  });
  return result.toUIMessageStreamResponse({
    messageMetadata: ({ part }) =>
      part.type === "finish-step" ? { atlaso: part.providerMetadata?.atlaso } : undefined,
  });
}
```

On the client, `useChat()` gives each assistant message
`message.metadata?.atlaso`, so `metadata.atlaso.memory.memoryIds` can show
which memories were in the prompt. Read it from the `finish-step` part as shown:
the final `finish` part has no provider metadata. `convertToModelMessages`
returns a promise, so `await` it.

## Example 6: the OpenAI Agents SDK

Give each run its own client through `RunConfig`. Never set the global default
client to a user's client: every concurrent run would use that user's memory.
This example needs Python 3.10 or newer and `openai-agents` 0.21 or later, which
declares `openai>=3,<4`; older pairs with `openai` 2.x can fail before any call.
Tested together: `openai-agents` 0.25.0 and `openai` 3.57.0 on Python 3.15.

```bash theme={null}
pip install atlaso "openai>=3,<4" "openai-agents>=0.21"
```

```python theme={null}
from agents import Agent, OpenAIProvider, RunConfig, Runner
from atlaso import AsyncAtlaso

atlaso = AsyncAtlaso()
agent = Agent(name="helper", instructions="Be brief.", model="openai/gpt-6.1-terra")

async def handle(user_id: str, text: str) -> str:
    scoped = atlaso.for_user(user_id).openai()   # one per run
    config = RunConfig(model_provider=OpenAIProvider(openai_client=scoped, use_responses=False))
    result = await Runner.run(agent, text, run_config=config)
    return result.final_output

# Don't: set_default_openai_client(scoped) makes every run use this user's memory.
```

## Choose providers

Many models are served by more than one provider. `routing()` sets which
providers may answer, in what order, and whether a backup may answer when
your first choice fails. Spread it into a TypeScript `create()` call, or pass
it as Python's `extra_body=`. It sends nothing on its own: an option you leave
out is not sent, so the gateway's default applies.

| Option (Python name) | Meaning |
| - | - |
| `order` | Try these providers first, in this order. |
| `only` | Use only these providers. |
| `ignore` | Never use these providers. |
| `allowFallbacks` (`allow_fallbacks`) | `false`: fail the call instead of letting a backup answer. |

Names are the provider names the gateway lists, such as `anthropic` or
`bedrock`. Your editor suggests today's names, and any other name is accepted,
so a provider added later works without an SDK update. `routing()` checks your
options before anything is sent: an unknown option, a non-boolean
`allowFallbacks`, or an empty or repeated name throws `InvalidRequestError` with
code `invalid_routing`. The gateway checks the rest (for example, at most 16
names in a list) and answers `400 unsupported_parameter`, which `classify()`
reports as `invalid_request`, not retryable.

To see who answered, read the receipt. `answeredBy(receipt)` (Python
`answered_by`) gives the provider's name, taken from the receipt's model id.
`receipt.providerHost` (Python `provider_host`) is the host name of the server that answered.

> [tab] Python
>
> ```python theme={null}
> from atlaso import answered_by, routing
>
> raw = user.openai().chat.completions.with_raw_response.create(
>     model="anthropic/claude-sonnet-5.5",
>     messages=[{"role": "user", "content": "What is my demo project called?"}],
>     extra_body=routing(order=["anthropic", "bedrock"]),   # add allow_fallbacks=False to forbid a backup
> )
> tracked = atlaso.read_receipt(raw)
> who = answered_by(tracked.receipt)
> if who != "anthropic":
>     print(f"A backup answered: {who} ({tracked.receipt.provider_host})")
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { answeredBy, routing } from "atlaso";
>
> const routed = atlaso.readReceipt(
>   await user.openai().chat.completions.create({
>     model: "anthropic/claude-sonnet-5.5",
>     messages: [{ role: "user", content: "What is my demo project called?" }],
>     ...routing({ order: ["anthropic", "bedrock"] }),   // add allowFallbacks: false to forbid a backup
>   }).withResponse(),
> );
> const who = answeredBy(routed.receipt);
> if (who !== "anthropic") console.log(`A backup answered: ${who} (${routed.receipt.providerHost})`);
> ```

## Errors and retries

`classify()` turns any error into one typed record: the SDK's own errors, your
OpenAI client's errors and network failures. It has `code`, `kind`, `status`,
`retryable`, the retry wait in milliseconds, `request_id` and `doc_url`. `kind`
groups codes: `auth`, `user_id`, `key_scope`, `invalid_request`, `rate_limit`,
`quota`, `provider`, `memory_unavailable`, `not_found`, `conflict`, `server`,
`network`, `edge_blocked`, `edge_error` or `unknown`. See [Errors](https://docs.atlaso.ai/gateway/errors.md) for every code.

> [tab] Python
>
> ```python theme={null}
> from openai import APIError
>
> try:
>     user.openai().chat.completions.create(
>         model="openai/gpt-6.1-terra",
>         messages=[{"role": "user", "content": "Hello"}],
>     )
> except APIError as err:
>     info = atlaso.classify(err)
>     print(info.code, info.kind, info.retryable)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> try {
>   await user.openai().chat.completions.create({
>     model: "openai/gpt-6.1-terra",
>     messages: [{ role: "user", content: "Hello" }],
>   });
> } catch (err) {
>   const info = atlaso.classify(err);
>   console.log(info.code, info.kind, info.retryable);
> }
> ```

Who retries what:

* **Model calls** are retried by your OpenAI client, with its own `maxRetries`
  setting. The SDK does not add a second layer. The clients behind `openai()` and
  `anthropic()` take the Atlaso object's `maxRetries` (`max_retries`), and its
  `timeoutMs` (`timeout`) when you set one; otherwise the provider's own timeout. A client timeout, or an edge
  502, 504 or 524 page, with automatic retries can make the provider run and
  bill the same non-streamed call twice, because the provider keeps working
  after your client or the network in front of the gateway gives up (a 524
  means the request reached the gateway). For long answers, set a longer timeout or stream
  the reply.
* **Answers from the network in front of the gateway** (any 4xx or 5xx
  without `x-request-id`, HTML or JSON): a 403 is kind `edge_blocked`, never
  retried by the SDK or its scoped clients: the request never reached Atlaso,
  and Atlaso did not check your API key.
  Any other such page is kind `edge_error` and may be retried automatically,
  with the same rules as any other reply with that status (for example a 502
  while the gateway restarts for a deploy). The message holds at most the
  page's short title; if it keeps happening, contact support with the time of
  the call. See
  [Blocked before reaching Atlaso](https://docs.atlaso.ai/gateway/errors.md#blocked-before-reaching-atlaso).
* **Memory calls** are retried by the SDK only when that is safe: list, delete
  and erase on rate limits and passing failures; add only when the fact cannot
  have been saved, such as a rate limit or a connection that never opened. If
  the connection still has not opened after the retries, add raises
  `NotSentError` (kind `network`, `safe_to_repeat` / `safeToRepeat` true):
  nothing was saved, so sending it again later is safe. Any other add failure
  returns `unknown`, whose error is never retryable. A
  `retry-after` longer than the time left ends the call instead of waiting.
  Set `maxRetries` / `max_retries` and `timeoutMs` / `timeout` on `Atlaso`.
* **Arguments refused before sending**, such as an empty or `..` fact ID, raise
  `InvalidRequestError` (kind `invalid_request`, never retryable; in Python it is
  also a `ValueError`). Fix the argument; retrying cannot help.
* A failure in the middle of a stream is never retried, because part of the
  answer was already sent.

## Test without a network

The separate `atlaso/testing` and `atlaso.testing` imports provide an offline
gateway with isolated user stores. In TypeScript, pass its `fetch` to Atlaso:
`user.openai()` uses it too. In Python, pass its HTTP client to Atlaso and to your
own OpenAI client, and use `user.client(openai)`. Use made-up users and facts; neither fake opens a connection.

> [tab] Python
>
> ```python theme={null}
> from openai import OpenAI
> from atlaso import Atlaso
> from atlaso.testing import FakeGateway
>
> gateway = FakeGateway()
> with gateway.httpx_client() as http:
>     atlaso = Atlaso(api_key=gateway.api_key, base_url=gateway.base_url, http_client=http)
>     openai = OpenAI(**atlaso.client_options(), http_client=http)
>     user = atlaso.for_user("u1")
>     saved = user.memory.add("Prefers metric units")
>     assert saved.outcome == "added"
>     reply = user.client(openai).chat.completions.create(
>         model="openai/gpt-6.1-terra",
>         messages=[{"role": "user", "content": "Which units?"}],
>     )
>     assert saved.memory.id in reply.choices[0].message.content
>     assert list(atlaso.for_user("u2").memory.list()) == []
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import OpenAI from "openai";
> import { Atlaso } from "atlaso";
> import { createFakeGateway } from "atlaso/testing";
>
> const gateway = createFakeGateway();
> const atlaso = new Atlaso({ apiKey: gateway.apiKey, baseURL: gateway.baseURL, fetch: gateway.fetch, OpenAI });
> const user = atlaso.forUser("u1");
> const saved = await user.memory.add("Prefers metric units");
> if (saved.outcome !== "added") throw new Error(saved.outcome);
> const reply = await user.openai().chat.completions.create({
>   model: "openai/gpt-6.1-terra",
>   messages: [{ role: "user", content: "Which units?" }],
> });
> if (!reply.choices[0]?.message.content?.includes(saved.memory.id)) throw new Error("missing memory");
> for await (const _fact of atlaso.forUser("u2").memory.list()) throw new Error("cross-user fact");
> ```

A fake checks your code's behaviour, not answer quality. Python also has
`AsyncAtlaso`, with the same methods for `asyncio` (`await` the memory calls and
`await tracked.done()` for streams).

## Export a user's memories

Use `export()` for the memory portion of a right-of-access response. It collects
all pages for this user in this key's project, newest first, into one typed
object with a UTC generation time, fact count, and page count. It does not read
another user or project. The gateway's existing list API determines which facts
are exposed; this is not an export of account billing or model call records.

> [tab] Python
>
> ```python theme={null}
> exported = user.memory.export(page_size=100)
> print(exported.fact_count, exported.page_count, exported.generated_at)
> access_response = exported.to_dict()
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> const exported = await user.memory.export({ pageSize: 100 });
> console.log(exported.factCount, exported.pageCount, exported.generatedAt);
> const accessResponse = JSON.stringify(exported);
> console.log(accessResponse);
> ```

To use less local memory, use `user.memory.exportStream({ pageSize: 100 })` in TypeScript
or `user.memory.export_stream(page_size=100)` in Python. Both fetch lazily and keep
one page of facts in memory. Python's async scope supports `await memory.export()`
and `async for` over `memory.export_stream()`. Page sizes are 1 to 100.
The gateway pages by keyset, so managed list and export can continue beyond
10,000 facts. A missing or deleted cursor can still return `invalid_after`.

An export is not an atomic snapshot: changes during pagination can affect it;
an erase during an export can end it early. Pause writes and erases if you need
a stable copy. A vanished cursor raises `CursorInvalidError`; no partial export
object is returned. A streaming consumer must discard its partial output on
failure. Restart only after resolving a vanished cursor.
Export reads facts; [erase](#erase-a-user) removes them.

## Erase a user

> [!WARNING]
>
> Erase is permanent: deleted facts cannot be recovered. Run it last; erasing before Example 3 leaves its receipt empty.

> [tab] Python
>
> ```python theme={null}
> erased = user.memory.erase()        # this user, this project
> if erased.outcome == "pending":
>     erased = erased.resume()      # resending an erase is safe
> print(erased.outcome)
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> let erased = await user.memory.erase();   // this user, this project
> if (erased.outcome === "pending") erased = await erased.resume();   // resending is safe
> console.log(erased.outcome);
> ```

## Agent memory tools

Agent adapters expose a read-only `search_memories` tool by default beside
`remember` and `list_memories`. It searches only the user bound by `forUser(id)`
(Python: `for_user(id)`); the model cannot supply a different user id. TypeScript
offers it through `user.tools.forOpenAI()` and `user.tools.aiSdk()`. Python offers it
through `user.tools.for_openai()` and `user.tools.functions()` (also on `AsyncAtlaso`).

`user.tools.for_openai()` (TypeScript `user.tools.forOpenAI()`) is not a list. Pass its `definitions` as the model's tools,
then run each tool call the model returns with `run(call)`, which returns the
result text for the tool message. Use a model that takes tools on Chat
Completions: models such as `openai/gpt-6.1-terra` take tools only through
`POST /v1/responses` and answer `400 unsupported_parameter` (param `tools`) here.

> [tab] Python
>
> ```python theme={null}
> memory_tools = user.tools.for_openai()
> tool_reply = user.openai().chat.completions.create(
>     model="openai/gpt-4o-mini",
>     messages=[{"role": "user", "content": "Remember that I prefer metric units."}],
>     tools=memory_tools.definitions,
> )
> for tool_call in tool_reply.choices[0].message.tool_calls or []:
>     print(tool_call.function.name, memory_tools.run(tool_call))   # for this user only
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> const memoryTools = user.tools.forOpenAI();
> const toolReply = await user.openai().chat.completions.create({
>   model: "openai/gpt-4o-mini",
>   messages: [{ role: "user", content: "Remember that I prefer metric units." }],
>   tools: memoryTools.definitions as unknown as OpenAI.ChatCompletionTool[],
> });
> for (const toolCall of toolReply.choices[0].message.tool_calls ?? []) {
>   if (toolCall.type === "function")
>     console.log(toolCall.function.name, await memoryTools.run(toolCall));   // for this user only
> }
> ```

Send each result back as a `tool` message with the call's ID, then call the model
again for its answer.

## Client identification and local hooks

Requests sent or scoped by the library carry `x-atlaso-client` with only
`atlaso-ts/<version>` or `atlaso-py/<version>`. It includes no machine, operating
system, or user data. An application's own header wins. Disable the automatic
header with `clientHeader: false` or `client_header=False`. When manually merging
`headers()` with application headers, apply your application header last.

Pass `onReceipt`, `onError`, and `onNotice` to `Atlaso` in TypeScript, or
`on_receipt`, `on_error`, and `on_notice` in Python. These callbacks run only in your process and receive an
independent receipt snapshot, `ErrorInfo`, or a retirement-notice string, respectively.
`onNotice`/`on_notice` receives that string for each observed reply, independently of
`readReceipt()` / `read_receipt()`. The library logs each distinct retirement notice once by default; see the
[client support policy](https://docs.atlaso.ai/gateway/client-support.md). The library sends nothing to a
logging service. No separate fact, model request, or answer object is passed to callbacks.
`ErrorInfo.message` and `Receipt.raw` (`raw_headers` and `raw_atlaso` in Python)
carry remote text or metadata; treat those
values as untrusted and select the fields you need before logging them.

A non-streaming `readReceipt()` / `read_receipt()` call reports immediately. A stream reports once it
finishes, fails, or is closed; tracking does not consume a stream for you. Memory
operations report after their retry policy finishes. Paginated list and export
report once per fetched page. An uncertain add reports its receipt and error.
A thrown memory operation reports `ErrorInfo`. A model error thrown by the
provider SDK before `readReceipt()` / `read_receipt()` runs is the caller's to catch and classify with
`atlaso.classify(error)` (Python `atlaso.classify(exc)`). Calls you make without
`readReceipt()` / `read_receipt()` do not produce receipt callbacks; retirement notices on observed replies still do.
The AI SDK adapter observes its model calls automatically when you pass
these hooks to `createAtlaso()` or reuse an `Atlaso` instance. Python callbacks
must be synchronous, including on `AsyncAtlaso`.

A callback failure never changes the call's result. It produces at most one
generic warning per `Atlaso` instance through `console.warn` or Python warnings;
the callback exception is not printed. TypeScript also contains rejected
callback promises.

> [tab] Python
>
> ```python theme={null}
> from atlaso import Atlaso
> observed_receipts = []
> observed_errors = []
> observed = Atlaso(on_receipt=observed_receipts.append, on_error=observed_errors.append,
>                   client_header=False)
>
> def report_model_error(create):
>     try:
>         return create()                 # call the provider SDK here, then read_receipt() the raw reply
>     except Exception as exc:
>         observed_errors.append(observed.classify(exc))
>         raise
> ```

> [tab] TypeScript
>
> ```typescript theme={null}
> import { Atlaso, type Receipt, type ErrorInfo } from "atlaso";
> const observedReceipts: Receipt[] = [];
> const observedErrors: ErrorInfo[] = [];
> const observed = new Atlaso({
>   clientHeader: false,
>   onReceipt: receipt => { observedReceipts.push(receipt); },
>   onError: error => { observedErrors.push(error); },
> });
> console.log(observed.baseURL);
>
> export async function reportModelError<T>(create: () => Promise<T>): Promise<T> {
>   try {
>     return await create();             // call the provider SDK here, then readReceipt() the raw reply
>   } catch (error) {
>     observedErrors.push(observed.classify(error));
>     throw error;
>   }
> }
> ```

See the generated [TypeScript reference](https://docs.atlaso.ai/gateway/reference/typescript.md),
[Python reference](https://docs.atlaso.ai/gateway/reference/python.md), and
[runtime and support policy](https://docs.atlaso.ai/gateway/client-support.md).


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