Files
leaudit-platform-frontend/app/api/prompts/prompts.ts
T

548 lines
16 KiB
TypeScript

import { postgrestGet, postgrestPut, postgrestPost, postgrestDelete, type PostgrestParams } from '../postgrest-client';
import { formatDate } from '../../utils';
// 提示词模板接口
export interface PromptTemplate {
id: number;
template_name: string;
template_type: string;
description: string | null;
template_content: string;
variables: Record<string, string>; // 变量定义
status: number;
version: string;
created_by: number;
created_at: string;
updated_at: string;
template_code?: string; // 模板代码(VLM_Extraction 类型时使用)
template_abbreviation?: string; // 模板简称(VLM_Extraction 类型时使用)
}
// 提示词模板前端接口
export interface PromptTemplateUI {
id: string;
template_name: string;
template_type: 'LLM_Extraction' | 'VLM_Extraction' | 'Evaluation' | 'Summary' | 'Common';
description: string;
template_content: string;
variables: Record<string, string>; // 变量定义
status: 'active' | 'inactive' | 'system';
version: string;
created_by: number;
created_by_username?: string; // 创建者用户名
created_at: string;
updated_at: string;
template_code?: string; // 模板代码(VLM_Extraction 类型时使用)
template_abbreviation?: string; // 模板简称(VLM_Extraction 类型时使用)
}
// 搜索参数接口
export interface PromptSearchParams {
name?: string;
type?: string;
status?: string;
page?: number;
pageSize?: number;
}
/**
* 从不同格式的 API 响应中提取数据
* @param responseData API 响应数据
* @returns 提取后的数据或 null
*/
function extractApiData<T>(responseData: unknown): T | null {
if (!responseData) return null;
// 格式1: { code: number, msg: string, data: T }
if (typeof responseData === 'object' && responseData !== null &&
'code' in responseData &&
'data' in responseData &&
(responseData as { data: unknown }).data) {
return (responseData as { data: T }).data;
}
// 格式2: 直接是数据对象
return responseData as T;
}
/**
* 将API状态值转换为UI状态值
* @param status API状态值(数字)
* @returns UI状态值(字符串)
*/
function mapStatusToUI(status: number): 'active' | 'inactive' | 'system' {
switch(status) {
case 0: return 'inactive';
case 1: return 'active';
case 2: return 'system';
default: return 'inactive';
}
}
/**
* 将UI状态值转换为API状态值
* @param status UI状态值(字符串)
* @returns API状态值(数字)
*/
function mapStatusToAPI(status: string): number {
switch(status) {
case 'active': return 1;
case 'inactive': return 0;
case 'system': return 2;
default: return 0;
}
}
/**
* 将数据库模板转换为UI模板
* @param template 数据库模板(可能包含关联的用户信息)
* @returns UI模板
*/
export function convertToUITemplate(template: PromptTemplate & { sso_users?: { username: string } }): PromptTemplateUI {
return {
id: template.id ? template.id.toString() : '',
template_name: template.template_name,
template_type: template.template_type as "LLM_Extraction" | "VLM_Extraction" | "Evaluation" | "Summary" | "Common",
description: template.description || '',
template_content: template.template_content,
variables: template.variables || {}, // 如果variables为null,则使用空对象
status: mapStatusToUI(template.status),
version: template.version,
created_by: template.created_by,
created_by_username: template.sso_users?.username, // 从关联的用户信息中提取用户名
created_at: formatDate(template.created_at),
updated_at: formatDate(template.updated_at),
template_code: template.template_code,
template_abbreviation: template.template_abbreviation
};
}
/**
* 获取提示词模板列表
* @param searchParams 搜索参数
* @param frontendJWT JWT token (可选)
* @returns 提示词模板列表和总数
*/
export async function getPromptTemplates(searchParams: PromptSearchParams = {}, frontendJWT?: string): Promise<{
data?: { templates: PromptTemplateUI[], total: number };
error?: string;
status?: number;
}> {
try {
// console.log('获取提示词模板列表,参数:', searchParams);
const TYPE = 'Common,LLM_Extraction,VLM_Extraction,Evaluation,Summary';
const page = searchParams.page || 1;
const pageSize = searchParams.pageSize || 10;
// 构建查询参数,包含对 sso_users 表的左连接
const params: PostgrestParams = {
select: `id,template_name,template_type,description,template_content,variables,status,version,created_by,created_at,updated_at,template_code,template_abbreviation,sso_users!created_by(username)`,
order: 'updated_at.desc',
headers: {
'Prefer': 'count=exact'
},
limit: pageSize,
offset: (page - 1) * pageSize,
filter: {} as Record<string, string>,
token: frontendJWT
};
// 添加筛选条件
const filter: Record<string, string> = {};
filter['status'] = `gte.0`;
if (searchParams.name) {
filter['template_name'] = `ilike.%${searchParams.name}%`;
}
if (searchParams.type) {
filter['template_type'] = `eq.${searchParams.type}`;
}else{
filter['template_type'] = `in.(${TYPE})`;
}
if (searchParams.status) {
let statusValue: number;
switch (searchParams.status) {
case 'active': statusValue = 1; break;
case 'inactive': statusValue = 0; break;
case 'system': statusValue = 2; break;
default: statusValue = -1;
}
if (statusValue >= 0) {
filter['status'] = `eq.${statusValue}`;
}
}
params.filter = filter;
// 发送API请求
// console.log('API请求参数:', params);
const response = await postgrestGet<PromptTemplate[]>('prompt_templates', params);
if (response.error) {
console.error('API返回错误:', response.error);
return { error: response.error, status: response.status };
}
// 提取API返回的数据
const extractedData = extractApiData<PromptTemplate[]>(response.data);
if (!extractedData) {
console.error('提取数据失败,原始响应:', response.data);
return { error: '获取提示词模板数据失败', status: 500 };
}
// console.log(`成功获取${extractedData.length}条提示词模板数据`);
// 从响应头中获取总数
let totalCount = 0;
const responseWithHeaders = response as { data: PromptTemplate[]; headers: Record<string, string> };
if(responseWithHeaders.headers){
const rangeHeader = responseWithHeaders.headers['content-range'];
if(rangeHeader){
const total = rangeHeader.split('/')[1];
if(total !== '*'){
totalCount = parseInt(total, 10);
}
}
}
// 返回转换后的数据
return {
data: {
templates: extractedData.map(convertToUITemplate),
total: totalCount
}
};
} catch (error) {
console.error('获取提示词模板出错:', error);
return {
error: error instanceof Error ? error.message : '获取提示词模板失败',
status: 500
};
}
}
/**
* 获取提示词模板详情
* @param id 模板ID
* @param frontendJWT JWT token (可选)
* @returns 提示词模板详情
*/
export async function getPromptTemplate(id: string, frontendJWT?: string): Promise<{
data?: PromptTemplateUI;
error?: string;
status?: number;
}> {
try {
if (!id) {
return { error: '模板ID不能为空', status: 400 };
}
const params: PostgrestParams = {
select: `id,template_name,template_type,description,template_content,variables,status,version,created_by,created_at,updated_at,template_code,template_abbreviation,sso_users!created_by(username)`,
filter: {
'id': `eq.${id}`
},
token: frontendJWT
};
const response = await postgrestGet<PromptTemplate[]>('prompt_templates', params);
if (response.error) {
return { error: response.error, status: response.status };
}
const extractedData = extractApiData<PromptTemplate[]>(response.data);
if (!extractedData || extractedData.length === 0) {
return { error: '未找到指定模板', status: 404 };
}
return { data: convertToUITemplate(extractedData[0]) };
} catch (error) {
console.error('获取提示词模板详情失败:', error);
return {
error: error instanceof Error ? error.message : '获取提示词模板详情失败',
status: 500
};
}
}
/**
* 创建提示词模板
* @param template 提示词模板数据
* @param userId 当前用户ID
* @param frontendJWT JWT token (可选)
* @returns 创建的提示词模板
*/
export async function createPromptTemplate(template: Partial<PromptTemplateUI>, userId: number, frontendJWT?: string): Promise<{
data?: PromptTemplateUI;
error?: string;
status?: number;
}> {
try {
// 验证必填字段
if (!template.template_name || !template.template_type || !template.template_content) {
return { error: '模板名称、类型和内容不能为空', status: 400 };
}
// 验证用户ID
if (!userId) {
return { error: '用户ID不能为空', status: 400 };
}
// 准备变量数据
let variablesData: Record<string, string> = {};
if (typeof template.variables === 'string') {
try {
variablesData = JSON.parse(template.variables);
} catch (e) {
console.error('解析变量JSON失败:', e);
}
} else if (template.variables) {
variablesData = template.variables;
}
// 准备API数据
const apiTemplate: Partial<PromptTemplate> = {
template_name: template.template_name,
template_type: template.template_type,
description: template.description || null,
template_content: template.template_content,
variables: variablesData,
status: mapStatusToAPI(template.status || 'active'),
version: template.version || 'v1.0',
created_by: userId, // 使用当前登录用户ID
template_code: template.template_code,
template_abbreviation: template.template_abbreviation
};
if(apiTemplate){
// console.log('apiTemplate', apiTemplate);
// throw new Error('测试错误');
}
const response = await postgrestPost<PromptTemplate, Partial<PromptTemplate>>(
'prompt_templates',
apiTemplate,
frontendJWT
);
if (response.error) {
return { error: response.error, status: response.status };
}
const extractedData = extractApiData<PromptTemplate>(response.data);
if (!extractedData) {
return { error: '创建提示词模板失败', status: 500 };
}
return { data: convertToUITemplate(extractedData) };
} catch (error) {
console.error('创建提示词模板失败:', error);
return {
error: error instanceof Error ? error.message : '创建提示词模板失败',
status: 500
};
}
}
/**
* 更新提示词模板
* @param id 模板ID
* @param template 提示词模板数据
* @param frontendJWT JWT token (可选)
* @returns 更新后的提示词模板
*/
export async function updatePromptTemplate(id: string, template: Partial<PromptTemplateUI>, frontendJWT?: string): Promise<{
data?: PromptTemplateUI;
error?: string;
status?: number;
}> {
try {
if (!id) {
return { error: '模板ID不能为空', status: 400 };
}
// 准备变量数据
let variablesData: Record<string, string> = {};
if (typeof template.variables === 'string') {
try {
variablesData = JSON.parse(template.variables);
} catch (e) {
console.error('解析变量JSON失败:', e);
}
} else if (template.variables) {
variablesData = template.variables;
}
// 准备API数据
const apiTemplate: Partial<PromptTemplate> = {};
if (template.template_name !== undefined) {
apiTemplate.template_name = template.template_name;
}
if (template.template_type !== undefined) {
apiTemplate.template_type = template.template_type;
}
if (template.description !== undefined) {
apiTemplate.description = template.description;
}
if (template.template_content !== undefined) {
apiTemplate.template_content = template.template_content;
}
if (template.variables !== undefined) {
apiTemplate.variables = variablesData;
}
if (template.status !== undefined) {
apiTemplate.status = mapStatusToAPI(template.status);
}
if (template.version !== undefined) {
apiTemplate.version = template.version;
}
if (template.template_code !== undefined) {
apiTemplate.template_code = template.template_code;
}
if (template.template_abbreviation !== undefined) {
apiTemplate.template_abbreviation = template.template_abbreviation;
}
// if(apiTemplate){
// console.log('apiTemplate', apiTemplate);
// throw new Error('测试错误');
// }
const response = await postgrestPut<PromptTemplate, Partial<PromptTemplate>>(
'prompt_templates',
apiTemplate,
{ id },
frontendJWT
);
if (response.error) {
return { error: response.error, status: response.status };
}
const extractedData = extractApiData<PromptTemplate>(response.data);
if (!extractedData) {
return { error: '更新提示词模板失败', status: 500 };
}
return { data: convertToUITemplate(extractedData) };
} catch (error) {
console.error('更新提示词模板失败:', error);
return {
error: error instanceof Error ? error.message : '更新提示词模板失败',
status: 500
};
}
}
/**
* 删除提示词模板
* @param id 模板ID
* @param frontendJWT JWT token (可选)
* @returns 成功或失败信息
*/
export async function deletePromptTemplate(id: string, frontendJWT?: string): Promise<{
success?: boolean;
error?: string;
status?: number;
}> {
try {
if (!id) {
return { error: '模板ID不能为空', status: 400 };
}
// 使用真实删除替代状态更新
const response = await postgrestDelete<PromptTemplate>(
'prompt_templates',
{
filter: {
'id': `eq.${id}`
},
token: frontendJWT
}
);
if (response.error) {
return { error: response.error, status: response.status };
}
return { success: true };
} catch (error) {
console.error('删除提示词模板失败:', error);
return {
error: error instanceof Error ? error.message : '删除提示词模板失败',
status: 500
};
}
}
/**
* 获取指定类型的提示词模板选项
* @param templateType 模板类型(如 'VLM_Extraction', 'LLM_Extraction' 等)
* @param frontendJWT JWT token (可选)
* @returns 模板选项列表 { value: template_code, label: template_abbreviation }
*/
export async function getPromptTemplateOptions(templateType: string, frontendJWT?: string): Promise<{
data?: Array<{ value: string; label: string }>;
error?: string;
status?: number;
}> {
try {
if (!templateType) {
return { error: '模板类型不能为空', status: 400 };
}
const params: PostgrestParams = {
select: 'template_code,template_abbreviation',
filter: {
'template_type': `eq.${templateType}`,
'status': 'gte.0' // 只查询有效状态的模板
},
order: 'template_abbreviation.asc', // 按标签排序
token: frontendJWT
};
const response = await postgrestGet<Array<{ template_code: string; template_abbreviation: string }>>('prompt_templates', params);
if (response.error) {
console.error('获取提示词模板选项失败:', response.error);
return { error: response.error, status: response.status };
}
const extractedData = extractApiData<Array<{ template_code: string; template_abbreviation: string }>>(response.data);
if (!extractedData) {
console.error('提取提示词模板选项数据失败');
return { error: '获取提示词模板选项失败', status: 500 };
}
// 转换为选项格式
const options = extractedData.map(item => ({
value: item.template_code,
label: item.template_abbreviation
}));
return { data: options };
} catch (error) {
console.error('获取提示词模板选项出错:', error);
return {
error: error instanceof Error ? error.message : '获取提示词模板选项失败',
status: 500
};
}
}