UNPKG

@tanstack/ai

Version:

Core TanStack AI library - Open source AI SDK

97 lines (96 loc) 2.59 kB
function uiMessagesToWire(messages) { const wire = []; for (const msg of messages) { const parts = msg.parts ?? []; if (msg.role === "system") { wire.push({ ...msg, content: parts.length > 0 ? collectText(parts) : msg.content ?? "" }); continue; } if (msg.role === "user") { wire.push({ ...msg, content: parts.length > 0 ? collectUserContent(parts) : msg.content ?? "" }); continue; } for (const part of parts) { if (part.type === "thinking") { wire.push({ role: "reasoning", id: deriveReasoningId(msg.id, part), content: part.content }); } } const text = collectText(parts); const toolCalls = collectToolCalls(parts); wire.push({ ...msg, ...text !== "" && { content: text }, ...toolCalls && { toolCalls } }); for (const part of parts) { if (part.type === "tool-result") { wire.push({ role: "tool", id: deriveToolMessageId(part.toolCallId), toolCallId: part.toolCallId, content: part.content, ...part.error !== void 0 && { error: part.error } }); } } } return wire; } function collectText(parts) { return parts.filter((p) => p.type === "text").map((p) => p.content).join(""); } function collectUserContent(parts) { const hasMultimodal = parts.some( (p) => p.type === "image" || p.type === "audio" || p.type === "video" || p.type === "document" ); if (!hasMultimodal) { return collectText(parts); } const out = []; for (const p of parts) { if (p.type === "text") { out.push({ type: "text", text: p.content }); } else if (p.type === "image" || p.type === "audio" || p.type === "video" || p.type === "document") { out.push(p); } } return out; } function collectToolCalls(parts) { const calls = []; for (const p of parts) { if (p.type === "tool-call") { calls.push({ id: p.id, type: "function", function: { name: p.name, arguments: p.arguments } }); } } return calls.length > 0 ? calls : void 0; } function deriveReasoningId(messageId, part) { return `${messageId}-reasoning-${part.id ?? hashContent(part.content)}`; } function deriveToolMessageId(toolCallId) { return `tool-${toolCallId}`; } function hashContent(s) { let h = 0; for (let i = 0; i < s.length; i++) h = h * 31 + s.charCodeAt(i) | 0; return Math.abs(h).toString(36); } export { uiMessagesToWire }; //# sourceMappingURL=ag-ui-wire.js.map