# AI

> AI: models paid from your NoClick balance, for code that isn't an agent, and your agents as models.

```python
reply = noclick.AI.chat("Summarize this in one line: ...")
vectors = noclick.AI.embed(["first", "second"]).vectors
image = noclick.AI.image("A lighthouse at dusk, watercolor")
clip = noclick.AI.video("Waves rolling under a lighthouse at dusk").wait()
words = noclick.AI.transcribe("https://example.com/call.mp3")
answer = noclick.AI.chat("Where's my refund?", model="agent:support")
```

Every call is charged in US dollars to your account; inside `as_user` it is
attributed to that user and counts against its spend cap. `AI.base_url`
serves chat completions, responses, embeddings and the model list to any
OpenAI client.

## AI

```typescript
class AI
```

Models paid from your NoClick balance, for code that isn't an agent: chat, embeddings, images,
videos and transcription; and your agents as `agent:<name>` models. Model ids are OpenRouter ids with the
`openrouter/` prefix, except transcription's, NoClick's own `noclick/transcribe-1`; leave `model` out for
NoClick's default of each kind.

| Attribute | Type | Description |
| --- | --- | --- |
| `baseUrl` | `string` | The OpenAI-compatible endpoint (`https://api.noclick.com/v1/ai` on the hosted API): point any OpenAI client at it with your NoClick key for chat completions, responses, embeddings and the model list. |

### AI.chat

```typescript
static chat(
  messages: string | readonly (AIChatMessage | string)[],
  options?: AIChatOptions,
): Promise<ChatReply>
```

Send a conversation to a chat model: OpenAI-shaped messages, or a string as one user message.
`model: "agent:<name>"` talks to one of your agents instead: it brings its own tools and keeps the
conversation (`conversation: reply.conversation` continues it). The answer streams, so a long turn
never times out. A request with no conversation whose messages end in an assistant reply the agent
gave recently continues that reply's conversation, so a chat UI that resends the whole history
keeps one thread (invite-only beta).

    const reply = await AI.chat("Summarize: the meeting moved to Friday at 3pm.", { maxTokens: 200 });
    console.log(reply.text, reply.costUsd);

Parameters:

- `messages` (`string | readonly (AIChatMessage | string)[]`, required)
- `options.model` (`string`): An OpenRouter id with the `openrouter/` prefix, or `agent:<name>` for one of your agents; NoClick's default when omitted.
- `options.maxTokens` (`number`)
- `options.temperature` (`number`)
- `options.responseFormat` (`JsonObject`): Ask for JSON: `{ type: "json_schema", json_schema: ... }`.
- `options.tools` (`JsonObject[]`): OpenAI-format tool definitions, such as `await toolkit.definitions({ format: "openai" })`. An agent takes none.
- `options.toolChoice` (`"auto" | "none" | "required" | JsonObject`): Which of `tools` the model calls: `auto` (its choice), `none`, `required` (one of them), or one by name,
`{ type: "function", function: { name: "submit" } }`. A model may refuse to be made to (`AIReasoning.mandatory`).
- `options.reasoningEffort` (`string`): How hard a model that reasons thinks first, among its `reasoning.efforts` (`AI.models`): its reasoning counts
toward `maxTokens`, so a lower effort leaves more of them for the answer, and `none` turns it off where the model
can stop.
- `options.conversation` (`string`): An agent's conversation to continue (`reply.conversation`); only the messages after the last assistant message are sent.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.
- `options.signal` (`AbortSignal`)

Returns: The answer: its `text`, the `message` to append to the conversation, and
the tokens it used and what it cost.

Types:

