Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

ai-angular.md

350 lines14.4 KB

1---
2title: "@tanstack/ai-angular"
3id: ai-angular
4order: 6
5description: "API reference for @tanstack/ai-angular: the injectChat injectable, generation injectables, and Angular signal bindings for the headless TanStack AI client."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-angular"
9 - angular
10 - signals
11 - injectChat
12 - injectables
13 - api reference
14---
15​
16Angular injectables for TanStack AI, built on signals. To build your first chat, start with the [Quick Start](../getting-started/quick-start). For a typed chat layout, see [Angular Chat UI](../ui/angular).
17​
18## Installation
19​
20<!-- ::start:tabs variant="package-manager" mode="install" -->
21​
22angular: @tanstack/ai-angular
23​
24<!-- ::end:tabs -->
25​
26> [!WARNING]
27> Call every `inject*` function in an Angular injection context: a class field initializer, the constructor, or `runInInjectionContext`. Outside one, the call throws.
28​
29```typescript
30import { Injector, inject, runInInjectionContext } from "@angular/core";
31import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
32​
33export class MyComponent {
34 // Field initializer
35 chat = injectChat({ connection: fetchServerSentEvents("/api/chat"), threadId: "support-chat" });
36​
37 private injector = inject(Injector);
38​
39 // Later, outside the constructor
40 openSecondChat() {
41 return runInInjectionContext(this.injector, () =>
42 injectChat({ connection: fetchServerSentEvents("/api/chat"), threadId: "support-chat" }),
43 );
44 }
46```
47​
48## `injectChat(options)`
49​
50Holds the messages and the run state of one chat, and talks to your server route.
51​
52```typescript
53import { Component } from "@angular/core";
54import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
55​
56@Component({
57 selector: "app-chat",
58 standalone: true,
59 template: `
60 @for (message of chat.messages(); track message.id) {
61 <p>
62 <strong>{{ message.role }}:</strong>
63 @for (part of message.parts; track $index) {
64 @if (part.type === 'text') {
65 <span>{{ part.content }}</span>
66 }
67 }
68 </p>
69 }
70 <input #input />
71 <button
72 (click)="chat.sendMessage(input.value); input.value = ''"
73 [disabled]="chat.isLoading()"
74 >
75 Send
76 </button>
77 `,
78})
79export class ChatComponent {
80 chat = injectChat({
81 connection: fetchServerSentEvents("/api/chat"),
82 threadId: "support-chat",
83 });
85```
86​
87### Options
88​
89You must pass `threadId`. You must also pass `connection` or `fetcher`, not both.
90​
91| Option | What it does |
92| --- | --- |
93| `connection` | Connection adapter, for example `fetchServerSentEvents("/api/chat")`. See [Transports](../transports/overview). |
94| `fetcher` | A function that returns a `Response` or a stream. Use it with server functions. |
95| `tools` | Client tools from `.client()`. They run when the model calls them. Reactive. See [Client Tools](../tools/client-tools). |
96| `threadId` | Required. The id of this chat. Use a stable id for each conversation, for example the id from your route. |
97| `initialMessages` | The messages to show first. |
98| `forwardedProps` | JSON sent to the server in the AG-UI `forwardedProps` field, for example `{ model: "gpt-6.1-sol" }`. Reactive. |
99| `persistence` | `true` to load the thread from the server, or a storage adapter. See [Chat Persistence](../persistence/chat-persistence). |
100| `outputSchema` | A Standard Schema. Adds typed `partial` and `final` signals to the return value. See [Streaming structured output](../structured-outputs/streaming). |
101| `context` | Client-only runtime context for client tools. It is not sent to the server. Reactive. |
102| `live` | Subscribe while `live` is `true`. Reactive. |
103| `queue` | What `sendMessage` does while a run is busy. Default: queue the message. See [Queueing](../chat/queueing). |
104| `interrupts` | Definitions from `defineInterrupt()`. See [Interrupts](../interrupts/overview). |
105| `byok`, `byokProvider` | A keyring from `defineByok()`. See [Bring Your Own Key](../advanced/byok). |
106| `devtools` | Display options for TanStack AI Devtools. |
107​
108The injectable also takes the `ChatClient` callbacks (`onResponse`, `onChunk`, `onFinish`, `onError`, `onInterruptStateChange`, `onCustomEvent`) and the other client options. See [`ChatClient` options](./ai-client#constructor-options).
109​
110A reactive option is a `ReactiveOption<T>`: a plain value, a `Signal<T>`, or a getter `() => T`. A getter runs in `computed`, so the signals it reads are tracked. A change updates the current chat.
111​
112```typescript
113import { Component, signal } from "@angular/core";
114import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
115​
116@Component({ selector: "app-model-chat", standalone: true, template: "" })
117export class ModelChatComponent {
118 model = signal("gpt-6.1-sol");
119​
120 chat = injectChat({
121 connection: fetchServerSentEvents("/api/chat"),
122 threadId: "support-chat",
123 forwardedProps: () => ({ model: this.model() }),
124 });
126```
127​
128### Returns
129​
130State values are read-only Angular `Signal`s. Call them to read the value, for example `chat.messages()`. Cleanup runs in `DestroyRef.onDestroy`.
131​
132| Field | What it is |
133| --- | --- |
134| `messages` | The `UIMessage` array of the chat. |
135| `sendMessage(content, options?)` | Sends a user message. `content` is a string or `{ content, id?, metadata? }`. `options` takes `whenBusy` and `body`. |
136| `isLoading` | `true` while a response streams. |
137| `error` | The last error, or `undefined`. |
138| `status` | `"ready"`, `"submitted"`, `"streaming"`, or `"error"`. |
139| `stop()` | Stops the current response. |
140| `reload()` | Runs the last user message again. |
141| `append(message)` | Adds a `UIMessage` or `ModelMessage` and starts a run. |
142| `addToolResult(result)` | Gives the result of a client tool by hand: `{ toolCallId, tool, output, state?, errorText? }`. |
143| `setMessages(messages)`, `clear()` | Replace or clear the messages. |
144| `queue`, `cancelQueued(id)` | Messages that wait while a run is busy. See [Queueing](../chat/queueing). |
145| `runId` | The id of the run in flight, or `null`. |
146| `interrupts` | Pending interrupts. Each item has `resolveInterrupt(...)`. See [Interrupts](../interrupts/overview). |
147| `resolveInterrupts`, `cancelInterrupts`, `retryInterrupts`, `resumeInterruptsUnsafe` | Act on all pending interrupts at once. |
148| `interruptErrors`, `resuming` | Errors from the last resume, and `true` while a resume runs. |
149| `isHydrating` | `true` while the chat loads from persistence. |
150| `hasOlderMessages`, `loadOlderMessages()` | Page in older messages. See [Chat Persistence](../persistence/chat-persistence). |
151| `isSubscribed`, `connectionStatus`, `sessionGenerating` | State of the live subscription. |
152| `partial`, `final` | Structured output. Only when you pass `outputSchema`. |
153​
154### Example: tool approval
155​
156A tool with `needsApproval: true` pauses the run. The pending call shows up in `interrupts`.
157​
158```typescript
159import { Component } from "@angular/core";
160import { toolDefinition } from "@tanstack/ai";
161import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
162import { z } from "zod";
163​
164const deleteFileTool = toolDefinition({
165 name: "delete_file",
166 description: "Delete a file",
167 needsApproval: true,
168 inputSchema: z.object({ path: z.string() }),
169});
170​
171@Component({
172 selector: "app-approval-chat",
173 standalone: true,
174 template: `
175 @for (interrupt of chat.interrupts(); track interrupt.id) {
176 @if (interrupt.kind === 'tool-approval') {
177 <div>
178 <p>Approve: {{ interrupt.toolName }}</p>
179 <button (click)="interrupt.resolveInterrupt(true)">Approve</button>
180 <button (click)="interrupt.resolveInterrupt(false)">Deny</button>
181 </div>
182 }
183 }
184 `,
185})
186export class ApprovalChatComponent {
187 chat = injectChat({
188 connection: fetchServerSentEvents("/api/chat"),
189 threadId: "support-chat",
190 tools: [deleteFileTool],
191 });
193```
194​
195See [Tool Approval](../interrupts/tool-approval) for the server side.
196​
197## `createChatHook(options)`
198​
199This package does not export `createChatHook` from its main entry. `@tanstack/ai-angular/ui` has a `createChatHook` that binds chat options and typed UI components. See [Angular Chat UI](../ui/angular).
200​
201## Generation hooks
202​
203Each injectable runs one generation request and keeps its result. See [Generation Hooks](../media/generation-hooks).
204​
205| Injectable | `generate()` input | `result` |
206| --- | --- | --- |
207| `injectGenerateImage` | `ImageGenerateInput` | `ImageGenerationResult` |
208| `injectGenerateAudio` | `AudioGenerateInput` | `AudioGenerationResult` |
209| `injectGenerateSpeech` | `SpeechGenerateInput` | `TTSResult` |
210| `injectTranscription` | `TranscriptionGenerateInput` | `TranscriptionResult` |
211| `injectSummarize` | `SummarizeGenerateInput` | `SummarizationResult` |
212| `injectGenerateVideo` | `VideoGenerateInput` | `VideoGenerateResult` |
213| `injectGeneration` | Your own input type | Your own result type |
214​
215```typescript
216import { Component } from "@angular/core";
217import { injectGenerateImage, fetchServerSentEvents } from "@tanstack/ai-angular";
218​
219@Component({
220 selector: "app-image",
221 standalone: true,
222 template: `
223 <button
224 (click)="image.generate({ prompt: 'A mountain at sunset' })"
225 [disabled]="image.isLoading()"
226 >
227 Generate
228 </button>
229 `,
230})
231export class ImageComponent {
232 image = injectGenerateImage({
233 connection: fetchServerSentEvents("/api/generate/image"),
234 threadId: "image-studio",
235 });
237```
238​
239Options: `threadId` (required), `connection` or `fetcher`, `body` (reactive), `persistence`, `byok`, `byokProvider`, `devtools`, `onResult`, `onError`, `onProgress`, `onChunk`.
240​
241Returns: `generate(input)`, `result`, `isLoading`, `error`, `status`, `stop()`, `reset()`, `runId`. The state fields are read-only signals. Cleanup runs in `DestroyRef.onDestroy`.
242​
243`injectGenerateVideo` also returns `jobId` and `videoStatus` signals, and takes `onJobCreated` and `onStatusUpdate`.
244​
245## Realtime chat
246​
247This package does not export a realtime injectable. Use `RealtimeClient`, which this package re-exports. See [Realtime Chat](../media/realtime-chat).
248​
249## `injectAudioRecorder(options?)`
250​
251Records audio from the microphone. See [Audio Recording](../media/audio-recording).
252​
253Returns `recording` and `isRecording` (signals), `isSupported`, `start()`, `stop()`, and `cancel()`. Pass `onComplete` to transform the recording. Then `recording` and `stop()` use the transformed type.
254​
255## `injectByok(client)`
256​
257Subscribes to a BYOK keyring and returns a read-only `Signal` of its snapshot. See [Bring Your Own Key](../advanced/byok).
258​
259```typescript
260import { Component, computed } from "@angular/core";
261import { injectByok } from "@tanstack/ai-angular";
262import { byok } from "./byok";
263​
264@Component({
265 selector: "app-key-status",
266 standalone: true,
267 template: `<p>{{ last4() }}</p>`,
268})
269export class KeyStatusComponent {
270 snapshot = injectByok(byok);
271​
272 last4 = computed(() => {
273 const openai = this.snapshot().status.openai;
274 return openai && "masked" in openai ? openai.masked : "No key";
275 });
277```
278​
279The snapshot has `status`, `locked`, `prompt`, and `storageError`. Save a key from your own UI with `byok.update(provider, value)`.
280​
281## MCP App bridge
282​
283This package does not export a bridge injectable. Use `createMcpAppBridge`, which this package re-exports. See [MCP Apps](../mcp/apps).
284​
285## `injectRegisterWebMCPTools(tools, options?)`
286​
287Exposes client tools to the browser WebMCP API for the current injection owner. Angular removes them when it destroys that owner. See [WebMCP Tools](../tools/webmcp).
288​
289```typescript
290import { Component } from "@angular/core";
291import { injectRegisterWebMCPTools } from "@tanstack/ai-angular";
292import { searchProducts } from "./tools";
293​
294@Component({ selector: "app-products", standalone: true, template: "" })
295export class ProductsComponent {
296 registration = injectRegisterWebMCPTools([searchProducts], {
297 onError: (error) => console.error(error),
298 });
300```
301​
302Options: `toolOptions`, `context`, and `onError`. `context` is required when a tool declares a required runtime context.
303​
304## `injectPageWebMCPTools(options?)`
305​
306Reads the WebMCP tools that the page registered, as client tools. The signal starts empty and updates when the page adds or removes a tool. Pass the signal to `injectChat` as `tools`. See [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
307​
308```typescript
309import { Component } from "@angular/core";
310import { injectPageWebMCPTools } from "@tanstack/ai-angular";
311​
312@Component({ selector: "app-page-tools", standalone: true, template: "" })
313export class PageToolsComponent {
314 pageTools = injectPageWebMCPTools({
315 filter: (tool) => tool.origin === location.origin,
316 });
318```
319​
320Options: `filter` (return `false` to skip a tool) and `onError`.
321​
322## Re-exports from `@tanstack/ai-client`
323​
324You can import these from `@tanstack/ai-angular` directly. See [`@tanstack/ai-client`](./ai-client) for details.
325​
326| Group | Exports |
327| --- | --- |
328| Connection adapters | `fetchServerSentEvents`, `fetchHttpStream`, `fetchJson`, `xhrServerSentEvents`, `xhrHttpStream`, `webSocket`, `stream`, `rpcStream` |
329| Typed options | `createChatClientOptions`, `clientTools` |
330| Persistence | `localStoragePersistence`, `sessionStoragePersistence`, `indexedDBPersistence` |
331| Clients | `ChatClient`, `GenerationClient`, `VideoGenerationClient`, `RealtimeClient`, `AudioRecorder`, `InterruptManager` |
332| WebMCP and MCP Apps | `registerWebMCPTools`, `getWebMCPTools`, `subscribeWebMCPTools`, `createMcpAppBridge` |
333| Errors | `UnsupportedResponseStreamError`, `StreamTruncatedError`, `DurableStreamIncompleteError`, `StreamReconnectLimitError`, `StorageUnavailableError` |
334| Stream helpers | `StreamProcessor`, chunk strategies, `parsePartialJSON`, message converters |
335​
336BYOK helpers (`defineByok`, `defaultByokStorage`, and more) are on the `@tanstack/ai-angular/byok` subpath.
337​
338## Types
339​
340| Type | What it is |
341| --- | --- |
342| `InjectChatOptions`, `InjectChatResult` | The options and return value of `injectChat`. |
343| `ReactiveOption<T>` | `T`, `Signal<T>`, or `() => T`. |
344| `UIMessage<TTools>` | A chat message with typed parts. |
345| `InferChatMessages<T>` | The message type for a `createChatClientOptions` result. |
346| `MultimodalContent`, `SendMessageOptions`, `WhenBusy`, `QueueOption`, `QueuedMessage` | Send and queue types. |
347| `DeepPartial<T>` | The type of `partial` while structured output streams. |
348| `Inject<Name>Options`, `Inject<Name>Result` | Options and return types for the generation and recorder injectables. The WebMCP injectables export only an options type. |
349​
350Pass a plain tools array to `injectChat` or `createChatClientOptions`. Tool names, inputs, and outputs stay typed without `as const`. Import `toolDefinition` from `@tanstack/ai`. This package does not re-export it.