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

ai-angular.md

579 lines18.3 KB

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```bash
23npm install @tanstack/ai-angular
24```
25​
26## `injectChat(options?)`
27​
28Main injectable for managing chat state in Angular with full type safety.
29​
30```typescript
31import { Component } from "@angular/core";
32import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
33​
34@Component({
35 selector: "app-chat",
36 standalone: true,
37 template: `...`,
38})
39export class ChatComponent {
40 // injectChat is called in a field initializer — valid injection context.
41 chat = injectChat({
42 connection: fetchServerSentEvents("/api/chat"),
43 });
45```
46​
47### Options
48​
49Extends `ChatClientOptions` from `@tanstack/ai-client` (minus internal state callbacks):
50​
51- `connection` - Connection adapter (required, or use `fetcher`)
52- `fetcher?` - Direct async function for one-shot generation (alternative to `connection`)
53- `tools?` - Array of client tool implementations (with `.client()` method)
54- `initialMessages?` - Initial messages array
55- `id?` - Unique identifier for this chat instance
56- `threadId?` - Thread ID for AG-UI run correlation. Persists across sends; auto-generated if omitted
57- `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`
58- `body?` - **Deprecated.** Use `forwardedProps` instead. Still works for backward compatibility; values are merged into `forwardedProps` on the wire. Reactive (same forms as `forwardedProps`)
59- `context?` - Typed client-local runtime context passed to client tool implementations. Reactive (same forms). This value is not serialized to the server
60- `live?` - Enable live subscription mode (auto-subscribes/unsubscribes). Reactive (same forms)
61- `outputSchema?` - Standard-schema-compatible schema (Zod, Valibot, ArkType, or JSON Schema). When provided, adds typed `partial` and `final` signals to the return value
62- `persistence?` - Persistence configuration
63- `devtools?` - Display options for TanStack AI Devtools
64- `onResponse?` - Callback when response is received
65- `onChunk?` - Callback when stream chunk is received
66- `onFinish?` - Callback when response finishes
67- `onError?` - Callback when error occurs
68- `onCustomEvent?` - Callback for custom stream events
69- `streamProcessor?` - Stream processing configuration
70​
71**Reactive options** (`body`, `forwardedProps`, `context`, `live`) accept a `ReactiveOption<T>`, which is one of:
72​
73```typescript
74import type { Signal } from "@angular/core";
75​
76type ReactiveOption<T> = T | Signal<T> | (() => T);
77```
78​
79A 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.
80​
81**Note:** Client tools are automatically executed — no `onToolCall` callback needed!
82​
83### Returns
84​
85```typescript
86import type { Signal } from "@angular/core";
87import type {
88 UIMessage,
89 MultimodalContent,
90 DeepPartial,
91} from "@tanstack/ai-angular";
92import type { ModelMessage, InferSchemaType } from "@tanstack/ai/client";
93import type { ChatClientState, ConnectionStatus } from "@tanstack/ai-client";
94type TSchema = any;
95​
96interface InjectChatResult {
97 messages: Signal<UIMessage[]>;
98 sendMessage: (content: string | MultimodalContent) => Promise<void>;
99 append: (message: ModelMessage | UIMessage) => Promise<void>;
100 addToolResult: (result: {
101 toolCallId: string;
102 tool: string;
103 output: any;
104 state?: "output-available" | "output-error";
105 errorText?: string;
106 }) => Promise<void>;
107 addToolApprovalResponse: (response: {
108 id: string;
109 approved: boolean;
110 }) => Promise<void>;
111 reload: () => Promise<void>;
112 stop: () => void;
113 clear: () => void;
114 setMessages: (messages: UIMessage[]) => void;
115 isLoading: Signal<boolean>;
116 error: Signal<Error | undefined>;
117 status: Signal<ChatClientState>;
118 isSubscribed: Signal<boolean>;
119 connectionStatus: Signal<ConnectionStatus>;
120 sessionGenerating: Signal<boolean>;
121 // Only present when outputSchema is supplied:
122 partial: Signal<DeepPartial<InferSchemaType<TSchema>>>;
123 final: Signal<InferSchemaType<TSchema> | null>;
125```
126​
127**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`.
128​
129## Connection Adapters
130​
131Re-exported from `@tanstack/ai-client` for convenience:
132​
133```typescript
134import {
135 fetchServerSentEvents,
136 fetchHttpStream,
137 xhrServerSentEvents,
138 xhrHttpStream,
139 stream,
140 rpcStream,
141 type ConnectionAdapter,
142} from "@tanstack/ai-angular";
143```
144​
145## Example: Basic Chat
146​
147```typescript
148import { Component } from "@angular/core";
149import { CommonModule } from "@angular/common";
150import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
151​
152@Component({
153 selector: "app-chat",
154 standalone: true,
155 imports: [CommonModule],
156 template: `
157 <ul>
158 @for (message of chat.messages(); track message.id) {
159 <li>
160 <strong>{{ message.role }}:</strong>
161 @for (part of message.parts; track $index) {
162 @if (part.type === 'thinking') {
163 <em>Thinking: {{ part.content }}</em>
164 } @else if (part.type === 'text') {
165 <span>{{ part.content }}</span>
166 }
167 }
168 </li>
169 }
170 </ul>
171 <input #input placeholder="Type a message..." />
172 <button
173 (click)="chat.sendMessage(input.value); input.value = ''"
174 [disabled]="chat.isLoading()"
175 >
176 Send
177 </button>
178 @if (chat.isLoading()) {
179 <p>Thinking...</p>
180 }
181 `,
182})
183export class ChatComponent {
184 chat = injectChat({
185 connection: fetchServerSentEvents("/api/chat"),
186 });
188```
189​
190## Example: Tool Approval
191​
192```typescript
193import { Component } from "@angular/core";
194import { CommonModule } from "@angular/common";
195import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
196​
197@Component({
198 selector: "app-approval-chat",
199 standalone: true,
200 imports: [CommonModule],
201 template: `
202 @for (message of chat.messages(); track message.id) {
203 @for (part of message.parts; track $index) {
204 @if (
205 part.type === 'tool-call' &&
206 part.state === 'approval-requested' &&
207 part.approval
208 ) {
209 <div>
210 <p>Approve: {{ part.name }}</p>
211 <button (click)="chat.addToolApprovalResponse({ id: part.approval!.id, approved: true })">
212 Approve
213 </button>
214 <button (click)="chat.addToolApprovalResponse({ id: part.approval!.id, approved: false })">
215 Deny
216 </button>
217 </div>
218 }
219 }
220 }
221 `,
222})
223export class ApprovalChatComponent {
224 chat = injectChat({
225 connection: fetchServerSentEvents("/api/chat"),
226 });
228```
229​
230## Example: Client Tools with Type Safety
231​
232```typescript
233import { Component } from "@angular/core";
234import { CommonModule } from "@angular/common";
235import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
236import {
237 createChatClientOptions,
238 type InferChatMessages,
239} from "@tanstack/ai-client";
240import { toolDefinition } from "@tanstack/ai";
241import { z } from "zod";
242​
243const updateUIDef = toolDefinition({
244 name: "updateUI",
245 description: "Show a notification in the UI",
246 inputSchema: z.object({ message: z.string(), type: z.string() }),
247});
248​
249const saveToStorageDef = toolDefinition({
250 name: "saveToStorage",
251 description: "Save a value to localStorage",
252 inputSchema: z.object({ key: z.string(), value: z.string() }),
253});
254​
255@Component({
256 selector: "app-typed-chat",
257 standalone: true,
258 imports: [CommonModule],
259 template: `
260 @for (message of chat.messages(); track message.id) {
261 @for (part of message.parts; track $index) {
262 @if (part.type === 'tool-call' && part.name === 'updateUI') {
263 <div>Tool executed: {{ part.name }}</div>
264 }
265 }
266 }
267 `,
268})
269export class TypedChatComponent {
270 // Create client implementations
271 private updateUI = updateUIDef.client((input) => {
272 // input is fully typed!
273 return { success: true };
274 });
275​
276 private saveToStorage = saveToStorageDef.client((input) => {
277 localStorage.setItem(input.key, input.value);
278 return { saved: true };
279 });
280​
281 // Create typed tools array (no 'as const' needed!)
282 private tools = [this.updateUI, this.saveToStorage];
283​
284 chat = injectChat({
285 connection: fetchServerSentEvents("/api/chat"),
286 tools: this.tools, // Automatic execution, full type safety
287 });
289```
290​
291## Example: Reactive Options with Signals
292​
293```typescript
294import { Component, signal } from "@angular/core";
295import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
296​
297@Component({
298 selector: "app-reactive-chat",
299 standalone: true,
300 template: `
301 <button (click)="toggleLanguage()">Toggle Language</button>
302 @for (message of chat.messages(); track message.id) {
303 <p>{{ message.role }}: {{ message.parts[0]?.content }}</p>
304 }
305 `,
306})
307export class ReactiveChatComponent {
308 language = signal("en");
309​
310 // forwardedProps is reactive — the signal is read on every request
311 chat = injectChat({
312 connection: fetchServerSentEvents("/api/chat"),
313 forwardedProps: () => ({ language: this.language() }),
314 });
315​
316 toggleLanguage() {
317 this.language.set(this.language() === "en" ? "fr" : "en");
318 }
320```
321​
322## Example: Structured Output
323​
324```typescript
325import { Component } from "@angular/core";
326import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
327import { z } from "zod";
328​
329const recipeSchema = z.object({
330 title: z.string(),
331 ingredients: z.array(z.string()),
332 steps: z.array(z.string()),
333});
334​
335@Component({
336 selector: "app-recipe-chat",
337 standalone: true,
338 template: `
339 <button (click)="chat.sendMessage('Give me a pasta recipe')">Ask</button>
340 @if (chat.partial().title) {
341 <h2>{{ chat.partial().title }}</h2>
342 }
343 @if (chat.final()) {
344 <ul>
345 @for (step of chat.final()!.steps; track $index) {
346 <li>{{ step }}</li>
347 }
348 </ul>
349 }
350 `,
351})
352export class RecipeChatComponent {
353 chat = injectChat({
354 connection: fetchServerSentEvents("/api/chat"),
355 outputSchema: recipeSchema,
356 });
358```
359​
360## Generation Injectables
361​
362Angular 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.
363​
364### `injectGeneration(options)`
365​
366Base injectable for custom generation types. All specialized injectables below are built on this.
367​
368```typescript
369import { Component } from "@angular/core";
370import { injectGeneration } from "@tanstack/ai-angular";
371import { fetchServerSentEvents } from "@tanstack/ai-client";
372​
373@Component({ selector: "app-custom", standalone: true, template: `...` })
374export class CustomGenerationComponent {
375 gen = injectGeneration({
376 connection: fetchServerSentEvents("/api/generate/custom"),
377 });
378​
379 // Call gen.generate(input), read gen.result(), gen.isLoading(), etc.
381```
382​
383**Options:** `connection?`, `fetcher?`, `id?`, `body?` (reactive), `devtools?`, `onResult?`, `onError?`, `onProgress?`, `onChunk?`
384​
385**Returns:** `generate`, `result`, `isLoading`, `error`, `status`, `stop`, `reset`, `runId`. All reactive state is a read-only `Signal<T>`.
386​
387### `injectGenerateImage(options)`
388​
389Image generation injectable. `generate()` accepts `ImageGenerateInput`, result is `ImageGenerationResult`.
390​
391```typescript
392import { Component } from "@angular/core";
393import { injectGenerateImage } from "@tanstack/ai-angular";
394import { fetchServerSentEvents } from "@tanstack/ai-client";
395​
396@Component({
397 selector: "app-image",
398 standalone: true,
399 template: `
400 <button (click)="gen.generate({ prompt: 'A mountain at sunset' })" [disabled]="gen.isLoading()">
401 Generate
402 </button>
403 @if (gen.result()) {
404 <img [src]="gen.result()!.images[0]!.url" alt="Generated image" />
405 }
406 `,
407})
408export class ImageComponent {
409 gen = injectGenerateImage({
410 connection: fetchServerSentEvents("/api/generate/image"),
411 });
413```
414​
415### `injectGenerateAudio(options)`
416​
417Audio generation injectable (music, sound effects). `generate()` accepts `AudioGenerateInput`, result is `AudioGenerationResult`.
418​
419```typescript
420import { Component } from "@angular/core";
421import { injectGenerateAudio } from "@tanstack/ai-angular";
422import { fetchServerSentEvents } from "@tanstack/ai-client";
423​
424@Component({
425 selector: "app-audio",
426 standalone: true,
427 template: `
428 <button (click)="gen.generate({ prompt: 'An upbeat electronic track', duration: 10 })" [disabled]="gen.isLoading()">
429 Generate
430 </button>
431 @if (gen.result()) {
432 <audio [src]="gen.result()!.audio.url" controls></audio>
433 }
434 `,
435})
436export class AudioComponent {
437 gen = injectGenerateAudio({
438 connection: fetchServerSentEvents("/api/generate/audio"),
439 });
441```
442​
443### `injectGenerateSpeech(options)`
444​
445Text-to-speech injectable. `generate()` accepts `SpeechGenerateInput`, result is `TTSResult`.
446​
447### `injectTranscription(options)`
448​
449Audio transcription injectable. `generate()` accepts `TranscriptionGenerateInput`, result is `TranscriptionResult`.
450​
451### `injectSummarize(options)`
452​
453Text summarization injectable. `generate()` accepts `SummarizeGenerateInput`, result is `SummarizationResult`.
454​
455### `injectGenerateVideo(options)`
456​
457Video generation injectable with job polling. Returns additional `jobId` and `videoStatus` signals. Accepts extra `onJobCreated?` and `onStatusUpdate?` callbacks.
458​
459```typescript
460import { Component } from "@angular/core";
461import { injectGenerateVideo } from "@tanstack/ai-angular";
462import { fetchServerSentEvents } from "@tanstack/ai-client";
463​
464@Component({
465 selector: "app-video",
466 standalone: true,
467 template: `
468 <button (click)="gen.generate({ prompt: 'A time-lapse of a sunset' })" [disabled]="gen.isLoading()">
469 Generate
470 </button>
471 @if (gen.videoStatus()) {
472 <p>Status: {{ gen.videoStatus()!.status }}</p>
473 }
474 @if (gen.result()) {
475 <video [src]="gen.result()!.url" controls></video>
476 }
477 `,
478})
479export class VideoComponent {
480 gen = injectGenerateVideo({
481 connection: fetchServerSentEvents("/api/generate/video"),
482 onJobCreated: (jobId) => console.log("Job created:", jobId),
483 });
485```
486​
487**Additional returns (video only):**
488- `jobId: Signal<string | null>` — The polling job ID, once the server creates it
489- `videoStatus: Signal<VideoStatusInfo | null>` — Real-time status updates from the polling loop
490​
491All generation injectables automatically clean up via `DestroyRef.onDestroy`.
492​
493## Injection Context
494​
495Angular's DI system requires that `inject()` is called during component construction. Every `inject*` function in this package calls `inject()` internally. Valid call sites:
496​
497```typescript
498import { inject, runInInjectionContext, Injector } from "@angular/core";
499import { injectChat, fetchServerSentEvents } from "@tanstack/ai-angular";
500​
501const injector = inject(Injector);
502​
503// Field initializer (recommended)
504export class MyComponent {
505 chat = injectChat({ connection: fetchServerSentEvents("/api/chat") });
507​
508// Constructor
509export class MyComponentAlt {
510 chat: ReturnType<typeof injectChat>;
511 constructor() {
512 this.chat = injectChat({ connection: fetchServerSentEvents("/api/chat") });
513 }
515​
516// Inside runInInjectionContext
517const chat = runInInjectionContext(injector, () =>
518 injectChat({ connection: fetchServerSentEvents("/api/chat") }),
519);
520```
521​
522## `createChatClientOptions(options)`
523​
524Helper to create typed chat options (re-exported from `@tanstack/ai-client`).
525​
526```typescript
527import {
528 createChatClientOptions,
529 type InferChatMessages,
530} from "@tanstack/ai-client";
531import { fetchServerSentEvents } from "@tanstack/ai-angular";
532import { tool1, tool2 } from "./tools";
533​
534// Create typed tools array (no 'as const' needed!)
535const tools = [tool1, tool2];
536​
537const chatOptions = createChatClientOptions({
538 connection: fetchServerSentEvents("/api/chat"),
539 tools,
540});
541​
542type Messages = InferChatMessages<typeof chatOptions>;
543```
544​
545## Types
546​
547Re-exported from `@tanstack/ai-angular` (sourced from `@tanstack/ai-client`):
548​
549- `UIMessage<TTools>` - Message type with tool type parameter
550- `InjectChatOptions<TTools, TSchema, TContext>` - Chat injectable options
551- `InjectChatResult<TTools, TSchema>` - Chat injectable return type
552- `ReactiveOption<T>` - Union of `T | Signal<T> | (() => T)` for reactive option fields
553- `DeepPartial<T>` - Recursive partial; used to type the in-flight `partial` value
554- `ChatRequestBody` - Request body type
555- `MultimodalContent` - Multimodal content type for `sendMessage`
556- `ConnectionAdapter` - Connection adapter interface
557- `InferChatMessages<T>` - Extract message type from options
558- `GenerationClientState` - Generation lifecycle state
559- `ImageGenerateInput` - Image generation input type
560- `AudioGenerateInput` - Audio generation input type
561- `SpeechGenerateInput` - Speech generation input type
562- `TranscriptionGenerateInput` - Transcription input type
563- `SummarizeGenerateInput` - Summarization input type
564- `VideoGenerateInput` - Video generation input type
565- `VideoGenerateResult` - Video generation result type
566- `VideoStatusInfo` - Video job status info
567​
568Tool authoring types — import directly from `@tanstack/ai` (not re-exported by `@tanstack/ai-angular`):
569​
570- `toolDefinition()` - Create isomorphic tool definition
571- `ToolDefinitionInstance` - Tool definition type
572- `ClientTool` - Client tool type
573- `ServerTool` - Server tool type
574​
575## Next Steps
576​
577- [Getting Started](../getting-started/quick-start) - Learn the basics
578- [Tools Guide](../tools/tools) - Learn about the isomorphic tool system
579- [Client Tools](../tools/client-tools) - Learn about client-side tools