```typescript
/** One message of a conversation, in the OpenAI shape (`tool_calls` and `tool_call_id` included). */
type AIChatMessage = { role: string; content?: unknown } & JsonObject;

type JsonObject = { [key: string]: unknown };

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### AI.embed

```typescript
static embed(
  texts: string | readonly string[],
  options?: CallOptions & { model?: string; dimensions?: number },
): Promise<Embeddings>
```

Turn text into vectors: one string, or up to 2,048. `dimensions` shortens them, for models that allow it.

Parameters:

- `texts` (`string | readonly string[]`, required)
- `options.model` (`string`)
- `options.dimensions` (`number`)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: One vector per text, in order, with their length and what the call cost.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### AI.image

```typescript
static image(
  prompt: string,
  options?: CallOptions & {
    model?: string;
    size?: string;
    images?: readonly string[];
  },
): Promise<GeneratedImage>
```

Make one image, kept as one of your account's files (its `url` keeps working); `size` is
`"WIDTHxHEIGHT"` in an aspect ratio the model makes (its own shape unless you say). `images` are
pictures (URLs, up to 8) to make it from: one to edit, the prompt saying what to change, or several to combine.

Parameters:

- `prompt` (`string`, required)
- `options.model` (`string`)
- `options.size` (`string`)
- `options.images` (`readonly string[]`)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The image, kept as one of your account's files: a `url` that keeps working, its
`file_id`, its size and what it cost.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### AI.video

```typescript
static video(
  prompt: string,
  options?: VideoOptions,
): Promise<Operation<GeneratedVideo>>
```

Start one video. It takes minutes, so it runs as an `Operation` whose `wait()` resolves to the
`GeneratedVideo`, kept as one of your account's files. Its price is quoted before it starts
(`usdPerSecond` in `AI.models({ kind: "video" })`) and charged when it's done. `firstFrame` starts it
from a picture.

    const job = await AI.video("Waves rolling under a lighthouse at dusk", { seconds: 8, aspectRatio: "9:16" });
    const clip = await job.wait({ timeoutS: 600 });
    console.log(clip.url, clip.seconds, clip.costUsd);
    const waving = await AI.video("She turns and waves", { firstFrame: "https://example.com/me.jpg" });

Parameters:

- `prompt` (`string`, required)
- `options.model` (`string`)
- `options.seconds` (`number`): Among the lengths the model makes; about 8 when omitted.
- `options.resolution` (`string`): `720p`, `1080p`, as the model makes them; 720p where it can when omitted.
- `options.aspectRatio` (`string`): `16:9`, `9:16`, as the model makes them.
- `options.audio` (`boolean`, default `true`): Sound, where the model makes it (default true).
- `options.firstFrame` (`string`): A picture the video starts from, to bring a photo to life: one of your account's files by its id, or a JPEG,
PNG or WebP image's https URL, up to 10 MB, on a model whose `frameImages` list `first_frame`.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: An `Operation` at once, whose `wait()` gives the `GeneratedVideo`, kept as one
of your account's files.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### AI.transcribe

```typescript
static transcribe(
  audio: TranscribeAudio,
  options: TranscribeOptions & { background: true },
): Promise<Operation<Transcript>>
static transcribe(
  audio: TranscribeAudio,
  options?: TranscribeOptions & { background?: false },
): Promise<Transcript>
```

Write down what is said in a recording: an `https` URL to it, or its bytes, up to 2 hours (25 MB as
bytes, 200 MB behind a URL), in MP3, WAV, M4A, MP4, OGG, WebM, AAC, FLAC or AIFF. `language` (ISO
639-1) skips detection. It runs on `noclick/transcribe-1`, which takes the whole recording in one call
and gives a segment per sentence, priced per minute of audio as `usdPerMinute` in `AI.models`.

`speakers` tells the voices apart, at the same price, each voice keeping its label from start to end,
and gives a segment per voice's turn. `true` labels each segment's `speaker` `speaker_1`, `speaker_2`,
... in the order they first speak; a list of names (`["rep", "customer"]`) says how many voices there
are, and NoClick works out which is which from what they say, giving a voice it can't tell the next
unused name in speaking order.

`{ background: true }` returns an `Operation` at once, whose `wait()` resolves to the transcript: for
a recording that may take longer than one request waits (90 seconds), as a very long one can (forty
minutes usually take about 20 seconds). A call that doesn't run in the background and passes 90 seconds
rejects with `RequestTimeout` naming its operation, which still finishes and holds the transcript.

Parameters:

- `audio` (`TranscribeAudio`, required)
- `options.model` (`string`)
- `options.language` (`string`)
- `options.speakers` (`boolean | string[]`): `true`, or a name per voice.
- `options.background` (`boolean`, required): Return an `Operation` at once instead of waiting.
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: The transcript: its `text`, timed `segments`, the `language` and how long the audio
was. With `background=True`, an `Operation` at once, whose `wait()` gives it.

Types:

```typescript
/** A recording: an `https` URL to it, or its bytes. */
type TranscribeAudio = string | Uint8Array | ArrayBuffer | Blob;

/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### AI.headers

