| import type { ChatMessage } from '@freellmapi/shared/types.js';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| export type ContentTextBlock = { type: 'text'; text: string };
|
| export type ContentBlock = ContentTextBlock | { type: string; [key: string]: unknown };
|
|
|
| export function contentToString(content: unknown): string {
|
| if (typeof content === 'string') return content;
|
| if (content == null) return '';
|
| if (Array.isArray(content)) {
|
| return content
|
| .map((b) => {
|
| if (typeof b === 'string') return b;
|
| const block = b as { type?: string; text?: unknown };
|
|
|
|
|
|
|
|
|
| if (typeof block?.text === 'string' && (block.type === 'text' || block.type === undefined)) {
|
| return block.text;
|
| }
|
| return '';
|
| })
|
| .join('');
|
| }
|
| return '';
|
| }
|
|
|
| export function flattenMessageContent(messages: ChatMessage[]): ChatMessage[] {
|
| return messages.map((m) => ({
|
| ...m,
|
| content: contentToString(m.content),
|
| }));
|
| }
|
|
|
|
|
|
|
|
|
| export function contentHasImage(content: unknown): boolean {
|
| if (!Array.isArray(content)) return false;
|
| return content.some((block) => {
|
| const type = (block as { type?: string })?.type;
|
| return type === 'image_url' || type === 'image';
|
| });
|
| }
|
|
|
|
|
|
|
| export function messageHasImage(messages: ChatMessage[]): boolean {
|
| return messages.some((m) => contentHasImage(m.content));
|
| }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| export function normalizeOutboundContent<T>(payload: T): T {
|
| const choices = (payload as { choices?: unknown })?.choices;
|
| if (!Array.isArray(choices)) return payload;
|
| for (const choice of choices) {
|
| const delta = (choice as { delta?: { content?: unknown } })?.delta;
|
| if (delta && Array.isArray(delta.content)) {
|
| delta.content = contentToString(delta.content);
|
| }
|
| const message = (choice as { message?: { content?: unknown } })?.message;
|
| if (message && Array.isArray(message.content)) {
|
| message.content = contentToString(message.content);
|
| }
|
| }
|
| return payload;
|
| }
|
|
|