Open History to see the last commit
1---
2title: "@tanstack/ai-angular"
3id: ai-angular
4order: 6
5description: "API reference for @tanstack/ai-angular — Angular signal-based injectables including injectChat for streaming chat with full type safety."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-angular"
9 - angular
10 - signals
11 - injectChat
12 - injectables
13 - api reference
14---
15
16Angular signal-based bindings for TanStack AI, providing convenient Angular bindings for the headless client.
17
18> **Injection context requirement:** Every `inject*` function in this package calls Angular's `inject()` internally. They **must** be called within an Angular injection context — a component or directive class field initializer, the constructor, or inside `runInInjectionContext`. Calling them outside an injection context will throw a runtime error.
19
20## Installation
21
22<!-- ::start:tabs variant="package-manager" mode="install" -->
23
24angular: @tanstack/ai-angular
25
26<!-- ::end:tabs -->
27
28## `injectRegisterWebMCPTools(tools, options?)`
29
30Register executable client tools for the current Angular injection owner. Angular removes them when it destroys that owner.
31
32For a complete setup and behavior guide, see [WebMCP Tools](../tools/webmcp).
33
34```typescript
35import { Component } from "@angular/core";
36import {
37 injectRegisterWebMCPTools,
38 type InjectRegisterWebMCPToolsOptions,
39} from "@tanstack/ai-angular";
40import { searchProducts } from "./tools";
41
42const tools = [searchProducts];
43const options: InjectRegisterWebMCPToolsOptions<typeof tools> = {
44 onError(error) {
45 console.error(error);
46 },
47};
48
49@Component({ selector: "app-products", standalone: true, template: "" })
50export class ProductsComponent {
51 registration = injectRegisterWebMCPTools(tools, options);
52}
53```
54
55`InjectRegisterWebMCPToolsOptions<TTools, TContext>` contains `toolOptions`, `context`, and `onError`. The injectable owns the registration signal.
56
57The `context` field is required when a tool declares a required runtime context. Call this function only in an Angular injection context.
58
59## `injectPageWebMCPTools(options?)`
60
61Read the WebMCP tools on the page as client tools. The signal starts empty and updates when the page adds or removes a tool. Pass the signal to `injectChat` as `tools`. Call it in an injection context.
62
63```ts
64import { Component } from "@angular/core";
65import { injectPageWebMCPTools } from "@tanstack/ai-angular";
66
67@Component({ selector: "app-page-tools", standalone: true, template: "" })
68export class PageTools {
69 pageTools = injectPageWebMCPTools({
70 filter: (tool) => tool.origin === location.origin,
71 });
72}
73```
74
75`filter` skips a tool when it returns `false`. `onError` gets a failed WebMCP read. For a complete guide, see [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
76
77## `injectChat(options?)`
78
79Main injectable for managing chat state in Angular with full type safety.
80
81```typescript
82import { Component } from "@angular/core";
83import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
84
85@Component({
86 selector: "app-chat",
87 standalone: true,
88 template: `...`,
89})
90export class ChatComponent {
91 // injectChat is called in a field initializer — valid injection context.
92 chat = injectChat({
93 connection: fetchServerSentEvents("/api/chat"),
94 });
95}
96```
97
98### Options
99
100Extends `ChatClientOptions` from `@tanstack/ai-client` (minus internal state callbacks):
101
102- `connection` - Connection adapter (required, or use `fetcher`)
103- `fetcher?` - Direct async function for one-shot generation (alternative to `connection`)
104- `tools?` - Array of client tool implementations (with `.client()` method). Reactive: pass a `Signal` or getter to change the tools after the chat is created.
105- `initialMessages?` - Initial messages array
106- `threadId?` - The only identity for this chat. Required when persistence is on. If omitted, minted after mount.
107- `forwardedProps?` - Arbitrary client-controlled JSON forwarded to the server in the AG-UI `RunAgentInput.forwardedProps` field. Reactive — accepts a plain value, an Angular `Signal`, or a zero-arg getter; changes sync automatically via `effect`
108- `body?` - **Deprecated.** Use `forwardedProps` instead. Still works for backward compatibility; values are merged into `forwardedProps` on the wire. Reactive (same forms as `forwardedProps`)
109- `byok?` - Optional BYOK keyring from `defineByok`. On each send the client prepares the resolved provider and stamps `x-byok-*` request headers. Keys never go in the body
110- `byokProvider?` - Optional function that returns the provider slug for this chat. If it returns a slug, only that key is prepared and sent. Otherwise the merged `provider` from `forwardedProps`, `body`, and per-call `sendMessage` `body` is used. Later sources win. If no slug resolves, the send throws instead of attaching every stored key
111- `context?` - Typed client-local runtime context passed to client tool implementations. Reactive (same forms). This value is not serialized to the server
112- `live?` - Enable live subscription mode (auto-subscribes/unsubscribes). Reactive (same forms)
113- `outputSchema?` - Standard-schema-compatible schema (Zod, Valibot, ArkType, or JSON Schema). When provided, adds typed `partial` and `final` signals to the return value
114- `persistence?` - Persistence configuration
115- `devtools?` - Display options for TanStack AI Devtools
116- `onResponse?` - Callback when response is received
117- `onChunk?` - Callback when stream chunk is received
118- `onFinish?` - Callback when response finishes
119- `onError?` - Callback when error occurs
120- `onInterruptStateChange?` - Callback when interrupt state changes; context source is `hydrate` for restored state and `live` for streamed or client-initiated updates
121- `onCustomEvent?` - Callback for custom stream events
122- `streamProcessor?` - Stream processing configuration
123
124**Reactive options** (`body`, `forwardedProps`, `context`, `live`) accept a `ReactiveOption<T>`, which is one of:
125
126```typescript
127import type { Signal } from "@angular/core";
128
129type ReactiveOption<T> = T | Signal<T> | (() => T);
130```
131
132A plain value becomes a constant; a `Signal` is read directly; a zero-arg getter is wrapped in `computed` so any signals read inside it are tracked.
133
134**Note:** Client tools are automatically executed — no `onToolCall` callback needed!
135
136### Returns
137
138```typescript
139import type { Signal } from "@angular/core";
140import type {
141 UIMessage,
142 MultimodalContent,
143 DeepPartial,
144} from "@tanstack/ai-angular";
145import type { ModelMessage, InferSchemaType } from "@tanstack/ai/client";
146import type {
147 ChatClientState,
148 ConnectionStatus,
149 SendMessageOptions,
150} from "@tanstack/ai-client";
151type TSchema = any;
152
153interface InjectChatResult {
154 messages: Signal<UIMessage[]>;
155 sendMessage: (
156 content: string | MultimodalContent,
157 options?: SendMessageOptions,
158 ) => Promise<void>;
159 append: (message: ModelMessage | UIMessage) => Promise<void>;
160 addToolResult: (result: {
161 toolCallId: string;
162 tool: string;
163 output: any;
164 state?: "output-available" | "output-error";
165 errorText?: string;
166 }) => Promise<void>;
167 addToolApprovalResponse: (response: {
168 id: string;
169 approved: boolean;
170 }) => Promise<void>;
171 reload: () => Promise<void>;
172 stop: () => void;
173 clear: () => void;
174 setMessages: (messages: UIMessage[]) => void;
175 isLoading: Signal<boolean>;
176 error: Signal<Error | undefined>;
177 status: Signal<ChatClientState>;
178 isSubscribed: Signal<boolean>;
179 connectionStatus: Signal<ConnectionStatus>;
180 sessionGenerating: Signal<boolean>;
181 // Only present when outputSchema is supplied:
182 partial: Signal<DeepPartial<InferSchemaType<TSchema>>>;
183 final: Signal<InferSchemaType<TSchema> | null>;
184}
185```
186
187**Note:** All reactive state (`messages`, `isLoading`, `error`, `status`, `isSubscribed`, `connectionStatus`, `sessionGenerating`) is exposed as read-only Angular `Signal`s. Read them by calling them as functions (e.g., `chat.messages()`, `chat.isLoading()`). Cleanup is automatic via `DestroyRef.onDestroy`.
188
189## `injectByok(client)`
190
191Subscribe to a `ByokClient` snapshot in Angular. Call it in an injection context. The return value is a read-only `Signal`.
192
193```typescript
194import { Component } from "@angular/core";
195import { injectByok } from "@tanstack/ai-angular";
196import { byok } from "./byok";
197
198@Component({
199 selector: "app-key-status",
200 standalone: true,
201 template: `<p>{{ last4() }}</p>`,
202})
203export class KeyStatusComponent {
204 snapshot = injectByok(byok);
205
206 last4() {
207 const openai = this.snapshot().status.openai;
208 return openai && "masked" in openai ? openai.masked : "No key";
209 }
210}
211```
212
213`snapshot()` has `status`, `locked`, and `prompt`. Call `byok.update(provider, value)` from your own UI to save a key. See [Bring Your Own Key](../advanced/byok).
214
215## Connection Adapters
216
217Re-exported from `@tanstack/ai-client` for convenience:
218
219```typescript
220import {
221 fetchServerSentEvents,
222 fetchHttpStream,
223 xhrServerSentEvents,
224 xhrHttpStream,
225 stream,
226 rpcStream,
227 type ConnectionAdapter,
228} from "@tanstack/ai-angular";
229```
230
231## Example: Basic Chat
232
233```typescript
234import { Component } from "@angular/core";
235import { CommonModule } from "@angular/common";
236import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
237
238@Component({
239 selector: "app-chat",
240 standalone: true,
241 imports: [CommonModule],
242 template: `
243 <ul>
244 @for (message of chat.messages(); track message.id) {
245 <li>
246 <strong>{{ message.role }}:</strong>
247 @for (part of message.parts; track $index) {
248 @if (part.type === 'thinking') {
249 <em>Thinking: {{ part.content }}</em>
250 } @else if (part.type === 'text') {
251 <span>{{ part.content }}</span>
252 }
253 }
254 </li>
255 }
256 </ul>
257 <input #input placeholder="Type a message..." />
258 <button
259 (click)="chat.sendMessage(input.value); input.value = ''"
260 [disabled]="chat.isLoading()"
261 >
262 Send
263 </button>
264 @if (chat.isLoading()) {
265 <p>Thinking...</p>
266 }
267 `,
268})
269export class ChatComponent {
270 chat = injectChat({
271 connection: fetchServerSentEvents("/api/chat"),
272 });
273}
274```
275
276## Example: Tool Approval
277
278```typescript
279import { Component } from "@angular/core";
280import { CommonModule } from "@angular/common";
281import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
282
283@Component({
284 selector: "app-approval-chat",
285 standalone: true,
286 imports: [CommonModule],
287 template: `
288 @for (message of chat.messages(); track message.id) {
289 @for (part of message.parts; track $index) {
290 @if (
291 part.type === 'tool-call' &&
292 part.state === 'approval-requested' &&
293 part.approval
294 ) {
295 <div>
296 <p>Approve: {{ part.name }}</p>
297 <button (click)="chat.addToolApprovalResponse({ id: part.approval!.id, approved: true })">
298 Approve
299 </button>
300 <button (click)="chat.addToolApprovalResponse({ id: part.approval!.id, approved: false })">
301 Deny
302 </button>
303 </div>
304 }
305 }
306 }
307 `,
308})
309export class ApprovalChatComponent {
310 chat = injectChat({
311 connection: fetchServerSentEvents("/api/chat"),
312 });
313}
314```
315
316## Example: Client Tools with Type Safety
317
318```typescript
319import { Component } from "@angular/core";
320import { CommonModule } from "@angular/common";
321import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
322import {
323 createChatClientOptions,
324 type InferChatMessages,
325} from "@tanstack/ai-client";
326import { toolDefinition } from "@tanstack/ai";
327import { z } from "zod";
328
329const updateUIDef = toolDefinition({
330 name: "updateUI",
331 description: "Show a notification in the UI",
332 inputSchema: z.object({ message: z.string(), type: z.string() }),
333});
334
335const saveToStorageDef = toolDefinition({
336 name: "saveToStorage",
337 description: "Save a value to localStorage",
338 inputSchema: z.object({ key: z.string(), value: z.string() }),
339});
340
341@Component({
342 selector: "app-typed-chat",
343 standalone: true,
344 imports: [CommonModule],
345 template: `
346 @for (message of chat.messages(); track message.id) {
347 @for (part of message.parts; track $index) {
348 @if (part.type === 'tool-call' && part.name === 'updateUI') {
349 <div>Tool executed: {{ part.name }}</div>
350 }
351 }
352 }
353 `,
354})
355export class TypedChatComponent {
356 // Create client implementations
357 private updateUI = updateUIDef.client((input) => {
358 // input is fully typed!
359 return { success: true };
360 });
361
362 private saveToStorage = saveToStorageDef.client((input) => {
363 localStorage.setItem(input.key, input.value);
364 return { saved: true };
365 });
366
367 // Create typed tools array (no 'as const' needed!)
368 private tools = [this.updateUI, this.saveToStorage];
369
370 chat = injectChat({
371 connection: fetchServerSentEvents("/api/chat"),
372 tools: this.tools, // Automatic execution, full type safety
373 });
374}
375```
376
377## Example: Reactive Options with Signals
378
379```typescript
380import { Component, signal } from "@angular/core";
381import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
382
383@Component({
384 selector: "app-reactive-chat",
385 standalone: true,
386 template: `
387 <button (click)="toggleLanguage()">Toggle Language</button>
388 @for (message of chat.messages(); track message.id) {
389 <p>{{ message.role }}: {{ message.parts[0]?.content }}</p>
390 }
391 `,
392})
393export class ReactiveChatComponent {
394 language = signal("en");
395
396 // forwardedProps is reactive — the signal is read on every request
397 chat = injectChat({
398 connection: fetchServerSentEvents("/api/chat"),
399 forwardedProps: () => ({ language: this.language() }),
400 });
401
402 toggleLanguage() {
403 this.language.set(this.language() === "en" ? "fr" : "en");
404 }
405}
406```
407
408## Example: Structured Output
409
410```typescript
411import { Component } from "@angular/core";
412import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
413import { z } from "zod";
414
415const recipeSchema = z.object({
416 title: z.string(),
417 ingredients: z.array(z.string()),
418 steps: z.array(z.string()),
419});
420
421@Component({
422 selector: "app-recipe-chat",
423 standalone: true,
424 template: `
425 <button (click)="chat.sendMessage('Give me a pasta recipe')">Ask</button>
426 @if (chat.partial().title) {
427 <h2>{{ chat.partial().title }}</h2>
428 }
429 @if (chat.final()) {
430 <ul>
431 @for (step of chat.final()!.steps; track $index) {
432 <li>{{ step }}</li>
433 }
434 </ul>
435 }
436 `,
437})
438export class RecipeChatComponent {
439 chat = injectChat({
440 connection: fetchServerSentEvents("/api/chat"),
441 outputSchema: recipeSchema,
442 });
443}
444```
445
446## Generation Injectables
447
448Angular injectables for one-shot generation tasks (images, audio, speech, transcription, summarization, video). All share the same pattern: provide a `connection` or `fetcher`, call `generate()`, and read reactive signals.
449
450### `injectGeneration(options)`
451
452Base injectable for custom generation types. All specialized injectables below are built on this.
453
454```typescript
455import { Component } from "@angular/core";
456import { injectGeneration } from "@tanstack/ai-angular";
457import { fetchServerSentEvents } from "@tanstack/ai-client";
458
459@Component({ selector: "app-custom", standalone: true, template: `...` })
460export class CustomGenerationComponent {
461 gen = injectGeneration({
462 connection: fetchServerSentEvents("/api/generate/custom"),
463 });
464
465 // Call gen.generate(input), read gen.result(), gen.isLoading(), etc.
466}
467```
468
469**Options:** `connection?`, `fetcher?`, `threadId?`, `body?` (reactive), `devtools?`, `onResult?`, `onError?`, `onProgress?`, `onChunk?`
470
471**Returns:** `generate`, `result`, `isLoading`, `error`, `status`, `stop`, `reset`, `runId`. All reactive state is a read-only `Signal<T>`.
472
473### `injectGenerateImage(options)`
474
475Image generation injectable. `generate()` accepts `ImageGenerateInput`, result is `ImageGenerationResult`.
476
477```typescript
478import { Component } from "@angular/core";
479import { injectGenerateImage } from "@tanstack/ai-angular";
480import { fetchServerSentEvents } from "@tanstack/ai-client";
481
482@Component({
483 selector: "app-image",
484 standalone: true,
485 template: `
486 <button (click)="gen.generate({ prompt: 'A mountain at sunset' })" [disabled]="gen.isLoading()">
487 Generate
488 </button>
489 @if (gen.result()) {
490 <img [src]="gen.result()!.images[0]!.url" alt="Generated image" />
491 }
492 `,
493})
494export class ImageComponent {
495 gen = injectGenerateImage({
496 connection: fetchServerSentEvents("/api/generate/image"),
497 });
498}
499```
500
501### `injectGenerateAudio(options)`
502
503Audio generation injectable (music, sound effects). `generate()` accepts `AudioGenerateInput`, result is `AudioGenerationResult`.
504
505```typescript
506import { Component } from "@angular/core";
507import { injectGenerateAudio } from "@tanstack/ai-angular";
508import { fetchServerSentEvents } from "@tanstack/ai-client";
509
510@Component({
511 selector: "app-audio",
512 standalone: true,
513 template: `
514 <button (click)="gen.generate({ prompt: 'An upbeat electronic track', duration: 10 })" [disabled]="gen.isLoading()">
515 Generate
516 </button>
517 @if (gen.result()) {
518 <audio [src]="gen.result()!.audio.url" controls></audio>
519 }
520 `,
521})
522export class AudioComponent {
523 gen = injectGenerateAudio({
524 connection: fetchServerSentEvents("/api/generate/audio"),
525 });
526}
527```
528
529### `injectGenerateSpeech(options)`
530
531Text-to-speech injectable. `generate()` accepts `SpeechGenerateInput`, result is `TTSResult`.
532
533### `injectTranscription(options)`
534
535Audio transcription injectable. `generate()` accepts `TranscriptionGenerateInput`, result is `TranscriptionResult`.
536
537### `injectSummarize(options)`
538
539Text summarization injectable. `generate()` accepts `SummarizeGenerateInput`, result is `SummarizationResult`.
540
541### `injectGenerateVideo(options)`
542
543Video generation injectable with job polling. Returns additional `jobId` and `videoStatus` signals. Accepts extra `onJobCreated?` and `onStatusUpdate?` callbacks.
544
545```typescript
546import { Component } from "@angular/core";
547import { injectGenerateVideo } from "@tanstack/ai-angular";
548import { fetchServerSentEvents } from "@tanstack/ai-client";
549
550@Component({
551 selector: "app-video",
552 standalone: true,
553 template: `
554 <button (click)="gen.generate({ prompt: 'A time-lapse of a sunset' })" [disabled]="gen.isLoading()">
555 Generate
556 </button>
557 @if (gen.videoStatus()) {
558 <p>Status: {{ gen.videoStatus()!.status }}</p>
559 }
560 @if (gen.result()) {
561 <video [src]="gen.result()!.url" controls></video>
562 }
563 `,
564})
565export class VideoComponent {
566 gen = injectGenerateVideo({
567 connection: fetchServerSentEvents("/api/generate/video"),
568 onJobCreated: (jobId) => console.log("Job created:", jobId),
569 });
570}
571```
572
573**Additional returns (video only):**
574- `jobId: Signal<string | null>` — The polling job ID, once the server creates it
575- `videoStatus: Signal<VideoStatusInfo | null>` — Real-time status updates from the polling loop
576
577All generation injectables automatically clean up via `DestroyRef.onDestroy`.
578
579## Injection Context
580
581Angular's DI system requires that `inject()` is called during component construction. Every `inject*` function in this package calls `inject()` internally. Valid call sites:
582
583```typescript
584import { inject, runInInjectionContext, Injector } from "@angular/core";
585import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
586
587const injector = inject(Injector);
588
589// Field initializer (recommended)
590export class MyComponent {
591 chat = injectChat({ connection: fetchServerSentEvents("/api/chat") });
592}
593
594// Constructor
595export class MyComponentAlt {
596 chat: ReturnType<typeof injectChat>;
597 constructor() {
598 this.chat = injectChat({ connection: fetchServerSentEvents("/api/chat") });
599 }
600}
601
602// Inside runInInjectionContext
603const chat = runInInjectionContext(injector, () =>
604 injectChat({ connection: fetchServerSentEvents("/api/chat") }),
605);
606```
607
608## `createChatClientOptions(options)`
609
610Helper to create typed chat options (re-exported from `@tanstack/ai-client`).
611
612```typescript
613import {
614 createChatClientOptions,
615 type InferChatMessages,
616} from "@tanstack/ai-client";
617import { fetchServerSentEvents } from "@tanstack/ai-angular";
618import { tool1, tool2 } from "./tools";
619
620// Create typed tools array (no 'as const' needed!)
621const tools = [tool1, tool2];
622
623const chatOptions = createChatClientOptions({
624 connection: fetchServerSentEvents("/api/chat"),
625 tools,
626});
627
628type Messages = InferChatMessages<typeof chatOptions>;
629```
630
631## Types
632
633Re-exported from `@tanstack/ai-angular` (sourced from `@tanstack/ai-client`):
634
635- `UIMessage<TTools>` - Message type with tool type parameter
636- `InjectChatOptions<TTools, TSchema, TContext>` - Chat injectable options
637- `InjectChatResult<TTools, TSchema>` - Chat injectable return type
638- `ReactiveOption<T>` - Union of `T | Signal<T> | (() => T)` for reactive option fields
639- `DeepPartial<T>` - Recursive partial; used to type the in-flight `partial` value
640- `ChatRequestBody` - Request body type
641- `MultimodalContent` - Multimodal content type for `sendMessage`
642- `ConnectionAdapter` - Connection adapter interface
643- `InferChatMessages<T>` - Extract message type from options
644- `GenerationClientState` - Generation lifecycle state
645- `ImageGenerateInput` - Image generation input type
646- `AudioGenerateInput` - Audio generation input type
647- `SpeechGenerateInput` - Speech generation input type
648- `TranscriptionGenerateInput` - Transcription input type
649- `SummarizeGenerateInput` - Summarization input type
650- `VideoGenerateInput` - Video generation input type
651- `VideoGenerateResult` - Video generation result type
652- `VideoStatusInfo` - Video job status info
653
654Tool authoring types — import directly from `@tanstack/ai` (not re-exported by `@tanstack/ai-angular`):
655
656- `toolDefinition()` - Create isomorphic tool definition
657- `ToolDefinitionInstance` - Tool definition type
658- `ClientTool` - Client tool type
659- `ServerTool` - Server tool type
660
661## Next Steps
662
663- [Getting Started](../getting-started/quick-start) - Learn the basics
664- [Tools Guide](../tools/tools) - Learn about the isomorphic tool system
665- [Client Tools](../tools/client-tools) - Learn about client-side tools