```typescript
static headers(options?: CallOptions): Promise<Record<string, string>>
```

The headers a call to `AI.baseUrl` needs: your key as the bearer and, inside `asUser` (or with
`user`), the `NoClick-User` that attributes the call to that user and holds it to the user's spend
cap. Give them to an OpenAI client as `defaultHeaders`; without the user header the account pays.

    const gpt = new OpenAI({ baseURL: AI.baseUrl, apiKey: "-", defaultHeaders: await AI.headers({ user: "user_42" }) });

Parameters:

- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: `Authorization` and, when a user is in scope, `NoClick-User`.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}
```

### AI.models

```typescript
static models(
  options?: CallOptions & { kind?: AIModelKind; q?: string; model?: string },
): Promise<AIModel[]>
```

The models you can call, the default of each kind first, with their prices in US dollars; `agent`
lists the agents you (or the user you act for) can talk to as `agent:<name>`. `q` keeps those whose
id or name contains it (any case), `model` the one with that id (`openrouter/` may be left out).

    const [sonnet] = await AI.models({ model: "anthropic/claude-sonnet-4.6" });

Parameters:

- `options.kind` (`AIModelKind`)
- `options.q` (`string`)
- `options.model` (`string`)
- `options.user` (`UserOption`, default: the current user): `undefined` = the ambient user (`asUser`), `null` = the account itself.
- `options.client` (`NoClick`): The client to send with; defaults to the module client built from `NOCLICK_API_KEY`.

Returns: Every matching model with its prices in US dollars, the default of each kind first.

Types:

```typescript
/** `undefined` = the ambient user (from `asUser`), `null` = the account itself. */
type UserOption = UserRef | null | undefined;

/** A `User` or your own id for the user. */
type UserRef = string | UserLike;

/** Anything that can name a user lazily (a `User`). */
interface UserLike {
  _userId(): Promise<string>;
}

type AIModelKind = "chat" | "embedding" | "image" | "transcription" | "video" | "agent";
```

## ChatReply

```typescript
interface ChatReply
```

A model's (or an agent's) answer: `text`, and the whole `message` to append to the conversation.

| Attribute | Type | Description |
| --- | --- | --- |
| `text` | `string` | The answer as text (empty when the model only called tools). |
| `message` | `AIChatMessage` | The assistant message as the API sent it (`role`, `content`, `tool_calls`). |
| `model` | `string | null` |  |
| `finishReason` | `string | null` | `stop`, `length` (`maxTokens` reached, reasoning included: a model that spends them all reasoning answers with an empty `text`) or `tool_calls`. |
| `usage` | `Record<string, number>` | `prompt_tokens`, `completion_tokens`, `total_tokens`, and `reasoning_tokens`, the part of `completion_tokens` spent reasoning, where the model reports it (none for an agent). |
| `costUsd` | `number | null` | What the call cost, in US dollars. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |
| `reasoning` | `string | null` | What the model thought before it answered, where its provider returns it (null otherwise). |
| `toolCalls` | `JsonObject[]` | The tools the model asked to call (empty if none), in the shape `toolkit.handleOpenAI` runs. An agent runs its own. |
| `conversation` | `string | null` | An agent's conversation this reply is part of: pass it as `conversation` to continue it. |

Types:

```typescript
/** One message of a conversation, in the OpenAI shape (`tool_calls` and `tool_call_id` included). */
type AIChatMessage = { role: string; content?: unknown } & JsonObject;

