feat: Implement manual knowledge editing and enhance knowledge base features
- Added functionality for manual knowledge entry, allowing users to create and edit Markdown content directly in the browser. - Introduced new API endpoints for creating and updating manual knowledge entries. - Enhanced UI components to support the new manual knowledge editor, including integration with existing knowledge base features. - Updated knowledge retrieval logic to accommodate manual entries, ensuring seamless user experience across knowledge types. - Improved agent configuration to support custom system prompts, enhancing flexibility in agent responses.
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import ManualKnowledgeEditor from '@/components/manual-knowledge-editor.vue'
|
||||
</script>
|
||||
<template>
|
||||
<div id="app">
|
||||
<RouterView />
|
||||
<ManualKnowledgeEditor />
|
||||
</div>
|
||||
</template>
|
||||
<style>
|
||||
|
||||
@@ -41,6 +41,10 @@ export function uploadKnowledgeFile(kbId: string, data = {}) {
|
||||
return postUpload(`/api/v1/knowledge-bases/${kbId}/knowledge/file`, data);
|
||||
}
|
||||
|
||||
export function createManualKnowledge(kbId: string, data: { title: string; content: string; status: string }) {
|
||||
return post(`/api/v1/knowledge-bases/${kbId}/knowledge/manual`, data);
|
||||
}
|
||||
|
||||
export function listKnowledgeFiles(kbId: string, { page, page_size }: { page: number; page_size: number }) {
|
||||
return get(`/api/v1/knowledge-bases/${kbId}/knowledge?page=${page}&page_size=${page_size}`);
|
||||
}
|
||||
@@ -49,6 +53,10 @@ export function getKnowledgeDetails(id: string) {
|
||||
return get(`/api/v1/knowledge/${id}`);
|
||||
}
|
||||
|
||||
export function updateManualKnowledge(id: string, data: { title: string; content: string; status: string }) {
|
||||
return put(`/api/v1/knowledge/manual/${id}`, data);
|
||||
}
|
||||
|
||||
export function delKnowledgeDetails(id: string) {
|
||||
return del(`/api/v1/knowledge/${id}`);
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@ export interface AgentConfig {
|
||||
rerank_model_id: string
|
||||
knowledge_bases?: string[]
|
||||
system_prompt?: string // System prompt template with placeholders (optional)
|
||||
use_custom_system_prompt?: boolean
|
||||
available_tools?: ToolDefinition[] // GET 响应中包含,POST/PUT 不需要
|
||||
available_placeholders?: PlaceholderDefinition[] // GET 响应中包含,POST/PUT 不需要
|
||||
}
|
||||
|
||||
@@ -0,0 +1,964 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, reactive, computed, watch, nextTick, onBeforeUnmount } from 'vue'
|
||||
import { marked } from 'marked'
|
||||
import { MessagePlugin } from 'tdesign-vue-next'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
import { listKnowledgeBases, getKnowledgeDetails, createManualKnowledge, updateManualKnowledge } from '@/api/knowledge-base'
|
||||
import { sanitizeHTML, safeMarkdownToHTML } from '@/utils/security'
|
||||
|
||||
interface KnowledgeBaseOption {
|
||||
label: string
|
||||
value: string
|
||||
}
|
||||
|
||||
interface KnowledgeDetailResponse {
|
||||
id: string
|
||||
knowledge_base_id: string
|
||||
title?: string
|
||||
file_name?: string
|
||||
metadata?: any
|
||||
parse_status?: string
|
||||
}
|
||||
|
||||
type ManualStatus = 'draft' | 'publish'
|
||||
|
||||
const uiStore = useUIStore()
|
||||
|
||||
const visible = computed({
|
||||
get: () => uiStore.manualEditorVisible,
|
||||
set: (val: boolean) => {
|
||||
if (!val) {
|
||||
handleClose()
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
const mode = computed(() => uiStore.manualEditorMode)
|
||||
const knowledgeId = computed(() => uiStore.manualEditorKnowledgeId)
|
||||
|
||||
const form = reactive({
|
||||
kbId: '' as string,
|
||||
title: '',
|
||||
content: '',
|
||||
status: 'draft' as ManualStatus,
|
||||
})
|
||||
|
||||
const initialLoaded = ref(false)
|
||||
const kbOptions = ref<KnowledgeBaseOption[]>([])
|
||||
const kbLoading = ref(false)
|
||||
const contentLoading = ref(false)
|
||||
const saving = ref(false)
|
||||
const savingAction = ref<ManualStatus>('draft')
|
||||
const activeTab = ref<'edit' | 'preview'>('edit')
|
||||
const lastUpdatedAt = ref<string>('')
|
||||
|
||||
const textareaComponent = ref<any>(null)
|
||||
const textareaElement = ref<HTMLTextAreaElement | null>(null)
|
||||
const selectionRange = reactive({ start: 0, end: 0 })
|
||||
const selectionEvents = ['select', 'keyup', 'click', 'mouseup', 'input']
|
||||
|
||||
const resolveTextareaElement = (): HTMLTextAreaElement | null => {
|
||||
const component = textareaComponent.value as any
|
||||
if (!component) return null
|
||||
if (component.textareaRef) {
|
||||
return component.textareaRef as HTMLTextAreaElement
|
||||
}
|
||||
if (component.$el) {
|
||||
const el = component.$el.querySelector('textarea')
|
||||
if (el) {
|
||||
return el as HTMLTextAreaElement
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const handleTextareaSelectionEvent = () => {
|
||||
const textarea = textareaElement.value ?? resolveTextareaElement()
|
||||
if (!textarea) {
|
||||
return
|
||||
}
|
||||
selectionRange.start = textarea.selectionStart ?? 0
|
||||
selectionRange.end = textarea.selectionEnd ?? 0
|
||||
}
|
||||
|
||||
const detachTextareaListeners = () => {
|
||||
if (!textareaElement.value) {
|
||||
return
|
||||
}
|
||||
selectionEvents.forEach((eventName) => {
|
||||
textareaElement.value?.removeEventListener(eventName, handleTextareaSelectionEvent)
|
||||
})
|
||||
textareaElement.value = null
|
||||
}
|
||||
|
||||
const attachTextareaListeners = () => {
|
||||
nextTick(() => {
|
||||
const textarea = resolveTextareaElement()
|
||||
if (!textarea) {
|
||||
return
|
||||
}
|
||||
if (textareaElement.value === textarea) {
|
||||
return
|
||||
}
|
||||
detachTextareaListeners()
|
||||
textareaElement.value = textarea
|
||||
selectionEvents.forEach((eventName) => {
|
||||
textarea.addEventListener(eventName, handleTextareaSelectionEvent)
|
||||
})
|
||||
handleTextareaSelectionEvent()
|
||||
})
|
||||
}
|
||||
|
||||
const setSelectionRange = (start: number, end: number) => {
|
||||
selectionRange.start = start
|
||||
selectionRange.end = end
|
||||
nextTick(() => {
|
||||
const textarea = resolveTextareaElement()
|
||||
if (!textarea || activeTab.value !== 'edit') {
|
||||
return
|
||||
}
|
||||
textarea.focus()
|
||||
textarea.setSelectionRange(start, end)
|
||||
})
|
||||
}
|
||||
|
||||
const getSelectionRange = () => {
|
||||
return {
|
||||
start: selectionRange.start ?? 0,
|
||||
end: selectionRange.end ?? 0,
|
||||
}
|
||||
}
|
||||
|
||||
const clampRange = (start: number, end: number, length: number) => {
|
||||
let safeStart = Math.max(0, Math.min(start, length))
|
||||
let safeEnd = Math.max(0, Math.min(end, length))
|
||||
if (safeEnd < safeStart) {
|
||||
;[safeStart, safeEnd] = [safeEnd, safeStart]
|
||||
}
|
||||
return { safeStart, safeEnd }
|
||||
}
|
||||
|
||||
const updateContentWithSelection = (content: string, start: number, end: number) => {
|
||||
form.content = content
|
||||
setSelectionRange(start, end)
|
||||
}
|
||||
|
||||
const findLineStart = (value: string, index: number) => {
|
||||
if (index <= 0) return 0
|
||||
const lastNewline = value.lastIndexOf('\n', index - 1)
|
||||
return lastNewline === -1 ? 0 : lastNewline + 1
|
||||
}
|
||||
|
||||
const findLineEnd = (value: string, index: number) => {
|
||||
if (index >= value.length) return value.length
|
||||
const newlineIndex = value.indexOf('\n', index)
|
||||
return newlineIndex === -1 ? value.length : newlineIndex
|
||||
}
|
||||
|
||||
const transformSelectedLines = (transformer: (line: string, index: number) => string) => {
|
||||
const value = form.content ?? ''
|
||||
const { start, end } = getSelectionRange()
|
||||
const { safeStart, safeEnd } = clampRange(start, end, value.length)
|
||||
const lineStart = findLineStart(value, safeStart)
|
||||
const lineEnd = findLineEnd(value, safeEnd)
|
||||
const selected = value.slice(lineStart, lineEnd)
|
||||
const lines = selected.split('\n')
|
||||
const transformed = lines.map((line, index) => transformer(line, index))
|
||||
const result = transformed.join('\n')
|
||||
const newContent = value.slice(0, lineStart) + result + value.slice(lineEnd)
|
||||
updateContentWithSelection(newContent, lineStart, lineStart + result.length)
|
||||
}
|
||||
|
||||
const wrapSelection = (prefix: string, suffix: string, placeholder: string) => {
|
||||
const value = form.content ?? ''
|
||||
const { start, end } = getSelectionRange()
|
||||
const { safeStart, safeEnd } = clampRange(start, end, value.length)
|
||||
const hasSelection = safeEnd > safeStart
|
||||
const selectedText = hasSelection ? value.slice(safeStart, safeEnd) : placeholder
|
||||
const result =
|
||||
value.slice(0, safeStart) + prefix + selectedText + suffix + value.slice(safeEnd)
|
||||
const selectionStart = safeStart + prefix.length
|
||||
const selectionEnd = selectionStart + selectedText.length
|
||||
updateContentWithSelection(result, selectionStart, selectionEnd)
|
||||
}
|
||||
|
||||
const insertBlock = (
|
||||
text: string,
|
||||
selectionStartOffset?: number,
|
||||
selectionEndOffset?: number,
|
||||
) => {
|
||||
const value = form.content ?? ''
|
||||
const { start, end } = getSelectionRange()
|
||||
const { safeStart, safeEnd } = clampRange(start, end, value.length)
|
||||
const before = value.slice(0, safeStart)
|
||||
const after = value.slice(safeEnd)
|
||||
const result = before + text + after
|
||||
const base = safeStart
|
||||
const selectionStart =
|
||||
selectionStartOffset !== undefined ? base + selectionStartOffset : base + text.length
|
||||
const selectionEnd =
|
||||
selectionEndOffset !== undefined ? base + selectionEndOffset : selectionStart
|
||||
updateContentWithSelection(result, selectionStart, selectionEnd)
|
||||
}
|
||||
|
||||
const applyHeading = (level: number) => {
|
||||
const hashes = '#'.repeat(level)
|
||||
transformSelectedLines((line) => {
|
||||
const trimmed = line.replace(/^#+\s*/, '').trim()
|
||||
const content = trimmed || `标题${level}`
|
||||
return `${hashes} ${content}`
|
||||
})
|
||||
}
|
||||
|
||||
const listPrefixPattern =
|
||||
/^(\s*(?:[-*+]|\d+\.)\s+|\s*-\s+\[[ xX]\]\s+)/
|
||||
|
||||
const applyBulletList = () => {
|
||||
transformSelectedLines((line) => {
|
||||
const trimmed = line.trim()
|
||||
const content = trimmed.replace(listPrefixPattern, '').trim()
|
||||
return `- ${content || '列表项'}`
|
||||
})
|
||||
}
|
||||
|
||||
const applyOrderedList = () => {
|
||||
transformSelectedLines((line, index) => {
|
||||
const trimmed = line.trim()
|
||||
const content = trimmed.replace(listPrefixPattern, '').trim()
|
||||
return `${index + 1}. ${content || '列表项'}`
|
||||
})
|
||||
}
|
||||
|
||||
const applyTaskList = () => {
|
||||
transformSelectedLines((line) => {
|
||||
const trimmed = line.trim()
|
||||
const content = trimmed.replace(listPrefixPattern, '').trim()
|
||||
return `- [ ] ${content || '任务项'}`
|
||||
})
|
||||
}
|
||||
|
||||
const applyBlockquote = () => {
|
||||
transformSelectedLines((line) => {
|
||||
const trimmed = line.trim().replace(/^>\s?/, '').trim()
|
||||
return `> ${trimmed || '引用内容'}`
|
||||
})
|
||||
}
|
||||
|
||||
const insertCodeBlock = () => {
|
||||
const placeholder = '代码内容'
|
||||
const block = `\n\`\`\`\n${placeholder}\n\`\`\`\n`
|
||||
const startOffset = block.indexOf(placeholder)
|
||||
insertBlock(block, startOffset, startOffset + placeholder.length)
|
||||
}
|
||||
|
||||
const insertHorizontalRule = () => {
|
||||
insertBlock('\n---\n\n')
|
||||
}
|
||||
|
||||
const insertTable = () => {
|
||||
const template = '\n| 列1 | 列2 |\n| --- | --- |\n| 内容 | 内容 |\n'
|
||||
const placeholderIndex = template.indexOf('内容')
|
||||
insertBlock(template, placeholderIndex, placeholderIndex + 2)
|
||||
}
|
||||
|
||||
const insertLink = () => {
|
||||
const value = form.content ?? ''
|
||||
const { start, end } = getSelectionRange()
|
||||
const { safeStart, safeEnd } = clampRange(start, end, value.length)
|
||||
const selectedText =
|
||||
safeEnd > safeStart ? value.slice(safeStart, safeEnd) : '链接文本'
|
||||
const urlPlaceholder = 'https://'
|
||||
const result =
|
||||
value.slice(0, safeStart) +
|
||||
`[${selectedText}](${urlPlaceholder})` +
|
||||
value.slice(safeEnd)
|
||||
const urlStart = safeStart + selectedText.length + 3
|
||||
const urlEnd = urlStart + urlPlaceholder.length
|
||||
updateContentWithSelection(result, urlStart, urlEnd)
|
||||
}
|
||||
|
||||
const insertImage = () => {
|
||||
const value = form.content ?? ''
|
||||
const { start, end } = getSelectionRange()
|
||||
const { safeStart, safeEnd } = clampRange(start, end, value.length)
|
||||
const altText = safeEnd > safeStart ? value.slice(safeStart, safeEnd) : '描述'
|
||||
const urlPlaceholder = 'https://'
|
||||
const result =
|
||||
value.slice(0, safeStart) +
|
||||
`` +
|
||||
value.slice(safeEnd)
|
||||
const urlStart = safeStart + altText.length + 4
|
||||
const urlEnd = urlStart + urlPlaceholder.length
|
||||
updateContentWithSelection(result, urlStart, urlEnd)
|
||||
}
|
||||
|
||||
type ToolbarAction = () => void
|
||||
type ToolbarButton = {
|
||||
key: string
|
||||
tooltip: string
|
||||
action: ToolbarAction
|
||||
icon: string
|
||||
}
|
||||
type ToolbarGroup = {
|
||||
key: string
|
||||
buttons: ToolbarButton[]
|
||||
}
|
||||
|
||||
const toolbarGroups: ToolbarGroup[] = [
|
||||
{
|
||||
key: 'format',
|
||||
buttons: [
|
||||
{ key: 'bold', icon: 'textformat-bold', tooltip: '加粗', action: () => wrapSelection('**', '**', '加粗文本') },
|
||||
{ key: 'italic', icon: 'textformat-italic', tooltip: '斜体', action: () => wrapSelection('*', '*', '斜体文本') },
|
||||
{ key: 'strike', icon: 'textformat-strikethrough', tooltip: '删除线', action: () => wrapSelection('~~', '~~', '删除线') },
|
||||
{ key: 'inline-code', icon: 'code', tooltip: '行内代码', action: () => wrapSelection('`', '`', 'code') },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'heading',
|
||||
buttons: [
|
||||
{ key: 'h1', icon: 'numbers-1', tooltip: '一级标题', action: () => applyHeading(1) },
|
||||
{ key: 'h2', icon: 'numbers-2', tooltip: '二级标题', action: () => applyHeading(2) },
|
||||
{ key: 'h3', icon: 'numbers-3', tooltip: '三级标题', action: () => applyHeading(3) },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'list',
|
||||
buttons: [
|
||||
{ key: 'ul', icon: 'view-list', tooltip: '无序列表', action: applyBulletList },
|
||||
{ key: 'ol', icon: 'list-numbered', tooltip: '有序列表', action: applyOrderedList },
|
||||
{ key: 'task', icon: 'check-rectangle', tooltip: '任务列表', action: applyTaskList },
|
||||
{ key: 'quote', icon: 'quote', tooltip: '引用', action: applyBlockquote },
|
||||
],
|
||||
},
|
||||
{
|
||||
key: 'insert',
|
||||
buttons: [
|
||||
{ key: 'codeblock', icon: 'code-1', tooltip: '代码块', action: insertCodeBlock },
|
||||
{ key: 'link', icon: 'link', tooltip: '插入链接', action: insertLink },
|
||||
{ key: 'image', icon: 'image', tooltip: '插入图片', action: insertImage },
|
||||
{ key: 'table', icon: 'table', tooltip: '插入表格', action: insertTable },
|
||||
{ key: 'hr', icon: 'component-divider-horizontal', tooltip: '分割线', action: insertHorizontalRule },
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
const isPreviewMode = computed(() => activeTab.value === 'preview')
|
||||
const viewToggleIcon = computed(() => (isPreviewMode.value ? 'edit' : 'view-module'))
|
||||
const viewToggleTooltip = computed(() => (isPreviewMode.value ? '切换到编辑视图' : '切换到预览视图'))
|
||||
const viewToggleLabel = computed(() => (isPreviewMode.value ? '返回编辑' : '预览内容'))
|
||||
|
||||
const handleToolbarAction = (action: ToolbarAction) => {
|
||||
if (saving.value) {
|
||||
return
|
||||
}
|
||||
if (activeTab.value !== 'edit') {
|
||||
activeTab.value = 'edit'
|
||||
nextTick(() => {
|
||||
attachTextareaListeners()
|
||||
action()
|
||||
})
|
||||
} else {
|
||||
attachTextareaListeners()
|
||||
action()
|
||||
}
|
||||
}
|
||||
|
||||
const toggleEditorView = () => {
|
||||
activeTab.value = isPreviewMode.value ? 'edit' : 'preview'
|
||||
}
|
||||
|
||||
marked.use({
|
||||
mangle: false,
|
||||
headerIds: false,
|
||||
})
|
||||
|
||||
const previewHTML = computed(() => {
|
||||
if (!form.content) return '<p class="empty-preview">暂无内容</p>'
|
||||
const safeMarkdown = safeMarkdownToHTML(form.content)
|
||||
const html = marked.parse(safeMarkdown)
|
||||
return sanitizeHTML(html)
|
||||
})
|
||||
|
||||
const kbDisabled = computed(() => mode.value === 'edit' && !!form.kbId)
|
||||
|
||||
const dialogTitle = computed(() => {
|
||||
if (mode.value === 'edit') {
|
||||
return '编辑 Markdown 知识'
|
||||
}
|
||||
return '在线编辑 Markdown 知识'
|
||||
})
|
||||
|
||||
const loadKnowledgeBases = async () => {
|
||||
kbLoading.value = true
|
||||
try {
|
||||
const res: any = await listKnowledgeBases()
|
||||
const list: KnowledgeBaseOption[] = Array.isArray(res?.data)
|
||||
? res.data.map((item: any) => ({ label: item.name, value: item.id }))
|
||||
: []
|
||||
kbOptions.value = list
|
||||
|
||||
if (mode.value === 'create') {
|
||||
const presetKbId = uiStore.manualEditorKBId
|
||||
if (presetKbId) {
|
||||
const exists = list.find((item) => item.value === presetKbId)
|
||||
if (!exists) {
|
||||
kbOptions.value.unshift({ label: '当前知识库', value: presetKbId })
|
||||
}
|
||||
form.kbId = presetKbId
|
||||
} else {
|
||||
form.kbId = list[0]?.value ?? ''
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载知识库列表失败:', error)
|
||||
kbOptions.value = []
|
||||
} finally {
|
||||
kbLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const parseManualMetadata = (
|
||||
metadata: any,
|
||||
): { content: string; status: ManualStatus; updatedAt?: string } | null => {
|
||||
if (!metadata) {
|
||||
return null
|
||||
}
|
||||
try {
|
||||
let parsed = metadata
|
||||
if (typeof metadata === 'string') {
|
||||
parsed = JSON.parse(metadata)
|
||||
}
|
||||
if (parsed && typeof parsed === 'object') {
|
||||
const status = parsed.status === 'publish' ? 'publish' : 'draft'
|
||||
return {
|
||||
content: parsed.content || '',
|
||||
status,
|
||||
updatedAt: parsed.updated_at || parsed.updatedAt,
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('解析手工知识元数据失败:', error)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const loadKnowledgeContent = async () => {
|
||||
if (!knowledgeId.value) {
|
||||
return
|
||||
}
|
||||
contentLoading.value = true
|
||||
try {
|
||||
const res: any = await getKnowledgeDetails(knowledgeId.value)
|
||||
const data: KnowledgeDetailResponse | undefined = res?.data
|
||||
if (!data) {
|
||||
MessagePlugin.error('获取知识详情失败')
|
||||
return
|
||||
}
|
||||
|
||||
form.kbId = data.knowledge_base_id || form.kbId
|
||||
const meta = parseManualMetadata(data.metadata)
|
||||
form.title =
|
||||
data.title ||
|
||||
data.file_name?.replace(/\.md$/i, '') ||
|
||||
uiStore.manualEditorInitialTitle ||
|
||||
''
|
||||
form.content = meta?.content || uiStore.manualEditorInitialContent || ''
|
||||
form.status = meta?.status || (data.parse_status === 'completed' ? 'publish' : 'draft')
|
||||
if (meta?.updatedAt) {
|
||||
lastUpdatedAt.value = meta.updatedAt
|
||||
}
|
||||
|
||||
if (form.kbId && !kbOptions.value.find((item) => item.value === form.kbId)) {
|
||||
kbOptions.value.unshift({ label: '当前知识库', value: form.kbId })
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载手工知识失败:', error)
|
||||
MessagePlugin.error('获取知识详情失败')
|
||||
} finally {
|
||||
contentLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const resetForm = () => {
|
||||
form.kbId = uiStore.manualEditorKBId || ''
|
||||
form.title = uiStore.manualEditorInitialTitle || ''
|
||||
form.content = uiStore.manualEditorInitialContent || ''
|
||||
form.status = uiStore.manualEditorInitialStatus || 'draft'
|
||||
activeTab.value = 'edit'
|
||||
lastUpdatedAt.value = ''
|
||||
initialLoaded.value = false
|
||||
selectionRange.start = 0
|
||||
selectionRange.end = 0
|
||||
}
|
||||
|
||||
const generateDefaultTitle = () => {
|
||||
if (uiStore.manualEditorInitialTitle) {
|
||||
return uiStore.manualEditorInitialTitle
|
||||
}
|
||||
return `新建文档-${new Date().toLocaleString()}`
|
||||
}
|
||||
|
||||
const initialize = async () => {
|
||||
resetForm()
|
||||
await loadKnowledgeBases()
|
||||
|
||||
if (mode.value === 'edit') {
|
||||
await loadKnowledgeContent()
|
||||
} else {
|
||||
const presetKbId = uiStore.manualEditorKBId
|
||||
if (presetKbId) {
|
||||
form.kbId = presetKbId
|
||||
} else if (!form.kbId && kbOptions.value.length) {
|
||||
form.kbId = kbOptions.value[0].value
|
||||
}
|
||||
form.title = form.title || generateDefaultTitle()
|
||||
form.content = form.content || ''
|
||||
}
|
||||
|
||||
initialLoaded.value = true
|
||||
}
|
||||
|
||||
const validateForm = (targetStatus: ManualStatus): boolean => {
|
||||
if (!form.kbId) {
|
||||
MessagePlugin.warning('请选择目标知识库')
|
||||
return false
|
||||
}
|
||||
if (!form.title || !form.title.trim()) {
|
||||
MessagePlugin.warning('请输入知识标题')
|
||||
return false
|
||||
}
|
||||
if (!form.content || !form.content.trim()) {
|
||||
MessagePlugin.warning('请输入知识内容')
|
||||
return false
|
||||
}
|
||||
if (targetStatus === 'publish' && form.content.trim().length < 10) {
|
||||
MessagePlugin.warning('内容过短,建议补充更多信息后再发布')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const handleSave = async (targetStatus: ManualStatus) => {
|
||||
if (saving.value || !validateForm(targetStatus)) {
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
savingAction.value = targetStatus
|
||||
try {
|
||||
const payload = {
|
||||
title: form.title.trim(),
|
||||
content: form.content,
|
||||
status: targetStatus,
|
||||
}
|
||||
let response: any
|
||||
let knowledgeID = knowledgeId.value
|
||||
let kbId = form.kbId
|
||||
|
||||
if (mode.value === 'edit' && knowledgeId.value) {
|
||||
response = await updateManualKnowledge(knowledgeId.value, payload)
|
||||
} else {
|
||||
response = await createManualKnowledge(form.kbId, payload)
|
||||
knowledgeID = response?.data?.id || knowledgeID
|
||||
kbId = form.kbId
|
||||
}
|
||||
|
||||
if (response?.success) {
|
||||
MessagePlugin.success(targetStatus === 'draft' ? '草稿已保存' : '知识已发布并开始索引')
|
||||
if (knowledgeID) {
|
||||
uiStore.notifyManualEditorSuccess({
|
||||
kbId,
|
||||
knowledgeId: knowledgeID,
|
||||
status: targetStatus,
|
||||
})
|
||||
}
|
||||
uiStore.closeManualEditor()
|
||||
} else {
|
||||
const message = response?.message || '保存失败,请稍后重试'
|
||||
MessagePlugin.error(message)
|
||||
}
|
||||
} catch (error: any) {
|
||||
const message = error?.error?.message || error?.message || '保存失败,请稍后重试'
|
||||
MessagePlugin.error(message)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleClose = () => {
|
||||
uiStore.closeManualEditor()
|
||||
}
|
||||
|
||||
watch(visible, async (val) => {
|
||||
if (val) {
|
||||
await nextTick()
|
||||
await initialize()
|
||||
await nextTick()
|
||||
attachTextareaListeners()
|
||||
const length = form.content ? form.content.length : 0
|
||||
setSelectionRange(length, length)
|
||||
} else {
|
||||
detachTextareaListeners()
|
||||
resetForm()
|
||||
}
|
||||
})
|
||||
|
||||
watch(activeTab, (val) => {
|
||||
if (val === 'edit') {
|
||||
nextTick(() => {
|
||||
attachTextareaListeners()
|
||||
})
|
||||
} else {
|
||||
detachTextareaListeners()
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
detachTextareaListeners()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<t-dialog
|
||||
v-model:visible="visible"
|
||||
:header="dialogTitle"
|
||||
:closeBtn="true"
|
||||
:footer="false"
|
||||
width="880px"
|
||||
top="5%"
|
||||
class="manual-knowledge-editor"
|
||||
>
|
||||
<div class="editor-body" v-if="initialLoaded">
|
||||
<div class="form-row">
|
||||
<label class="form-label">目标知识库</label>
|
||||
<t-select
|
||||
v-model="form.kbId"
|
||||
:disabled="kbDisabled"
|
||||
:loading="kbLoading"
|
||||
:options="kbOptions"
|
||||
placeholder="请选择知识库"
|
||||
:popup-props="{ overlayStyle: { zIndex: 2200 } }"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="form-row">
|
||||
<label class="form-label">知识标题</label>
|
||||
<t-input
|
||||
v-model="form.title"
|
||||
maxlength="100"
|
||||
placeholder="请输入标题"
|
||||
showLimitNumber
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="status-row" v-if="mode === 'edit'">
|
||||
<t-tag theme="warning" v-if="form.status === 'draft'">当前状态:草稿</t-tag>
|
||||
<t-tag theme="success" v-else>当前状态:已发布</t-tag>
|
||||
<span v-if="lastUpdatedAt" class="status-timestamp">最近更新:{{ lastUpdatedAt }}</span>
|
||||
</div>
|
||||
|
||||
<div class="editor-toolbar">
|
||||
<template v-for="(group, groupIndex) in toolbarGroups" :key="group.key">
|
||||
<div class="toolbar-group">
|
||||
<template v-for="btn in group.buttons" :key="btn.key">
|
||||
<t-tooltip :content="btn.tooltip" placement="top">
|
||||
<button
|
||||
type="button"
|
||||
class="toolbar-btn"
|
||||
:class="`btn-${btn.key}`"
|
||||
@mousedown.prevent
|
||||
@click="handleToolbarAction(btn.action)"
|
||||
>
|
||||
<t-icon :name="btn.icon" size="18px" />
|
||||
</button>
|
||||
</t-tooltip>
|
||||
</template>
|
||||
</div>
|
||||
<div
|
||||
v-if="groupIndex < toolbarGroups.length - 1"
|
||||
class="toolbar-divider"
|
||||
></div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="editor-area">
|
||||
<div class="editor-pane" v-show="activeTab === 'edit'">
|
||||
<t-textarea
|
||||
ref="textareaComponent"
|
||||
v-if="!contentLoading"
|
||||
v-model="form.content"
|
||||
placeholder="支持 Markdown 语法,可使用 # 标题、列表、代码块等"
|
||||
:autosize="{ minRows: 16, maxRows: 24 }"
|
||||
/>
|
||||
<div v-else class="loading-placeholder">
|
||||
<t-loading size="small" text="正在加载内容" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor-pane" v-show="activeTab === 'preview'">
|
||||
<div class="preview-container" v-html="previewHTML" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dialog-footer">
|
||||
<div class="footer-left">
|
||||
<t-button variant="outline" theme="default" @click="handleClose">取消</t-button>
|
||||
</div>
|
||||
<div class="footer-right">
|
||||
<t-tooltip :content="viewToggleTooltip" placement="top">
|
||||
<t-button
|
||||
variant="outline"
|
||||
theme="default"
|
||||
class="toggle-view-btn"
|
||||
:class="{ active: isPreviewMode }"
|
||||
@click="toggleEditorView"
|
||||
>
|
||||
<t-icon :name="viewToggleIcon" size="16px" />
|
||||
<span>{{ viewToggleLabel }}</span>
|
||||
</t-button>
|
||||
</t-tooltip>
|
||||
<t-button
|
||||
variant="outline"
|
||||
theme="default"
|
||||
@click="handleSave('draft')"
|
||||
:loading="saving && savingAction === 'draft'"
|
||||
>
|
||||
暂存草稿
|
||||
</t-button>
|
||||
<t-button
|
||||
theme="primary"
|
||||
@click="handleSave('publish')"
|
||||
:loading="saving && savingAction === 'publish'"
|
||||
>
|
||||
发布入库
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="loading-wrapper">
|
||||
<t-loading size="medium" text="正在准备编辑器" />
|
||||
</div>
|
||||
</t-dialog>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.manual-knowledge-editor {
|
||||
:deep(.t-dialog__body) {
|
||||
padding: 20px 24px 12px;
|
||||
max-height: 80vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
}
|
||||
|
||||
.editor-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.form-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: #000000e6;
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.editor-toolbar {
|
||||
display: flex;
|
||||
flex-wrap: nowrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 14px;
|
||||
background: linear-gradient(180deg, #fbfcff 0%, #f3f5f7 100%);
|
||||
border: 1px solid #dce1e7;
|
||||
border-radius: 12px;
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.6), 0 6px 14px rgba(15, 24, 40, 0.06);
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.toolbar-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.toolbar-divider {
|
||||
width: 1px;
|
||||
height: 24px;
|
||||
background: linear-gradient(180deg, rgba(190, 196, 203, 0) 0%, rgba(190, 196, 203, 0.7) 50%, rgba(190, 196, 203, 0) 100%);
|
||||
}
|
||||
|
||||
.toolbar-btn {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
padding: 0;
|
||||
border-radius: 6px;
|
||||
color: #3d4652;
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
transition: all 0.18s ease;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.toolbar-btn:hover,
|
||||
.toolbar-btn.active {
|
||||
background: rgba(7, 192, 95, 0.12);
|
||||
color: #059669;
|
||||
transform: translateY(-0.5px);
|
||||
}
|
||||
|
||||
.toolbar-btn:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px rgba(7, 192, 95, 0.25);
|
||||
}
|
||||
|
||||
.toolbar-btn:active {
|
||||
transform: translateY(0);
|
||||
background: rgba(7, 192, 95, 0.18);
|
||||
}
|
||||
|
||||
:deep(.toggle-view-btn) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 0 16px;
|
||||
height: 32px;
|
||||
line-height: 32px;
|
||||
transition: all 0.18s ease;
|
||||
}
|
||||
|
||||
:deep(.toggle-view-btn span) {
|
||||
font-size: 13px;
|
||||
line-height: 1.05;
|
||||
}
|
||||
|
||||
:deep(.toggle-view-btn.active),
|
||||
:deep(.toggle-view-btn:hover) {
|
||||
background: rgba(7, 192, 95, 0.12) !important;
|
||||
color: #059669 !important;
|
||||
border-color: rgba(7, 192, 95, 0.4) !important;
|
||||
}
|
||||
|
||||
:deep(.toggle-view-btn .t-button__content) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
:deep(.toggle-view-btn .t-button__icon) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
:deep(.toggle-view-btn .t-button__icon svg) {
|
||||
display: block;
|
||||
position: relative;
|
||||
top: 1px;
|
||||
}
|
||||
|
||||
.status-timestamp {
|
||||
font-size: 12px;
|
||||
color: #00000066;
|
||||
}
|
||||
|
||||
.editor-area {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.editor-pane {
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
:deep(.t-textarea__inner) {
|
||||
font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.preview-container {
|
||||
min-height: 300px;
|
||||
max-height: 520px;
|
||||
overflow-y: auto;
|
||||
padding: 16px;
|
||||
background: #fafafa;
|
||||
font-size: 14px;
|
||||
line-height: 1.7;
|
||||
color: #222;
|
||||
|
||||
:deep(h1),
|
||||
:deep(h2),
|
||||
:deep(h3),
|
||||
:deep(h4) {
|
||||
margin-top: 16px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
:deep(code) {
|
||||
background: rgba(0, 0, 0, 0.05);
|
||||
padding: 2px 4px;
|
||||
border-radius: 4px;
|
||||
font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace;
|
||||
}
|
||||
|
||||
:deep(pre) {
|
||||
background: rgba(0, 0, 0, 0.05);
|
||||
padding: 12px;
|
||||
border-radius: 6px;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
:deep(blockquote) {
|
||||
border-left: 4px solid #07c05f;
|
||||
padding-left: 12px;
|
||||
color: #555;
|
||||
margin: 16px 0;
|
||||
background: rgba(7, 192, 95, 0.08);
|
||||
}
|
||||
|
||||
:deep(a) {
|
||||
color: #07c05f;
|
||||
}
|
||||
}
|
||||
|
||||
.dialog-footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.footer-right {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.loading-wrapper,
|
||||
.loading-placeholder {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 240px;
|
||||
}
|
||||
|
||||
.empty-preview {
|
||||
color: #999;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -39,13 +39,20 @@
|
||||
{{ kb.name }}
|
||||
</div>
|
||||
</div>
|
||||
<t-popup overlayInnerClassName="upload-popup" class="placement top center" content="上传知识"
|
||||
<t-popup overlayInnerClassName="upload-popup" class="placement top center" content="上传文档 / 在线编辑(支持拖拽上传)"
|
||||
placement="top" show-arrow destroy-on-close>
|
||||
<div class="upload-file-wrap" @click.stop="uploadFile" variant="outline"
|
||||
v-if="item.path === 'knowledge-bases' && $route.name === 'knowledgeBaseDetail'">
|
||||
<img class="upload-file-icon" :class="[item.path == currentpath ? 'active-upload' : '']"
|
||||
:src="getImgSrc(fileAddIcon)" alt="">
|
||||
</div>
|
||||
<t-dropdown
|
||||
v-if="item.path === 'knowledge-bases' && $route.name === 'knowledgeBaseDetail'"
|
||||
trigger="click"
|
||||
:options="uploadActionOptions"
|
||||
placement="right"
|
||||
@click="handleUploadAction"
|
||||
>
|
||||
<div class="upload-file-wrap" variant="outline">
|
||||
<img class="upload-file-icon" :class="[item.path == currentpath ? 'active-upload' : '']"
|
||||
:src="getImgSrc(fileAddIcon)" alt="">
|
||||
</div>
|
||||
</t-dropdown>
|
||||
</t-popup>
|
||||
</div>
|
||||
<div ref="submenuscrollContainer" @scroll="handleScroll" class="submenu" v-if="item.children">
|
||||
@@ -262,6 +269,10 @@ const kbMenuItem = computed(() => {
|
||||
})
|
||||
|
||||
const loading = ref(false)
|
||||
const uploadActionOptions = [
|
||||
{ content: '上传文档', value: 'upload' },
|
||||
{ content: '在线编辑', value: 'manual' },
|
||||
]
|
||||
const uploadFile = async () => {
|
||||
// 获取当前知识库ID
|
||||
const currentKbId = await getCurrentKbId();
|
||||
@@ -287,6 +298,34 @@ const uploadFile = async () => {
|
||||
|
||||
uploadInput.value.click()
|
||||
}
|
||||
const openManualEditor = async () => {
|
||||
const currentKbId = await getCurrentKbId();
|
||||
if (!currentKbId) {
|
||||
MessagePlugin.warning("请选择知识库");
|
||||
return;
|
||||
}
|
||||
uiStore.openManualEditor({
|
||||
mode: 'create',
|
||||
kbId: currentKbId,
|
||||
status: 'draft',
|
||||
onSuccess: ({ kbId }) => {
|
||||
if (kbId) {
|
||||
window.dispatchEvent(new CustomEvent('knowledgeFileUploaded', {
|
||||
detail: { kbId }
|
||||
}));
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
const handleUploadAction = async (data: { value: string }) => {
|
||||
if (data.value === 'upload') {
|
||||
uploadFile();
|
||||
return;
|
||||
}
|
||||
if (data.value === 'manual') {
|
||||
openManualEditor();
|
||||
}
|
||||
}
|
||||
const upload = async (e: any) => {
|
||||
const file = e.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
@@ -31,13 +31,21 @@ export default function (knowledgeBaseId?: string) {
|
||||
listKnowledgeFiles(targetKbId, query)
|
||||
.then((result: any) => {
|
||||
const { data, total: totalResult } = result;
|
||||
const cardList_ = data.map((item: any) => ({
|
||||
...item,
|
||||
file_name: item.file_name.substring(0, item.file_name.lastIndexOf(".")),
|
||||
updated_at: formatStringDate(new Date(item.updated_at)),
|
||||
isMore: false,
|
||||
file_type: item.file_type.toLocaleUpperCase(),
|
||||
}));
|
||||
const cardList_ = data.map((item: any) => {
|
||||
const rawName = item.file_name || item.title || item.source || '未命名文档'
|
||||
const dotIndex = rawName.lastIndexOf('.')
|
||||
const displayName = dotIndex > 0 ? rawName.substring(0, dotIndex) : rawName
|
||||
const fileTypeSource = item.file_type || (item.type === 'manual' ? 'MANUAL' : '')
|
||||
return {
|
||||
...item,
|
||||
original_file_name: item.file_name,
|
||||
display_name: displayName,
|
||||
file_name: displayName,
|
||||
updated_at: formatStringDate(new Date(item.updated_at)),
|
||||
isMore: false,
|
||||
file_type: fileTypeSource ? String(fileTypeSource).toLocaleUpperCase() : '',
|
||||
}
|
||||
});
|
||||
|
||||
if (query.page === 1) {
|
||||
cardList.value = cardList_;
|
||||
|
||||
@@ -8,7 +8,15 @@ export const useUIStore = defineStore('ui', {
|
||||
currentKBId: null as string | null,
|
||||
kbEditorInitialSection: null as string | null,
|
||||
settingsInitialSection: null as string | null,
|
||||
settingsInitialSubSection: null as string | null
|
||||
settingsInitialSubSection: null as string | null,
|
||||
manualEditorVisible: false,
|
||||
manualEditorMode: 'create' as 'create' | 'edit',
|
||||
manualEditorKBId: null as string | null,
|
||||
manualEditorKnowledgeId: null as string | null,
|
||||
manualEditorInitialTitle: '',
|
||||
manualEditorInitialContent: '',
|
||||
manualEditorInitialStatus: 'draft' as 'draft' | 'publish',
|
||||
manualEditorOnSuccess: null as null | ((payload: { kbId: string; knowledgeId: string; status: 'draft' | 'publish' }) => void)
|
||||
}),
|
||||
|
||||
actions: {
|
||||
@@ -50,6 +58,45 @@ export const useUIStore = defineStore('ui', {
|
||||
this.showKBEditorModal = false
|
||||
this.currentKBId = null
|
||||
this.kbEditorInitialSection = null
|
||||
},
|
||||
|
||||
openManualEditor(options: {
|
||||
mode?: 'create' | 'edit'
|
||||
kbId?: string | null
|
||||
knowledgeId?: string | null
|
||||
title?: string
|
||||
content?: string
|
||||
status?: 'draft' | 'publish'
|
||||
onSuccess?: (payload: { kbId: string; knowledgeId: string; status: 'draft' | 'publish' }) => void
|
||||
} = {}) {
|
||||
this.manualEditorMode = options.mode || 'create'
|
||||
this.manualEditorKBId = options.kbId ?? null
|
||||
this.manualEditorKnowledgeId = options.knowledgeId ?? null
|
||||
this.manualEditorInitialTitle = options.title || ''
|
||||
this.manualEditorInitialContent = options.content || ''
|
||||
this.manualEditorInitialStatus = options.status || 'draft'
|
||||
this.manualEditorOnSuccess = options.onSuccess || null
|
||||
this.manualEditorVisible = true
|
||||
},
|
||||
|
||||
closeManualEditor() {
|
||||
this.manualEditorVisible = false
|
||||
this.manualEditorKnowledgeId = null
|
||||
this.manualEditorInitialContent = ''
|
||||
this.manualEditorInitialTitle = ''
|
||||
this.manualEditorInitialStatus = 'draft'
|
||||
this.manualEditorOnSuccess = null
|
||||
},
|
||||
|
||||
notifyManualEditorSuccess(payload: { kbId: string; knowledgeId: string; status: 'draft' | 'publish' }) {
|
||||
if (typeof this.manualEditorOnSuccess === 'function') {
|
||||
try {
|
||||
this.manualEditorOnSuccess(payload)
|
||||
} catch (err) {
|
||||
console.error('Manual editor success callback error:', err)
|
||||
}
|
||||
}
|
||||
this.manualEditorOnSuccess = null
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -17,7 +17,8 @@ export type DisplayType =
|
||||
| 'thinking'
|
||||
| 'plan'
|
||||
| 'database_query'
|
||||
| 'web_search_results';
|
||||
| 'web_search_results'
|
||||
| 'web_fetch_results';
|
||||
|
||||
// Search result item
|
||||
export interface SearchResultItem {
|
||||
@@ -156,6 +157,24 @@ export interface WebSearchResultsData {
|
||||
count: number;
|
||||
}
|
||||
|
||||
// Web fetch result item
|
||||
export interface WebFetchResultItem {
|
||||
url: string;
|
||||
prompt?: string;
|
||||
summary?: string;
|
||||
raw_content?: string;
|
||||
content_length?: number;
|
||||
method?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// Web fetch results data
|
||||
export interface WebFetchResultsData {
|
||||
display_type: 'web_fetch_results';
|
||||
results: WebFetchResultItem[];
|
||||
count?: number;
|
||||
}
|
||||
|
||||
// Union type for all tool result data
|
||||
export type ToolResultData =
|
||||
| SearchResultsData
|
||||
@@ -167,7 +186,8 @@ export type ToolResultData =
|
||||
| ThinkingData
|
||||
| PlanData
|
||||
| DatabaseQueryData
|
||||
| WebSearchResultsData;
|
||||
| WebSearchResultsData
|
||||
| WebFetchResultsData;
|
||||
|
||||
// Action data (from index.vue)
|
||||
export interface ActionData {
|
||||
|
||||
@@ -57,6 +57,12 @@
|
||||
v-html="renderMarkdown(event.content)">
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="event.done" class="answer-toolbar">
|
||||
<t-button size="small" variant="outline" shape="round" @click.stop="handleAddToKnowledge(event)">
|
||||
<t-icon name="add" />
|
||||
<span>添加到知识库</span>
|
||||
</t-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tool Call Event -->
|
||||
@@ -190,8 +196,30 @@ import { marked } from 'marked';
|
||||
import DOMPurify from 'dompurify';
|
||||
import ToolResultRenderer from './ToolResultRenderer.vue';
|
||||
import { getChunkByIdOnly } from '@/api/knowledge-base';
|
||||
import { MessagePlugin } from 'tdesign-vue-next';
|
||||
import { useUIStore } from '@/stores/ui';
|
||||
|
||||
const router = useRouter();
|
||||
const uiStore = useUIStore();
|
||||
|
||||
const TOOL_NAME_I18N: Record<string, string> = {
|
||||
search_knowledge: '知识库检索',
|
||||
knowledge_search: '知识库检索',
|
||||
web_search: '网络搜索',
|
||||
web_fetch: '网页抓取',
|
||||
get_document_info: '获取文档信息',
|
||||
get_related_chunks: '查找相关片段',
|
||||
get_related_documents: '查找相关文档',
|
||||
get_document_content: '获取文档内容',
|
||||
todo_write: '计划管理',
|
||||
knowledge_graph_extract: '知识图谱抽取',
|
||||
thinking: '思考',
|
||||
};
|
||||
|
||||
const getLocalizedToolName = (toolName?: string | null): string => {
|
||||
if (!toolName) return '工具';
|
||||
return TOOL_NAME_I18N[toolName] || toolName;
|
||||
};
|
||||
|
||||
// 根元素引用
|
||||
const rootElement = ref<HTMLElement | null>(null);
|
||||
@@ -276,6 +304,7 @@ interface SessionData {
|
||||
|
||||
const props = defineProps<{
|
||||
session: SessionData;
|
||||
userQuery?: string;
|
||||
}>();
|
||||
|
||||
// Configure marked for security
|
||||
@@ -1164,7 +1193,8 @@ const getQueryText = (args: any): string => {
|
||||
// Get tool title - prefer summary over description, add query for search tools
|
||||
const getToolTitle = (event: any): string => {
|
||||
if (event.pending) {
|
||||
return `正在调用 ${event.tool_name}...`;
|
||||
const localizedName = getLocalizedToolName(event.tool_name);
|
||||
return `正在调用 ${localizedName}...`;
|
||||
}
|
||||
|
||||
const toolName = event.tool_name;
|
||||
@@ -1207,7 +1237,8 @@ const getToolTitle = (event: any): string => {
|
||||
// Tool description
|
||||
const getToolDescription = (event: any): string => {
|
||||
if (event.pending) {
|
||||
return `正在调用 ${event.tool_name}...`;
|
||||
const localizedName = getLocalizedToolName(event.tool_name);
|
||||
return `正在调用 ${localizedName}...`;
|
||||
}
|
||||
|
||||
const success = event.success === true;
|
||||
@@ -1224,7 +1255,8 @@ const getToolDescription = (event: any): string => {
|
||||
} else if (toolName === 'todo_write') {
|
||||
return success ? '更新任务列表' : '更新任务列表失败';
|
||||
} else {
|
||||
return success ? `调用 ${toolName}` : `调用 ${toolName} 失败`;
|
||||
const localizedName = getLocalizedToolName(toolName);
|
||||
return success ? `调用 ${localizedName}` : `调用 ${localizedName} 失败`;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1255,6 +1287,44 @@ const formatJSON = (obj: any): string => {
|
||||
return String(obj);
|
||||
}
|
||||
};
|
||||
|
||||
const buildManualMarkdown = (question: string, answer: string): string => {
|
||||
const safeQuestion = question?.trim() || '(无提问内容)';
|
||||
const safeAnswer = answer?.trim() || '(无回答内容)';
|
||||
return `# 用户提问\n${safeQuestion}\n\n# 助手回答\n${safeAnswer}\n`;
|
||||
};
|
||||
|
||||
const formatManualTitle = (question: string): string => {
|
||||
if (!question) {
|
||||
return '会话摘录';
|
||||
}
|
||||
const condensed = question.replace(/\s+/g, ' ').trim();
|
||||
if (!condensed) {
|
||||
return '会话摘录';
|
||||
}
|
||||
return condensed.length > 40 ? `${condensed.slice(0, 40)}...` : condensed;
|
||||
};
|
||||
|
||||
const handleAddToKnowledge = (answerEvent: any) => {
|
||||
const answerContent = (answerEvent?.content || '').trim();
|
||||
if (!answerContent) {
|
||||
MessagePlugin.warning('当前回答为空,无法保存到知识库');
|
||||
return;
|
||||
}
|
||||
|
||||
const question = (props.userQuery || '').trim();
|
||||
const manualContent = buildManualMarkdown(question, answerContent);
|
||||
const manualTitle = formatManualTitle(question);
|
||||
|
||||
uiStore.openManualEditor({
|
||||
mode: 'create',
|
||||
title: manualTitle,
|
||||
content: manualContent,
|
||||
status: 'draft',
|
||||
});
|
||||
|
||||
MessagePlugin.info('已打开编辑器,请选择知识库后保存');
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@@ -1549,6 +1619,18 @@ const formatJSON = (obj: any): string => {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.answer-toolbar {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 10px;
|
||||
|
||||
:deep(.t-button) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tool Event
|
||||
@@ -1560,13 +1642,19 @@ const formatJSON = (obj: any): string => {
|
||||
border-radius: 8px;
|
||||
border: 1px solid #e5e7eb;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
|
||||
|
||||
> * {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
border-color: #07c05f;
|
||||
box-shadow: 0 2px 8px rgba(7, 192, 95, 0.12);
|
||||
transform: translateY(-1px);
|
||||
// transform: translateY(-1px);
|
||||
}
|
||||
|
||||
&.action-error {
|
||||
@@ -1575,8 +1663,27 @@ const formatJSON = (obj: any): string => {
|
||||
}
|
||||
|
||||
&.action-pending {
|
||||
opacity: 0.7;
|
||||
opacity: 1;
|
||||
box-shadow: none;
|
||||
border-color: rgba(7, 192, 95, 0.35);
|
||||
background: linear-gradient(120deg, rgba(7, 192, 95, 0.04), rgba(255, 255, 255, 0.9));
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
120deg,
|
||||
rgba(255, 255, 255, 0) 0%,
|
||||
rgba(255, 255, 255, 0.8) 35%,
|
||||
rgba(7, 192, 95, 0.15) 55%,
|
||||
rgba(255, 255, 255, 0) 85%
|
||||
);
|
||||
transform: translateX(-100%);
|
||||
animation: actionPendingShimmer 1.6s ease-in-out infinite;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1730,6 +1837,18 @@ const formatJSON = (obj: any): string => {
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes actionPendingShimmer {
|
||||
0% {
|
||||
transform: translateX(-120%);
|
||||
}
|
||||
50% {
|
||||
transform: translateX(-10%);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(120%);
|
||||
}
|
||||
}
|
||||
|
||||
.action-name {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
|
||||
@@ -61,6 +61,12 @@
|
||||
:data="toolData as WebSearchResultsData"
|
||||
/>
|
||||
|
||||
<!-- Web Fetch Results Display -->
|
||||
<WebFetchResults
|
||||
v-else-if="displayType === 'web_fetch_results'"
|
||||
:data="toolData as WebFetchResultsData"
|
||||
/>
|
||||
|
||||
<!-- Fallback: Display raw output -->
|
||||
<div v-else class="fallback-output">
|
||||
<div class="fallback-header">
|
||||
@@ -86,7 +92,8 @@ import type {
|
||||
ThinkingData,
|
||||
PlanData,
|
||||
DatabaseQueryData,
|
||||
WebSearchResultsData
|
||||
WebSearchResultsData,
|
||||
WebFetchResultsData
|
||||
} from '@/types/tool-results';
|
||||
|
||||
import SearchResults from './tool-results/SearchResults.vue';
|
||||
@@ -99,6 +106,7 @@ import ThinkingDisplay from './tool-results/ThinkingDisplay.vue';
|
||||
import PlanDisplay from './tool-results/PlanDisplay.vue';
|
||||
import DatabaseQuery from './tool-results/DatabaseQuery.vue';
|
||||
import WebSearchResults from './tool-results/WebSearchResults.vue';
|
||||
import WebFetchResults from './tool-results/WebFetchResults.vue';
|
||||
|
||||
interface Props {
|
||||
displayType?: DisplayType;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="bot_msg">
|
||||
<div style="display: flex;flex-direction: column; gap:8px">
|
||||
<docInfo :session="session"></docInfo>
|
||||
<AgentStreamDisplay :session="session" v-if="session.isAgentMode"></AgentStreamDisplay>
|
||||
<AgentStreamDisplay :session="session" :user-query="userQuery" v-if="session.isAgentMode"></AgentStreamDisplay>
|
||||
<deepThink :deepSession="session" v-if="session.showThink && !session.isAgentMode"></deepThink>
|
||||
</div>
|
||||
<!-- 非 Agent 模式下才显示传统的 markdown 渲染 -->
|
||||
@@ -49,6 +49,11 @@ const props = defineProps({
|
||||
type: Object,
|
||||
required: false
|
||||
},
|
||||
userQuery: {
|
||||
type: String,
|
||||
required: false,
|
||||
default: ''
|
||||
},
|
||||
isFirstEnter: {
|
||||
type: Boolean,
|
||||
required: false
|
||||
|
||||
@@ -0,0 +1,268 @@
|
||||
<template>
|
||||
<div class="web-fetch-results">
|
||||
<div v-if="items.length > 0" class="results-list">
|
||||
<div
|
||||
v-for="(item, index) in items"
|
||||
:key="indexKey(index, item)"
|
||||
class="result-card"
|
||||
>
|
||||
<div class="result-header" @click="toggleCard(index)">
|
||||
<div class="result-title">
|
||||
<span class="result-index">#{{ index + 1 }}</span>
|
||||
<a
|
||||
v-if="item.url"
|
||||
:href="item.url"
|
||||
class="result-link"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
@click.stop
|
||||
>
|
||||
<span class="result-domain">{{ safeHostname(item.url) }}</span>
|
||||
</a>
|
||||
<span v-else class="result-domain">未知链接</span>
|
||||
</div>
|
||||
<div class="result-meta">
|
||||
<span v-if="item.method" class="meta-pill">{{ formatMethod(item.method) }}</span>
|
||||
<span v-if="item.content_length" class="meta-text">长度 {{ formatLength(item.content_length) }}</span>
|
||||
<t-icon
|
||||
:name="isExpanded(index) ? 'chevron-up' : 'chevron-down'"
|
||||
class="expand-icon"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="result-content" :class="{ expanded: isExpanded(index) }">
|
||||
<div class="info-section">
|
||||
<div class="info-field">
|
||||
<span class="field-label">URL</span>
|
||||
<span class="field-value">
|
||||
<a
|
||||
v-if="item.url"
|
||||
:href="item.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>{{ item.url }}</a>
|
||||
<span v-else>未提供</span>
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="item.prompt" class="info-field">
|
||||
<span class="field-label">提示词</span>
|
||||
<span class="field-value">{{ item.prompt }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="item.error" class="info-section">
|
||||
<div class="info-section-title error">错误信息</div>
|
||||
<div class="full-content error-text">{{ item.error }}</div>
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div v-if="item.summary" class="info-section">
|
||||
<div class="info-section-title">总结</div>
|
||||
<div class="full-content">{{ item.summary }}</div>
|
||||
</div>
|
||||
|
||||
<div v-if="item.raw_content" class="info-section">
|
||||
<div class="info-section-title">
|
||||
原始文本
|
||||
<span class="raw-length" v-if="item.content_length">
|
||||
({{ formatLength(item.content_length) }})
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="isRawExpanded(index)" class="full-content">
|
||||
{{ item.raw_content }}
|
||||
</div>
|
||||
<div v-else class="content-preview">
|
||||
{{ truncate(item.raw_content) }}
|
||||
</div>
|
||||
<button class="action-button" @click.stop="toggleRaw(index)">
|
||||
{{ isRawExpanded(index) ? '收起原文' : '展开原文' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="empty-state">未获取到网页内容</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import type { WebFetchResultsData, WebFetchResultItem } from '@/types/tool-results';
|
||||
|
||||
interface Props {
|
||||
data: WebFetchResultsData;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
|
||||
const items = computed<WebFetchResultItem[]>(() => props.data.results || []);
|
||||
const expandedCards = ref<Set<number>>(new Set());
|
||||
const expandedRaw = ref<Record<number, boolean>>({});
|
||||
|
||||
watch(
|
||||
items,
|
||||
(list) => {
|
||||
const set = new Set<number>();
|
||||
list.forEach((_item, idx) => {
|
||||
set.add(idx);
|
||||
});
|
||||
expandedCards.value = set;
|
||||
expandedRaw.value = {};
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
const toggleCard = (index: number) => {
|
||||
if (expandedCards.value.has(index)) {
|
||||
expandedCards.value.delete(index);
|
||||
} else {
|
||||
expandedCards.value.add(index);
|
||||
}
|
||||
};
|
||||
|
||||
const isExpanded = (index: number): boolean => expandedCards.value.has(index);
|
||||
|
||||
const toggleRaw = (index: number) => {
|
||||
expandedRaw.value[index] = !expandedRaw.value[index];
|
||||
};
|
||||
|
||||
const isRawExpanded = (index: number): boolean => !!expandedRaw.value[index];
|
||||
|
||||
const truncate = (content: string, maxLength = 480): string => {
|
||||
if (!content) return '';
|
||||
if (content.length <= maxLength) return content;
|
||||
return `${content.substring(0, maxLength)}…`;
|
||||
};
|
||||
|
||||
const safeHostname = (url: string): string => {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
return urlObj.hostname;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
};
|
||||
|
||||
const formatLength = (length: number): string => {
|
||||
if (!length || Number.isNaN(length)) return '0';
|
||||
if (length >= 10000) {
|
||||
return `${(length / 10000).toFixed(1)} 万字`;
|
||||
}
|
||||
if (length >= 1000) {
|
||||
return `${(length / 1000).toFixed(1)} 千字`;
|
||||
}
|
||||
return `${length} 字`;
|
||||
};
|
||||
|
||||
const formatMethod = (method: string): string => {
|
||||
if (!method) return '';
|
||||
if (method.toLowerCase() === 'chromedp') {
|
||||
return 'Chromedp';
|
||||
}
|
||||
if (method.toLowerCase() === 'http') {
|
||||
return 'HTTP';
|
||||
}
|
||||
return method;
|
||||
};
|
||||
|
||||
const indexKey = (index: number, item: WebFetchResultItem): string => {
|
||||
return `${index}-${item.url || 'unknown'}`;
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
@import './tool-results.less';
|
||||
|
||||
.web-fetch-results {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 8px 8px 0 8px;
|
||||
}
|
||||
|
||||
.results-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.result-index {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: #8b8b8b;
|
||||
}
|
||||
|
||||
.result-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: #1f2937;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
color: #07c05f;
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
.result-domain {
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
.meta-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
padding: 2px 8px;
|
||||
border-radius: 999px;
|
||||
background: #e8f8f0;
|
||||
color: #0f7a49;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.meta-text {
|
||||
font-size: 12px;
|
||||
color: #6b7280;
|
||||
}
|
||||
|
||||
.result-content.expanded {
|
||||
padding-top: 12px;
|
||||
}
|
||||
|
||||
.info-field .field-value a {
|
||||
color: #07c05f;
|
||||
text-decoration: none;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
.raw-length {
|
||||
font-size: 12px;
|
||||
color: #8b8b8b;
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
.action-button {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.info-section-title.error {
|
||||
color: #dc2626;
|
||||
}
|
||||
|
||||
.full-content.error-text {
|
||||
background: #fef2f2;
|
||||
border-color: #fecaca;
|
||||
color: #b91c1c;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<usermsg :content="session.content"></usermsg>
|
||||
</div>
|
||||
<div v-if="session.role == 'assistant'">
|
||||
<botmsg :content="session.content" :session="session" @scroll-bottom="scrollToBottom"
|
||||
<botmsg :content="session.content" :session="session" :user-query="getUserQuery(id)" @scroll-bottom="scrollToBottom"
|
||||
:isFirstEnter="isFirstEnter"></botmsg>
|
||||
</div>
|
||||
</div>
|
||||
@@ -60,6 +60,17 @@ const loading = ref(false);
|
||||
let fullContent = ref('')
|
||||
let userquery = ref('')
|
||||
const scrollContainer = ref(null)
|
||||
|
||||
const getUserQuery = (index) => {
|
||||
if (index <= 0) {
|
||||
return '';
|
||||
}
|
||||
const previous = messagesList[index - 1];
|
||||
if (previous && previous.role === 'user') {
|
||||
return previous.content || '';
|
||||
}
|
||||
return '';
|
||||
};
|
||||
watch([() => route.params], (newvalue) => {
|
||||
isFirstEnter.value = true;
|
||||
if (newvalue[0].chatid) {
|
||||
@@ -538,28 +549,53 @@ const handleAgentChunk = (data) => {
|
||||
break;
|
||||
|
||||
case 'tool_call':
|
||||
// Store pending tool call to pair with result later
|
||||
if (data.data && data.data.tool_name) {
|
||||
console.log('[Tool Call]', data.data.tool_name);
|
||||
// Store or update pending tool call to pair with result later
|
||||
if (data.data && (data.data.tool_name || data.data.tool_call_id)) {
|
||||
const incomingToolName = data.data.tool_name;
|
||||
const incomingArguments = data.data.arguments;
|
||||
|
||||
if (!message.agentEventStream) message.agentEventStream = [];
|
||||
if (!message._pendingToolCalls) message._pendingToolCalls = new Map();
|
||||
|
||||
const toolCallId = data.data.tool_call_id || (data.data.tool_name + '_' + Date.now());
|
||||
const toolCallId = data.data.tool_call_id || (incomingToolName ? (incomingToolName + '_' + Date.now()) : null);
|
||||
if (!toolCallId) {
|
||||
console.warn('[Tool Call] Received event without identifiable tool_call_id:', data.data);
|
||||
break;
|
||||
}
|
||||
|
||||
// Create tool call event
|
||||
const toolCallEvent = {
|
||||
type: 'tool_call',
|
||||
console.log('[Tool Call]', {
|
||||
tool_call_id: toolCallId,
|
||||
tool_name: data.data.tool_name,
|
||||
arguments: data.data.arguments,
|
||||
timestamp: Date.now(),
|
||||
pending: true
|
||||
};
|
||||
tool_name: incomingToolName,
|
||||
has_arguments: Boolean(incomingArguments)
|
||||
});
|
||||
|
||||
// Add to event stream
|
||||
message.agentEventStream.push(toolCallEvent);
|
||||
message._pendingToolCalls.set(toolCallId, toolCallEvent);
|
||||
let toolCallEvent = message._pendingToolCalls.get(toolCallId);
|
||||
if (!toolCallEvent) {
|
||||
toolCallEvent = message.agentEventStream.find(
|
||||
(event) => event.type === 'tool_call' && event.tool_call_id === toolCallId
|
||||
);
|
||||
}
|
||||
|
||||
if (toolCallEvent) {
|
||||
if (incomingToolName) toolCallEvent.tool_name = incomingToolName;
|
||||
if (incomingArguments) toolCallEvent.arguments = incomingArguments;
|
||||
toolCallEvent.pending = true;
|
||||
if (!toolCallEvent.timestamp) {
|
||||
toolCallEvent.timestamp = Date.now();
|
||||
}
|
||||
message._pendingToolCalls.set(toolCallId, toolCallEvent);
|
||||
} else {
|
||||
const newToolCallEvent = {
|
||||
type: 'tool_call',
|
||||
tool_call_id: toolCallId,
|
||||
tool_name: incomingToolName,
|
||||
arguments: incomingArguments,
|
||||
timestamp: Date.now(),
|
||||
pending: true
|
||||
};
|
||||
message.agentEventStream.push(newToolCallEvent);
|
||||
message._pendingToolCalls.set(toolCallId, newToolCallEvent);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import EmptyKnowledge from '@/components/empty-knowledge.vue';
|
||||
import { getSessionsList, createSessions, generateSessionsTitle } from "@/api/chat/index";
|
||||
import { useMenuStore } from '@/stores/menu';
|
||||
import { useUIStore } from '@/stores/ui';
|
||||
import { MessagePlugin } from 'tdesign-vue-next';
|
||||
import KnowledgeBaseEditorModal from './KnowledgeBaseEditorModal.vue';
|
||||
const usemenuStore = useMenuStore();
|
||||
const uiStore = useUIStore();
|
||||
@@ -53,15 +52,18 @@ const loadKnowledgeFiles = async (kbIdValue: string) => {
|
||||
}
|
||||
|
||||
const cardList_ = data.map((item: any) => {
|
||||
item["file_name"] = item.file_name.substring(
|
||||
0,
|
||||
item.file_name.lastIndexOf(".")
|
||||
);
|
||||
const rawName = item.file_name || item.title || item.source || '未命名文档'
|
||||
const dotIndex = rawName.lastIndexOf('.')
|
||||
const displayName = dotIndex > 0 ? rawName.substring(0, dotIndex) : rawName
|
||||
const fileTypeSource = item.file_type || (item.type === 'manual' ? 'MANUAL' : '')
|
||||
return {
|
||||
...item,
|
||||
original_file_name: item.file_name,
|
||||
display_name: displayName,
|
||||
file_name: displayName,
|
||||
updated_at: formatStringDate(new Date(item.updated_at)),
|
||||
isMore: false,
|
||||
file_type: item.file_type.toLocaleUpperCase(),
|
||||
file_type: fileTypeSource ? String(fileTypeSource).toLocaleUpperCase() : '',
|
||||
};
|
||||
});
|
||||
|
||||
@@ -113,7 +115,22 @@ watch(() => cardList.value, (newValue) => {
|
||||
updateStatus(analyzeList)
|
||||
}
|
||||
}, { deep: true })
|
||||
type KnowledgeCard = { id: string; parse_status: string; description?: string; file_name?: string; updated_at?: string; file_type?: string; isMore?: boolean };
|
||||
type KnowledgeCard = {
|
||||
id: string;
|
||||
knowledge_base_id?: string;
|
||||
parse_status: string;
|
||||
description?: string;
|
||||
file_name?: string;
|
||||
original_file_name?: string;
|
||||
display_name?: string;
|
||||
title?: string;
|
||||
type?: string;
|
||||
updated_at?: string;
|
||||
file_type?: string;
|
||||
isMore?: boolean;
|
||||
metadata?: any;
|
||||
error_message?: string;
|
||||
};
|
||||
const updateStatus = (analyzeList: KnowledgeCard[]) => {
|
||||
let query = ``;
|
||||
for (let i = 0; i < analyzeList.length; i++) {
|
||||
@@ -152,6 +169,24 @@ const delCard = (index: number, item: KnowledgeCard) => {
|
||||
delDialog.value = true;
|
||||
};
|
||||
|
||||
const manualEditorSuccess = ({ kbId: savedKbId }: { kbId: string; knowledgeId: string; status: 'draft' | 'publish' }) => {
|
||||
if (savedKbId === kbId.value) {
|
||||
loadKnowledgeFiles(savedKbId);
|
||||
}
|
||||
};
|
||||
|
||||
const handleManualEdit = (index: number, item: KnowledgeCard) => {
|
||||
if (cardList.value[index]) {
|
||||
cardList.value[index].isMore = false;
|
||||
}
|
||||
uiStore.openManualEditor({
|
||||
mode: 'edit',
|
||||
kbId: item.knowledge_base_id || kbId.value,
|
||||
knowledgeId: item.id,
|
||||
onSuccess: manualEditorSuccess,
|
||||
});
|
||||
};
|
||||
|
||||
const handleScroll = () => {
|
||||
const element = knowledgeScroll.value;
|
||||
if (element) {
|
||||
@@ -225,26 +260,52 @@ async function createNewSession(value: string): Promise<void> {
|
||||
<div class="card-content">
|
||||
<div class="card-content-nav">
|
||||
<span class="card-content-title">{{ item.file_name }}</span>
|
||||
<t-popup v-model="item.isMore" @overlay-click="delCard(index, item)" overlayClassName="card-more"
|
||||
<t-popup v-model="item.isMore" overlayClassName="card-more"
|
||||
:on-visible-change="onVisibleChange" trigger="click" destroy-on-close placement="bottom-right">
|
||||
<div variant="outline" class="more-wrap" @click.stop="openMore(index)"
|
||||
:class="[moreIndex == index ? 'active-more' : '']">
|
||||
<img class="more" src="@/assets/img/more.png" alt="" />
|
||||
</div>
|
||||
<template #content>
|
||||
<t-icon class="icon svg-icon del-card" name="delete" />
|
||||
<span class="del-card" style="margin-left: 8px">删除文档</span>
|
||||
<div class="card-menu">
|
||||
<div
|
||||
v-if="item.type === 'manual'"
|
||||
class="card-menu-item"
|
||||
@click.stop="handleManualEdit(index, item)"
|
||||
>
|
||||
<t-icon class="icon" name="edit" />
|
||||
<span>编辑文档</span>
|
||||
</div>
|
||||
<div
|
||||
class="card-menu-item danger"
|
||||
@click.stop="delCard(index, item)"
|
||||
>
|
||||
<t-icon class="icon" name="delete" />
|
||||
<span>删除文档</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</t-popup>
|
||||
</div>
|
||||
<div class="card-analyze" v-show="item.parse_status != 'completed'">
|
||||
<t-icon :name="item.parse_status == 'failed' ? 'close-circle' : 'loading'" class="card-analyze-loading"
|
||||
:class="[item.parse_status == 'failed' ? 'failure' : '']"></t-icon>
|
||||
<span class="card-analyze-txt" :class="[item.parse_status == 'failed' ? 'failure' : '']">{{
|
||||
item.parse_status == "failed" ? "解析失败" : "解析中..."
|
||||
}}</span>
|
||||
<div
|
||||
v-if="item.parse_status === 'processing' || item.parse_status === 'pending'"
|
||||
class="card-analyze"
|
||||
>
|
||||
<t-icon name="loading" class="card-analyze-loading"></t-icon>
|
||||
<span class="card-analyze-txt">解析中...</span>
|
||||
</div>
|
||||
<div v-show="item.parse_status == 'completed'" class="card-content-txt">
|
||||
<div
|
||||
v-else-if="item.parse_status === 'failed'"
|
||||
class="card-analyze failure"
|
||||
>
|
||||
<t-icon name="close-circle" class="card-analyze-loading failure"></t-icon>
|
||||
<span class="card-analyze-txt failure">解析失败</span>
|
||||
</div>
|
||||
<div v-else-if="item.parse_status === 'draft'" class="card-draft">
|
||||
<t-tag size="small" theme="warning" variant="light-outline">草稿</t-tag>
|
||||
<span class="card-draft-tip">暂存内容,未参与检索</span>
|
||||
</div>
|
||||
<div v-else-if="item.parse_status === 'completed'" class="card-content-txt">
|
||||
{{ item.description }}
|
||||
</div>
|
||||
</div>
|
||||
@@ -292,16 +353,13 @@ async function createNewSession(value: string): Promise<void> {
|
||||
}
|
||||
|
||||
.card-more .t-popup__content {
|
||||
width: 160px;
|
||||
height: 40px;
|
||||
line-height: 30px;
|
||||
padding-left: 14px;
|
||||
cursor: pointer;
|
||||
width: 180px;
|
||||
padding: 6px 0;
|
||||
margin-top: 4px !important;
|
||||
color: #000000e6;
|
||||
}
|
||||
.card-more .t-popup__content:hover {
|
||||
color: #FA5151 !important;
|
||||
color: inherit !important;
|
||||
}
|
||||
</style>
|
||||
<style scoped lang="less">
|
||||
@@ -435,6 +493,44 @@ async function createNewSession(value: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
.card-menu {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 140px;
|
||||
}
|
||||
|
||||
.card-menu-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
color: #000000e6;
|
||||
|
||||
&:hover {
|
||||
background: #f5f5f5;
|
||||
}
|
||||
|
||||
.icon {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
&.danger {
|
||||
color: #fa5151;
|
||||
}
|
||||
}
|
||||
|
||||
.card-draft {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px 0;
|
||||
}
|
||||
|
||||
.card-draft-tip {
|
||||
color: #b05b00;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.knowledge-card {
|
||||
border: 2px solid #fbfbfb;
|
||||
|
||||
@@ -65,6 +65,10 @@
|
||||
<div class="setting-info">
|
||||
<label>思考模型</label>
|
||||
<p class="desc">用于 Agent 推理和规划的 LLM 模型</p>
|
||||
<p class="hint-tip">
|
||||
<t-icon name="info-circle" class="tip-icon" />
|
||||
需要支持 Function call 的大尺寸模型,如 deepseek-v3.1-termius
|
||||
</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-select
|
||||
@@ -208,6 +212,15 @@
|
||||
</div>
|
||||
<div class="setting-control full-width" style="position: relative;">
|
||||
<div class="prompt-header">
|
||||
<div class="prompt-toggle">
|
||||
<span class="prompt-toggle-label">自定义 Prompt</span>
|
||||
<t-switch
|
||||
v-model="localUseCustomSystemPrompt"
|
||||
:label="['关闭', '开启']"
|
||||
size="large"
|
||||
@change="handleUseCustomPromptToggle"
|
||||
/>
|
||||
</div>
|
||||
<t-button
|
||||
theme="default"
|
||||
variant="outline"
|
||||
@@ -218,6 +231,9 @@
|
||||
恢复默认
|
||||
</t-button>
|
||||
</div>
|
||||
<p v-if="!localUseCustomSystemPrompt" class="prompt-disabled-hint">
|
||||
当前使用系统默认 Prompt,开启自定义后才会应用下方内容。
|
||||
</p>
|
||||
<div class="prompt-textarea-wrapper">
|
||||
<t-textarea
|
||||
ref="promptTextareaRef"
|
||||
@@ -227,6 +243,8 @@
|
||||
@blur="handleSystemPromptChange"
|
||||
@input="handlePromptInput"
|
||||
@keydown="handlePromptKeydown"
|
||||
:readonly="!localUseCustomSystemPrompt"
|
||||
:class="{ 'prompt-textarea-readonly': !localUseCustomSystemPrompt }"
|
||||
style="width: 100%; font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace; font-size: 13px;"
|
||||
/>
|
||||
</div>
|
||||
@@ -274,6 +292,7 @@ const localThinkingModelId = ref('')
|
||||
const localRerankModelId = ref('')
|
||||
const localAllowedTools = ref<string[]>([])
|
||||
const localSystemPrompt = ref('')
|
||||
const localUseCustomSystemPrompt = ref(false)
|
||||
|
||||
// 计算 Agent 是否就绪
|
||||
const isAgentReady = computed(() => {
|
||||
@@ -321,6 +340,7 @@ const isInitializing = ref(true) // 标记是否正在初始化,防止初始
|
||||
|
||||
// 保存的 Prompt 值,用于比较是否变化
|
||||
let savedSystemPrompt = ''
|
||||
let savedUseCustomSystemPrompt = false
|
||||
|
||||
// 恢复默认 Prompt 的加载状态
|
||||
const isResettingPrompt = ref(false)
|
||||
@@ -450,6 +470,9 @@ onMounted(async () => {
|
||||
localAllowedTools.value = config.allowed_tools || []
|
||||
localSystemPrompt.value = config.system_prompt || ''
|
||||
savedSystemPrompt = config.system_prompt || '' // 记录已保存的值
|
||||
const useCustomPrompt = config.use_custom_system_prompt ?? false
|
||||
localUseCustomSystemPrompt.value = useCustomPrompt
|
||||
savedUseCustomSystemPrompt = useCustomPrompt
|
||||
availableTools.value = config.available_tools || []
|
||||
availablePlaceholders.value = config.available_placeholders || []
|
||||
|
||||
@@ -556,14 +579,15 @@ const handleMaxIterationsChangeDebounced = (value: number) => {
|
||||
|
||||
try {
|
||||
const config: AgentConfig = {
|
||||
enabled: isAgentReady.value, // 自动根据配置状态设置
|
||||
max_iterations: numValue, // 确保是数字类型
|
||||
enabled: isAgentReady.value, // 自动根据配置状态设置
|
||||
max_iterations: numValue, // 确保是数字类型
|
||||
reflection_enabled: false,
|
||||
allowed_tools: localAllowedTools.value,
|
||||
temperature: localTemperature.value,
|
||||
thinking_model_id: localThinkingModelId.value,
|
||||
rerank_model_id: localRerankModelId.value,
|
||||
system_prompt: localSystemPrompt.value
|
||||
system_prompt: localSystemPrompt.value,
|
||||
use_custom_system_prompt: localUseCustomSystemPrompt.value
|
||||
}
|
||||
|
||||
await updateAgentConfig(config)
|
||||
@@ -627,7 +651,8 @@ const handleThinkingModelChange = async (value: string) => {
|
||||
temperature: localTemperature.value,
|
||||
thinking_model_id: value,
|
||||
rerank_model_id: localRerankModelId.value,
|
||||
system_prompt: localSystemPrompt.value
|
||||
system_prompt: localSystemPrompt.value,
|
||||
use_custom_system_prompt: localUseCustomSystemPrompt.value
|
||||
}
|
||||
|
||||
await updateAgentConfig(config)
|
||||
@@ -661,7 +686,8 @@ const handleRerankModelChange = async (value: string) => {
|
||||
temperature: localTemperature.value,
|
||||
thinking_model_id: localThinkingModelId.value,
|
||||
rerank_model_id: value,
|
||||
system_prompt: localSystemPrompt.value
|
||||
system_prompt: localSystemPrompt.value,
|
||||
use_custom_system_prompt: localUseCustomSystemPrompt.value
|
||||
}
|
||||
|
||||
await updateAgentConfig(config)
|
||||
@@ -742,7 +768,8 @@ const handleTemperatureChange = async (value: number) => {
|
||||
temperature: value,
|
||||
thinking_model_id: localThinkingModelId.value,
|
||||
rerank_model_id: localRerankModelId.value,
|
||||
system_prompt: localSystemPrompt.value
|
||||
system_prompt: localSystemPrompt.value,
|
||||
use_custom_system_prompt: localUseCustomSystemPrompt.value
|
||||
}
|
||||
|
||||
await updateAgentConfig(config)
|
||||
@@ -768,7 +795,8 @@ const handleAllowedToolsChange = async (value: string[]) => {
|
||||
temperature: localTemperature.value,
|
||||
thinking_model_id: localThinkingModelId.value,
|
||||
rerank_model_id: localRerankModelId.value,
|
||||
system_prompt: localSystemPrompt.value
|
||||
system_prompt: localSystemPrompt.value,
|
||||
use_custom_system_prompt: localUseCustomSystemPrompt.value
|
||||
}
|
||||
|
||||
await updateAgentConfig(config)
|
||||
@@ -782,6 +810,36 @@ const handleAllowedToolsChange = async (value: string[]) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 切换是否启用自定义 Prompt
|
||||
const handleUseCustomPromptToggle = async (value: boolean) => {
|
||||
if (isInitializing.value) return
|
||||
if (value === savedUseCustomSystemPrompt) return
|
||||
|
||||
try {
|
||||
const config: AgentConfig = {
|
||||
enabled: isAgentReady.value,
|
||||
max_iterations: localMaxIterations.value,
|
||||
reflection_enabled: false,
|
||||
allowed_tools: localAllowedTools.value,
|
||||
temperature: localTemperature.value,
|
||||
thinking_model_id: localThinkingModelId.value,
|
||||
rerank_model_id: localRerankModelId.value,
|
||||
system_prompt: localSystemPrompt.value,
|
||||
use_custom_system_prompt: value
|
||||
}
|
||||
|
||||
await updateAgentConfig(config)
|
||||
savedUseCustomSystemPrompt = value
|
||||
|
||||
MessagePlugin.success(value ? '已启用自定义 Prompt' : '已切换为默认 Prompt')
|
||||
} catch (error) {
|
||||
console.error('切换自定义 Prompt 失败:', error)
|
||||
MessagePlugin.error(getErrorMessage(error))
|
||||
// 回滚开关状态
|
||||
localUseCustomSystemPrompt.value = savedUseCustomSystemPrompt
|
||||
}
|
||||
}
|
||||
|
||||
// 处理系统 Prompt 键盘事件(作为备用,主要逻辑在原生事件监听器中)
|
||||
const handlePromptKeydown = (e: KeyboardEvent) => {
|
||||
// 如果正在显示占位符提示,且输入的是字母、数字或下划线,实时更新过滤
|
||||
@@ -994,7 +1052,8 @@ const handleResetToDefault = async () => {
|
||||
temperature: localTemperature.value,
|
||||
thinking_model_id: localThinkingModelId.value,
|
||||
rerank_model_id: localRerankModelId.value,
|
||||
system_prompt: '' // 空字符串表示使用默认
|
||||
system_prompt: '', // 空字符串表示使用默认
|
||||
use_custom_system_prompt: false
|
||||
}
|
||||
|
||||
await updateAgentConfig(tempConfig)
|
||||
@@ -1002,10 +1061,13 @@ const handleResetToDefault = async () => {
|
||||
// 重新加载配置以获取默认 Prompt 的完整内容
|
||||
const res = await getAgentConfig()
|
||||
const defaultPrompt = res.data.system_prompt || ''
|
||||
const useCustom = res.data.use_custom_system_prompt ?? false
|
||||
|
||||
// 设置为默认 Prompt 的内容
|
||||
localSystemPrompt.value = defaultPrompt
|
||||
savedSystemPrompt = defaultPrompt
|
||||
localUseCustomSystemPrompt.value = useCustom
|
||||
savedUseCustomSystemPrompt = useCustom
|
||||
|
||||
MessagePlugin.success('已恢复为默认 Prompt')
|
||||
confirmDialog.hide()
|
||||
@@ -1057,7 +1119,8 @@ const handleSystemPromptChange = async (e?: FocusEvent) => {
|
||||
temperature: localTemperature.value,
|
||||
thinking_model_id: localThinkingModelId.value,
|
||||
rerank_model_id: localRerankModelId.value,
|
||||
system_prompt: localSystemPrompt.value
|
||||
system_prompt: localSystemPrompt.value,
|
||||
use_custom_system_prompt: localUseCustomSystemPrompt.value
|
||||
}
|
||||
|
||||
await updateAgentConfig(config)
|
||||
@@ -1249,6 +1312,23 @@ watch(isAgentReady, (newValue, oldValue) => {
|
||||
margin: 0;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.hint-tip {
|
||||
margin: 8px 0 0 0;
|
||||
font-size: 12px;
|
||||
color: #999999;
|
||||
line-height: 1.5;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
|
||||
.tip-icon {
|
||||
font-size: 14px;
|
||||
color: #999999;
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.setting-control {
|
||||
@@ -1306,11 +1386,49 @@ watch(isAgentReady, (newValue, oldValue) => {
|
||||
|
||||
.prompt-header {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.prompt-toggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.prompt-toggle-label {
|
||||
font-size: 13px !important;
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.prompt-toggle :deep(.t-switch) {
|
||||
font-size: 0;
|
||||
}
|
||||
|
||||
.prompt-toggle :deep(.t-switch__label),
|
||||
.prompt-toggle :deep(.t-switch__content) {
|
||||
font-size: 12px !important;
|
||||
line-height: 18px;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
.prompt-toggle :deep(.t-switch__label--off),
|
||||
.prompt-toggle :deep(.t-switch__content) {
|
||||
color: #fafafa !important;
|
||||
}
|
||||
|
||||
.prompt-disabled-hint {
|
||||
margin: 0 0 8px;
|
||||
color: #666;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.prompt-textarea-readonly {
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
.prompt-textarea-wrapper {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user