|
| 1 | +import { |
| 2 | + InvalidToolArgumentsError, |
| 3 | + LanguageModelV1, |
| 4 | + NoSuchToolError, |
| 5 | +} from '@ai-sdk/provider'; |
| 6 | +import { ReactNode } from 'react'; |
| 7 | +import { z } from 'zod'; |
| 8 | + |
| 9 | +import { CallSettings } from '../../core/prompt/call-settings'; |
| 10 | +import { Prompt } from '../../core/prompt/prompt'; |
| 11 | +import { createStreamableUI } from '../streamable'; |
| 12 | +import { retryWithExponentialBackoff } from '../../core/util/retry-with-exponential-backoff'; |
| 13 | +import { getValidatedPrompt } from '../../core/prompt/get-validated-prompt'; |
| 14 | +import { convertZodToJSONSchema } from '../../core/util/convert-zod-to-json-schema'; |
| 15 | +import { prepareCallSettings } from '../../core/prompt/prepare-call-settings'; |
| 16 | +import { convertToLanguageModelPrompt } from '../../core/prompt/convert-to-language-model-prompt'; |
| 17 | +import { createResolvablePromise } from '../utils'; |
| 18 | +import { safeParseJSON } from '@ai-sdk/provider-utils'; |
| 19 | + |
| 20 | +type Streamable = ReactNode | Promise<ReactNode>; |
| 21 | + |
| 22 | +type Renderer<T extends Array<any>> = ( |
| 23 | + ...args: T |
| 24 | +) => |
| 25 | + | Streamable |
| 26 | + | Generator<Streamable, Streamable, void> |
| 27 | + | AsyncGenerator<Streamable, Streamable, void>; |
| 28 | + |
| 29 | +type RenderTool<PARAMETERS extends z.ZodTypeAny = any> = { |
| 30 | + description?: string; |
| 31 | + parameters: PARAMETERS; |
| 32 | + generate?: Renderer< |
| 33 | + [ |
| 34 | + z.infer<PARAMETERS>, |
| 35 | + { |
| 36 | + toolName: string; |
| 37 | + toolCallId: string; |
| 38 | + }, |
| 39 | + ] |
| 40 | + >; |
| 41 | +}; |
| 42 | + |
| 43 | +type RenderText = Renderer< |
| 44 | + [ |
| 45 | + { |
| 46 | + /** |
| 47 | + * The full text content from the model so far. |
| 48 | + */ |
| 49 | + content: string; |
| 50 | + /** |
| 51 | + * The new appended text content from the model since the last `text` call. |
| 52 | + */ |
| 53 | + delta: string; |
| 54 | + /** |
| 55 | + * Whether the model is done generating text. |
| 56 | + * If `true`, the `content` will be the final output and this call will be the last. |
| 57 | + */ |
| 58 | + done: boolean; |
| 59 | + }, |
| 60 | + ] |
| 61 | +>; |
| 62 | + |
| 63 | +type RenderResult = { |
| 64 | + value: ReactNode; |
| 65 | +} & Awaited<ReturnType<LanguageModelV1['doStream']>>; |
| 66 | + |
| 67 | +const defaultTextRenderer: RenderText = ({ content }: { content: string }) => |
| 68 | + content; |
| 69 | + |
| 70 | +/** |
| 71 | + * `experimental_streamUI` is a helper function to create a streamable UI from LLMs. |
| 72 | + */ |
| 73 | +export async function experimental_streamUI< |
| 74 | + TOOLS extends Record<string, RenderTool>, |
| 75 | +>({ |
| 76 | + model, |
| 77 | + tools, |
| 78 | + system, |
| 79 | + prompt, |
| 80 | + messages, |
| 81 | + maxRetries, |
| 82 | + abortSignal, |
| 83 | + initial, |
| 84 | + text, |
| 85 | + ...settings |
| 86 | +}: CallSettings & |
| 87 | + Prompt & { |
| 88 | + /** |
| 89 | + * The language model to use. |
| 90 | + */ |
| 91 | + model: LanguageModelV1; |
| 92 | + |
| 93 | + /** |
| 94 | + * The tools that the model can call. The model needs to support calling tools. |
| 95 | + */ |
| 96 | + tools?: TOOLS; |
| 97 | + |
| 98 | + text?: RenderText; |
| 99 | + initial?: ReactNode; |
| 100 | + }): Promise<RenderResult> { |
| 101 | + // TODO: Remove these errors after the experimental phase. |
| 102 | + if (typeof model === 'string') { |
| 103 | + throw new Error( |
| 104 | + '`model` cannot be a string in `experimental_streamUI`. Use the actual model instance instead.', |
| 105 | + ); |
| 106 | + } |
| 107 | + if ('functions' in settings) { |
| 108 | + throw new Error( |
| 109 | + '`functions` is not supported in `experimental_streamUI`, use `tools` instead.', |
| 110 | + ); |
| 111 | + } |
| 112 | + if ('provider' in settings) { |
| 113 | + throw new Error( |
| 114 | + '`provider` is no longer needed in `experimental_streamUI`. Use `model` instead.', |
| 115 | + ); |
| 116 | + } |
| 117 | + if (tools) { |
| 118 | + for (const [name, tool] of Object.entries(tools)) { |
| 119 | + if ('render' in tool) { |
| 120 | + throw new Error( |
| 121 | + 'Tool definition in `experimental_streamUI` should not have `render` property. Use `generate` instead. Found in tool: ' + |
| 122 | + name, |
| 123 | + ); |
| 124 | + } |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + const ui = createStreamableUI(initial); |
| 129 | + |
| 130 | + // The default text renderer just returns the content as string. |
| 131 | + const textRender = text || defaultTextRenderer; |
| 132 | + |
| 133 | + let finished: Promise<void> | undefined; |
| 134 | + |
| 135 | + async function handleRender( |
| 136 | + args: [payload: any] | [payload: any, options: any], |
| 137 | + renderer: undefined | Renderer<any>, |
| 138 | + res: ReturnType<typeof createStreamableUI>, |
| 139 | + ) { |
| 140 | + if (!renderer) return; |
| 141 | + |
| 142 | + const resolvable = createResolvablePromise<void>(); |
| 143 | + |
| 144 | + if (finished) { |
| 145 | + finished = finished.then(() => resolvable.promise); |
| 146 | + } else { |
| 147 | + finished = resolvable.promise; |
| 148 | + } |
| 149 | + |
| 150 | + const value = renderer(...args); |
| 151 | + if ( |
| 152 | + value instanceof Promise || |
| 153 | + (value && |
| 154 | + typeof value === 'object' && |
| 155 | + 'then' in value && |
| 156 | + typeof value.then === 'function') |
| 157 | + ) { |
| 158 | + const node = await (value as Promise<React.ReactNode>); |
| 159 | + res.update(node); |
| 160 | + resolvable.resolve(void 0); |
| 161 | + } else if ( |
| 162 | + value && |
| 163 | + typeof value === 'object' && |
| 164 | + Symbol.asyncIterator in value |
| 165 | + ) { |
| 166 | + const it = value as AsyncGenerator< |
| 167 | + React.ReactNode, |
| 168 | + React.ReactNode, |
| 169 | + void |
| 170 | + >; |
| 171 | + while (true) { |
| 172 | + const { done, value } = await it.next(); |
| 173 | + res.update(value); |
| 174 | + if (done) break; |
| 175 | + } |
| 176 | + resolvable.resolve(void 0); |
| 177 | + } else if (value && typeof value === 'object' && Symbol.iterator in value) { |
| 178 | + const it = value as Generator<React.ReactNode, React.ReactNode, void>; |
| 179 | + while (true) { |
| 180 | + const { done, value } = it.next(); |
| 181 | + res.update(value); |
| 182 | + if (done) break; |
| 183 | + } |
| 184 | + resolvable.resolve(void 0); |
| 185 | + } else { |
| 186 | + res.update(value); |
| 187 | + resolvable.resolve(void 0); |
| 188 | + } |
| 189 | + } |
| 190 | + |
| 191 | + const retry = retryWithExponentialBackoff({ maxRetries }); |
| 192 | + const validatedPrompt = getValidatedPrompt({ system, prompt, messages }); |
| 193 | + const result = await retry(() => |
| 194 | + model.doStream({ |
| 195 | + mode: { |
| 196 | + type: 'regular', |
| 197 | + tools: |
| 198 | + tools == null |
| 199 | + ? undefined |
| 200 | + : Object.entries(tools).map(([name, tool]) => ({ |
| 201 | + type: 'function', |
| 202 | + name, |
| 203 | + description: tool.description, |
| 204 | + parameters: convertZodToJSONSchema(tool.parameters), |
| 205 | + })), |
| 206 | + }, |
| 207 | + ...prepareCallSettings(settings), |
| 208 | + inputFormat: validatedPrompt.type, |
| 209 | + prompt: convertToLanguageModelPrompt(validatedPrompt), |
| 210 | + abortSignal, |
| 211 | + }), |
| 212 | + ); |
| 213 | + |
| 214 | + const [stream, forkedStream] = result.stream.tee(); |
| 215 | + |
| 216 | + (async () => { |
| 217 | + try { |
| 218 | + // Consume the forked stream asynchonously. |
| 219 | + |
| 220 | + let content = ''; |
| 221 | + let hasToolCall = false; |
| 222 | + |
| 223 | + const reader = forkedStream.getReader(); |
| 224 | + while (true) { |
| 225 | + const { done, value } = await reader.read(); |
| 226 | + if (done) break; |
| 227 | + |
| 228 | + switch (value.type) { |
| 229 | + case 'text-delta': { |
| 230 | + content += value.textDelta; |
| 231 | + handleRender( |
| 232 | + [{ content, done: false, delta: value.textDelta }], |
| 233 | + textRender, |
| 234 | + ui, |
| 235 | + ); |
| 236 | + break; |
| 237 | + } |
| 238 | + |
| 239 | + case 'tool-call-delta': { |
| 240 | + hasToolCall = true; |
| 241 | + break; |
| 242 | + } |
| 243 | + |
| 244 | + case 'tool-call': { |
| 245 | + const toolName = value.toolName as keyof TOOLS & string; |
| 246 | + |
| 247 | + if (!tools) { |
| 248 | + throw new NoSuchToolError({ toolName: toolName }); |
| 249 | + } |
| 250 | + |
| 251 | + const tool = tools[toolName]; |
| 252 | + if (!tool) { |
| 253 | + throw new NoSuchToolError({ |
| 254 | + toolName, |
| 255 | + availableTools: Object.keys(tools), |
| 256 | + }); |
| 257 | + } |
| 258 | + |
| 259 | + const parseResult = safeParseJSON({ |
| 260 | + text: value.args, |
| 261 | + schema: tool.parameters, |
| 262 | + }); |
| 263 | + |
| 264 | + if (parseResult.success === false) { |
| 265 | + throw new InvalidToolArgumentsError({ |
| 266 | + toolName, |
| 267 | + toolArgs: value.args, |
| 268 | + cause: parseResult.error, |
| 269 | + }); |
| 270 | + } |
| 271 | + |
| 272 | + handleRender( |
| 273 | + [ |
| 274 | + parseResult.value, |
| 275 | + { |
| 276 | + toolName, |
| 277 | + toolCallId: value.toolCallId, |
| 278 | + }, |
| 279 | + ], |
| 280 | + tool.generate, |
| 281 | + ui, |
| 282 | + ); |
| 283 | + |
| 284 | + break; |
| 285 | + } |
| 286 | + |
| 287 | + case 'error': { |
| 288 | + throw value.error; |
| 289 | + } |
| 290 | + |
| 291 | + case 'finish': { |
| 292 | + // Nothing to do here. |
| 293 | + } |
| 294 | + } |
| 295 | + } |
| 296 | + |
| 297 | + if (hasToolCall) { |
| 298 | + await finished; |
| 299 | + ui.done(); |
| 300 | + } else { |
| 301 | + handleRender([{ content, done: true }], textRender, ui); |
| 302 | + await finished; |
| 303 | + ui.done(); |
| 304 | + } |
| 305 | + } catch (error) { |
| 306 | + // During the stream rendering, we don't want to throw the error to the |
| 307 | + // parent scope but only let the React's error boundary to catch it. |
| 308 | + ui.error(error); |
| 309 | + } |
| 310 | + })(); |
| 311 | + |
| 312 | + return { |
| 313 | + ...result, |
| 314 | + stream, |
| 315 | + value: ui.value, |
| 316 | + }; |
| 317 | +} |
0 commit comments