feat(agent): implement agent management UI and operations
This commit is contained in:
@@ -11,6 +11,7 @@ import {
|
||||
import { MoreVert as MoreVertIcon } from '@mui/icons-material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { IFlow } from '@/interfaces/database/agent';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
interface AgentCardProps {
|
||||
agent: IFlow;
|
||||
@@ -21,6 +22,17 @@ interface AgentCardProps {
|
||||
const AgentCard: React.FC<AgentCardProps> = ({ agent, onMenuClick, onViewAgent }) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const getAvatarSrc = (src?: string) => {
|
||||
if (!src) return undefined;
|
||||
// Already a valid data URL
|
||||
if (/^data:image\/(png|jpeg|jpg|webp);base64,/.test(src)) return src;
|
||||
// HTTP(S) URL
|
||||
if (/^https?:\/\//.test(src)) return src;
|
||||
// Raw base64 without header -> assume png
|
||||
if (/^[A-Za-z0-9+/=]+$/.test(src)) return `data:image/png;base64,${src}`;
|
||||
return src;
|
||||
};
|
||||
|
||||
const getPermissionInfo = (permission: string) => {
|
||||
switch (permission) {
|
||||
case 'me':
|
||||
@@ -34,26 +46,18 @@ const AgentCard: React.FC<AgentCardProps> = ({ agent, onMenuClick, onViewAgent }
|
||||
|
||||
const permissionInfo = getPermissionInfo(agent.permission || 'me');
|
||||
|
||||
const formatDate = (dateStr?: string) => {
|
||||
if (!dateStr) return t('common.unknown');
|
||||
return dateStr;
|
||||
};
|
||||
|
||||
const nodeCount = agent.dsl?.graph?.nodes?.length ?? 0;
|
||||
const edgeCount = agent.dsl?.graph?.edges?.length ?? 0;
|
||||
|
||||
return (
|
||||
<Card sx={{ borderRadius: 2 }}>
|
||||
<Card sx={{ borderRadius: 2, height: 260 }}>
|
||||
<CardContent>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
|
||||
<Avatar src={agent.avatar} sx={{ bgcolor: 'primary.main' }}>{agent.title?.[0] || 'A'}</Avatar>
|
||||
<Avatar src={getAvatarSrc(agent.avatar)} sx={{ bgcolor: 'primary.main' }} />
|
||||
<Box>
|
||||
<Typography variant="h6" fontWeight={600}>{agent.title || t('common.untitled')}</Typography>
|
||||
<Typography variant="h6" fontWeight={600} className='ellipsis1'>{agent.title}</Typography>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
|
||||
{agent.canvas_category && (
|
||||
<Chip label={agent.canvas_category} size="small" />
|
||||
)}
|
||||
<Chip
|
||||
label={permissionInfo.label}
|
||||
size="small"
|
||||
@@ -72,24 +76,18 @@ const AgentCard: React.FC<AgentCardProps> = ({ agent, onMenuClick, onViewAgent }
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
sx={{
|
||||
mt: 1,
|
||||
mb: 2,
|
||||
display: '-webkit-box',
|
||||
WebkitLineClamp: 2,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
className='ellipsis2'
|
||||
sx={{ mt: 1 }}
|
||||
>
|
||||
{agent.description || t('common.noDescription')}
|
||||
{agent.description || '-'}
|
||||
</Typography>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
justifyContent: 'space-between',
|
||||
mt: 2,
|
||||
p: 1.5,
|
||||
mt: 1,
|
||||
p: 1,
|
||||
backgroundColor: '#F8F9FA',
|
||||
borderRadius: 1,
|
||||
}}
|
||||
@@ -109,12 +107,12 @@ const AgentCard: React.FC<AgentCardProps> = ({ agent, onMenuClick, onViewAgent }
|
||||
</Box>
|
||||
|
||||
<Typography variant="caption" color="text.secondary" sx={{ mt: 1, display: 'block' }}>
|
||||
{t('common.updatedAt') || 'Updated'}: {formatDate(agent.update_date)}
|
||||
{t('agent.updatedAt')}: {dayjs(agent.update_date).format('YYYY-MM-DD HH:mm:ss')}
|
||||
</Typography>
|
||||
|
||||
{agent.nickname && (
|
||||
<Typography variant="caption" color="text.secondary" sx={{ display: 'block' }}>
|
||||
{t('knowledge.creator') || 'Creator'}: {agent.nickname}
|
||||
{t('agent.creator')}: {agent.nickname}
|
||||
</Typography>
|
||||
)}
|
||||
</CardContent>
|
||||
|
||||
@@ -51,6 +51,13 @@ const AgentGridView: React.FC<AgentGridViewProps> = ({
|
||||
handleMenuClose();
|
||||
};
|
||||
|
||||
const handleEdit = () => {
|
||||
if (selectedAgent && onEdit) {
|
||||
onEdit(selectedAgent);
|
||||
}
|
||||
handleMenuClose();
|
||||
};
|
||||
|
||||
const handleView = () => {
|
||||
if (selectedAgent && onView) {
|
||||
onView(selectedAgent);
|
||||
@@ -80,14 +87,14 @@ const AgentGridView: React.FC<AgentGridViewProps> = ({
|
||||
return (
|
||||
<Box sx={{ textAlign: 'center', py: 8 }}>
|
||||
<Typography variant="h6" color="text.secondary" gutterBottom>
|
||||
{searchTerm ? (t('agent.noMatchingAgents') || 'No matching agents') : (t('agent.noAgents') || 'No agents')}
|
||||
{searchTerm ? (t('agent.noMatchingAgents')) : (t('agent.noAgents'))}
|
||||
</Typography>
|
||||
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
|
||||
{searchTerm ? (t('agent.tryAdjustingFilters') || 'Try adjusting filters') : (t('agent.createFirstAgent') || 'Create your first agent')}
|
||||
{searchTerm ? (t('agent.tryAdjustingFilters')) : (t('agent.createFirstAgent'))}
|
||||
</Typography>
|
||||
{(!searchTerm && onCreateAgent) && (
|
||||
<Button variant="contained" startIcon={<AddIcon />} onClick={onCreateAgent}>
|
||||
{t('agent.createAgent') || 'Create Agent'}
|
||||
{t('agent.createAgent')}
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
@@ -113,9 +120,11 @@ const AgentGridView: React.FC<AgentGridViewProps> = ({
|
||||
)}
|
||||
|
||||
<Menu anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={handleMenuClose}>
|
||||
<MenuItem onClick={handleView}>{t('common.viewDetails')}</MenuItem>
|
||||
{onEdit && (
|
||||
<MenuItem onClick={handleEdit}>{t('agent.editAgent')}</MenuItem>
|
||||
)}
|
||||
<MenuItem onClick={handleDelete} sx={{ color: 'error.main' }}>
|
||||
{t('common.delete')}
|
||||
{t('agent.deleteAgent')}
|
||||
</MenuItem>
|
||||
</Menu>
|
||||
</Box>
|
||||
|
||||
@@ -150,15 +150,15 @@ export const ExceptiveType = ['xlsx', 'xls', 'pdf', 'docx', ...Images];
|
||||
export const SupportedPreviewDocumentTypes = [...ExceptiveType];
|
||||
//#endregion
|
||||
|
||||
// export enum Platform {
|
||||
// RAGFlow = 'RAGFlow',
|
||||
// Dify = 'Dify',
|
||||
// FastGPT = 'FastGPT',
|
||||
// Coze = 'Coze',
|
||||
// }
|
||||
export enum Platform {
|
||||
RAGFlow = 'RAGFlow',
|
||||
Dify = 'Dify',
|
||||
FastGPT = 'FastGPT',
|
||||
Coze = 'Coze',
|
||||
}
|
||||
|
||||
// export enum ThemeEnum {
|
||||
// Dark = 'dark',
|
||||
// Light = 'light',
|
||||
// System = 'system',
|
||||
// }
|
||||
export enum ThemeEnum {
|
||||
Dark = 'dark',
|
||||
Light = 'light',
|
||||
System = 'system',
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import agentService from '@/services/agent_service';
|
||||
import type { IFlow } from '@/interfaces/database/agent';
|
||||
import type { IAgentPaginationParams } from '@/interfaces/request/agent';
|
||||
import type { IAgentPaginationParams, IAgentCreateRequestBody, IAgentSettingRequestBody } from '@/interfaces/request/agent';
|
||||
import logger from '@/utils/logger';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSnackbar } from '@/hooks/useSnackbar';
|
||||
|
||||
export interface UseAgentListState {
|
||||
agents: IFlow[];
|
||||
@@ -79,4 +81,80 @@ export const useAgentList = (initialParams?: IAgentPaginationParams) => {
|
||||
setPageSize,
|
||||
refresh,
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
export function useAgentOperations() {
|
||||
const { t } = useTranslation();
|
||||
const { showMessage } = useSnackbar();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const createAgent = useCallback(async (body: IAgentCreateRequestBody) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const res = await agentService.setCanvas(body);
|
||||
const newId = res?.data?.data?.id || res?.data?.id;
|
||||
showMessage.success(t('agent.createAgentSuccess'));
|
||||
return { success: true, id: newId } as const;
|
||||
} catch (err: any) {
|
||||
const errorMessage = err?.response?.data?.message || err?.message || t('agent.createAgentFailed');
|
||||
setError(errorMessage);
|
||||
showMessage.error(errorMessage);
|
||||
return { success: false, error: errorMessage } as const;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [t, showMessage]);
|
||||
|
||||
const editAgent = useCallback(async (data: Partial<IAgentSettingRequestBody>) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const res = await agentService.settingAgent(data);
|
||||
const code = res?.data?.code;
|
||||
if (code === 0) {
|
||||
showMessage.success(t('message.updated'));
|
||||
return { success: true } as const;
|
||||
}
|
||||
const msg = res?.data?.message || t('common.operationFailed');
|
||||
showMessage.error(msg);
|
||||
return { success: false, error: msg } as const;
|
||||
} catch (err: any) {
|
||||
const errorMessage = err?.response?.data?.message || err?.message || t('common.operationFailed');
|
||||
setError(errorMessage);
|
||||
showMessage.error(errorMessage);
|
||||
return { success: false, error: errorMessage } as const;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [t, showMessage]);
|
||||
|
||||
const deleteAgents = useCallback(async (ids: string[]) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
const res = await agentService.removeCanvas(ids);
|
||||
const code = res?.data?.code;
|
||||
if (code === 0) {
|
||||
showMessage.success(t('message.deleted'));
|
||||
return { success: true } as const;
|
||||
}
|
||||
const msg = res?.data?.message || t('common.operationFailed');
|
||||
showMessage.error(msg);
|
||||
return { success: false, error: msg } as const;
|
||||
} catch (err: any) {
|
||||
const errorMessage = err?.response?.data?.message || err?.message || t('common.operationFailed');
|
||||
setError(errorMessage);
|
||||
showMessage.error(errorMessage);
|
||||
return { success: false, error: errorMessage } as const;
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [t, showMessage]);
|
||||
|
||||
const clearError = useCallback(() => setError(null), []);
|
||||
|
||||
return { loading, error, createAgent, editAgent, deleteAgents, clearError };
|
||||
}
|
||||
@@ -63,6 +63,7 @@ export interface IOperatorNode {
|
||||
export declare interface IFlow {
|
||||
avatar?: string;
|
||||
canvas_type: null;
|
||||
canvas_category?: string;
|
||||
create_date: string;
|
||||
create_time: number;
|
||||
description: null;
|
||||
@@ -75,7 +76,6 @@ export declare interface IFlow {
|
||||
permission: string;
|
||||
nickname: string;
|
||||
operator_permission: number;
|
||||
canvas_category: string;
|
||||
}
|
||||
|
||||
export interface IFlowTemplate {
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
import type { Edge, Node } from '@xyflow/react';
|
||||
import type { IReference, Message } from './chat';
|
||||
|
||||
export type DSLComponents = Record<string, IOperator>;
|
||||
|
||||
export interface DSL {
|
||||
components: DSLComponents;
|
||||
history: any[];
|
||||
path?: string[][];
|
||||
answer?: any[];
|
||||
graph?: IGraph;
|
||||
messages: Message[];
|
||||
reference: IReference[];
|
||||
globals: Record<string, any>;
|
||||
retrieval: IReference[];
|
||||
}
|
||||
|
||||
export interface IOperator {
|
||||
obj: IOperatorNode;
|
||||
downstream: string[];
|
||||
upstream: string[];
|
||||
parent_id?: string;
|
||||
}
|
||||
|
||||
export interface IOperatorNode {
|
||||
component_name: string;
|
||||
params: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export declare interface IFlow {
|
||||
avatar?: string;
|
||||
canvas_type: null;
|
||||
create_date: string;
|
||||
create_time: number;
|
||||
description: string;
|
||||
dsl: DSL;
|
||||
id: string;
|
||||
title: string;
|
||||
update_date: string;
|
||||
update_time: number;
|
||||
user_id: string;
|
||||
permission: string;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export interface IFlowTemplate {
|
||||
avatar: string;
|
||||
canvas_type: string;
|
||||
create_date: string;
|
||||
create_time: number;
|
||||
description: {
|
||||
en: string;
|
||||
zh: string;
|
||||
};
|
||||
dsl: DSL;
|
||||
id: string;
|
||||
title: {
|
||||
en: string;
|
||||
zh: string;
|
||||
};
|
||||
update_date: string;
|
||||
update_time: number;
|
||||
}
|
||||
|
||||
export type ICategorizeItemResult = Record<
|
||||
string,
|
||||
Omit<ICategorizeItem, 'name'>
|
||||
>;
|
||||
|
||||
export interface IGenerateForm {
|
||||
max_tokens?: number;
|
||||
temperature?: number;
|
||||
top_p?: number;
|
||||
presence_penalty?: number;
|
||||
frequency_penalty?: number;
|
||||
cite?: boolean;
|
||||
prompt: number;
|
||||
llm_id: string;
|
||||
parameters: { key: string; component_id: string };
|
||||
}
|
||||
export interface ICategorizeItem {
|
||||
name: string;
|
||||
description?: string;
|
||||
examples?: string;
|
||||
to?: string;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export interface ICategorizeForm extends IGenerateForm {
|
||||
category_description: ICategorizeItemResult;
|
||||
}
|
||||
|
||||
export interface IRelevantForm extends IGenerateForm {
|
||||
yes: string;
|
||||
no: string;
|
||||
}
|
||||
|
||||
export interface ISwitchCondition {
|
||||
items: ISwitchItem[];
|
||||
logical_operator: string;
|
||||
to: string[] | string;
|
||||
}
|
||||
|
||||
export interface ISwitchItem {
|
||||
cpn_id: string;
|
||||
operator: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface ISwitchForm {
|
||||
conditions: ISwitchCondition[];
|
||||
end_cpn_id: string;
|
||||
no: string;
|
||||
}
|
||||
|
||||
export interface IBeginForm {
|
||||
prologue?: string;
|
||||
}
|
||||
|
||||
export interface IRetrievalForm {
|
||||
similarity_threshold?: number;
|
||||
keywords_similarity_weight?: number;
|
||||
top_n?: number;
|
||||
top_k?: number;
|
||||
rerank_id?: string;
|
||||
empty_response?: string;
|
||||
kb_ids: string[];
|
||||
}
|
||||
|
||||
export interface ICodeForm {
|
||||
inputs?: Array<{ name?: string; component_id?: string }>;
|
||||
lang: string;
|
||||
script?: string;
|
||||
}
|
||||
|
||||
export type BaseNodeData<TForm extends any> = {
|
||||
label: string; // operator type
|
||||
name: string; // operator name
|
||||
color?: string;
|
||||
form?: TForm;
|
||||
};
|
||||
|
||||
export type BaseNode<T = any> = Node<BaseNodeData<T>>;
|
||||
|
||||
export type IBeginNode = BaseNode<IBeginForm>;
|
||||
export type IRetrievalNode = BaseNode<IRetrievalForm>;
|
||||
export type IGenerateNode = BaseNode<IGenerateForm>;
|
||||
export type ICategorizeNode = BaseNode<ICategorizeForm>;
|
||||
export type ISwitchNode = BaseNode<ISwitchForm>;
|
||||
export type IRagNode = BaseNode;
|
||||
export type IRelevantNode = BaseNode;
|
||||
export type ILogicNode = BaseNode;
|
||||
export type INoteNode = BaseNode;
|
||||
export type IMessageNode = BaseNode;
|
||||
export type IRewriteNode = BaseNode;
|
||||
export type IInvokeNode = BaseNode;
|
||||
export type ITemplateNode = BaseNode;
|
||||
export type IEmailNode = BaseNode;
|
||||
export type IIterationNode = BaseNode;
|
||||
export type IIterationStartNode = BaseNode;
|
||||
export type IKeywordNode = BaseNode;
|
||||
export type ICodeNode = BaseNode<ICodeForm>;
|
||||
export type IAgentNode = BaseNode;
|
||||
|
||||
export type RAGFlowNodeType =
|
||||
| IBeginNode
|
||||
| IRetrievalNode
|
||||
| IGenerateNode
|
||||
| ICategorizeNode
|
||||
| ISwitchNode
|
||||
| IRagNode
|
||||
| IRelevantNode
|
||||
| ILogicNode
|
||||
| INoteNode
|
||||
| IMessageNode
|
||||
| IRewriteNode
|
||||
| IInvokeNode
|
||||
| ITemplateNode
|
||||
| IEmailNode
|
||||
| IIterationNode
|
||||
| IIterationStartNode
|
||||
| IKeywordNode;
|
||||
|
||||
export interface IGraph {
|
||||
nodes: RAGFlowNodeType[];
|
||||
edges: Edge[];
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { DSL } from "../database/agent";
|
||||
|
||||
/**
|
||||
* 分页请求参数
|
||||
*/
|
||||
@@ -12,3 +14,26 @@ export interface IDebugSingleRequestBody {
|
||||
component_id: string;
|
||||
params: Record<string, any>;
|
||||
}
|
||||
|
||||
export interface IAgentCreateRequestBody {
|
||||
title: string;
|
||||
avatar?: string;
|
||||
description?: string | { zh?: string; en?: string };
|
||||
dsl: DSL;
|
||||
canvas_category: string;
|
||||
}
|
||||
|
||||
export interface IAgentSettingRequestBody {
|
||||
avatar?: string;
|
||||
canvas_category?: string;
|
||||
description?: string;
|
||||
id: string;
|
||||
title: string;
|
||||
permission: string;
|
||||
}
|
||||
|
||||
export interface IAgentSetDSLRequestBody {
|
||||
id: string;
|
||||
title: string;
|
||||
dsl: DSL;
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
export interface IDebugSingleRequestBody {
|
||||
component_id: string;
|
||||
params: any[];
|
||||
}
|
||||
@@ -66,6 +66,7 @@ export default {
|
||||
moreActions: 'More Actions',
|
||||
disable: 'Disable',
|
||||
enable: 'Enable',
|
||||
onlyMe: 'Only Me',
|
||||
team: 'Team',
|
||||
public: 'Public',
|
||||
unknown: 'Unknown',
|
||||
@@ -1211,6 +1212,33 @@ This auto-tagging feature enhances retrieval by adding another layer of domain-s
|
||||
'If your model provider is not listed but claims to be "OpenAI-compatible", select the OpenAI-API-compatible card to add the relevant model(s). ',
|
||||
mcp: 'MCP',
|
||||
},
|
||||
agent: {
|
||||
agentList: 'Agent List',
|
||||
noMatchingAgents: 'No matching agents',
|
||||
noAgents: 'No agents',
|
||||
tryAdjustingFilters: 'Try adjusting your filters',
|
||||
createFirstAgent: 'Create your first agent',
|
||||
createAgent: 'Create agent',
|
||||
updatedAt: 'Updated At',
|
||||
creator: 'Creator',
|
||||
nodes: 'Nodes',
|
||||
edges: 'Edges',
|
||||
editAgent: 'Edit Agent',
|
||||
deleteAgent: 'Delete Agent',
|
||||
|
||||
forms: {
|
||||
title: 'Title',
|
||||
avatar: 'Avatar',
|
||||
description: 'Description',
|
||||
permissionSettings: 'Permission Settings',
|
||||
},
|
||||
|
||||
// create agent
|
||||
useTemplate: 'Use Template',
|
||||
createAgentSuccess: 'Agent created successfully',
|
||||
createAgentFailed: 'Agent creation failed',
|
||||
|
||||
},
|
||||
message: {
|
||||
registered: 'Registered!',
|
||||
logout: 'logout',
|
||||
@@ -1345,151 +1373,6 @@ This auto-tagging feature enhances retrieval by adding another layer of domain-s
|
||||
total: 'Total {{total}}',
|
||||
page: '{{page}} /Page',
|
||||
},
|
||||
dataflowParser: {
|
||||
parseSummary: 'Parse Summary',
|
||||
parseSummaryTip: 'Parser:deepdoc',
|
||||
rerunFromCurrentStep: 'Rerun From Current Step',
|
||||
rerunFromCurrentStepTip: 'Changes detected. Click to re-run.',
|
||||
confirmRerun: 'Confirm Rerun Process',
|
||||
confirmRerunModalContent: `
|
||||
<p class="text-sm text-text-disabled font-medium mb-2">
|
||||
You are about to rerun the process starting from the <strong class="text-text-primary">{{step}}</strong> step.
|
||||
</p>
|
||||
<p class="text-sm mb-3 text-text-secondary">This will:</p>
|
||||
<ul class="list-disc list-inside space-y-1 text-sm text-text-secondary">
|
||||
<li>Overwrite existing results from the current step onwards</li>
|
||||
<li>Create a new log entry for tracking</li>
|
||||
<li>Previous steps will remain unchanged</li>
|
||||
</ul>`,
|
||||
changeStepModalTitle: 'Step Switch Warning',
|
||||
changeStepModalContent: `
|
||||
<p>You are currently editing the results of this stage.</p>
|
||||
<p>If you switch to a later stage, your changes will be lost. </p>
|
||||
<p>To keep them, please click Rerun to re-run the current stage.</p> `,
|
||||
changeStepModalConfirmText: 'Switch Anyway',
|
||||
changeStepModalCancelText: 'Cancel',
|
||||
unlinkPipelineModalTitle: 'Unlink data pipeline',
|
||||
unlinkPipelineModalContent: `
|
||||
<p>Once unlinked, this Dataset will no longer be connected to the current Data Pipeline.</p>
|
||||
<p>Files that are already being parsed will continue until completion</p>
|
||||
<p>Files that are not yet parsed will no longer be processed</p> <br/>
|
||||
<p>Are you sure you want to proceed?</p> `,
|
||||
unlinkPipelineModalConfirmText: 'Unlink',
|
||||
},
|
||||
dataflow: {
|
||||
parser: 'Parser',
|
||||
parserDescription:
|
||||
'Extracts raw text and structure from files for downstream processing.',
|
||||
tokenizer: 'Tokenizer',
|
||||
tokenizerRequired: 'Please add the Tokenizer node first',
|
||||
tokenizerDescription:
|
||||
'Transforms text into the required data structure (e.g., vector embeddings for Embedding Search) depending on the chosen search method.',
|
||||
splitter: 'Token Splitter',
|
||||
splitterDescription:
|
||||
'Split text into chunks by token length with optional delimiters and overlap.',
|
||||
hierarchicalMergerDescription:
|
||||
'Split documents into sections by title hierarchy with regex rules for finer control.',
|
||||
hierarchicalMerger: 'Title Splitter',
|
||||
extractor: 'Context Generator',
|
||||
extractorDescription:
|
||||
'Use an LLM to extract structured insights from document chunks—such as summaries, classifications, etc.',
|
||||
outputFormat: 'Output format',
|
||||
lang: 'Language',
|
||||
fileFormats: 'File format',
|
||||
fileFormatOptions: {
|
||||
pdf: 'PDF',
|
||||
spreadsheet: 'Spreadsheet',
|
||||
image: 'Image',
|
||||
email: 'Email',
|
||||
'text&markdown': 'Text & Markup',
|
||||
word: 'Word',
|
||||
slides: 'PPT',
|
||||
audio: 'Audio',
|
||||
},
|
||||
fields: 'Field',
|
||||
addParser: 'Add Parser',
|
||||
hierarchy: 'Hierarchy',
|
||||
regularExpressions: 'Regular Expressions',
|
||||
overlappedPercent: 'Overlapped percent',
|
||||
searchMethod: 'Search method',
|
||||
begin: 'File',
|
||||
parserMethod: 'Parsing method',
|
||||
systemPrompt: 'System Prompt',
|
||||
systemPromptPlaceholder:
|
||||
'Enter system prompt for image analysis, if empty the system default value will be used',
|
||||
exportJson: 'Export JSON',
|
||||
viewResult: 'View Result',
|
||||
running: 'Running',
|
||||
summary: 'Augmented Context',
|
||||
keywords: 'Keywords',
|
||||
questions: 'Questions',
|
||||
metadata: 'Metadata',
|
||||
fieldName: 'Result Destination',
|
||||
prompts: {
|
||||
system: {
|
||||
keywords: `Role
|
||||
You are a text analyzer.
|
||||
|
||||
Task
|
||||
Extract the most important keywords/phrases of a given piece of text content.
|
||||
|
||||
Requirements
|
||||
- Summarize the text content, and give the top 5 important keywords/phrases.
|
||||
- The keywords MUST be in the same language as the given piece of text content.
|
||||
- The keywords are delimited by ENGLISH COMMA.
|
||||
- Output keywords ONLY.`,
|
||||
questions: `Role
|
||||
You are a text analyzer.
|
||||
|
||||
Task
|
||||
Propose 3 questions about a given piece of text content.
|
||||
|
||||
Requirements
|
||||
- Understand and summarize the text content, and propose the top 3 important questions.
|
||||
- The questions SHOULD NOT have overlapping meanings.
|
||||
- The questions SHOULD cover the main content of the text as much as possible.
|
||||
- The questions MUST be in the same language as the given piece of text content.
|
||||
- One question per line.
|
||||
- Output questions ONLY.`,
|
||||
summary: `Act as a precise summarizer. Your task is to create a summary of the provided content that is both concise and faithful to the original.
|
||||
|
||||
Key Instructions:
|
||||
1. Accuracy: Strictly base the summary on the information given. Do not introduce any new facts, conclusions, or interpretations that are not explicitly stated.
|
||||
2. Language: Write the summary in the same language as the source text.
|
||||
3. Objectivity: Present the key points without bias, preserving the original intent and tone of the content. Do not editorialize.
|
||||
4. Conciseness: Focus on the most important ideas, omitting minor details and fluff.`,
|
||||
metadata: `Extract important structured information from the given content. Output ONLY a valid JSON string with no additional text. If no important structured information is found, output an empty JSON object: {}.
|
||||
|
||||
Important structured information may include: names, dates, locations, events, key facts, numerical data, or other extractable entities.`,
|
||||
},
|
||||
user: {
|
||||
keywords: `Text Content
|
||||
[Insert text here]`,
|
||||
questions: `Text Content
|
||||
[Insert text here]`,
|
||||
summary: `Text to Summarize:
|
||||
[Insert text here]`,
|
||||
metadata: `Content: [INSERT CONTENT HERE]`,
|
||||
},
|
||||
},
|
||||
cancel: 'Cancel',
|
||||
switchPromptMessage:
|
||||
'The prompt word will change. Please confirm whether to abandon the existing prompt word?',
|
||||
tokenizerSearchMethodOptions: {
|
||||
full_text: 'Full-text',
|
||||
embedding: 'Embedding',
|
||||
},
|
||||
filenameEmbeddingWeight: 'Filename embedding weight',
|
||||
tokenizerFieldsOptions: {
|
||||
text: 'Processed Text',
|
||||
keywords: 'Keywords',
|
||||
questions: 'Questions',
|
||||
summary: 'Augmented Context',
|
||||
},
|
||||
imageParseMethodOptions: {
|
||||
ocr: 'OCR',
|
||||
},
|
||||
},
|
||||
datasetOverview: {
|
||||
downloadTip: 'Files being downloaded from data sources. ',
|
||||
processingTip: 'Files being processed by data flows.',
|
||||
|
||||
@@ -65,6 +65,7 @@ export default {
|
||||
moreActions: '更多操作',
|
||||
disable: '禁用',
|
||||
enable: '启用',
|
||||
onlyMe: '仅自己',
|
||||
team: '团队',
|
||||
public: '公开',
|
||||
unknown: '未知',
|
||||
@@ -1311,149 +1312,6 @@ General:实体和关系提取提示来自 GitHub - microsoft/graphrag:基于
|
||||
total: '总共 {{total}} 条',
|
||||
page: '{{page}}条/页',
|
||||
},
|
||||
dataflowParser: {
|
||||
parseSummary: '解析摘要',
|
||||
parseSummaryTip: '解析器: deepdoc',
|
||||
rerunFromCurrentStep: '从当前步骤重新运行',
|
||||
rerunFromCurrentStepTip: '已修改,点击重新运行。',
|
||||
confirmRerun: '确认重新运行流程',
|
||||
confirmRerunModalContent: `
|
||||
<p class="text-sm text-text-disabled font-medium mb-2">
|
||||
您即将从 <strong class="text-text-primary">{{step}}</strong> 步骤开始重新运行该过程
|
||||
</p>
|
||||
<p class="text-sm mb-3 text-text-secondary">这将:</p>
|
||||
<ul class="list-disc list-inside space-y-1 text-sm text-text-secondary">
|
||||
<li>从当前步骤开始覆盖现有结果</li>
|
||||
<li>创建新的日志条目进行跟踪</li>
|
||||
<li>之前的步骤将保持不变</li>
|
||||
</ul>`,
|
||||
changeStepModalTitle: '切换步骤警告',
|
||||
changeStepModalContent: `
|
||||
<p>您目前正在编辑此阶段的结果。</p>
|
||||
<p>如果您切换到后续阶段,您的更改将会丢失。</p>
|
||||
<p>要保留这些更改,请点击“重新运行”以重新运行当前阶段。</p> `,
|
||||
changeStepModalConfirmText: '继续切换',
|
||||
changeStepModalCancelText: '取消',
|
||||
unlinkPipelineModalTitle: '解绑数据流',
|
||||
unlinkPipelineModalContent: `
|
||||
<p>一旦取消链接,该数据集将不再连接到当前数据管道。</p>
|
||||
<p>正在解析的文件将继续解析,直到完成。</p>
|
||||
<p>尚未解析的文件将不再被处理。</p> <br/>
|
||||
<p>你确定要继续吗?</p> `,
|
||||
unlinkPipelineModalConfirmText: '解绑',
|
||||
},
|
||||
dataflow: {
|
||||
parser: '解析器',
|
||||
parserDescription: '从文件中提取原始文本和结构以供下游处理。',
|
||||
tokenizer: '分词器',
|
||||
tokenizerRequired: '请先添加Tokenizer节点',
|
||||
tokenizerDescription:
|
||||
'根据所选的搜索方法,将文本转换为所需的数据结构(例如,用于嵌入搜索的向量嵌入)。',
|
||||
splitter: '分词器拆分器',
|
||||
splitterDescription:
|
||||
'根据分词器长度将文本拆分成块,并带有可选的分隔符和重叠。',
|
||||
hierarchicalMergerDescription:
|
||||
'使用正则表达式规则按标题层次结构将文档拆分成多个部分,以实现更精细的控制。',
|
||||
hierarchicalMerger: '标题拆分器',
|
||||
extractor: '提取器',
|
||||
extractorDescription:
|
||||
'使用 LLM 从文档块(例如摘要、分类等)中提取结构化见解。',
|
||||
outputFormat: '输出格式',
|
||||
lang: '语言',
|
||||
fileFormats: '文件格式',
|
||||
fields: '字段',
|
||||
addParser: '增加解析器',
|
||||
hierarchy: '层次结构',
|
||||
regularExpressions: '正则表达式',
|
||||
overlappedPercent: '重叠百分比',
|
||||
searchMethod: '搜索方法',
|
||||
begin: '文件',
|
||||
parserMethod: '解析方法',
|
||||
systemPrompt: '系统提示词',
|
||||
systemPromptPlaceholder:
|
||||
'请输入用于图像分析的系统提示词,若为空则使用系统缺省值',
|
||||
exportJson: '导出 JSON',
|
||||
viewResult: '查看结果',
|
||||
running: '运行中',
|
||||
summary: '增强上下文',
|
||||
keywords: '关键词',
|
||||
questions: '问题',
|
||||
metadata: '元数据',
|
||||
fieldName: '结果目的地',
|
||||
prompts: {
|
||||
system: {
|
||||
keywords: `角色
|
||||
你是一名文本分析员。
|
||||
|
||||
任务
|
||||
从给定的文本内容中提取最重要的关键词/短语。
|
||||
|
||||
要求
|
||||
- 总结文本内容,并给出最重要的5个关键词/短语。
|
||||
- 关键词必须与给定的文本内容使用相同的语言。
|
||||
- 关键词之间用英文逗号分隔。
|
||||
- 仅输出关键词。`,
|
||||
questions: `角色
|
||||
你是一名文本分析员。
|
||||
|
||||
任务
|
||||
针对给定的文本内容提出3个问题。
|
||||
|
||||
要求
|
||||
- 理解并总结文本内容,并提出最重要的3个问题。
|
||||
- 问题的含义不应重叠。
|
||||
- 问题应尽可能涵盖文本的主要内容。
|
||||
- 问题必须与给定的文本内容使用相同的语言。
|
||||
- 每行一个问题。
|
||||
- 仅输出问题。`,
|
||||
summary: `扮演一个精准的摘要者。你的任务是为提供的内容创建一个简洁且忠实于原文的摘要。
|
||||
|
||||
关键说明:
|
||||
1. 准确性:摘要必须严格基于所提供的信息。请勿引入任何未明确说明的新事实、结论或解释。
|
||||
2. 语言:摘要必须使用与原文相同的语言。
|
||||
3. 客观性:不带偏见地呈现要点,保留内容的原始意图和语气。请勿进行编辑。
|
||||
4. 简洁性:专注于最重要的思想,省略细节和多余的内容。`,
|
||||
metadata: `从给定内容中提取重要的结构化信息。仅输出有效的 JSON 字符串,不包含任何附加文本。如果未找到重要的结构化信息,则输出一个空的 JSON 对象:{}。
|
||||
|
||||
重要的结构化信息可能包括:姓名、日期、地点、事件、关键事实、数字数据或其他可提取实体。`,
|
||||
},
|
||||
user: {
|
||||
keywords: `文本内容
|
||||
[在此处插入文本]`,
|
||||
questions: `文本内容
|
||||
[在此处插入文本]`,
|
||||
summary: `要总结的文本:
|
||||
[在此处插入文本]`,
|
||||
metadata: `内容:[在此处插入内容]`,
|
||||
},
|
||||
},
|
||||
cancel: '取消',
|
||||
filenameEmbeddingWeight: '文件名嵌入权重',
|
||||
switchPromptMessage: '提示词将发生变化,请确认是否放弃已有提示词?',
|
||||
fileFormatOptions: {
|
||||
pdf: 'PDF',
|
||||
spreadsheet: '电子表格',
|
||||
image: '图片',
|
||||
email: '邮件',
|
||||
'text&markdown': '文本和标记',
|
||||
word: 'Word',
|
||||
slides: 'PPT',
|
||||
audio: '音频',
|
||||
},
|
||||
tokenizerSearchMethodOptions: {
|
||||
full_text: '全文',
|
||||
embedding: '嵌入',
|
||||
},
|
||||
tokenizerFieldsOptions: {
|
||||
text: '处理后的文本',
|
||||
keywords: '关键词',
|
||||
questions: '问题',
|
||||
summary: '增强上下文',
|
||||
},
|
||||
imageParseMethodOptions: {
|
||||
ocr: 'OCR',
|
||||
},
|
||||
},
|
||||
datasetOverview: {
|
||||
downloadTip: '正在从数据源下载文件。',
|
||||
processingTip: '正在由数据流处理文件。',
|
||||
|
||||
260
src/pages/agent/components/CreateAgentDialog.tsx
Normal file
260
src/pages/agent/components/CreateAgentDialog.tsx
Normal file
@@ -0,0 +1,260 @@
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Button,
|
||||
Box,
|
||||
Typography,
|
||||
List,
|
||||
ListItemButton,
|
||||
ListItemText,
|
||||
Grid,
|
||||
Card,
|
||||
CardContent,
|
||||
CardActions,
|
||||
Avatar,
|
||||
} from '@mui/material';
|
||||
import { Add as AddIcon } from '@mui/icons-material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import agentService from '@/services/agent_service';
|
||||
import type { IFlowTemplate } from '@/interfaces/database/agent';
|
||||
import { useSnackbar } from '@/hooks/useSnackbar';
|
||||
import { AgentCategory } from '@/constants/agent';
|
||||
import { IAgentCreateRequestBody } from '@/interfaces/request/agent';
|
||||
import { useAgentOperations } from '@/hooks/agent-hooks';
|
||||
|
||||
interface CreateAgentDialogProps {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onCreated?: (newId?: string) => void;
|
||||
}
|
||||
|
||||
const CreateAgentDialog: React.FC<CreateAgentDialogProps> = ({ open, onClose, onCreated }) => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { showMessage } = useSnackbar();
|
||||
const ops = useAgentOperations();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [templates, setTemplates] = useState<IFlowTemplate[]>([]);
|
||||
const [activeCategory, setActiveCategory] = useState<string>('Recommended');
|
||||
const categoryRefs = useRef<Record<string, HTMLDivElement | null>>({});
|
||||
const lang = i18n.language?.startsWith('zh') ? 'zh' : 'en';
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
let mounted = true;
|
||||
setLoading(true);
|
||||
agentService
|
||||
.listTemplates()
|
||||
.then((res: any) => {
|
||||
const data = res?.data?.data || [];
|
||||
if (mounted) {
|
||||
setTemplates(data);
|
||||
}
|
||||
})
|
||||
.catch((err: any) => {
|
||||
console.error('listTemplates error', err);
|
||||
showMessage.error(t('common.fetchFailed'));
|
||||
})
|
||||
.finally(() => {
|
||||
if (mounted) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
mounted = false;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const categories = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
templates.forEach((tpl) => {
|
||||
if (tpl.canvas_type) set.add(tpl.canvas_type);
|
||||
});
|
||||
const arr = Array.from(set);
|
||||
// 将 Recommended 放在第一位
|
||||
arr.sort((a, b) => {
|
||||
if (a === 'Recommended') return -1;
|
||||
if (b === 'Recommended') return 1;
|
||||
return a.localeCompare(b);
|
||||
});
|
||||
return arr;
|
||||
}, [templates]);
|
||||
|
||||
// 当分类列表变化时,默认选中 Recommended 或第一个分类
|
||||
useEffect(() => {
|
||||
if (categories.length > 0) {
|
||||
if (!categories.includes(activeCategory)) {
|
||||
setActiveCategory(categories.includes('Recommended') ? 'Recommended' : categories[0]);
|
||||
}
|
||||
}
|
||||
}, [categories]);
|
||||
|
||||
// 保证选中项在可视区域
|
||||
useEffect(() => {
|
||||
const el = categoryRefs.current[activeCategory];
|
||||
if (el) {
|
||||
el.scrollIntoView({ block: 'nearest', inline: 'nearest' });
|
||||
}
|
||||
}, [activeCategory]);
|
||||
|
||||
const filteredTemplates = useMemo(() => {
|
||||
return templates.filter((tpl) => tpl.canvas_type === activeCategory);
|
||||
}, [templates, activeCategory]);
|
||||
|
||||
const handleUseTemplate = async (tpl: IFlowTemplate) => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const body: IAgentCreateRequestBody = {
|
||||
title: (tpl.title as any)?.[lang] || 'Untitled',
|
||||
avatar: tpl.avatar,
|
||||
description: (tpl.description as any)?.[lang] || '',
|
||||
dsl: tpl.dsl,
|
||||
canvas_category: (tpl as any).canvas_category || AgentCategory.AgentCanvas,
|
||||
};
|
||||
const result = await ops.createAgent(body);
|
||||
if (result.success) {
|
||||
if (onCreated) onCreated(result.id);
|
||||
}
|
||||
onClose();
|
||||
} catch (err: any) {
|
||||
console.error('create agent by template error', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateBlankAgent = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
const body: IAgentCreateRequestBody = {
|
||||
title: lang === 'zh' ? '空白智能体' : 'Blank Agent',
|
||||
dsl: {
|
||||
components: {},
|
||||
history: [],
|
||||
globals: {},
|
||||
retrieval: [],
|
||||
graph: { nodes: [], edges: [] },
|
||||
messages: [],
|
||||
},
|
||||
canvas_category: AgentCategory.AgentCanvas,
|
||||
};
|
||||
const result = await ops.createAgent(body);
|
||||
if (result.success) {
|
||||
if (onCreated) onCreated(result.id);
|
||||
}
|
||||
onClose();
|
||||
} catch (err: any) {
|
||||
console.error('create blank agent error', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
fullWidth
|
||||
maxWidth="lg"
|
||||
PaperProps={{ sx: { height: '85%' } }}
|
||||
>
|
||||
<DialogTitle>{t('agent.createAgent')}</DialogTitle>
|
||||
<DialogContent dividers sx={{ overflowY: 'auto', p: 2 }}>
|
||||
<Box display="flex" gap={2} sx={{ height: 560 }}>
|
||||
{/* 左侧分类 */}
|
||||
<Box sx={{ width: 220, borderRight: '1px solid', borderColor: 'divider', overflowY: 'auto' }}>
|
||||
<List>
|
||||
{categories.map((cat) => (
|
||||
<ListItemButton
|
||||
key={cat}
|
||||
selected={activeCategory === cat}
|
||||
onClick={() => setActiveCategory(cat)}
|
||||
ref={(el) => { categoryRefs.current[cat] = el; }}
|
||||
>
|
||||
<ListItemText
|
||||
primary={cat}
|
||||
primaryTypographyProps={{
|
||||
color: activeCategory === cat ? 'primary' : 'text.primary',
|
||||
fontWeight: activeCategory === cat ? 700 : 400,
|
||||
}}
|
||||
/>
|
||||
</ListItemButton>
|
||||
))}
|
||||
</List>
|
||||
</Box>
|
||||
|
||||
{/* 右侧模板网格 */}
|
||||
<Box flex={1} px={2} sx={{ overflowY: 'auto' }}>
|
||||
<Grid container spacing={2}>
|
||||
{activeCategory === 'Recommended' && (
|
||||
<Grid size={{ xs: 12, sm: 6, md: 4 }}>
|
||||
<Card
|
||||
variant="outlined"
|
||||
sx={{
|
||||
height: 220,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
cursor: 'pointer',
|
||||
p: 4,
|
||||
}}
|
||||
onClick={handleCreateBlankAgent}
|
||||
>
|
||||
<Box display="flex" flexDirection="column" alignItems="center" gap={1}>
|
||||
<AddIcon fontSize="large" />
|
||||
<Typography variant="subtitle1">
|
||||
{lang === 'zh' ? '新建空白智能体' : 'New Blank Agent'}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Card>
|
||||
</Grid>
|
||||
)}
|
||||
{filteredTemplates.map((tpl) => (
|
||||
<Grid key={tpl.id} size={{ xs: 12, sm: 6, md: 4 }}>
|
||||
<Card variant="outlined" sx={{ height: 220, display: 'flex', flexDirection: 'column' }}>
|
||||
<CardContent sx={{ flexGrow: 1, pb: 0 }}>
|
||||
<Box display="flex" alignItems="center" gap={2}>
|
||||
<Avatar src={tpl.avatar} />
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 1}}>
|
||||
<Typography variant="h6" className='ellipsis2'>
|
||||
{(tpl.title as any)?.[lang] || (tpl.title as any)}
|
||||
</Typography>
|
||||
<Typography
|
||||
variant="body2"
|
||||
color="text.secondary"
|
||||
className='ellipsis3'
|
||||
>
|
||||
{(tpl.description as any)?.[lang] || ''}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
</CardContent>
|
||||
<CardActions sx={{ justifyContent: 'flex-end', mt: 'auto', p: 2, pt: 1 }}>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={() => handleUseTemplate(tpl)}
|
||||
disabled={loading}
|
||||
>
|
||||
{t('agent.useTemplate')}
|
||||
</Button>
|
||||
</CardActions>
|
||||
</Card>
|
||||
</Grid>
|
||||
))}
|
||||
</Grid>
|
||||
{(!loading && filteredTemplates.length === 0) && (
|
||||
<Box sx={{ textAlign: 'center', py: 6 }}>
|
||||
<Typography color="text.secondary">{t('agent.noTemplates')}</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>{t('common.close')}</Button>
|
||||
</DialogActions>
|
||||
</Dialog >
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateAgentDialog;
|
||||
223
src/pages/agent/components/EditAgentDialog.tsx
Normal file
223
src/pages/agent/components/EditAgentDialog.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
import React, { useEffect, useMemo, useState, useRef } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogTitle,
|
||||
DialogContent,
|
||||
DialogActions,
|
||||
Button,
|
||||
Box,
|
||||
TextField,
|
||||
Avatar,
|
||||
Grid,
|
||||
IconButton,
|
||||
FormControl,
|
||||
InputLabel,
|
||||
Select,
|
||||
MenuItem,
|
||||
Typography,
|
||||
} from '@mui/material';
|
||||
import { PhotoCamera as PhotoCameraIcon, Delete as DeleteIcon } from '@mui/icons-material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { IFlow } from '@/interfaces/database/agent';
|
||||
import { useAgentOperations } from '@/hooks/agent-hooks';
|
||||
|
||||
export interface EditAgentDialogProps {
|
||||
open: boolean;
|
||||
agent: IFlow | null;
|
||||
onClose: () => void;
|
||||
onSaved?: () => void;
|
||||
}
|
||||
|
||||
const PERMISSION_OPTIONS = [
|
||||
{ value: 'me', labelKey: 'common.onlyMe' },
|
||||
{ value: 'team', labelKey: 'common.team' },
|
||||
] as const;
|
||||
|
||||
const EditAgentDialog: React.FC<EditAgentDialogProps> = ({ open, agent, onClose, onSaved }) => {
|
||||
const { t } = useTranslation();
|
||||
const ops = useAgentOperations();
|
||||
|
||||
const [title, setTitle] = useState('');
|
||||
const [avatar, setAvatar] = useState('');
|
||||
const [description, setDescription] = useState('');
|
||||
const [permission, setPermission] = useState<'me' | 'team' | 'public'>('me');
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const resizeImageToDataUrl = (file: File, maxDim = 256): Promise<string> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (e) => {
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
const canvas = document.createElement('canvas');
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return reject(new Error('Canvas not supported'));
|
||||
const scale = Math.min(1, maxDim / Math.max(img.width, img.height));
|
||||
const w = Math.max(1, Math.round(img.width * scale));
|
||||
const h = Math.max(1, Math.round(img.height * scale));
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
// prefer jpeg for smaller size, fallback to png
|
||||
const mime = file.type === 'image/png' ? 'image/png' : 'image/jpeg';
|
||||
const dataUrl = canvas.toDataURL(mime, 0.85);
|
||||
resolve(dataUrl.replace(/\s/g, ''));
|
||||
};
|
||||
img.onerror = () => reject(new Error('Invalid image'));
|
||||
img.src = e.target?.result as string;
|
||||
};
|
||||
reader.onerror = () => reject(new Error('Read failed'));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
};
|
||||
|
||||
const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = event.target.files?.[0];
|
||||
if (!file) return;
|
||||
try {
|
||||
if (!file.type.startsWith('image/')) {
|
||||
console.warn('Not an image file');
|
||||
return;
|
||||
}
|
||||
const dataUrl = await resizeImageToDataUrl(file, 256);
|
||||
setAvatar(dataUrl);
|
||||
} catch (err) {
|
||||
console.error('Avatar upload error:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAvatarDelete = () => {
|
||||
setAvatar('');
|
||||
};
|
||||
|
||||
const handleAvatarClick = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (open && agent) {
|
||||
setTitle(agent.title || '');
|
||||
setAvatar(agent.avatar || '');
|
||||
setDescription(agent.description || '');
|
||||
setPermission((agent.permission as any) || 'me');
|
||||
}
|
||||
if (!open) {
|
||||
// reset when closing to avoid stale state
|
||||
setTitle('');
|
||||
setAvatar('');
|
||||
setDescription('');
|
||||
setPermission('me');
|
||||
}
|
||||
}, [open, agent]);
|
||||
|
||||
const canSubmit = useMemo(() => {
|
||||
return Boolean(title && title.trim().length > 0 && agent?.id);
|
||||
}, [title, agent]);
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!agent?.id) return;
|
||||
const res = await ops.editAgent({
|
||||
id: agent.id,
|
||||
title: title.trim(),
|
||||
avatar: avatar || undefined,
|
||||
description: description?.trim() ? description.trim() : null,
|
||||
permission,
|
||||
canvas_category: agent.canvas_category as any,
|
||||
} as any);
|
||||
if (res.success) {
|
||||
if (onSaved) onSaved();
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onClose={onClose} fullWidth maxWidth="sm">
|
||||
<DialogTitle>{t('common.edit')}</DialogTitle>
|
||||
<DialogContent dividers>
|
||||
<Box display="flex" flexDirection="column" gap={2}>
|
||||
<Grid container spacing={2} alignItems="center">
|
||||
<Grid size={{ xs: 12 }}>
|
||||
<Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', gap: 2 }}>
|
||||
<Avatar
|
||||
src={avatar}
|
||||
sx={{ width: 96, height: 96, cursor: 'pointer' }}
|
||||
onClick={handleAvatarClick}
|
||||
>
|
||||
{!avatar && <PhotoCameraIcon sx={{ fontSize: 40 }} />}
|
||||
</Avatar>
|
||||
|
||||
<Box sx={{ display: 'flex', gap: 1 }}>
|
||||
<Button
|
||||
variant="outlined"
|
||||
size="small"
|
||||
startIcon={<PhotoCameraIcon />}
|
||||
onClick={handleAvatarClick}
|
||||
>
|
||||
{t('knowledge.uploadAvatar')}
|
||||
</Button>
|
||||
{avatar && (
|
||||
<IconButton size="small" color="error" onClick={handleAvatarDelete}>
|
||||
<DeleteIcon />
|
||||
</IconButton>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
style={{ display: 'none' }}
|
||||
onChange={handleAvatarUpload}
|
||||
/>
|
||||
</Box>
|
||||
</Grid>
|
||||
</Grid>
|
||||
|
||||
<TextField
|
||||
label={t('agent.forms.title')}
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
fullWidth
|
||||
required
|
||||
/>
|
||||
|
||||
<TextField
|
||||
label={t('agent.forms.description')}
|
||||
value={description}
|
||||
onChange={(e) => setDescription(e.target.value)}
|
||||
fullWidth
|
||||
multiline
|
||||
minRows={3}
|
||||
/>
|
||||
|
||||
<FormControl fullWidth>
|
||||
<InputLabel>{t('agent.forms.permissionSettings')}</InputLabel>
|
||||
<Select
|
||||
value={permission}
|
||||
label={t('agent.forms.permissionSettings')}
|
||||
onChange={(e) => setPermission(e.target.value as any)}
|
||||
>
|
||||
{PERMISSION_OPTIONS.map((opt) => (
|
||||
<MenuItem key={opt.value} value={opt.value}>
|
||||
{t(opt.labelKey)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={onClose}>{t('dialog.cancel')}</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={handleSave}
|
||||
disabled={!canSubmit || ops.loading}
|
||||
>
|
||||
{t('common.confirm')}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditAgentDialog;
|
||||
0
src/pages/agent/detail.tsx
Normal file
0
src/pages/agent/detail.tsx
Normal file
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useMemo, useState } from 'react';
|
||||
import React, { useCallback, useMemo, useState, useEffect } from 'react';
|
||||
import {
|
||||
Box,
|
||||
Typography,
|
||||
@@ -9,12 +9,19 @@ import {
|
||||
Pagination,
|
||||
Stack,
|
||||
} from '@mui/material';
|
||||
import { Search as SearchIcon, Refresh as RefreshIcon } from '@mui/icons-material';
|
||||
import { useAgentList } from '@/hooks/agent-hooks';
|
||||
import { Search as SearchIcon, Refresh as RefreshIcon, Add as AddIcon } from '@mui/icons-material';
|
||||
import { useAgentList, useAgentOperations } from '@/hooks/agent-hooks';
|
||||
import AgentGridView from '@/components/agent/AgentGridView';
|
||||
import CreateAgentDialog from '@/pages/agent/components/CreateAgentDialog';
|
||||
import EditAgentDialog from '@/pages/agent/components/EditAgentDialog';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDialog } from '@/hooks/useDialog';
|
||||
|
||||
function AgentListPage() {
|
||||
const [searchValue, setSearchValue] = useState('');
|
||||
const [createOpen, setCreateOpen] = useState(false);
|
||||
const [editOpen, setEditOpen] = useState(false);
|
||||
const [editTarget, setEditTarget] = useState<any>(null);
|
||||
const {
|
||||
agents,
|
||||
total,
|
||||
@@ -26,6 +33,10 @@ function AgentListPage() {
|
||||
refresh,
|
||||
} = useAgentList({ page: 1, page_size: 10 });
|
||||
|
||||
const { t } = useTranslation();
|
||||
const dialog = useDialog();
|
||||
const ops = useAgentOperations();
|
||||
|
||||
const totalPages = useMemo(() => {
|
||||
return Math.ceil((agents?.length || 0) / pageSize) || 1;
|
||||
}, [agents, pageSize]);
|
||||
@@ -36,20 +47,42 @@ function AgentListPage() {
|
||||
return (agents || []).slice(startIndex, endIndex);
|
||||
}, [agents, currentPage, pageSize]);
|
||||
|
||||
const handleSearch = useCallback(() => {
|
||||
setKeywords(searchValue);
|
||||
setCurrentPage(1);
|
||||
const handleSearch = useCallback((value: string) => {
|
||||
// 仅更新输入值,实际搜索在 500ms 防抖后触发
|
||||
setSearchValue(value);
|
||||
}, []);
|
||||
|
||||
// 500ms 防抖:在用户停止输入 500ms 后触发搜索
|
||||
useEffect(() => {
|
||||
const handler = setTimeout(() => {
|
||||
setKeywords(searchValue);
|
||||
setCurrentPage(1);
|
||||
}, 500);
|
||||
return () => clearTimeout(handler);
|
||||
}, [searchValue, setKeywords, setCurrentPage]);
|
||||
|
||||
return (
|
||||
<Box sx={{ p: 3 }}>
|
||||
<Typography variant="h4" fontWeight={600} mb={2}>Agent 列表</Typography>
|
||||
{/* 页面标题 */}
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
|
||||
<Typography variant="h4" fontWeight={600}>
|
||||
{t('agent.agentList')}
|
||||
</Typography>
|
||||
<Button
|
||||
variant="contained"
|
||||
startIcon={<AddIcon />}
|
||||
onClick={() => setCreateOpen(true)}
|
||||
sx={{ borderRadius: 2 }}
|
||||
>
|
||||
{t('agent.createAgent')}
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Paper sx={{ p: 2, mb: 2 }}>
|
||||
<Box display="flex" gap={2} alignItems="center">
|
||||
<TextField
|
||||
value={searchValue}
|
||||
onChange={(e) => setSearchValue(e.target.value)}
|
||||
onChange={(e) => handleSearch(e.target.value)}
|
||||
placeholder="搜索名称或描述"
|
||||
size="small"
|
||||
InputProps={{
|
||||
@@ -60,7 +93,6 @@ function AgentListPage() {
|
||||
)
|
||||
}}
|
||||
/>
|
||||
<Button variant="contained" onClick={handleSearch}>搜索</Button>
|
||||
<Button variant="outlined" startIcon={<RefreshIcon />} onClick={refresh}>刷新</Button>
|
||||
</Box>
|
||||
</Paper>
|
||||
@@ -69,6 +101,19 @@ function AgentListPage() {
|
||||
agents={currentPageData}
|
||||
loading={loading}
|
||||
searchTerm={searchValue}
|
||||
onCreateAgent={() => setCreateOpen(true)}
|
||||
onEdit={(agent) => { setEditTarget(agent); setEditOpen(true); }}
|
||||
onDelete={async (agent) => {
|
||||
const confirmed = await dialog.confirm({
|
||||
title: t('dialog.confirmDelete'),
|
||||
content: t('dialog.confirmDeleteMessage'),
|
||||
confirmText: t('dialog.delete'),
|
||||
cancelText: t('dialog.cancel'),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
const res = await ops.deleteAgents([agent.id]);
|
||||
if (res.success) refresh();
|
||||
}}
|
||||
/>
|
||||
|
||||
{totalPages >= 1 && (
|
||||
@@ -89,6 +134,20 @@ function AgentListPage() {
|
||||
</Stack>
|
||||
</Box>
|
||||
)}
|
||||
<CreateAgentDialog
|
||||
open={createOpen}
|
||||
onClose={() => setCreateOpen(false)}
|
||||
onCreated={() => {
|
||||
setCreateOpen(false);
|
||||
refresh();
|
||||
}}
|
||||
/>
|
||||
<EditAgentDialog
|
||||
open={editOpen}
|
||||
agent={editTarget}
|
||||
onClose={() => { setEditOpen(false); setEditTarget(null); }}
|
||||
onSaved={() => { setEditOpen(false); setEditTarget(null); refresh(); }}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import api from './api';
|
||||
import request from '@/utils/request';
|
||||
import type { IAgentPaginationParams } from '@/interfaces/request/agent';
|
||||
import type {
|
||||
IAgentCreateRequestBody, IAgentPaginationParams,
|
||||
IAgentSetDSLRequestBody, IAgentSettingRequestBody
|
||||
} from '@/interfaces/request/agent';
|
||||
|
||||
/**
|
||||
* 智能体服务
|
||||
@@ -12,8 +15,67 @@ const agentService = {
|
||||
listCanvas: (params?: IAgentPaginationParams) => {
|
||||
return request.get(api.listTeamCanvas, { params });
|
||||
},
|
||||
/**
|
||||
* 获取系统模板列表
|
||||
*/
|
||||
listTemplates: () => {
|
||||
return request.get(api.listTemplates);
|
||||
},
|
||||
/**
|
||||
* 新建或更新 Canvas(Agent/Dataflow)
|
||||
*/
|
||||
setCanvas: (body: IAgentCreateRequestBody) => {
|
||||
return request.post(api.setCanvas, body);
|
||||
},
|
||||
/**
|
||||
* 获取智能体详情
|
||||
* @param canvas_id Canvas ID
|
||||
*/
|
||||
getCanvas: (canvas_id: string) => {
|
||||
return request.get(`${api.getCanvas}/${canvas_id}`);
|
||||
},
|
||||
/**
|
||||
* 获取智能体实时运行状态
|
||||
* @param canvas_id Canvas ID
|
||||
*/
|
||||
getCanvasSSE: (canvas_id: string) => {
|
||||
return request.get(`${api.getCanvasSSE}/${canvas_id}`);
|
||||
},
|
||||
/**
|
||||
* 删除 Canvas(Agent/Dataflow)
|
||||
* @param canvas_ids ID列表
|
||||
*/
|
||||
removeCanvas: (canvas_ids: string[]) => {
|
||||
return request.post(api.removeCanvas, { canvas_ids });
|
||||
},
|
||||
|
||||
/**
|
||||
* 获取 Canvas 设置
|
||||
*/
|
||||
settingAgent: (data: Partial<IAgentSettingRequestBody>) => {
|
||||
return request.post(api.settingCanvas, data);
|
||||
},
|
||||
/**
|
||||
* 设置智能体DSL
|
||||
*/
|
||||
setAgentDSL: (data: Partial<IAgentSetDSLRequestBody>) => {
|
||||
return request.post(api.setCanvas, data);
|
||||
},
|
||||
/**
|
||||
* 获取智能体版本详情
|
||||
* @param version_id 版本ID
|
||||
*/
|
||||
getVersion: (version_id: string) => {
|
||||
return request.get(`${api.getVersion}/${version_id}`);
|
||||
},
|
||||
/**
|
||||
* 获取智能体版本列表
|
||||
* @param canvas_id Canvas ID
|
||||
*/
|
||||
getAgentVersionList: (canvas_id: string) => {
|
||||
return request.get(`${api.getListVersion}/${canvas_id}`);
|
||||
},
|
||||
|
||||
|
||||
};
|
||||
|
||||
export default agentService;
|
||||
@@ -160,6 +160,54 @@ export const theme = createTheme({
|
||||
},
|
||||
},
|
||||
},
|
||||
MuiTypography: {
|
||||
styleOverrides: {
|
||||
root: {
|
||||
variants: [
|
||||
{
|
||||
props: { className: 'ellipsis1' },
|
||||
style: {
|
||||
lineClamp: 1,
|
||||
WebkitLineClamp: 1,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
display: '-webkit-box',
|
||||
overflow: 'hidden',
|
||||
},
|
||||
},
|
||||
{
|
||||
props: { className: 'ellipsis2' },
|
||||
style: {
|
||||
lineClamp: 2,
|
||||
WebkitLineClamp: 2,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
display: '-webkit-box',
|
||||
overflow: 'hidden',
|
||||
},
|
||||
},
|
||||
{
|
||||
props: { className: 'ellipsis3' },
|
||||
style: {
|
||||
lineClamp: 3,
|
||||
WebkitLineClamp: 3,
|
||||
WebkitBoxOrient: 'vertical',
|
||||
display: '-webkit-box',
|
||||
overflow: 'hidden',
|
||||
},
|
||||
},
|
||||
{
|
||||
props: { className: 'no-ellipsis' },
|
||||
style: {
|
||||
lineClamp: 'unset',
|
||||
WebkitLineClamp: 'unset',
|
||||
WebkitBoxOrient: 'unset',
|
||||
display: 'unset',
|
||||
overflow: 'unset',
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
xGridEnUS,
|
||||
|
||||
Reference in New Issue
Block a user