type JsonObject = { [key: string]: unknown };
```

## Embeddings

```typescript
interface Embeddings
```

One vector per input, in the order you passed them.

| Attribute | Type | Description |
| --- | --- | --- |
| `vectors` | `number[][]` |  |
| `dimensions` | `number` | The length of each vector. |
| `model` | `string | null` |  |
| `usage` | `Record<string, number>` | Tokens used: `prompt_tokens`, `total_tokens`. |
| `costUsd` | `number | null` | What the call cost, in US dollars. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## GeneratedImage

```typescript
interface GeneratedImage
```

An image a model made, kept as one of your account's files.

| Attribute | Type | Description |
| --- | --- | --- |
| `url` | `string` | A link to the image that keeps working. |
| `width` | `number | null` |  |
| `height` | `number | null` |  |
| `model` | `string | null` |  |
| `costUsd` | `number | null` | What the image cost, in US dollars. |
| `expiresAt` | `Date | null` | When `url` stops working: null, since the file is kept. |
| `fileId` | `string | null` | The file in your account's files. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## GeneratedVideo

```typescript
interface GeneratedVideo
```

A video a model made, kept as one of your account's files.

| Attribute | Type | Description |
| --- | --- | --- |
| `url` | `string` | A link to the video that keeps working. |
| `fileId` | `string | null` | The file in your account's files. |
| `mimeType` | `string | null` |  |
| `seconds` | `number | null` |  |
| `resolution` | `string | null` |  |
| `model` | `string | null` |  |
| `costUsd` | `number | null` | What the video cost, in US dollars. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## Transcript

```typescript
interface Transcript
```

What was said in a recording, as one `text` and as timed `segments`.

| Attribute | Type | Description |
| --- | --- | --- |
| `text` | `string` |  |
| `language` | `string | null` | The spoken language as an ISO 639-1 code (`en`), detected unless you passed one; ISO 639-3 (`yue`) for a language with no two-letter code. |
| `durationS` | `number | null` |  |
| `segments` | `TranscriptSegment[]` |  |
| `model` | `string | null` |  |
| `costUsd` | `number | null` | What the transcription cost, in US dollars. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type JsonObject = { [key: string]: unknown };
```

## TranscriptSegment

```typescript
interface TranscriptSegment
```

A stretch of speech: what was said between `startS` and `endS`, and by whom when you asked for `speakers`.

| Attribute | Type | Description |
| --- | --- | --- |
| `startS` | `number` |  |
| `endS` | `number` |  |
| `text` | `string` |  |
| `speaker` | `string` | Who said it: one of the names you gave `speakers`, or `speaker_1`, `speaker_2`, ... in the order the voices first speak (absent unless you asked). |

## AIModel

```typescript
interface AIModel
```

A model you can call, and what it costs in US dollars (its provider's own price). Only the
prices for its `kind` are set: per token for chat and embedding models, per token of the image an
image model makes, per minute of audio for transcription ones, per second for video ones, none for
an agent.

| Attribute | Type | Description |
| --- | --- | --- |
| `id` | `string` | The id to pass as `model`, like `openrouter/anthropic/claude-sonnet-4.6` or `agent:support`. |
| `name` | `string | null` |  |
| `kind` | `AIModelKind` | `chat`, `embedding`, `image`, `transcription` or `agent`. |
| `contextLength` | `number | null` | The most tokens a request can hold (chat and embedding models). |
| `inputUsdPerToken` | `number | null` |  |
| `outputUsdPerToken` | `number | null` |  |
| `usdPerMinute` | `number | null` |  |
| `usdPerMinuteWithSpeakers` | `number | null` | What a minute of audio costs with `speakers`; null for a model of another kind. |
| `usdPerSecond` | `number | null` | What a second of video costs, for the clip a call naming no length or resolution makes. |
| `parameters` | `string[] | null` | The request fields a chat model takes, as its provider lists them (`tools`, `tool_choice`, `reasoning_effort`, `temperature`, ...): one it doesn't list has no effect. Null for other kinds. |
| `reasoning` | `AIReasoning | null` | How a chat model reasons; null for one that doesn't. |
| `frameImages` | `string[] | null` | The frames a video model can start or end on a picture (`first_frame`, `last_frame`): one listing `first_frame` takes `AI.video(prompt, { firstFrame })`. Null for other kinds. |
| `raw` | `JsonObject` | The response JSON exactly as the API sent it. |

Types:

```typescript
type AIModelKind = "chat" | "embedding" | "image" | "transcription" | "video" | "agent";

type JsonObject = { [key: string]: unknown };
```

## AIReasoning

```typescript
interface AIReasoning
```

How a chat model reasons before it answers. Its reasoning counts toward `maxTokens`, so a short budget can go
entirely on reasoning and leave the answer empty (`finishReason` `length`).

| Attribute | Type | Description |
| --- | --- | --- |
| `mandatory` | `boolean` | It always reasons, whatever `reasoningEffort` says. Anthropic's models refuse a forced tool (`toolChoice` `required` or naming a function) while they reason, so on one of theirs that always does, only `auto` and `none` work. |
| `efforts` | `string[]` | The `reasoningEffort` values it takes (`none` among them where it can stop reasoning). |
| `defaultEffort` | `string | null` | Its effort when a call names none. |
