feat(agent): 接入Agent调试与RAG召回链路

This commit is contained in:
2026-05-31 23:51:55 +08:00
parent 21c9eaa44d
commit 1e004f1a83
29 changed files with 1859 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
chatWithAgent,
deleteAgent,
getAgentById,
listAgents,
queryAgents,
saveAgent,
} from '../agent';
import { get, post } from '../request';
vi.mock('../request', () => ({
get: vi.fn(),
post: vi.fn(),
}));
describe('agent api', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('maps agent endpoints correctly', () => {
listAgents();
queryAgents({ agentCode: 'demo' });
getAgentById('1001');
saveAgent({ agentCode: 'agent_1', agentName: 'Agent 1', storeId: '2001', status: 'ENABLED' });
deleteAgent('1001');
chatWithAgent('1001', { messages: [{ role: 'user', content: '你好' }] });
expect(post).toHaveBeenCalledWith('/agents/list');
expect(post).toHaveBeenCalledWith('/agents/query', { agentCode: 'demo' });
expect(get).toHaveBeenCalledWith('/agents/detail', { params: { id: '1001' } });
expect(post).toHaveBeenCalledWith('/agents/save', {
agentCode: 'agent_1',
agentName: 'Agent 1',
storeId: '2001',
status: 'ENABLED',
});
expect(post).toHaveBeenCalledWith('/agents/delete', undefined, { params: { id: '1001' } });
expect(post).toHaveBeenCalledWith('/agents/1001/chat', { messages: [{ role: 'user', content: '你好' }] });
});
});

70
frontend/src/api/agent.ts Normal file
View File

@@ -0,0 +1,70 @@
import { get, post } from './request';
export interface AgentDefinition {
id?: string;
agentCode: string;
agentName: string;
systemPrompt?: string;
storeId: string;
status: string;
remark?: string;
}
export interface AgentDefinitionQueryRequest {
agentCode?: string;
agentName?: string;
status?: string;
storeId?: string;
}
export interface AgentMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
export interface AgentChatRequest {
messages: AgentMessage[];
ragEnabled?: boolean;
}
export interface AgentReferenceChunk {
chunkId: string;
documentId: string;
chunkContent: string;
score?: number;
}
export interface AgentChatResponse {
agentId: string;
agentCode: string;
agentName: string;
storeId: string;
storeName?: string;
answer: string;
modelRequestId: string;
references: AgentReferenceChunk[];
}
export function listAgents() {
return post<AgentDefinition[]>('/agents/list');
}
export function queryAgents(query?: AgentDefinitionQueryRequest) {
return post<AgentDefinition[], AgentDefinitionQueryRequest | undefined>('/agents/query', query);
}
export function getAgentById(id: string) {
return get<AgentDefinition>('/agents/detail', { params: { id } });
}
export function saveAgent(data: Partial<AgentDefinition> & { id?: string }) {
return post<boolean>('/agents/save', data);
}
export function deleteAgent(id: string) {
return post<boolean>('/agents/delete', undefined, { params: { id } });
}
export function chatWithAgent(agentId: string, data: AgentChatRequest) {
return post<AgentChatResponse, AgentChatRequest>(`/agents/${agentId}/chat`, data);
}

View File

