llama-stack/llama_stack/ui/lib/format-message-content.ts
ehhuang 2708312168
feat(ui): implement chat completion views (#2201)
# What does this PR do?
 Implements table and detail views for chat completions

<img width="1548" alt="image"
src="https://github.com/user-attachments/assets/01061b7f-0d47-4b3b-b5ac-2df8f9035ef6"
/>
<img width="1549" alt="image"
src="https://github.com/user-attachments/assets/738d8612-8258-4c2c-858b-bee39030649f"
/>


## Test Plan
npm run test
2025-05-22 22:05:54 -07:00

61 lines
1.7 KiB
TypeScript

import { ChatMessage, ChatMessageContentPart } from "@/lib/types";
import { formatToolCallToString } from "@/lib/format-tool-call";
export function extractTextFromContentPart(
content: string | ChatMessageContentPart[] | null | undefined,
): string {
if (content === null || content === undefined) {
return "";
}
if (typeof content === "string") {
return content;
} else if (Array.isArray(content)) {
const parts: string[] = [];
for (const item of content) {
if (
item &&
typeof item === "object" &&
item.type === "text" &&
typeof item.text === "string"
) {
parts.push(item.text);
} else if (
item &&
typeof item === "object" &&
item.type === "image_url"
) {
parts.push("[Image]"); // Placeholder for images
} else if (typeof item === "string") {
// Handle cases where an array might contain plain strings
parts.push(item);
}
}
return parts.join(" ");
} else {
return content;
}
}
export function extractDisplayableText(
message: ChatMessage | undefined | null,
): string {
if (!message) {
return "";
}
let textPart = extractTextFromContentPart(message.content);
let toolCallPart = "";
if (message.tool_calls && message.tool_calls.length > 0) {
// For summary, usually the first tool call is sufficient
toolCallPart = formatToolCallToString(message.tool_calls[0]);
}
if (textPart && toolCallPart) {
return `${textPart} ${toolCallPart}`;
} else if (toolCallPart) {
return toolCallPart;
} else {
return textPart; // textPart will be "" if message.content was initially null/undefined/empty array etc.
}
}