import type { PromptVariable, ThoughtItem, UserInputFormItem, VisionFile } from '~/api/dify-chat'; /** * 替换提示模板中的变量 * @param str 提示模板字符串 * @param promptVariables 提示变量列表 * @param inputs 输入值 * @returns 替换后的字符串 */ export function replaceVarWithValues(str: string, promptVariables: PromptVariable[], inputs: Record) { return str.replace(/\{\{([^}]+)\}\}/g, (match, key) => { const name = inputs[key]; if (name) return name; const valueObj: PromptVariable | undefined = promptVariables.find(v => v.key === key); return valueObj ? `{{${valueObj.key}}}` : match; }); } /** * 将用户输入表单转换为提示变量 * @param useInputs 用户输入表单项列表 * @returns 提示变量列表 */ export const userInputsFormToPromptVariables = (useInputs: UserInputFormItem[] | null) => { if (!useInputs) return []; const promptVariables: PromptVariable[] = []; useInputs.forEach((item: any) => { const [type, content] = (() => { const type = Object.keys(item)[0]; return [type === 'text-input' ? 'string' : type, item[type]]; })(); if (type === 'string' || type === 'paragraph') { promptVariables.push({ key: content.variable, name: content.label, required: content.required, type, max_length: content.max_length, options: [], }); } else if (type === 'number') { promptVariables.push({ key: content.variable, name: content.label, required: content.required, type, options: [], }); } else if (type === 'file' || type === 'file-list') { promptVariables.push({ ...content, key: content.variable, name: content.label, required: content.required, type, max_length: content.max_length, options: [], }); } else { promptVariables.push({ key: content.variable, name: content.label, required: content.required, type: 'select', options: content.options, }); } }); return promptVariables; }; /** * 排序代理思考列表 * @param list 思考列表 * @returns 排序后的列表 */ export const sortAgentSorts = (list: ThoughtItem[]) => { if (!list) return list; if (list.some(item => (item as any).position === undefined)) return list; const temp = [...list]; temp.sort((a, b) => (a as any).position - (b as any).position); return temp; }; /** * 为思考列表添加文件信息 * @param list 思考列表 * @param messageFiles 消息文件列表 * @returns 添加文件信息后的列表 */ export const addFileInfos = (list: ThoughtItem[], messageFiles: VisionFile[]) => { if (!list || !messageFiles) return list; return list.map((item) => { if ((item as any).files && (item as any).files?.length > 0) { return { ...item, message_files: (item as any).files.map((fileId: string) => messageFiles.find(file => file.id === fileId)) as VisionFile[], }; } return item; }); }; /** * 将Unicode编码转换为字符 * @param text 包含Unicode编码的文本 * @returns 转换后的文本 */ export function unicodeToChar(text: string) { return text.replace(/\\u[0-9a-f]{4}/g, (match) => { return String.fromCharCode(parseInt(match.substring(2), 16)); }); }