openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
40 lines (39 loc) • 1.5 kB
JavaScript
//#region src/shared/chat-content.ts
/** Coerces arbitrary provider content values into displayable text without throwing. */
function coerceChatContentText(value) {
if (typeof value === "string") return value;
if (value == null) return "";
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint" || typeof value === "symbol") return String(value);
if (typeof value === "object") try {
return JSON.stringify(value) ?? "";
} catch {
return "";
}
return "";
}
/** Extracts normalized plain text from string content or OpenAI-style text blocks. */
function extractTextFromChatContent(content, opts) {
const normalize = opts?.normalizeText ?? ((text) => text.replace(/\s+/g, " ").trim());
const joinWith = opts?.joinWith ?? " ";
const sanitize = (text) => {
const raw = coerceChatContentText(text);
return opts?.sanitizeText ? opts.sanitizeText(raw) : raw;
};
if (typeof content === "string") {
const normalized = normalize(sanitize(content));
return normalized ? normalized : null;
}
if (!Array.isArray(content)) return null;
const chunks = [];
for (const block of content) {
if (!block || typeof block !== "object") continue;
if (block.type !== "text") continue;
const text = block.text;
const value = sanitize(text);
if (value.trim()) chunks.push(value);
}
const joined = normalize(chunks.join(joinWith));
return joined ? joined : null;
}
//#endregion
export { extractTextFromChatContent as n, coerceChatContentText as t };