|
| 1 | +import { realtimeStreams } from "@trigger.dev/core/v3"; |
| 2 | + |
| 3 | +/** |
| 4 | + * The default stream key used for chat transport communication. |
| 5 | + * |
| 6 | + * Both `TriggerChatTransport` (frontend) and `pipeChat` (backend) use this key |
| 7 | + * by default to ensure they communicate over the same stream. |
| 8 | + */ |
| 9 | +export const CHAT_STREAM_KEY = "chat"; |
| 10 | + |
| 11 | +/** |
| 12 | + * Options for `pipeChat`. |
| 13 | + */ |
| 14 | +export type PipeChatOptions = { |
| 15 | + /** |
| 16 | + * Override the stream key to pipe to. |
| 17 | + * Must match the `streamKey` option on `TriggerChatTransport`. |
| 18 | + * |
| 19 | + * @default "chat" |
| 20 | + */ |
| 21 | + streamKey?: string; |
| 22 | + |
| 23 | + /** |
| 24 | + * An AbortSignal to cancel the stream. |
| 25 | + */ |
| 26 | + signal?: AbortSignal; |
| 27 | + |
| 28 | + /** |
| 29 | + * The target run ID to pipe the stream to. |
| 30 | + * @default "self" (current run) |
| 31 | + */ |
| 32 | + target?: string; |
| 33 | +}; |
| 34 | + |
| 35 | +/** |
| 36 | + * An object that has a `toUIMessageStream()` method, like the result of `streamText()` from the AI SDK. |
| 37 | + */ |
| 38 | +type UIMessageStreamable = { |
| 39 | + toUIMessageStream: (...args: any[]) => AsyncIterable<unknown> | ReadableStream<unknown>; |
| 40 | +}; |
| 41 | + |
| 42 | +function isUIMessageStreamable(value: unknown): value is UIMessageStreamable { |
| 43 | + return ( |
| 44 | + typeof value === "object" && |
| 45 | + value !== null && |
| 46 | + "toUIMessageStream" in value && |
| 47 | + typeof (value as any).toUIMessageStream === "function" |
| 48 | + ); |
| 49 | +} |
| 50 | + |
| 51 | +function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> { |
| 52 | + return ( |
| 53 | + typeof value === "object" && |
| 54 | + value !== null && |
| 55 | + Symbol.asyncIterator in value |
| 56 | + ); |
| 57 | +} |
| 58 | + |
| 59 | +function isReadableStream(value: unknown): value is ReadableStream<unknown> { |
| 60 | + return ( |
| 61 | + typeof value === "object" && |
| 62 | + value !== null && |
| 63 | + typeof (value as any).getReader === "function" |
| 64 | + ); |
| 65 | +} |
| 66 | + |
| 67 | +/** |
| 68 | + * Pipes a chat stream to the realtime stream, making it available to the |
| 69 | + * `TriggerChatTransport` on the frontend. |
| 70 | + * |
| 71 | + * Accepts any of: |
| 72 | + * - A `StreamTextResult` from the AI SDK (has `.toUIMessageStream()`) |
| 73 | + * - An `AsyncIterable` of `UIMessageChunk`s |
| 74 | + * - A `ReadableStream` of `UIMessageChunk`s |
| 75 | + * |
| 76 | + * This must be called from inside a Trigger.dev task's `run` function. |
| 77 | + * |
| 78 | + * @example |
| 79 | + * ```ts |
| 80 | + * import { task } from "@trigger.dev/sdk"; |
| 81 | + * import { pipeChat, type ChatTaskPayload } from "@trigger.dev/ai"; |
| 82 | + * import { streamText, convertToModelMessages } from "ai"; |
| 83 | + * |
| 84 | + * export const myChatTask = task({ |
| 85 | + * id: "my-chat-task", |
| 86 | + * run: async (payload: ChatTaskPayload) => { |
| 87 | + * const result = streamText({ |
| 88 | + * model: openai("gpt-4o"), |
| 89 | + * messages: convertToModelMessages(payload.messages), |
| 90 | + * }); |
| 91 | + * |
| 92 | + * await pipeChat(result); |
| 93 | + * }, |
| 94 | + * }); |
| 95 | + * ``` |
| 96 | + * |
| 97 | + * @example |
| 98 | + * ```ts |
| 99 | + * // Deep inside your agent library — pipeChat works from anywhere inside a task |
| 100 | + * async function runAgentLoop(messages: CoreMessage[]) { |
| 101 | + * const result = streamText({ model, messages }); |
| 102 | + * await pipeChat(result); |
| 103 | + * } |
| 104 | + * ``` |
| 105 | + * |
| 106 | + * @param source - A StreamTextResult, AsyncIterable, or ReadableStream of UIMessageChunks |
| 107 | + * @param options - Optional configuration |
| 108 | + * @returns A promise that resolves when the stream has been fully piped |
| 109 | + */ |
| 110 | +export async function pipeChat( |
| 111 | + source: UIMessageStreamable | AsyncIterable<unknown> | ReadableStream<unknown>, |
| 112 | + options?: PipeChatOptions |
| 113 | +): Promise<void> { |
| 114 | + const streamKey = options?.streamKey ?? CHAT_STREAM_KEY; |
| 115 | + |
| 116 | + // Resolve the source to an AsyncIterable or ReadableStream |
| 117 | + let stream: AsyncIterable<unknown> | ReadableStream<unknown>; |
| 118 | + |
| 119 | + if (isUIMessageStreamable(source)) { |
| 120 | + stream = source.toUIMessageStream(); |
| 121 | + } else if (isAsyncIterable(source) || isReadableStream(source)) { |
| 122 | + stream = source; |
| 123 | + } else { |
| 124 | + throw new Error( |
| 125 | + "pipeChat: source must be a StreamTextResult (with .toUIMessageStream()), " + |
| 126 | + "an AsyncIterable, or a ReadableStream" |
| 127 | + ); |
| 128 | + } |
| 129 | + |
| 130 | + // Pipe to the realtime stream |
| 131 | + const instance = realtimeStreams.pipe(streamKey, stream, { |
| 132 | + signal: options?.signal, |
| 133 | + target: options?.target, |
| 134 | + }); |
| 135 | + |
| 136 | + await instance.wait(); |
| 137 | +} |
0 commit comments