AI Message Text Utils (utils/text.ts)

pi · packages/ai/src/utils/text.ts · typescript · MIT
ai, chat, tag:text-processing, tag:utility

Extracts and renders plain text content from AI message structures, including system message sections and content blocks. Reuse when formatting or concatenating LLM message text.

// Source: https://github.com/earendil-works/pi | License: MIT | Copyright 2025 Mario Zechner
// Provided via justclaw.it.com; keep this notice with the code.
import type { ImageContent, SystemMessage, TextContent, ThinkingContent, ToolCall } from "../types.ts";

type Content = TextContent | ImageContent | ThinkingContent | ToolCall;

/** Extract and join text from message content. */
export function contentText(content: string | readonly Content[], separator = "\n"): string {
	if (typeof content === "string") return content;
	return content
		.filter((block) => block.type === "text")
		.map((block) => block.text)
		.join(separator);
}

/** Render a system message as a complete prompt: its content followed by its sections. */
export function getSystemMessageText(message: SystemMessage): st

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key