@@ -0,0 +1,270 @@
<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { computed, onMounted, ref } from 'vue';
import { chatWithAgent, listAgents, type AgentDefinition, type AgentMessage, type AgentReferenceChunk } from '@/api/agent';
interface ChatBubble {
id: string;
role: 'user' | 'assistant';
content: string;
references?: AgentReferenceChunk[];
requestId?: string;
}
const loading = ref(false);
const sending = ref(false);
const agents = ref<AgentDefinition[]>([]);
const selectedAgentId = ref('');
const inputText = ref('');
const messages = ref<ChatBubble[]>([]);
const ragEnabled = ref(true);
const selectedAgent = computed(() => agents.value.find((agent) => agent.id === selectedAgentId.value));
async function loadAgents() {
loading.value = true;
try {
const response = await listAgents();
agents.value = (response.data ?? []).filter((item) => item.status === 'ENABLED');
if (!selectedAgentId.value && agents.value.length > 0) {
const firstAgent = agents.value[0];
selectedAgentId.value = firstAgent && firstAgent.id ? firstAgent.id : '';
}
} finally {
loading.value = false;
}
}
function buildRequestMessages(nextUserText: string): AgentMessage[] {
const historyMessages: AgentMessage[] = messages.value.map((message) => ({
role: message.role,
content: message.content,
}));
historyMessages.push({ role: 'user', content: nextUserText });
return historyMessages;
}
async function sendMessage() {
const trimmed = inputText.value.trim();
if (!selectedAgentId.value) {
ElMessage.warning('请先选择Agent');
return;
}
if (!trimmed) {
return;
}
const requestMessages = buildRequestMessages(trimmed);
const userBubble: ChatBubble = {
id: `${Date.now()}_u`,
role: 'user',
content: trimmed,
};
messages.value.push(userBubble);
inputText.value = '';
sending.value = true;
try {
const response = await chatWithAgent(selectedAgentId.value, {
messages: requestMessages,
ragEnabled: ragEnabled.value,
});
const result = response.data;
messages.value.push({
id: `${Date.now()}_a`,
role: 'assistant',
content: result?.answer ?? '',
references: result?.references ?? [],
requestId: result?.modelRequestId,
});
} finally {
sending.value = false;
}
}
function clearChat() {
messages.value = [];
}
onMounted(loadAgents);
</script>
<template>
<section class="page-panel agent-debug">
<div class="page-panel__header">
<h2>Agent 调试</h2>
<span>Chat Debugger</span>
</div>
<div class="debug-toolbar">
<el-select v-model="selectedAgentId" class="debug-toolbar__agent" :loading="loading" placeholder="请选择Agent">
<el-option
v-for="item in agents"
:key="item.id"
:label="`${item.agentName}(${item.agentCode})`"
:value="item.id"
/>
</el-select>
<el-switch v-model="ragEnabled" active-text="RAG对话" inactive-text="普通对话" />
<el-button @click="loadAgents">刷新Agent</el-button>
<el-button @click="clearChat">清空会话</el-button>
</div>
<div class="debug-chat">
<div v-for="bubble in messages" :key="bubble.id" class="chat-row" :class="`chat-row--${bubble.role}`">
<div class="chat-bubble">
<div class="chat-bubble__role">{{ bubble.role === 'user' ? '用户' : '助手' }}</div>
<div class="chat-bubble__content">{{ bubble.content }}</div>
<template v-if="bubble.role === 'assistant'">
<div v-if="bubble.references?.length" class="chat-bubble__refs">
<div class="chat-bubble__refs-title">引用切片</div>
<ul>
<li v-for="reference in bubble.references" :key="reference.chunkId">
<span class="ref-meta">#{{ reference.chunkId }} · 相似度 {{ (reference.score ?? 0).toFixed(4) }}</span>
<span>{{ reference.chunkContent }}</span>
</li>
</ul>
</div>
<div v-if="bubble.requestId" class="chat-bubble__request-id">requestId: {{ bubble.requestId }}</div>
</template>
</div>
</div>
<div v-if="messages.length === 0" class="chat-empty">
选择Agent后输入问题发起对话调试
</div>
</div>
<div class="debug-input">
<el-input
v-model="inputText"
type="textarea"
:rows="3"
resize="none"
:disabled="sending || !selectedAgent"
placeholder="输入问题回车发送Shift+Enter换行"
@keydown.enter.exact.prevent="sendMessage"
/>
<el-button type="primary" :loading="sending" :disabled="!selectedAgent" @click="sendMessage">发送</el-button>
</div>
</section>
</template>
<style scoped>
.agent-debug {
display: flex;
flex-direction: column;
}
.debug-toolbar {
display: flex;
gap: 10px;
padding: 16px 22px 12px;
}
.debug-toolbar__agent {
width: 320px;
}
.debug-chat {
flex: 1;
min-height: 420px;
max-height: 58vh;
padding: 12px 22px;
overflow-y: auto;
border-top: 1px solid var(--app-border-soft);
border-bottom: 1px solid var(--app-border-soft);
background: #fafcff;
}
.chat-row {
display: flex;
margin-bottom: 14px;
}
.chat-row--user {
justify-content: flex-end;
}
.chat-row--assistant {
justify-content: flex-start;
}
.chat-bubble {
width: min(80%, 860px);
padding: 12px;
border-radius: 8px;
border: 1px solid var(--app-border);
background: #ffffff;
}
.chat-row--user .chat-bubble {
background: #eef5ff;
border-color: #d3e5ff;
}
.chat-bubble__role {
margin-bottom: 6px;
color: var(--app-text-muted);
font-size: 12px;
font-weight: 600;
}
.chat-bubble__content {
white-space: pre-wrap;
line-height: 1.6;
}
.chat-bubble__refs {
margin-top: 12px;
padding: 10px;
border-radius: 8px;
background: #f8fafc;
}
.chat-bubble__refs-title {
margin-bottom: 8px;
color: #344054;
font-size: 12px;
font-weight: 600;
}
.chat-bubble__refs ul {
margin: 0;
padding-left: 16px;
}
.chat-bubble__refs li {
margin-bottom: 8px;
display: flex;
flex-direction: column;
gap: 4px;
}
.ref-meta {
color: var(--app-text-muted);
font-size: 12px;
}
.chat-bubble__request-id {
margin-top: 8px;
color: var(--app-text-muted);
font-size: 12px;
}
.chat-empty {
color: var(--app-text-muted);
text-align: center;
padding: 36px 0;
}
.debug-input {
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px 22px 18px;
}
.debug-input .el-button {
align-self: flex-end;
}
</style>

