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

tool-result-content.ts

32 lines1.1 KB

1import type { UIMessage } from '../types'
2​
3type ToolResultPart = Extract<
4 UIMessage['parts'][number],
5 { type: 'tool-result' }
6>
7​
8/** `string | Array<ContentPart>` — a tool result's raw content. */
9type ToolResultContent = ToolResultPart['content']
10​
11type ContentPartItem = Exclude<ToolResultContent, string>[number]
12​
13/**
14 * Reduce a tool-result part's `content` to a plain string for rendering.
15 *
16 * Tool results carry `string | Array<ContentPart>` (multimodal results are
17 * normalized to an array of content parts upstream). The `ChatMessage`
18 * renderers operate on plain strings, so array content is flattened to the
19 * concatenation of its text parts. Non-text parts (image, audio, video,
20 * document) have no string form here and are skipped — matching the
21 * text-extraction behavior used elsewhere for `string | Array<ContentPart>`.
22 */
23export function toolResultContentToString(content: ToolResultContent): string {
24 if (typeof content === 'string') return content
25 return content
26 .filter(
27 (part): part is Extract<ContentPartItem, { type: 'text' }> =>
28 part.type === 'text',
29 )
30 .map((part) => part.content)
31 .join('')