@tanstack/ai-angular 0.0.1

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.
@@ -0,0 +1,155 @@
1
+ import { GenerationClient } from '@tanstack/ai-client'
2
+ import { createGenerationDevtoolsBridge } from '@tanstack/ai-client/devtools'
3
+ import {
4
+ DestroyRef,
5
+ Injector,
6
+ afterNextRender,
7
+ assertInInjectionContext,
8
+ effect,
9
+ inject,
10
+ signal,
11
+ } from '@angular/core'
12
+ import { toReactive } from './internal/to-reactive'
13
+ import type { Signal } from '@angular/core'
14
+ import type { StreamChunk } from '@tanstack/ai'
15
+ import type {
16
+ AIDevtoolsDisplayOptions,
17
+ ConnectConnectionAdapter,
18
+ GenerationClientOptions,
19
+ GenerationClientState,
20
+ GenerationFetcher,
21
+ InferGenerationOutput,
22
+ } from '@tanstack/ai-client'
23
+ import type { ReactiveOption } from './internal/to-reactive'
24
+
25
+ let nextId = 0
26
+
27
+ export interface InjectGenerationOptions<TInput, TResult, TOutput = TResult> {
28
+ /** Connect-based adapter for streaming transport (SSE, HTTP stream, custom) */
29
+ connection?: ConnectConnectionAdapter
30
+ /** Direct async function for one-shot generation (no streaming protocol needed) */
31
+ fetcher?: GenerationFetcher<TInput, TResult>
32
+ /** Unique identifier for this generation instance */
33
+ id?: string
34
+ /** Additional request body params. Reactive. */
35
+ body?: ReactiveOption<Record<string, any>>
36
+ /** Display options for TanStack AI Devtools. */
37
+ devtools?: AIDevtoolsDisplayOptions
38
+ /**
39
+ * Callback when a result is received. Can optionally return a transformed value.
40
+ *
41
+ * - Return a non-null value to transform and store it as the result
42
+ * - Return `null` to keep the previous result unchanged
43
+ * - Return nothing (`void`) to store the raw result as-is
44
+ */
45
+ onResult?: (result: TResult) => TOutput | null | void
46
+ /** Callback when an error occurs */
47
+ onError?: (error: Error) => void
48
+ /** Callback when progress is reported (0-100) */
49
+ onProgress?: (progress: number, message?: string) => void
50
+ /** Callback for each stream chunk (connect-based adapter mode only) */
51
+ onChunk?: (chunk: StreamChunk) => void
52
+ }
53
+
54
+ export interface InjectGenerationResult<TOutput> {
55
+ /** Trigger a generation request */
56
+ generate: (input: Record<string, any>) => Promise<void>
57
+ /** The generation result, or null if not yet generated */
58
+ result: Signal<TOutput | null>
59
+ /** Whether a generation is currently in progress */
60
+ isLoading: Signal<boolean>
61
+ /** Current error, if any */
62
+ error: Signal<Error | undefined>
63
+ /** Current state of the generation client */
64
+ status: Signal<GenerationClientState>
65
+ /** Abort the current generation */
66
+ stop: () => void
67
+ /** Clear result, error, and return to idle */
68
+ reset: () => void
69
+ }
70
+
71
+ export function injectGeneration<
72
+ TInput extends Record<string, any>,
73
+ TResult,
74
+ TOnResult extends ((result: TResult) => any) | undefined = undefined,
75
+ >(
76
+ options: Omit<InjectGenerationOptions<TInput, TResult>, 'onResult'> & {
77
+ onResult?: TOnResult
78
+ },
79
+ ): InjectGenerationResult<InferGenerationOutput<TResult, TOnResult>> {
80
+ assertInInjectionContext(injectGeneration)
81
+
82
+ type TOutput = InferGenerationOutput<TResult, TOnResult>
83
+
84
+ const destroyRef = inject(DestroyRef)
85
+ const injector = inject(Injector)
86
+ const clientId = options.id || `injectGeneration-${nextId++}`
87
+
88
+ const result = signal<TOutput | null>(null)
89
+ const isLoading = signal(false)
90
+ const error = signal<Error | undefined>(undefined)
91
+ const status = signal<GenerationClientState>('idle')
92
+
93
+ const bodySource =
94
+ options.body !== undefined ? toReactive(options.body) : undefined
95
+
96
+ const clientOptions: GenerationClientOptions<TInput, TResult, TOutput> = {
97
+ id: clientId,
98
+ ...(bodySource !== undefined && { body: bodySource() }),
99
+ devtoolsBridgeFactory: createGenerationDevtoolsBridge,
100
+ devtools: {
101
+ ...options.devtools,
102
+ framework: 'angular',
103
+ hookName: 'injectGeneration',
104
+ },
105
+ onResult: (r: TResult) => options.onResult?.(r),
106
+ onError: (e: Error) => options.onError?.(e),
107
+ onProgress: (p: number, m?: string) => options.onProgress?.(p, m),
108
+ onChunk: (c: StreamChunk) => options.onChunk?.(c),
109
+ onResultChange: (r: TOutput | null) => result.set(r),
110
+ onLoadingChange: (l: boolean) => isLoading.set(l),
111
+ onErrorChange: (e: Error | undefined) => error.set(e),
112
+ onStatusChange: (s: GenerationClientState) => status.set(s),
113
+ }
114
+
115
+ let client: GenerationClient<TInput, TResult, TOutput>
116
+ if (options.connection) {
117
+ client = new GenerationClient({
118
+ ...clientOptions,
119
+ connection: options.connection,
120
+ })
121
+ } else if (options.fetcher) {
122
+ client = new GenerationClient({
123
+ ...clientOptions,
124
+ fetcher: options.fetcher,
125
+ })
126
+ } else {
127
+ throw new Error(
128
+ 'injectGeneration requires either a connection or fetcher option',
129
+ )
130
+ }
131
+
132
+ if (bodySource) {
133
+ effect(
134
+ () => {
135
+ client.updateOptions({ body: bodySource() })
136
+ },
137
+ { injector },
138
+ )
139
+ }
140
+
141
+ afterNextRender(() => client.mountDevtools(), { injector })
142
+ destroyRef.onDestroy(() => client.dispose())
143
+
144
+ return {
145
+ generate: ((input: TInput) => client.generate(input)) as (
146
+ input: Record<string, any>,
147
+ ) => Promise<void>,
148
+ result: result.asReadonly(),
149
+ isLoading: isLoading.asReadonly(),
150
+ error: error.asReadonly(),
151
+ status: status.asReadonly(),
152
+ stop: () => client.stop(),
153
+ reset: () => client.reset(),
154
+ }
155
+ }
@@ -0,0 +1,58 @@
1
+ import { injectGeneration } from './inject-generation'
2
+ import type { Signal } from '@angular/core'
3
+ import type { SummarizationResult } from '@tanstack/ai'
4
+ import type {
5
+ GenerationClientState,
6
+ InferGenerationOutput,
7
+ SummarizeGenerateInput,
8
+ } from '@tanstack/ai-client'
9
+ import type { InjectGenerationOptions } from './inject-generation'
10
+
11
+ export type InjectSummarizeOptions<TOutput = SummarizationResult> = Omit<
12
+ InjectGenerationOptions<SummarizeGenerateInput, SummarizationResult, TOutput>,
13
+ 'onResult'
14
+ > & {
15
+ onResult?: (result: SummarizationResult) => TOutput | null | void
16
+ }
17
+
18
+ export interface InjectSummarizeResult<TOutput = SummarizationResult> {
19
+ generate: (input: SummarizeGenerateInput) => Promise<void>
20
+ result: Signal<TOutput | null>
21
+ isLoading: Signal<boolean>
22
+ error: Signal<Error | undefined>
23
+ status: Signal<GenerationClientState>
24
+ stop: () => void
25
+ reset: () => void
26
+ }
27
+
28
+ export function injectSummarize<
29
+ TOnResult extends ((result: SummarizationResult) => any) | undefined =
30
+ undefined,
31
+ >(
32
+ options: Omit<InjectSummarizeOptions, 'onResult'> & {
33
+ onResult?: TOnResult
34
+ },
35
+ ): InjectSummarizeResult<
36
+ InferGenerationOutput<SummarizationResult, TOnResult>
37
+ > {
38
+ const devtools = {
39
+ ...options.devtools,
40
+ framework: 'angular' as const,
41
+ hookName: 'injectSummarize',
42
+ outputKind: 'text' as const,
43
+ }
44
+ const { generate, result, isLoading, error, status, stop, reset } =
45
+ injectGeneration<SummarizeGenerateInput, SummarizationResult, TOnResult>({
46
+ ...options,
47
+ devtools,
48
+ })
49
+ return {
50
+ generate: generate as (input: SummarizeGenerateInput) => Promise<void>,
51
+ result,
52
+ isLoading,
53
+ error,
54
+ status,
55
+ stop,
56
+ reset,
57
+ }
58
+ }
@@ -0,0 +1,66 @@
1
+ import { injectGeneration } from './inject-generation'
2
+ import type { Signal } from '@angular/core'
3
+ import type { TranscriptionResult } from '@tanstack/ai'
4
+ import type {
5
+ GenerationClientState,
6
+ InferGenerationOutput,
7
+ TranscriptionGenerateInput,
8
+ } from '@tanstack/ai-client'
9
+ import type { InjectGenerationOptions } from './inject-generation'
10
+
11
+ export type InjectTranscriptionOptions<TOutput = TranscriptionResult> = Omit<
12
+ InjectGenerationOptions<
13
+ TranscriptionGenerateInput,
14
+ TranscriptionResult,
15
+ TOutput
16
+ >,
17
+ 'onResult'
18
+ > & {
19
+ onResult?: (result: TranscriptionResult) => TOutput | null | void
20
+ }
21
+
22
+ export interface InjectTranscriptionResult<TOutput = TranscriptionResult> {
23
+ generate: (input: TranscriptionGenerateInput) => Promise<void>
24
+ result: Signal<TOutput | null>
25
+ isLoading: Signal<boolean>
26
+ error: Signal<Error | undefined>
27
+ status: Signal<GenerationClientState>
28
+ stop: () => void
29
+ reset: () => void
30
+ }
31
+
32
+ export function injectTranscription<
33
+ TOnResult extends ((result: TranscriptionResult) => any) | undefined =
34
+ undefined,
35
+ >(
36
+ options: Omit<InjectTranscriptionOptions, 'onResult'> & {
37
+ onResult?: TOnResult
38
+ },
39
+ ): InjectTranscriptionResult<
40
+ InferGenerationOutput<TranscriptionResult, TOnResult>
41
+ > {
42
+ const devtools = {
43
+ ...options.devtools,
44
+ framework: 'angular' as const,
45
+ hookName: 'injectTranscription',
46
+ outputKind: 'text' as const,
47
+ }
48
+ const { generate, result, isLoading, error, status, stop, reset } =
49
+ injectGeneration<
50
+ TranscriptionGenerateInput,
51
+ TranscriptionResult,
52
+ TOnResult
53
+ >({
54
+ ...options,
55
+ devtools,
56
+ })
57
+ return {
58
+ generate: generate as (input: TranscriptionGenerateInput) => Promise<void>,
59
+ result,
60
+ isLoading,
61
+ error,
62
+ status,
63
+ stop,
64
+ reset,
65
+ }
66
+ }
@@ -0,0 +1,26 @@
1
+ import { computed, isSignal } from '@angular/core'
2
+ import type { Signal } from '@angular/core'
3
+
4
+ /**
5
+ * A value that may be supplied to `injectChat` either as a static value, an
6
+ * Angular `Signal`, or a zero-arg getter. The getter form lets callers read
7
+ * other signals so the option stays reactive.
8
+ */
9
+ export type ReactiveOption<T> = T | Signal<T> | (() => T)
10
+
11
+ /**
12
+ * Normalize a {@link ReactiveOption} into a `Signal`-like getter `() => T`.
13
+ *
14
+ * - A `Signal` is returned as-is (already a getter that tracks reads).
15
+ * - A zero-arg function is wrapped in `computed` so reads inside it are tracked.
16
+ * - A plain value becomes a constant non-reactive fn (never re-fires).
17
+ */
18
+ export function toReactive<T>(value: ReactiveOption<T>): () => T {
19
+ if (isSignal(value)) {
20
+ return value
21
+ }
22
+ if (typeof value === 'function') {
23
+ return computed(value as () => T)
24
+ }
25
+ return () => value
26
+ }
package/src/types.ts ADDED
@@ -0,0 +1,141 @@
1
+ import type {
2
+ AnyClientTool,
3
+ InferSchemaType,
4
+ ModelMessage,
5
+ SchemaInput,
6
+ } from '@tanstack/ai'
7
+ import type {
8
+ AIDevtoolsDisplayOptions,
9
+ ChatClientOptions,
10
+ ChatClientState,
11
+ ChatRequestBody,
12
+ ClientContextOptionFromTools,
13
+ ConnectionStatus,
14
+ DistributedOmit,
15
+ InferredClientContext,
16
+ MultimodalContent,
17
+ UIMessage,
18
+ } from '@tanstack/ai-client'
19
+ import type { Signal } from '@angular/core'
20
+ import type { ReactiveOption } from './internal/to-reactive'
21
+
22
+ export type { ChatRequestBody, MultimodalContent, UIMessage }
23
+ export type { ReactiveOption }
24
+
25
+ /**
26
+ * Recursive partial — every property and every nested array element is optional.
27
+ * Used to type the in-flight `partial` value while a structured-output stream
28
+ * is still arriving.
29
+ */
30
+ export type DeepPartial<T> =
31
+ T extends ReadonlyArray<infer U>
32
+ ? Array<DeepPartial<U>>
33
+ : T extends object
34
+ ? { [K in keyof T]?: DeepPartial<T[K]> }
35
+ : T
36
+
37
+ /**
38
+ * Options for {@link injectChat}.
39
+ *
40
+ * Mirrors the Vue `useChat` options, except:
41
+ * - State-change callbacks are managed internally and exposed as signals.
42
+ * - `body`, `forwardedProps`, and `live` accept a {@link ReactiveOption} so
43
+ * they can be a static value, a `Signal`, or a getter and stay reactive.
44
+ */
45
+ export type InjectChatOptions<
46
+ TTools extends ReadonlyArray<AnyClientTool> = any,
47
+ TSchema extends SchemaInput | undefined = undefined,
48
+ TContext = InferredClientContext<TTools>,
49
+ > = DistributedOmit<
50
+ ChatClientOptions<TTools, TContext>,
51
+ | 'onMessagesChange'
52
+ | 'onLoadingChange'
53
+ | 'onErrorChange'
54
+ | 'onStatusChange'
55
+ | 'onSubscriptionChange'
56
+ | 'onConnectionStatusChange'
57
+ | 'onSessionGeneratingChange'
58
+ | 'context'
59
+ | 'devtools'
60
+ | 'body'
61
+ | 'forwardedProps'
62
+ > & {
63
+ /** Display options for TanStack AI Devtools. */
64
+ devtools?: AIDevtoolsDisplayOptions
65
+ /** Additional request body params. Reactive. */
66
+ body?: ReactiveOption<Record<string, any>>
67
+ /** Forwarded request props (preferred over `body`). Reactive. */
68
+ forwardedProps?: ReactiveOption<Record<string, any>>
69
+ /** Whether to keep a live subscription open. Reactive. */
70
+ live?: ReactiveOption<boolean>
71
+ /**
72
+ * Standard-schema-compatible schema (Zod, Valibot, ArkType, or JSON Schema).
73
+ * Used to infer the shape of `partial` and `final`.
74
+ */
75
+ outputSchema?: TSchema
76
+ } & ClientContextOptionFromTools<TTools, ReactiveOption<TContext>>
77
+
78
+ /**
79
+ * Return shape of {@link injectChat}. When `outputSchema` is supplied, adds
80
+ * typed `partial` / `final` signals; otherwise the return is unchanged.
81
+ */
82
+ export type InjectChatResult<
83
+ TTools extends ReadonlyArray<AnyClientTool> = any,
84
+ TSchema extends SchemaInput | undefined = undefined,
85
+ > = BaseInjectChatResult<
86
+ TTools,
87
+ TSchema extends SchemaInput ? InferSchemaType<TSchema> : unknown
88
+ > &
89
+ (TSchema extends SchemaInput
90
+ ? {
91
+ /** Live progressively-parsed structured output. */
92
+ partial: Signal<DeepPartial<InferSchemaType<TSchema>>>
93
+ /** Final, schema-validated structured output. `null` until complete. */
94
+ final: Signal<InferSchemaType<TSchema> | null>
95
+ }
96
+ : Record<never, never>)
97
+
98
+ interface BaseInjectChatResult<
99
+ TTools extends ReadonlyArray<AnyClientTool> = any,
100
+ TData = unknown,
101
+ > {
102
+ /** Current messages in the conversation. */
103
+ messages: Signal<Array<UIMessage<TTools, TData>>>
104
+ /** Send a message (string or multimodal content). */
105
+ sendMessage: (content: string | MultimodalContent) => Promise<void>
106
+ /** Append a message to the conversation. */
107
+ append: (message: ModelMessage | UIMessage<TTools, TData>) => Promise<void>
108
+ /** Add the result of a client-side tool execution. */
109
+ addToolResult: (result: {
110
+ toolCallId: string
111
+ tool: string
112
+ output: any
113
+ state?: 'output-available' | 'output-error'
114
+ errorText?: string
115
+ }) => Promise<void>
116
+ /** Respond to a tool approval request. */
117
+ addToolApprovalResponse: (response: {
118
+ id: string
119
+ approved: boolean
120
+ }) => Promise<void>
121
+ /** Reload the last assistant message. */
122
+ reload: () => Promise<void>
123
+ /** Stop the current response generation. */
124
+ stop: () => void
125
+ /** Whether a response is currently being generated. */
126
+ isLoading: Signal<boolean>
127
+ /** Current error, if any. */
128
+ error: Signal<Error | undefined>
129
+ /** Set messages manually. */
130
+ setMessages: (messages: Array<UIMessage<TTools, TData>>) => void
131
+ /** Clear all messages. */
132
+ clear: () => void
133
+ /** Current generation status. */
134
+ status: Signal<ChatClientState>
135
+ /** Whether the subscription loop is active. */
136
+ isSubscribed: Signal<boolean>
137
+ /** Current connection lifecycle status. */
138
+ connectionStatus: Signal<ConnectionStatus>
139
+ /** Whether the shared session is actively generating. */
140
+ sessionGenerating: Signal<boolean>
141
+ }