View File

@@ -0,0 +1,195 @@
<script setup lang="ts">
import { Delete, Edit, Plus, RefreshRight } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { computed, onMounted, reactive, ref } from 'vue';
import { deleteAgent, queryAgents, saveAgent, type AgentDefinition } from '@/api/agent';
import { listRagStores, type RagStore } from '@/api/ragStores';
const loading = ref(false);
const saving = ref(false);
const dialogVisible = ref(false);
const agents = ref<AgentDefinition[]>([]);
const stores = ref<RagStore[]>([]);
const statusOptions = [
{ label: '启用', value: 'ENABLED' },
{ label: '禁用', value: 'DISABLED' },
];
const editForm = reactive<AgentDefinition>({
agentCode: '',
agentName: '',
systemPrompt: '',
storeId: '',
status: 'ENABLED',
remark: '',
});
const dialogTitle = computed(() => (editForm.id ? '编辑Agent' : '新增Agent'));
function resetForm(row?: AgentDefinition) {
editForm.id = row?.id;
editForm.agentCode = row?.agentCode ?? '';
editForm.agentName = row?.agentName ?? '';
editForm.systemPrompt = row?.systemPrompt ?? '';
editForm.storeId = row?.storeId ?? stores.value[0]?.id ?? '';
editForm.status = row?.status ?? 'ENABLED';
editForm.remark = row?.remark ?? '';
}
async function loadStores() {
const response = await listRagStores();
stores.value = response.data ?? [];
}
async function loadAgents() {
loading.value = true;
try {
const response = await queryAgents();
agents.value = response.data ?? [];
} finally {
loading.value = false;
}
}
function openCreateDialog() {
resetForm();
dialogVisible.value = true;
}
function openEditDialog(row: AgentDefinition) {
resetForm(row);
dialogVisible.value = true;
}
async function submitAgent() {
if (!editForm.agentCode || !editForm.agentName || !editForm.storeId) {
ElMessage.warning('请填写Agent编码、名称和绑定知识库');
return;
}
saving.value = true;
try {
await saveAgent({ ...editForm });
ElMessage.success('保存成功');
dialogVisible.value = false;
await loadAgents();
} finally {
saving.value = false;
}
}
async function removeAgent(row: AgentDefinition) {
if (!row.id) {
return;
}
await ElMessageBox.confirm(`确认删除Agent「${row.agentName || row.agentCode}」?`, '删除确认', {
type: 'warning',
confirmButtonText: '删除',
cancelButtonText: '取消',
});
await deleteAgent(row.id);
ElMessage.success('已删除');
await loadAgents();
}
function storeLabel(storeId?: string) {
const store = stores.value.find((item) => item.id === storeId);
return store?.storeName ?? store?.storeCode ?? storeId ?? '-';
}
onMounted(async () => {
await loadStores();
resetForm();
await loadAgents();
});
</script>
<template>
<section class="page-panel">
<div class="page-panel__header">
<h2>Agent 管理</h2>
<span>Agent Config</span>
</div>
<div class="toolbar">
<div class="toolbar__actions">
<el-button :icon="RefreshRight" @click="loadAgents">刷新</el-button>
<el-button type="primary" :icon="Plus" @click="openCreateDialog">新增Agent</el-button>
</div>
</div>
<el-table v-loading="loading" :data="agents" row-key="id">
<el-table-column prop="agentCode" label="Agent编码" min-width="140" />
<el-table-column prop="agentName" label="Agent名称" min-width="140" />
<el-table-column label="知识库" min-width="140">
<template #default="{ row }">{{ storeLabel(row.storeId) }}</template>
</el-table-column>
<el-table-column prop="status" label="状态" width="100">
<template #default="{ row }">
<el-tag :type="row.status === 'ENABLED' ? 'success' : 'info'">
{{ row.status === 'ENABLED' ? '启用' : '禁用' }}
</el-tag>
</template>
</el-table-column>
<el-table-column prop="systemPrompt" label="系统提示词" min-width="220" show-overflow-tooltip />
<el-table-column label="操作" width="160" fixed="right">
<template #default="{ row }">
<el-button link type="primary" :icon="Edit" @click="openEditDialog(row)">编辑</el-button>
<el-button link type="danger" :icon="Delete" @click="removeAgent(row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog v-model="dialogVisible" :title="dialogTitle" width="720px">
<el-form :model="editForm" label-width="120px">
<el-form-item label="Agent编码" required>
<el-input v-model="editForm.agentCode" placeholder="如 AGENT_RAG_HELPER" />
</el-form-item>
<el-form-item label="Agent名称" required>
<el-input v-model="editForm.agentName" placeholder="如 知识问答助手" />
</el-form-item>
<el-form-item label="绑定知识库" required>
<el-select v-model="editForm.storeId">
<el-option
v-for="store in stores"
:key="store.id"
:label="`${store.storeName}(${store.storeCode})`"
:value="store.id"
/>
</el-select>
</el-form-item>
<el-form-item label="系统提示词">
<el-input v-model="editForm.systemPrompt" type="textarea" :rows="4" />
</el-form-item>
<el-form-item label="状态">
<el-radio-group v-model="editForm.status">
<el-radio-button v-for="item in statusOptions" :key="item.value" :value="item.value">
{{ item.label }}
</el-radio-button>
</el-radio-group>
</el-form-item>
<el-form-item label="备注">
<el-input v-model="editForm.remark" type="textarea" :rows="2" />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" :loading="saving" @click="submitAgent">保存</el-button>
</template>
</el-dialog>
</section>
</template>
<style scoped>
.toolbar {
display: flex;
justify-content: flex-end;
padding: 16px 22px;
}
.toolbar__actions {
display: flex;
gap: 8px;
}
</style>