@tanstack/ai-angular 0.1.10 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/README.md +158 -0
- package/dist/fesm2022/tanstack-ai-angular.mjs +532 -0
- package/dist/fesm2022/tanstack-ai-angular.mjs.map +1 -0
- package/dist/types/tanstack-ai-angular.d.ts +357 -0
- package/package.json +4 -4
- package/src/index.ts +7 -0
- package/src/inject-audio-recorder.ts +96 -0
- package/src/inject-generate-audio.ts +5 -8
- package/src/inject-generate-image.ts +5 -8
- package/src/inject-generate-speech.ts +7 -7
- package/src/inject-generate-video.ts +17 -9
- package/src/inject-generation.ts +19 -6
- package/src/inject-summarize.ts +10 -11
- package/src/inject-transcription.ts +5 -8
package/dist/README.md
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
<img src="https://raw.githubusercontent.com/TanStack/ai/main/media/header_ai.png" alt="TanStack AI" />
|
|
3
|
+
</div>
|
|
4
|
+
|
|
5
|
+
<br />
|
|
6
|
+
|
|
7
|
+
<div align="center">
|
|
8
|
+
<a href="https://npmjs.com/package/@tanstack/ai-angular" target="_parent">
|
|
9
|
+
<img alt="NPM downloads" src="https://img.shields.io/npm/dm/@tanstack/ai-angular.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/TanStack/ai" target="_parent">
|
|
12
|
+
<img alt="GitHub stars" src="https://img.shields.io/github/stars/TanStack/ai.svg?style=social&label=Star" />
|
|
13
|
+
</a>
|
|
14
|
+
<a href="https://github.com/TanStack/ai/releases" target="_parent">
|
|
15
|
+
<img alt="Release" src="https://img.shields.io/github/v/release/tanstack/ai" />
|
|
16
|
+
</a>
|
|
17
|
+
<a href="https://bundlephobia.com/result?p=@tanstack/ai-angular@latest" target="_parent">
|
|
18
|
+
<img alt="Bundle size" src="https://badgen.net/bundlephobia/minzip/@tanstack/ai-angular@latest" />
|
|
19
|
+
</a>
|
|
20
|
+
<a href="https://twitter.com/tan_stack">
|
|
21
|
+
<img alt="Follow @TanStack" src="https://img.shields.io/twitter/follow/tan_stack.svg?style=social" />
|
|
22
|
+
</a>
|
|
23
|
+
</div>
|
|
24
|
+
|
|
25
|
+
# TanStack AI — Angular
|
|
26
|
+
|
|
27
|
+
Angular signal-based bindings for TanStack AI — streaming chat, tool-calling agents, and media generation built on Angular's native reactivity model.
|
|
28
|
+
|
|
29
|
+
## <a href="https://tanstack.com/ai">Read the docs -></a>
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pnpm add @tanstack/ai-angular @tanstack/ai
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
npm install @tanstack/ai-angular @tanstack/ai
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Minimal Usage
|
|
42
|
+
|
|
43
|
+
> **Important:** All `inject*` functions use Angular's dependency injection system and **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.
|
|
44
|
+
|
|
45
|
+
The example below shows a standalone component that streams chat messages from a server endpoint via SSE:
|
|
46
|
+
|
|
47
|
+
```typescript
|
|
48
|
+
import { Component } from '@angular/core'
|
|
49
|
+
import { CommonModule } from '@angular/common'
|
|
50
|
+
import { injectChat } from '@tanstack/ai-angular'
|
|
51
|
+
import { fetchServerSentEvents } from '@tanstack/ai-client'
|
|
52
|
+
|
|
53
|
+
@Component({
|
|
54
|
+
selector: 'app-chat',
|
|
55
|
+
standalone: true,
|
|
56
|
+
imports: [CommonModule],
|
|
57
|
+
template: `
|
|
58
|
+
<ul>
|
|
59
|
+
@for (message of chat.messages(); track message.id) {
|
|
60
|
+
<li>{{ message.role }}: {{ message.content }}</li>
|
|
61
|
+
}
|
|
62
|
+
</ul>
|
|
63
|
+
<input #input placeholder="Type a message..." />
|
|
64
|
+
<button (click)="chat.sendMessage(input.value); input.value = ''">
|
|
65
|
+
Send
|
|
66
|
+
</button>
|
|
67
|
+
@if (chat.isLoading()) {
|
|
68
|
+
<p>Thinking...</p>
|
|
69
|
+
}
|
|
70
|
+
`,
|
|
71
|
+
})
|
|
72
|
+
export class ChatComponent {
|
|
73
|
+
// injectChat is called in a field initializer — this is a valid injection context.
|
|
74
|
+
chat = injectChat({
|
|
75
|
+
connection: fetchServerSentEvents('/api/chat'),
|
|
76
|
+
})
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
All state is exposed as Angular `Signal`s. Read them by calling them as functions:
|
|
81
|
+
|
|
82
|
+
| Signal | Type | Description |
|
|
83
|
+
| ------------------------- | -------------------- | ------------------------------------------- |
|
|
84
|
+
| `chat.messages()` | `UIMessage[]` | Current message list |
|
|
85
|
+
| `chat.isLoading()` | `boolean` | Whether a response is streaming |
|
|
86
|
+
| `chat.error()` | `Error \| undefined` | Last error, if any |
|
|
87
|
+
| `chat.status()` | `ChatClientState` | `'ready'`, `'streaming'`, `'error'`, ... |
|
|
88
|
+
| `chat.isSubscribed()` | `boolean` | Whether a live (SSE push) session is active |
|
|
89
|
+
| `chat.connectionStatus()` | `ConnectionStatus` | Transport connection status |
|
|
90
|
+
|
|
91
|
+
Available methods on the return value: `sendMessage`, `append`, `reload`, `stop`, `clear`, `setMessages`, `addToolResult`, `addToolApprovalResponse`.
|
|
92
|
+
|
|
93
|
+
## Server endpoint
|
|
94
|
+
|
|
95
|
+
The client pairs with any endpoint that returns a TanStack AI SSE stream:
|
|
96
|
+
|
|
97
|
+
```typescript
|
|
98
|
+
import { chat, toServerSentEventsResponse } from '@tanstack/ai'
|
|
99
|
+
import { openaiText } from '@tanstack/ai-openai'
|
|
100
|
+
|
|
101
|
+
export async function POST(request: Request) {
|
|
102
|
+
const body = await request.json()
|
|
103
|
+
|
|
104
|
+
const stream = chat({
|
|
105
|
+
adapter: openaiText('gpt-5.5'),
|
|
106
|
+
messages: body.messages,
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
return toServerSentEventsResponse(stream)
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Available Functions
|
|
114
|
+
|
|
115
|
+
| Function | Description |
|
|
116
|
+
| ---------------------- | ---------------------------------------------------------------- |
|
|
117
|
+
| `injectChat` | Streaming chat with messages, tool calls, and structured outputs |
|
|
118
|
+
| `injectGeneration` | Generic generation client (streaming or one-shot) |
|
|
119
|
+
| `injectGenerateImage` | Image generation |
|
|
120
|
+
| `injectGenerateAudio` | Audio generation |
|
|
121
|
+
| `injectGenerateVideo` | Video generation |
|
|
122
|
+
| `injectGenerateSpeech` | Text-to-speech |
|
|
123
|
+
| `injectSummarize` | Summarization |
|
|
124
|
+
| `injectTranscription` | Audio transcription |
|
|
125
|
+
|
|
126
|
+
All generation functions return signals (`result`, `isLoading`, `error`, `status`) and methods (`generate`, `stop`, `reset`).
|
|
127
|
+
|
|
128
|
+
## Injection Context
|
|
129
|
+
|
|
130
|
+
Angular's DI system requires that `inject()` is called during component construction. Every `inject*` function in this package calls `inject()` internally. Valid call sites:
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
// Field initializer (recommended)
|
|
134
|
+
export class MyComponent {
|
|
135
|
+
chat = injectChat({ connection: fetchServerSentEvents('/api/chat') })
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Constructor
|
|
139
|
+
export class MyComponent {
|
|
140
|
+
chat: ReturnType<typeof injectChat>
|
|
141
|
+
constructor() {
|
|
142
|
+
this.chat = injectChat({ connection: fetchServerSentEvents('/api/chat') })
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Inside runInInjectionContext
|
|
147
|
+
const chat = runInInjectionContext(injector, () =>
|
|
148
|
+
injectChat({ connection: fetchServerSentEvents('/api/chat') }),
|
|
149
|
+
)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
## Get Involved
|
|
153
|
+
|
|
154
|
+
- Read the [docs](https://tanstack.com/ai).
|
|
155
|
+
- Participate in [GitHub discussions](https://github.com/TanStack/ai/discussions).
|
|
156
|
+
- Chat with the community on [Discord](https://discord.com/invite/WrRKjPJ).
|
|
157
|
+
- See [CONTRIBUTING.md](https://github.com/TanStack/ai/blob/main/CONTRIBUTING.md) for setup instructions.
|
|
158
|
+
- [Become a sponsor](https://github.com/sponsors/tannerlinsley/).
|
|
@@ -0,0 +1,532 @@
|
|
|
1
|
+
import { ChatClient, GenerationClient, AudioRecorder, VideoGenerationClient } from '@tanstack/ai-client';
|
|
2
|
+
export { createChatClientOptions, fetchHttpStream, fetchServerSentEvents, rpcStream, stream, xhrHttpStream, xhrServerSentEvents } from '@tanstack/ai-client';
|
|
3
|
+
import { createChatDevtoolsBridge, createGenerationDevtoolsBridge, createVideoDevtoolsBridge } from '@tanstack/ai-client/devtools';
|
|
4
|
+
import { isSignal, computed, assertInInjectionContext, inject, DestroyRef, Injector, signal, effect, afterNextRender } from '@angular/core';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Normalize a {@link ReactiveOption} into a `Signal`-like getter `() => T`.
|
|
8
|
+
*
|
|
9
|
+
* - A `Signal` is returned as-is (already a getter that tracks reads).
|
|
10
|
+
* - A zero-arg function is wrapped in `computed` so reads inside it are tracked.
|
|
11
|
+
* - A plain value becomes a constant non-reactive fn (never re-fires).
|
|
12
|
+
*/
|
|
13
|
+
function toReactive(value) {
|
|
14
|
+
if (isSignal(value)) {
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
if (typeof value === 'function') {
|
|
18
|
+
return computed(value);
|
|
19
|
+
}
|
|
20
|
+
return () => value;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
let nextId$2 = 0;
|
|
24
|
+
function injectChat(options = {}) {
|
|
25
|
+
assertInInjectionContext(injectChat);
|
|
26
|
+
const destroyRef = inject(DestroyRef);
|
|
27
|
+
const injector = inject(Injector);
|
|
28
|
+
const clientId = options.id || `injectChat-${nextId$2++}`;
|
|
29
|
+
const messages = signal(options.initialMessages || [], ...(ngDevMode ? [{ debugName: "messages" }] : /* istanbul ignore next */ []));
|
|
30
|
+
const isLoading = signal(false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
|
|
31
|
+
const error = signal(undefined, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
|
|
32
|
+
const status = signal('ready', ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
|
|
33
|
+
const isSubscribed = signal(false, ...(ngDevMode ? [{ debugName: "isSubscribed" }] : /* istanbul ignore next */ []));
|
|
34
|
+
const connectionStatus = signal('disconnected', ...(ngDevMode ? [{ debugName: "connectionStatus" }] : /* istanbul ignore next */ []));
|
|
35
|
+
const sessionGenerating = signal(false, ...(ngDevMode ? [{ debugName: "sessionGenerating" }] : /* istanbul ignore next */ []));
|
|
36
|
+
// Reactive option sources. Plain values become constant computeds.
|
|
37
|
+
const bodySource = options.body !== undefined ? toReactive(options.body) : undefined;
|
|
38
|
+
const forwardedPropsSource = options.forwardedProps !== undefined
|
|
39
|
+
? toReactive(options.forwardedProps)
|
|
40
|
+
: undefined;
|
|
41
|
+
const contextSource = options.context !== undefined ? toReactive(options.context) : undefined;
|
|
42
|
+
const liveSource = options.live !== undefined ? toReactive(options.live) : undefined;
|
|
43
|
+
const transport = options.connection
|
|
44
|
+
? { connection: options.connection }
|
|
45
|
+
: { fetcher: options.fetcher };
|
|
46
|
+
const client = new ChatClient({
|
|
47
|
+
devtoolsBridgeFactory: createChatDevtoolsBridge,
|
|
48
|
+
...transport,
|
|
49
|
+
id: clientId,
|
|
50
|
+
...(options.initialMessages !== undefined && {
|
|
51
|
+
initialMessages: options.initialMessages,
|
|
52
|
+
}),
|
|
53
|
+
...(options.persistence !== undefined && {
|
|
54
|
+
persistence: options.persistence,
|
|
55
|
+
}),
|
|
56
|
+
...(bodySource !== undefined && { body: bodySource() }),
|
|
57
|
+
...(options.threadId !== undefined && { threadId: options.threadId }),
|
|
58
|
+
...(forwardedPropsSource !== undefined && {
|
|
59
|
+
forwardedProps: forwardedPropsSource(),
|
|
60
|
+
}),
|
|
61
|
+
...(contextSource !== undefined && { context: contextSource() }),
|
|
62
|
+
devtools: {
|
|
63
|
+
...options.devtools,
|
|
64
|
+
framework: 'angular',
|
|
65
|
+
hookName: 'injectChat',
|
|
66
|
+
outputKind: options.outputSchema ? 'structured' : 'chat',
|
|
67
|
+
},
|
|
68
|
+
onResponse: (response) => options.onResponse?.(response),
|
|
69
|
+
onChunk: (chunk) => options.onChunk?.(chunk),
|
|
70
|
+
onFinish: (message) => options.onFinish?.(message),
|
|
71
|
+
onError: (err) => options.onError?.(err),
|
|
72
|
+
tools: options.tools,
|
|
73
|
+
onCustomEvent: (eventType, data, context) => options.onCustomEvent?.(eventType, data, context),
|
|
74
|
+
...(options.streamProcessor !== undefined && {
|
|
75
|
+
streamProcessor: options.streamProcessor,
|
|
76
|
+
}),
|
|
77
|
+
onMessagesChange: (m) => messages.set(m),
|
|
78
|
+
onLoadingChange: (v) => isLoading.set(v),
|
|
79
|
+
onStatusChange: (v) => status.set(v),
|
|
80
|
+
onErrorChange: (v) => error.set(v),
|
|
81
|
+
onSubscriptionChange: (v) => isSubscribed.set(v),
|
|
82
|
+
onConnectionStatusChange: (v) => connectionStatus.set(v),
|
|
83
|
+
onSessionGeneratingChange: (v) => sessionGenerating.set(v),
|
|
84
|
+
});
|
|
85
|
+
messages.set(client.getMessages());
|
|
86
|
+
// Sync reactive body / forwardedProps / context to the client.
|
|
87
|
+
if (bodySource || forwardedPropsSource || contextSource) {
|
|
88
|
+
effect(() => {
|
|
89
|
+
const newBody = bodySource?.();
|
|
90
|
+
const newForwardedProps = forwardedPropsSource?.();
|
|
91
|
+
const newContext = contextSource?.();
|
|
92
|
+
client.updateOptions({
|
|
93
|
+
...(newBody !== undefined && { body: newBody }),
|
|
94
|
+
...(newForwardedProps !== undefined && {
|
|
95
|
+
forwardedProps: newForwardedProps,
|
|
96
|
+
}),
|
|
97
|
+
...(newContext !== undefined && { context: newContext }),
|
|
98
|
+
});
|
|
99
|
+
}, { injector });
|
|
100
|
+
}
|
|
101
|
+
// Subscribe / unsubscribe based on reactive `live`.
|
|
102
|
+
if (liveSource) {
|
|
103
|
+
effect(() => {
|
|
104
|
+
if (liveSource()) {
|
|
105
|
+
client.subscribe();
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
client.unsubscribe();
|
|
109
|
+
}
|
|
110
|
+
}, { injector });
|
|
111
|
+
}
|
|
112
|
+
afterNextRender(() => client.mountDevtools(), { injector });
|
|
113
|
+
destroyRef.onDestroy(() => {
|
|
114
|
+
if (liveSource?.()) {
|
|
115
|
+
client.unsubscribe();
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
client.stop();
|
|
119
|
+
}
|
|
120
|
+
client.dispose();
|
|
121
|
+
});
|
|
122
|
+
// Active structured-output part = the one on the assistant message after the
|
|
123
|
+
// latest user message. Ported from ai-vue/src/use-chat.ts.
|
|
124
|
+
const activeStructuredPart = computed(() => {
|
|
125
|
+
const list = messages();
|
|
126
|
+
let lastUserIndex = -1;
|
|
127
|
+
for (let i = list.length - 1; i >= 0; i--) {
|
|
128
|
+
if (list[i]?.role === 'user') {
|
|
129
|
+
lastUserIndex = i;
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
if (lastUserIndex === -1)
|
|
134
|
+
return null;
|
|
135
|
+
for (let i = list.length - 1; i > lastUserIndex; i--) {
|
|
136
|
+
const m = list[i];
|
|
137
|
+
if (m?.role !== 'assistant')
|
|
138
|
+
continue;
|
|
139
|
+
const part = m.parts.find((p) => p.type === 'structured-output');
|
|
140
|
+
if (part)
|
|
141
|
+
return part;
|
|
142
|
+
}
|
|
143
|
+
return null;
|
|
144
|
+
}, ...(ngDevMode ? [{ debugName: "activeStructuredPart" }] : /* istanbul ignore next */ []));
|
|
145
|
+
const partial = computed(() => {
|
|
146
|
+
const part = activeStructuredPart();
|
|
147
|
+
if (!part)
|
|
148
|
+
return {};
|
|
149
|
+
const v = part.partial ?? part.data;
|
|
150
|
+
return (v ?? {});
|
|
151
|
+
}, ...(ngDevMode ? [{ debugName: "partial" }] : /* istanbul ignore next */ []));
|
|
152
|
+
const final = computed(() => {
|
|
153
|
+
const part = activeStructuredPart();
|
|
154
|
+
if (!part || part.status !== 'complete')
|
|
155
|
+
return null;
|
|
156
|
+
return part.data;
|
|
157
|
+
}, ...(ngDevMode ? [{ debugName: "final" }] : /* istanbul ignore next */ []));
|
|
158
|
+
const sendMessage = async (content) => {
|
|
159
|
+
await client.sendMessage(content);
|
|
160
|
+
};
|
|
161
|
+
const append = async (message) => {
|
|
162
|
+
await client.append(message);
|
|
163
|
+
};
|
|
164
|
+
const reload = async () => {
|
|
165
|
+
await client.reload();
|
|
166
|
+
};
|
|
167
|
+
const stop = () => client.stop();
|
|
168
|
+
const clear = () => client.clear();
|
|
169
|
+
const setMessages = (m) => client.setMessagesManually(m);
|
|
170
|
+
const addToolResult = async (result) => {
|
|
171
|
+
await client.addToolResult(result);
|
|
172
|
+
};
|
|
173
|
+
const addToolApprovalResponse = async (response) => {
|
|
174
|
+
await client.addToolApprovalResponse(response);
|
|
175
|
+
};
|
|
176
|
+
// eslint-disable-next-line no-restricted-syntax -- return shape diverges from conditional InjectChatResult<TTools, TSchema>; TS can't structurally narrow the TSchema-gated partial/final signals
|
|
177
|
+
return {
|
|
178
|
+
messages: messages.asReadonly(),
|
|
179
|
+
sendMessage,
|
|
180
|
+
append,
|
|
181
|
+
reload,
|
|
182
|
+
stop,
|
|
183
|
+
isLoading: isLoading.asReadonly(),
|
|
184
|
+
error: error.asReadonly(),
|
|
185
|
+
status: status.asReadonly(),
|
|
186
|
+
isSubscribed: isSubscribed.asReadonly(),
|
|
187
|
+
connectionStatus: connectionStatus.asReadonly(),
|
|
188
|
+
sessionGenerating: sessionGenerating.asReadonly(),
|
|
189
|
+
setMessages,
|
|
190
|
+
clear,
|
|
191
|
+
addToolResult,
|
|
192
|
+
addToolApprovalResponse,
|
|
193
|
+
partial,
|
|
194
|
+
final,
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
let nextId$1 = 0;
|
|
199
|
+
// `TTransformed` infers from the `onResult` return position (a covariant
|
|
200
|
+
// inference site that works even for an optional nested property), which types
|
|
201
|
+
// the callback parameter as `TResult` and narrows `result`. Inferring the
|
|
202
|
+
// whole callback as a defaulted type parameter instead collapses to the
|
|
203
|
+
// default, leaving the parameter `any` — a hard error under `strict`. See
|
|
204
|
+
// issue #848.
|
|
205
|
+
function injectGeneration(options) {
|
|
206
|
+
assertInInjectionContext(injectGeneration);
|
|
207
|
+
const destroyRef = inject(DestroyRef);
|
|
208
|
+
const injector = inject(Injector);
|
|
209
|
+
const clientId = options.id || `injectGeneration-${nextId$1++}`;
|
|
210
|
+
const result = signal(null, ...(ngDevMode ? [{ debugName: "result" }] : /* istanbul ignore next */ []));
|
|
211
|
+
const isLoading = signal(false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
|
|
212
|
+
const error = signal(undefined, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
|
|
213
|
+
const status = signal('idle', ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
|
|
214
|
+
const bodySource = options.body !== undefined ? toReactive(options.body) : undefined;
|
|
215
|
+
const clientOptions = {
|
|
216
|
+
id: clientId,
|
|
217
|
+
...(bodySource !== undefined && { body: bodySource() }),
|
|
218
|
+
devtoolsBridgeFactory: createGenerationDevtoolsBridge,
|
|
219
|
+
devtools: {
|
|
220
|
+
...options.devtools,
|
|
221
|
+
framework: 'angular',
|
|
222
|
+
hookName: 'injectGeneration',
|
|
223
|
+
},
|
|
224
|
+
// The transform's raw return type (`TTransformed`) and the stored output
|
|
225
|
+
// (`TOutput`, with null/void/undefined stripped) are identical at runtime;
|
|
226
|
+
// the cast bridges the relationship that the conditional type hides.
|
|
227
|
+
onResult: ((r) => options.onResult?.(r)),
|
|
228
|
+
onError: (e) => options.onError?.(e),
|
|
229
|
+
onProgress: (p, m) => options.onProgress?.(p, m),
|
|
230
|
+
onChunk: (c) => options.onChunk?.(c),
|
|
231
|
+
onResultChange: (r) => result.set(r),
|
|
232
|
+
onLoadingChange: (l) => isLoading.set(l),
|
|
233
|
+
onErrorChange: (e) => error.set(e),
|
|
234
|
+
onStatusChange: (s) => status.set(s),
|
|
235
|
+
};
|
|
236
|
+
let client;
|
|
237
|
+
if (options.connection) {
|
|
238
|
+
client = new GenerationClient({
|
|
239
|
+
...clientOptions,
|
|
240
|
+
connection: options.connection,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
else if (options.fetcher) {
|
|
244
|
+
client = new GenerationClient({
|
|
245
|
+
...clientOptions,
|
|
246
|
+
fetcher: options.fetcher,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
else {
|
|
250
|
+
throw new Error('injectGeneration requires either a connection or fetcher option');
|
|
251
|
+
}
|
|
252
|
+
if (bodySource) {
|
|
253
|
+
effect(() => {
|
|
254
|
+
client.updateOptions({ body: bodySource() });
|
|
255
|
+
}, { injector });
|
|
256
|
+
}
|
|
257
|
+
afterNextRender(() => client.mountDevtools(), { injector });
|
|
258
|
+
destroyRef.onDestroy(() => client.dispose());
|
|
259
|
+
return {
|
|
260
|
+
generate: ((input) => client.generate(input)),
|
|
261
|
+
result: result.asReadonly(),
|
|
262
|
+
isLoading: isLoading.asReadonly(),
|
|
263
|
+
error: error.asReadonly(),
|
|
264
|
+
status: status.asReadonly(),
|
|
265
|
+
stop: () => client.stop(),
|
|
266
|
+
reset: () => client.reset(),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function injectGenerateImage(options) {
|
|
271
|
+
const devtools = {
|
|
272
|
+
...options.devtools,
|
|
273
|
+
framework: 'angular',
|
|
274
|
+
hookName: 'injectGenerateImage',
|
|
275
|
+
outputKind: 'image',
|
|
276
|
+
};
|
|
277
|
+
const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
|
|
278
|
+
...options,
|
|
279
|
+
devtools,
|
|
280
|
+
});
|
|
281
|
+
return {
|
|
282
|
+
generate: generate,
|
|
283
|
+
result,
|
|
284
|
+
isLoading,
|
|
285
|
+
error,
|
|
286
|
+
status,
|
|
287
|
+
stop,
|
|
288
|
+
reset,
|
|
289
|
+
};
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Angular injectable for generating audio (music, sound effects) using AI models.
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* ```typescript
|
|
297
|
+
* import { Component } from '@angular/core'
|
|
298
|
+
* import { injectGenerateAudio } from '@tanstack/ai-angular'
|
|
299
|
+
* import { fetchServerSentEvents } from '@tanstack/ai-client'
|
|
300
|
+
*
|
|
301
|
+
* @Component({
|
|
302
|
+
* selector: 'app-audio',
|
|
303
|
+
* template: `
|
|
304
|
+
* <button (click)="generate({ prompt: 'An upbeat electronic track', duration: 10 })">
|
|
305
|
+
* Generate
|
|
306
|
+
* </button>
|
|
307
|
+
* @if (result()) {
|
|
308
|
+
* <audio [src]="result()!.audio.url" controls></audio>
|
|
309
|
+
* }
|
|
310
|
+
* `,
|
|
311
|
+
* })
|
|
312
|
+
* export class AudioComponent {
|
|
313
|
+
* private gen = injectGenerateAudio({
|
|
314
|
+
* connection: fetchServerSentEvents('/api/generate/audio'),
|
|
315
|
+
* })
|
|
316
|
+
*
|
|
317
|
+
* generate = this.gen.generate
|
|
318
|
+
* result = this.gen.result
|
|
319
|
+
* isLoading = this.gen.isLoading
|
|
320
|
+
* }
|
|
321
|
+
* ```
|
|
322
|
+
*/
|
|
323
|
+
function injectGenerateAudio(options) {
|
|
324
|
+
const devtools = {
|
|
325
|
+
...options.devtools,
|
|
326
|
+
framework: 'angular',
|
|
327
|
+
hookName: 'injectGenerateAudio',
|
|
328
|
+
outputKind: 'audio',
|
|
329
|
+
};
|
|
330
|
+
const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
|
|
331
|
+
...options,
|
|
332
|
+
devtools,
|
|
333
|
+
});
|
|
334
|
+
return {
|
|
335
|
+
generate: generate,
|
|
336
|
+
result,
|
|
337
|
+
isLoading,
|
|
338
|
+
error,
|
|
339
|
+
status,
|
|
340
|
+
stop,
|
|
341
|
+
reset,
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function injectGenerateSpeech(options) {
|
|
346
|
+
const devtools = {
|
|
347
|
+
...options.devtools,
|
|
348
|
+
framework: 'angular',
|
|
349
|
+
hookName: 'injectGenerateSpeech',
|
|
350
|
+
outputKind: 'audio',
|
|
351
|
+
};
|
|
352
|
+
const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
|
|
353
|
+
...options,
|
|
354
|
+
devtools,
|
|
355
|
+
});
|
|
356
|
+
return {
|
|
357
|
+
generate: generate,
|
|
358
|
+
result,
|
|
359
|
+
isLoading,
|
|
360
|
+
error,
|
|
361
|
+
status,
|
|
362
|
+
stop,
|
|
363
|
+
reset,
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function injectTranscription(options) {
|
|
368
|
+
const devtools = {
|
|
369
|
+
...options.devtools,
|
|
370
|
+
framework: 'angular',
|
|
371
|
+
hookName: 'injectTranscription',
|
|
372
|
+
outputKind: 'text',
|
|
373
|
+
};
|
|
374
|
+
const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
|
|
375
|
+
...options,
|
|
376
|
+
devtools,
|
|
377
|
+
});
|
|
378
|
+
return {
|
|
379
|
+
generate: generate,
|
|
380
|
+
result,
|
|
381
|
+
isLoading,
|
|
382
|
+
error,
|
|
383
|
+
status,
|
|
384
|
+
stop,
|
|
385
|
+
reset,
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function injectAudioRecorder(options = {}) {
|
|
390
|
+
assertInInjectionContext(injectAudioRecorder);
|
|
391
|
+
const destroyRef = inject(DestroyRef);
|
|
392
|
+
const recorder = new AudioRecorder({
|
|
393
|
+
...(options.audio !== undefined && { audio: options.audio }),
|
|
394
|
+
...(options.mimeType !== undefined && { mimeType: options.mimeType }),
|
|
395
|
+
...(options.onError !== undefined && { onError: options.onError }),
|
|
396
|
+
});
|
|
397
|
+
const isRecording = signal(false, ...(ngDevMode ? [{ debugName: "isRecording" }] : /* istanbul ignore next */ []));
|
|
398
|
+
const recording = signal(null, ...(ngDevMode ? [{ debugName: "recording" }] : /* istanbul ignore next */ []));
|
|
399
|
+
const unsubscribe = recorder.subscribe((state) => {
|
|
400
|
+
isRecording.set(state === 'recording');
|
|
401
|
+
});
|
|
402
|
+
destroyRef.onDestroy(() => {
|
|
403
|
+
unsubscribe();
|
|
404
|
+
recorder.cancel();
|
|
405
|
+
});
|
|
406
|
+
const stop = async () => {
|
|
407
|
+
const rawRecording = await recorder.stop();
|
|
408
|
+
const transformed = await options.onComplete?.(rawRecording);
|
|
409
|
+
// Only `undefined` (returning nothing) keeps the raw recording; a returned
|
|
410
|
+
// null is a real value, matching the inferred output type.
|
|
411
|
+
const output = transformed === undefined ? rawRecording : transformed;
|
|
412
|
+
recording.set(output);
|
|
413
|
+
return output;
|
|
414
|
+
};
|
|
415
|
+
return {
|
|
416
|
+
recording: recording.asReadonly(),
|
|
417
|
+
isRecording: isRecording.asReadonly(),
|
|
418
|
+
isSupported: AudioRecorder.isSupported(),
|
|
419
|
+
start: () => recorder.start(),
|
|
420
|
+
stop,
|
|
421
|
+
cancel: () => recorder.cancel(),
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function injectSummarize(options) {
|
|
426
|
+
const devtools = {
|
|
427
|
+
...options.devtools,
|
|
428
|
+
framework: 'angular',
|
|
429
|
+
hookName: 'injectSummarize',
|
|
430
|
+
outputKind: 'text',
|
|
431
|
+
};
|
|
432
|
+
const { generate, result, isLoading, error, status, stop, reset } = injectGeneration({
|
|
433
|
+
...options,
|
|
434
|
+
devtools,
|
|
435
|
+
});
|
|
436
|
+
return {
|
|
437
|
+
generate: generate,
|
|
438
|
+
result,
|
|
439
|
+
isLoading,
|
|
440
|
+
error,
|
|
441
|
+
status,
|
|
442
|
+
stop,
|
|
443
|
+
reset,
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
let nextId = 0;
|
|
448
|
+
// `TTransformed` infers from the `onResult` return position so the callback
|
|
449
|
+
// parameter is typed as `VideoGenerateResult` and `result` narrows to the
|
|
450
|
+
// transform's return. See issue #848.
|
|
451
|
+
function injectGenerateVideo(options) {
|
|
452
|
+
assertInInjectionContext(injectGenerateVideo);
|
|
453
|
+
const destroyRef = inject(DestroyRef);
|
|
454
|
+
const injector = inject(Injector);
|
|
455
|
+
const clientId = options.id || `injectGenerateVideo-${nextId++}`;
|
|
456
|
+
const result = signal(null, ...(ngDevMode ? [{ debugName: "result" }] : /* istanbul ignore next */ []));
|
|
457
|
+
const jobId = signal(null, ...(ngDevMode ? [{ debugName: "jobId" }] : /* istanbul ignore next */ []));
|
|
458
|
+
const videoStatus = signal(null, ...(ngDevMode ? [{ debugName: "videoStatus" }] : /* istanbul ignore next */ []));
|
|
459
|
+
const isLoading = signal(false, ...(ngDevMode ? [{ debugName: "isLoading" }] : /* istanbul ignore next */ []));
|
|
460
|
+
const error = signal(undefined, ...(ngDevMode ? [{ debugName: "error" }] : /* istanbul ignore next */ []));
|
|
461
|
+
const status = signal('idle', ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
|
|
462
|
+
const bodySource = options.body !== undefined ? toReactive(options.body) : undefined;
|
|
463
|
+
const baseOptions = {
|
|
464
|
+
id: clientId,
|
|
465
|
+
...(bodySource !== undefined && { body: bodySource() }),
|
|
466
|
+
devtoolsBridgeFactory: createVideoDevtoolsBridge,
|
|
467
|
+
devtools: {
|
|
468
|
+
...options.devtools,
|
|
469
|
+
framework: 'angular',
|
|
470
|
+
hookName: 'injectGenerateVideo',
|
|
471
|
+
outputKind: 'video',
|
|
472
|
+
},
|
|
473
|
+
// The transform's raw return type (`TTransformed`) and the stored output
|
|
474
|
+
// (`TOutput`, with null/void/undefined stripped) are identical at runtime;
|
|
475
|
+
// the cast bridges the relationship that the conditional type hides.
|
|
476
|
+
onResult: ((r) => options.onResult?.(r)),
|
|
477
|
+
onError: (e) => options.onError?.(e),
|
|
478
|
+
onProgress: (p, m) => options.onProgress?.(p, m),
|
|
479
|
+
onChunk: (c) => options.onChunk?.(c),
|
|
480
|
+
onJobCreated: (id) => options.onJobCreated?.(id),
|
|
481
|
+
onStatusUpdate: (s) => options.onStatusUpdate?.(s),
|
|
482
|
+
onResultChange: (r) => result.set(r),
|
|
483
|
+
onLoadingChange: (l) => isLoading.set(l),
|
|
484
|
+
onErrorChange: (e) => error.set(e),
|
|
485
|
+
onStatusChange: (s) => status.set(s),
|
|
486
|
+
onJobIdChange: (id) => jobId.set(id),
|
|
487
|
+
onVideoStatusChange: (s) => videoStatus.set(s),
|
|
488
|
+
};
|
|
489
|
+
let client;
|
|
490
|
+
if (options.connection) {
|
|
491
|
+
client = new VideoGenerationClient({
|
|
492
|
+
...baseOptions,
|
|
493
|
+
connection: options.connection,
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
else if (options.fetcher) {
|
|
497
|
+
client = new VideoGenerationClient({
|
|
498
|
+
...baseOptions,
|
|
499
|
+
fetcher: options.fetcher,
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
else {
|
|
503
|
+
throw new Error('injectGenerateVideo requires either a connection or fetcher option');
|
|
504
|
+
}
|
|
505
|
+
if (bodySource) {
|
|
506
|
+
effect(() => {
|
|
507
|
+
client.updateOptions({ body: bodySource() });
|
|
508
|
+
}, { injector });
|
|
509
|
+
}
|
|
510
|
+
afterNextRender(() => client.mountDevtools(), { injector });
|
|
511
|
+
destroyRef.onDestroy(() => client.dispose());
|
|
512
|
+
return {
|
|
513
|
+
generate: (input) => client.generate(input),
|
|
514
|
+
result: result.asReadonly(),
|
|
515
|
+
jobId: jobId.asReadonly(),
|
|
516
|
+
videoStatus: videoStatus.asReadonly(),
|
|
517
|
+
isLoading: isLoading.asReadonly(),
|
|
518
|
+
error: error.asReadonly(),
|
|
519
|
+
status: status.asReadonly(),
|
|
520
|
+
stop: () => client.stop(),
|
|
521
|
+
reset: () => client.reset(),
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
// Chat
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Generated bundle index. Do not edit.
|
|
529
|
+
*/
|
|
530
|
+
|
|
531
|
+
export { injectAudioRecorder, injectChat, injectGenerateAudio, injectGenerateImage, injectGenerateSpeech, injectGenerateVideo, injectGeneration, injectSummarize, injectTranscription };
|
|
532
|
+
//# sourceMappingURL=tanstack-ai-angular.mjs.map
|