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:
@@ -305,6 +305,17 @@ Reranker(重排器)是目前RAG领域中非常先进的技术,它们在工
|
||||
未知情况处理: 如果文档中没有足够的信息来回答问题,请告知“根据所掌握的资料,无法回答这个问题”
|
||||
引用要求:在回答时,如果引用了某个文档内容,请在句子末尾加上文档编号
|
||||
|
||||
---
|
||||
|
||||
## 手工知识在线编辑
|
||||
|
||||
平台的知识库页面新增“上传文档 / 在线编辑”双入口,支持直接在浏览器中撰写并维护 Markdown 知识:
|
||||
|
||||
- 草稿模式用于暂存内容,草稿不会参与检索。
|
||||
- 发布操作会自动触发向量化与索引构建。
|
||||
- 已发布的 Markdown 知识可再次打开编辑并重新发布。
|
||||
- 在对话页面的助手回答末尾提供“添加到知识库”工具,可一键带入当前问答到编辑器中确认后保存。
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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%;
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ toolchain go1.24.2
|
||||
|
||||
require (
|
||||
github.com/PuerkitoBio/goquery v1.10.3
|
||||
github.com/chromedp/chromedp v0.14.2
|
||||
github.com/elastic/go-elasticsearch/v7 v7.17.10
|
||||
github.com/elastic/go-elasticsearch/v8 v8.18.0
|
||||
github.com/gin-contrib/cors v1.7.5
|
||||
@@ -53,6 +54,8 @@ require (
|
||||
github.com/bytedance/sonic/loader v0.2.4 // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.2 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 // indirect
|
||||
github.com/chromedp/sysutil v1.1.0 // indirect
|
||||
github.com/clbanning/mxj v1.8.4 // indirect
|
||||
github.com/cloudwego/base64x v0.1.5 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
@@ -63,11 +66,15 @@ require (
|
||||
github.com/gabriel-vasile/mimetype v1.4.8 // indirect
|
||||
github.com/gin-contrib/sse v1.0.0 // indirect
|
||||
github.com/go-ini/ini v1.67.0 // indirect
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.26.0 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect
|
||||
@@ -85,7 +92,7 @@ require (
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
github.com/mailru/easyjson v0.7.7 // indirect
|
||||
github.com/mailru/easyjson v0.9.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.15 // indirect
|
||||
github.com/minio/crc64nvme v1.0.1 // indirect
|
||||
|
||||
@@ -28,6 +28,12 @@ github.com/cenkalti/backoff/v5 v5.0.2 h1:rIfFVxEf1QsI7E1ZHfp/B4DF/6QBAUhmgkxc0H7
|
||||
github.com/cenkalti/backoff/v5 v5.0.2/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327 h1:UQ4AU+BGti3Sy/aLU8KVseYKNALcX9UXY6DfpwQ6J8E=
|
||||
github.com/chromedp/cdproto v0.0.0-20250724212937-08a3db8b4327/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
|
||||
github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
|
||||
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
|
||||
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
|
||||
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
|
||||
github.com/clbanning/mxj v1.8.4 h1:HuhwZtbyvyOw+3Z1AowPkU87JkJUSv751ELWaiTpj8I=
|
||||
github.com/clbanning/mxj v1.8.4/go.mod h1:BVjHeAH+rl9rs6f+QIpeRl0tfu10SXn1pUSa5PVGJng=
|
||||
github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
|
||||
@@ -76,6 +82,8 @@ github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
|
||||
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
@@ -95,6 +103,12 @@ github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc
|
||||
github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
|
||||
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
@@ -144,7 +158,6 @@ github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g=
|
||||
github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ=
|
||||
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
@@ -158,12 +171,14 @@ github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
|
||||
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||
github.com/mailru/easyjson v0.9.0 h1:PrnmzHw7262yW8sTBwxi1PdJA3Iw/EKBa8psRf7d9a4=
|
||||
github.com/mailru/easyjson v0.9.0/go.mod h1:1+xMtQp2MRNVL/V1bOzuP3aP8VNwRW55fQUto+XFtTU=
|
||||
github.com/mark3labs/mcp-go v0.43.0 h1:lgiKcWMddh4sngbU+hoWOZ9iAe/qp/m851RQpj3Y7jA=
|
||||
github.com/mark3labs/mcp-go v0.43.0/go.mod h1:YnJfOL382MIWDx1kMY+2zsRHU/q78dBg9aFb8W6Thdw=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
@@ -202,6 +217,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
|
||||
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
|
||||
github.com/panjf2000/ants/v2 v2.11.2 h1:AVGpMSePxUNpcLaBO34xuIgM1ZdKOiGnpxLXixLi5Jo=
|
||||
github.com/panjf2000/ants/v2 v2.11.2/go.mod h1:8u92CYMUc6gyvTIw8Ru7Mt7+/ESnJahz5EVtqfrilek=
|
||||
github.com/parquet-go/parquet-go v0.25.0 h1:GwKy11MuF+al/lV6nUsFw8w8HCiPOSAx1/y8yFxjH5c=
|
||||
|
||||
@@ -577,6 +577,8 @@ func (e *AgentEngine) streamThinkingToEventBus(
|
||||
}
|
||||
logger.Debug(context.Background(), "[Agent] streamLLM opts tool_choice=auto temperature=", e.config.Temperature)
|
||||
|
||||
pendingToolCalls := make(map[string]bool)
|
||||
|
||||
// Generate a single ID for this entire thinking stream
|
||||
thinkingID := generateEventID("thinking")
|
||||
logger.Debugf(ctx, "[Agent][Thinking][Iteration-%d] ThinkingID: %s", iteration+1, thinkingID)
|
||||
@@ -586,6 +588,25 @@ func (e *AgentEngine) streamThinkingToEventBus(
|
||||
messages,
|
||||
opts,
|
||||
func(chunk *types.StreamResponse, fullContent string) {
|
||||
if chunk.ResponseType == types.ResponseTypeToolCall && chunk.Data != nil {
|
||||
toolCallID, _ := chunk.Data["tool_call_id"].(string)
|
||||
toolName, _ := chunk.Data["tool_name"].(string)
|
||||
|
||||
if toolCallID != "" && toolName != "" && !pendingToolCalls[toolCallID] {
|
||||
pendingToolCalls[toolCallID] = true
|
||||
e.eventBus.Emit(ctx, event.Event{
|
||||
ID: fmt.Sprintf("%s-tool-call-pending", toolCallID),
|
||||
Type: event.EventAgentToolCall,
|
||||
SessionID: sessionID,
|
||||
Data: event.AgentToolCallData{
|
||||
ToolCallID: toolCallID,
|
||||
ToolName: toolName,
|
||||
Iteration: iteration,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if chunk.Content != "" {
|
||||
// logger.Debugf(ctx, "[Agent][Thinking][Iteration-%d] Emitting thought chunk: %d chars",
|
||||
// iteration+1, len(chunk.Content))
|
||||
|
||||
+45
-15
@@ -3,6 +3,7 @@ package agent
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// formatFileSize formats file size in human-readable format
|
||||
@@ -23,6 +24,23 @@ func formatFileSize(size int64) string {
|
||||
return fmt.Sprintf("%.2f GB", float64(size)/GB)
|
||||
}
|
||||
|
||||
// formatDocSummary cleans and truncates document summaries for table display
|
||||
func formatDocSummary(summary string, maxLen int) string {
|
||||
cleaned := strings.TrimSpace(summary)
|
||||
if cleaned == "" {
|
||||
return "-"
|
||||
}
|
||||
cleaned = strings.ReplaceAll(cleaned, "\n", " ")
|
||||
cleaned = strings.ReplaceAll(cleaned, "\r", " ")
|
||||
cleaned = strings.Join(strings.Fields(cleaned), " ")
|
||||
|
||||
runes := []rune(cleaned)
|
||||
if len(runes) <= maxLen {
|
||||
return cleaned
|
||||
}
|
||||
return strings.TrimSpace(string(runes[:maxLen])) + "..."
|
||||
}
|
||||
|
||||
// RecentDocInfo contains brief information about a recently added document
|
||||
type RecentDocInfo struct {
|
||||
KnowledgeID string
|
||||
@@ -63,6 +81,11 @@ func AvailablePlaceholders() []PlaceholderDefinition {
|
||||
Label: "网络检索模式开关状态",
|
||||
Description: "网络检索(web_search)工具是否启用的状态说明,值为 Enabled 或 Disabled",
|
||||
},
|
||||
{
|
||||
Name: "current_time",
|
||||
Label: "当前系统时间",
|
||||
Description: "格式为 RFC3339 的当前系统时间,用于帮助模型感知实时性",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,8 +107,8 @@ func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string {
|
||||
// Display recent documents if available
|
||||
if len(kb.RecentDocs) > 0 {
|
||||
builder.WriteString(" - Recently added documents:\n\n")
|
||||
builder.WriteString(" | # | Document Name | Type | Created At | Knowledge ID | File Size |\n")
|
||||
builder.WriteString(" |---|---------------|------|------------|--------------|----------|\n")
|
||||
builder.WriteString(" | # | Document Name | Type | Created At | Knowledge ID | File Size | Summary |\n")
|
||||
builder.WriteString(" |---|---------------|------|------------|--------------|----------|---------|\n")
|
||||
for j, doc := range kb.RecentDocs {
|
||||
if j >= 10 { // Limit to 10 documents
|
||||
break
|
||||
@@ -96,8 +119,9 @@ func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string {
|
||||
}
|
||||
// Format file size
|
||||
fileSize := formatFileSize(doc.FileSize)
|
||||
builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s |\n",
|
||||
j+1, docName, doc.Type, doc.CreatedAt, doc.KnowledgeID, fileSize))
|
||||
summary := formatDocSummary(doc.Description, 120)
|
||||
builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s | %s |\n",
|
||||
j+1, docName, doc.Type, doc.CreatedAt, doc.KnowledgeID, fileSize, summary))
|
||||
}
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
@@ -125,7 +149,8 @@ func renderPromptPlaceholders(template string, knowledgeBases []*KnowledgeBaseIn
|
||||
// Supported placeholders:
|
||||
// - {{knowledge_bases}}
|
||||
// - {{web_search_status}} -> "Enabled" or "Disabled"
|
||||
func renderPromptPlaceholdersWithStatus(template string, knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool) string {
|
||||
// - {{current_time}} -> current time string
|
||||
func renderPromptPlaceholdersWithStatus(template string, knowledgeBases []*KnowledgeBaseInfo, webSearchEnabled bool, currentTime string) string {
|
||||
result := renderPromptPlaceholders(template, knowledgeBases)
|
||||
status := "Disabled"
|
||||
if webSearchEnabled {
|
||||
@@ -134,6 +159,9 @@ func renderPromptPlaceholdersWithStatus(template string, knowledgeBases []*Knowl
|
||||
if strings.Contains(result, "{{web_search_status}}") {
|
||||
result = strings.ReplaceAll(result, "{{web_search_status}}", status)
|
||||
}
|
||||
if strings.Contains(result, "{{current_time}}") {
|
||||
result = strings.ReplaceAll(result, "{{current_time}}", currentTime)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -145,7 +173,8 @@ func BuildReActSystemPromptWithStatus(knowledgeBases []*KnowledgeBaseInfo, webSe
|
||||
} else {
|
||||
template = DefaultSystemPromptTemplate
|
||||
}
|
||||
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled)
|
||||
currentTime := time.Now().Format(time.RFC3339)
|
||||
return renderPromptPlaceholdersWithStatus(template, knowledgeBases, webSearchEnabled, currentTime)
|
||||
}
|
||||
|
||||
// DefaultSystemPromptTemplate returns the default system prompt template
|
||||
@@ -165,24 +194,26 @@ Your pretraining data may be outdated or incorrect. Do NOT rely on any internal
|
||||
# Status
|
||||
|
||||
- Web Search: {{web_search_status}}
|
||||
- Current Time: {{current_time}}
|
||||
|
||||
# Rules
|
||||
|
||||
<Thinking_and_Planning>
|
||||
- Record your KB-first compliance in the thinking step: briefly list the attempted KB strategies and why they were insufficient before you switch to web_search.
|
||||
- Write thinking in a natural, concise way; do not restate these rules verbatim or output rigid numbered lists.
|
||||
- IMPORTANT: Unless the user question is trivially simple (e.g., directly confirming visible information), you MUST use the thinking tool to break down complex problems, track thinking progress iteratively, and adjust the approach when retrieved content changes or exceptions block the original workflow.
|
||||
- IMPORTANT: Record your KB-first compliance in the thinking step: briefly list the attempted KB strategies and why they were insufficient before you switch to web_search.
|
||||
- For multi-turn conversations, examine prior retrieved evidence first; if it cannot answer the new question, plan and execute fresh retrieval before responding.
|
||||
- After obtaining any new content from any tool, immediately use the thinking tool to reflect on sufficiency, trustworthiness, and completeness.
|
||||
- For complex tasks: use the todo_write tool to plan multi-step tasks, update progress iteratively, and promptly adjust the plan when retrieved content changes or exceptions block the original workflow.
|
||||
- Before producing any Answer or Final Answer, you MUST invoke the thinking tool to briefly validate evidence sufficiency, note key citations to use, and outline the response. Do not emit the Answer until this thinking step is completed.
|
||||
</Thinking_and_Planning>
|
||||
|
||||
|
||||
<KB_and_Web_Retrieval>
|
||||
- Mandatory KB-first policy: ALWAYS attempt knowledge base retrieval before any web_search (even if web_search is enabled).
|
||||
- Mandatory KB-first policy: ALWAYS attempt knowledge base retrieval before any web_search (even if web_search is enabled, or the user explicitly requests “real-time” answers).
|
||||
- Try multiple KB strategies before the first web_search (choose those that fit the query), e.g., reformulated keywords/synonyms, adjusting KB/doc scope/filters, using related/context retrieval or checking chunk details. Avoid mechanically enumerating “1), 2)” or stating counts.
|
||||
- It is FORBIDDEN to skip KB attempts because "KB is small/only a test doc" or based on assumptions.
|
||||
- Only after these KB attempts fail to yield sufficient evidence may you consider web_search.
|
||||
- Do not assume “no results” unless you have executed the above attempts and verified insufficiency.
|
||||
- Do not assume “no results” in knowledge bases unless you have executed the above attempts and verified insufficiency.
|
||||
- Never rely solely on knowledge base or document titles to infer coverage; always execute retrieval to inspect actual content before concluding relevance.
|
||||
- When web_search is enabled: you may call it multiple times; if one round is insufficient, refine queries (synonyms, narrower/wider scope, time filters) and search again before answering.
|
||||
- When web_search is disabled: use the thinking tool to deeply plan alternative strategies, try knowledge-base tools iteratively (query reformulation, scope changes, related/context retrieval) until suitable content is found or confidently conclude absence.
|
||||
</KB_and_Web_Retrieval>
|
||||
@@ -212,16 +243,15 @@ Your pretraining data may be outdated or incorrect. Do NOT rely on any internal
|
||||
- Within the Answer section (not in intermediate tool steps), place citations inline near the content they support. Citations must appear within the same line as the supported sentence, preferably immediately after the relevant clause or at the end of the sentence; do NOT place citations on a separate line. Do NOT aggregate all citations at the end of the answer.
|
||||
Include only sources actually used in the answer.
|
||||
Item formats (compact attributes for easy parsing):
|
||||
- Knowledge Base: <kb kb_id="<kb_id>" doc="<doc_name>" chunk_id="<chunk_id>" />
|
||||
- Knowledge Base: <kb doc="<doc_name>" chunk_id="<chunk_id>" />
|
||||
- Web Page: <web url="<url>" title="<title>" />
|
||||
Good Example:
|
||||
Paragraph explaining concept A... <kb kb_id="kb_123" doc="spec.md" chunk_id="c_42" />...
|
||||
Statement supported by multiple sources... <kb kb_id="kb_456" doc="design.md" chunk_id="c_7" /> <web url="https://example.com" title="Example" />
|
||||
Statement supported by multiple sources... <kb doc="design.md" chunk_id="c_7" /> <web url="https://example.com" title="Example" />
|
||||
|
||||
Bad Example:
|
||||
Paragraph explaining concept A...
|
||||
<kb kb_id="kb_123" doc="spec.md" chunk_id="c_42" />
|
||||
<kb doc="spec.md" chunk_id="c_42" />
|
||||
Paragraph summarizing current news...
|
||||
<web url="https://example.com" title="Example" />
|
||||
</Citations_and_Evidence>
|
||||
`
|
||||
|
||||
@@ -11,8 +11,8 @@ type AvailableTool struct {
|
||||
// Keep this in sync with registered tools in this package.
|
||||
func AvailableToolDefinitions() []AvailableTool {
|
||||
return []AvailableTool{
|
||||
{Name: "thinking", Label: "思考", Description: "AI 进行深度思考和推理"},
|
||||
{Name: "todo_write", Label: "制定计划", Description: "为复杂任务制定执行计划"},
|
||||
{Name: "thinking", Label: "思考", Description: "动态和反思性的问题解决思考工具"},
|
||||
{Name: "todo_write", Label: "制定计划", Description: "创建结构化的研究计划"},
|
||||
{Name: "knowledge_search", Label: "知识搜索", Description: "在知识库中搜索相关信息"},
|
||||
{Name: "get_related_chunks", Label: "获取相关片段", Description: "查找相关的知识片段"},
|
||||
{Name: "query_knowledge_graph", Label: "查询知识图谱", Description: "从知识图谱中查询关系"},
|
||||
|
||||
@@ -52,16 +52,6 @@ func NewKnowledgeSearchTool(
|
||||
- Need semantic (vector) or exact keyword searches
|
||||
- Want to search only specific documents within KBs
|
||||
|
||||
**Parameters**:
|
||||
- knowledge_base_ids (optional): Array of KB IDs to search (1-10). If omitted, searches all allowed KBs.
|
||||
- query (optional): Single search query (for simple hybrid search)
|
||||
- vector_queries (optional): Array of semantic queries for vector search (1-5 queries)
|
||||
- keyword_queries (optional): Array of keyword queries for keyword search (1-5 queries)
|
||||
- top_k (optional): Results per KB per query (default: 5, max: 20)
|
||||
- vector_threshold (optional): Minimum score for vector results (default: 0.6, 0.0-1.0)
|
||||
- keyword_threshold (optional): Minimum score for keyword results (default: 0.5, 0.0-1.0)
|
||||
- knowledge_ids (optional): Array of document IDs to filter results (only return results from these documents)
|
||||
- min_score (optional): Absolute minimum score to include results (default: 0.3, filters very low quality chunks)
|
||||
|
||||
**Search Modes**:
|
||||
- Simple: Provide single query parameter (hybrid search)
|
||||
@@ -110,11 +100,7 @@ func NewKnowledgeSearchTool(
|
||||
- Reranked scores are in 0-1 range and directly comparable
|
||||
- Results are merged, deduplicated and sorted by relevance
|
||||
- Use vector_queries for semantic/conceptual searches
|
||||
- Use keyword_queries for exact term matching
|
||||
- Results below threshold are automatically filtered
|
||||
- High relevance (>=0.8): directly usable
|
||||
- Medium relevance (0.6-0.8): reference only
|
||||
- Low relevance (<0.6): use with caution`
|
||||
- Use keyword_queries for exact term matching`
|
||||
|
||||
return &KnowledgeSearchTool{
|
||||
BaseTool: NewBaseTool("knowledge_search", description),
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// SequentialThinkingTool implements a dynamic and reflective problem-solving tool
|
||||
// This tool helps analyze problems through a flexible thinking process that can adapt and evolve
|
||||
type SequentialThinkingTool struct {
|
||||
BaseTool
|
||||
thoughtHistory []ThoughtData
|
||||
branches map[string][]ThoughtData
|
||||
}
|
||||
|
||||
// ThoughtData represents a single thought in the sequential thinking process
|
||||
type ThoughtData struct {
|
||||
Thought string `json:"thought"`
|
||||
ThoughtNumber int `json:"thought_number"`
|
||||
TotalThoughts int `json:"total_thoughts"`
|
||||
IsRevision bool `json:"is_revision,omitempty"`
|
||||
RevisesThought *int `json:"revises_thought,omitempty"`
|
||||
BranchFromThought *int `json:"branch_from_thought,omitempty"`
|
||||
BranchID string `json:"branch_id,omitempty"`
|
||||
NeedsMoreThoughts bool `json:"needs_more_thoughts,omitempty"`
|
||||
NextThoughtNeeded bool `json:"next_thought_needed"`
|
||||
}
|
||||
|
||||
// NewSequentialThinkingTool creates a new sequential thinking tool instance
|
||||
func NewSequentialThinkingTool() *SequentialThinkingTool {
|
||||
description := `A detailed tool for dynamic and reflective problem-solving through thoughts.
|
||||
|
||||
This tool helps analyze problems through a flexible thinking process that can adapt and evolve.
|
||||
|
||||
Each thought can build on, question, or revise previous insights as understanding deepens.
|
||||
|
||||
## When to Use This Tool
|
||||
|
||||
- Breaking down complex problems into steps
|
||||
- Planning and design with room for revision
|
||||
- Analysis that might need course correction
|
||||
- Problems where the full scope might not be clear initially
|
||||
- Problems that require a multi-step solution
|
||||
- Tasks that need to maintain context over multiple steps
|
||||
- Situations where irrelevant information needs to be filtered out
|
||||
|
||||
## Key Features
|
||||
|
||||
- You can adjust total_thoughts up or down as you progress
|
||||
- You can question or revise previous thoughts
|
||||
- You can add more thoughts even after reaching what seemed like the end
|
||||
- You can express uncertainty and explore alternative approaches
|
||||
- Not every thought needs to build linearly - you can branch or backtrack
|
||||
- Generates a solution hypothesis
|
||||
- Verifies the hypothesis based on the Chain of Thought steps
|
||||
- Repeats the process until satisfied
|
||||
- Provides a correct answer
|
||||
|
||||
## Parameters Explained
|
||||
|
||||
- **thought**: Your current thinking step, which can include:
|
||||
* Regular analytical steps
|
||||
* Revisions of previous thoughts
|
||||
* Questions about previous decisions
|
||||
* Realizations about needing more analysis
|
||||
* Changes in approach
|
||||
* Hypothesis generation
|
||||
* Hypothesis verification
|
||||
|
||||
- **next_thought_needed**: True if you need more thinking, even if at what seemed like the end
|
||||
- **thought_number**: Current number in sequence (can go beyond initial total if needed)
|
||||
- **total_thoughts**: Current estimate of thoughts needed (can be adjusted up/down)
|
||||
- **is_revision**: A boolean indicating if this thought revises previous thinking
|
||||
- **revises_thought**: If is_revision is true, which thought number is being reconsidered
|
||||
- **branch_from_thought**: If branching, which thought number is the branching point
|
||||
- **branch_id**: Identifier for the current branch (if any)
|
||||
- **needs_more_thoughts**: If reaching end but realizing more thoughts needed
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. Start with an initial estimate of needed thoughts, but be ready to adjust
|
||||
2. Feel free to question or revise previous thoughts
|
||||
3. Don't hesitate to add more thoughts if needed, even at the "end"
|
||||
4. Express uncertainty when present
|
||||
5. Mark thoughts that revise previous thinking or branch into new paths
|
||||
6. Ignore information that is irrelevant to the current step
|
||||
7. Generate a solution hypothesis when appropriate
|
||||
8. Verify the hypothesis based on the Chain of Thought steps
|
||||
9. Repeat the process until satisfied with the solution
|
||||
10. Provide a single, ideally correct answer as the final output
|
||||
11. Only set next_thought_needed to false when truly done and a satisfactory answer is reached`
|
||||
|
||||
return &SequentialThinkingTool{
|
||||
BaseTool: NewBaseTool("thinking", description),
|
||||
thoughtHistory: make([]ThoughtData, 0),
|
||||
branches: make(map[string][]ThoughtData),
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters returns the JSON schema for the tool's parameters
|
||||
func (t *SequentialThinkingTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"thought": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Your current thinking step",
|
||||
},
|
||||
"nextThoughtNeeded": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
"description": "Whether another thought step is needed",
|
||||
},
|
||||
"thoughtNumber": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Current thought number (numeric value, e.g., 1, 2, 3)",
|
||||
"minimum": 1,
|
||||
},
|
||||
"totalThoughts": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Estimated total thoughts needed (numeric value, e.g., 5, 10)",
|
||||
"minimum": 1,
|
||||
},
|
||||
"isRevision": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
"description": "Whether this revises previous thinking",
|
||||
},
|
||||
"revisesThought": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Which thought is being reconsidered",
|
||||
"minimum": 1,
|
||||
},
|
||||
"branchFromThought": map[string]interface{}{
|
||||
"type": "integer",
|
||||
"description": "Branching point thought number",
|
||||
"minimum": 1,
|
||||
},
|
||||
"branchId": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Branch identifier",
|
||||
},
|
||||
"needsMoreThoughts": map[string]interface{}{
|
||||
"type": "boolean",
|
||||
"description": "If more thoughts are needed",
|
||||
},
|
||||
},
|
||||
"required": []string{"thought", "nextThoughtNeeded", "thoughtNumber", "totalThoughts"},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute executes the sequential thinking tool
|
||||
func (t *SequentialThinkingTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
logger.Infof(ctx, "[Tool][SequentialThinking] Execute started")
|
||||
|
||||
// Validate and parse input
|
||||
thoughtData, err := t.validateThoughtData(args)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][SequentialThinking] Validation failed: %v", err)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: fmt.Sprintf("Validation failed: %v", err),
|
||||
}, err
|
||||
}
|
||||
|
||||
// Adjust totalThoughts if thoughtNumber exceeds it
|
||||
if thoughtData.ThoughtNumber > thoughtData.TotalThoughts {
|
||||
thoughtData.TotalThoughts = thoughtData.ThoughtNumber
|
||||
}
|
||||
|
||||
// Add to thought history
|
||||
t.thoughtHistory = append(t.thoughtHistory, thoughtData)
|
||||
|
||||
// Handle branching
|
||||
if thoughtData.BranchFromThought != nil && thoughtData.BranchID != "" {
|
||||
if t.branches[thoughtData.BranchID] == nil {
|
||||
t.branches[thoughtData.BranchID] = make([]ThoughtData, 0)
|
||||
}
|
||||
t.branches[thoughtData.BranchID] = append(t.branches[thoughtData.BranchID], thoughtData)
|
||||
}
|
||||
|
||||
logger.Debugf(ctx, "[Tool][SequentialThinking] %s", thoughtData.Thought)
|
||||
|
||||
// Prepare response data
|
||||
branchKeys := make([]string, 0, len(t.branches))
|
||||
for k := range t.branches {
|
||||
branchKeys = append(branchKeys, k)
|
||||
}
|
||||
|
||||
responseData := map[string]interface{}{
|
||||
"thought_number": thoughtData.ThoughtNumber,
|
||||
"total_thoughts": thoughtData.TotalThoughts,
|
||||
"next_thought_needed": thoughtData.NextThoughtNeeded,
|
||||
"branches": branchKeys,
|
||||
"thought_history_length": len(t.thoughtHistory),
|
||||
"display_type": "thinking",
|
||||
"thought": thoughtData.Thought,
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][SequentialThinking] Execute completed - Thought %d/%d", thoughtData.ThoughtNumber, thoughtData.TotalThoughts)
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: "Thought process recorded",
|
||||
Data: responseData,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// validateThoughtData validates and parses the input arguments
|
||||
func (t *SequentialThinkingTool) validateThoughtData(input map[string]interface{}) (ThoughtData, error) {
|
||||
var data ThoughtData
|
||||
|
||||
// Validate thought (required)
|
||||
thought, ok := input["thought"].(string)
|
||||
if !ok || thought == "" {
|
||||
return data, fmt.Errorf("invalid thought: must be a non-empty string")
|
||||
}
|
||||
data.Thought = thought
|
||||
|
||||
// Validate thoughtNumber (required)
|
||||
thoughtNumber, ok := input["thoughtNumber"].(float64)
|
||||
if !ok {
|
||||
// Try int type
|
||||
if num, ok := input["thoughtNumber"].(int); ok {
|
||||
data.ThoughtNumber = num
|
||||
} else {
|
||||
return data, fmt.Errorf("invalid thoughtNumber: must be a number")
|
||||
}
|
||||
} else {
|
||||
data.ThoughtNumber = int(thoughtNumber)
|
||||
}
|
||||
if data.ThoughtNumber < 1 {
|
||||
return data, fmt.Errorf("invalid thoughtNumber: must be >= 1")
|
||||
}
|
||||
|
||||
// Validate totalThoughts (required)
|
||||
totalThoughts, ok := input["totalThoughts"].(float64)
|
||||
if !ok {
|
||||
// Try int type
|
||||
if num, ok := input["totalThoughts"].(int); ok {
|
||||
data.TotalThoughts = num
|
||||
} else {
|
||||
return data, fmt.Errorf("invalid totalThoughts: must be a number")
|
||||
}
|
||||
} else {
|
||||
data.TotalThoughts = int(totalThoughts)
|
||||
}
|
||||
if data.TotalThoughts < 1 {
|
||||
return data, fmt.Errorf("invalid totalThoughts: must be >= 1")
|
||||
}
|
||||
|
||||
// Validate nextThoughtNeeded (required)
|
||||
nextThoughtNeeded, ok := input["nextThoughtNeeded"].(bool)
|
||||
if !ok {
|
||||
return data, fmt.Errorf("invalid nextThoughtNeeded: must be a boolean")
|
||||
}
|
||||
data.NextThoughtNeeded = nextThoughtNeeded
|
||||
|
||||
// Optional fields
|
||||
if isRevision, ok := input["isRevision"].(bool); ok {
|
||||
data.IsRevision = isRevision
|
||||
}
|
||||
|
||||
if revisesThought, ok := input["revisesThought"].(float64); ok {
|
||||
num := int(revisesThought)
|
||||
data.RevisesThought = &num
|
||||
} else if revisesThought, ok := input["revisesThought"].(int); ok {
|
||||
data.RevisesThought = &revisesThought
|
||||
}
|
||||
|
||||
if branchFromThought, ok := input["branchFromThought"].(float64); ok {
|
||||
num := int(branchFromThought)
|
||||
data.BranchFromThought = &num
|
||||
} else if branchFromThought, ok := input["branchFromThought"].(int); ok {
|
||||
data.BranchFromThought = &branchFromThought
|
||||
}
|
||||
|
||||
if branchID, ok := input["branchId"].(string); ok {
|
||||
data.BranchID = branchID
|
||||
}
|
||||
|
||||
if needsMoreThoughts, ok := input["needsMoreThoughts"].(bool); ok {
|
||||
data.NeedsMoreThoughts = needsMoreThoughts
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
@@ -1,115 +0,0 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// ThinkingTool implements the thinking tool functionality
|
||||
// This is a no-op tool inspired by code-agent and tau-bench
|
||||
// It logs thoughts for transparency and better decision-making
|
||||
type ThinkingTool struct {
|
||||
BaseTool
|
||||
}
|
||||
|
||||
// NewThinkingTool creates a new thinking tool instance
|
||||
func NewThinkingTool() *ThinkingTool {
|
||||
description := `Deep reasoning tool for systematic thinking. Use this frequently to analyze, plan, and reflect.
|
||||
|
||||
## Purpose
|
||||
|
||||
This tool helps you:
|
||||
- **Analyze problems** before acting
|
||||
- **Plan your approach** for complex tasks
|
||||
- **Evaluate results** after tool calls
|
||||
- **Reflect** on strategy and adjust
|
||||
|
||||
This is a no-op tool - it doesn't fetch data, but helps organize your reasoning transparently.
|
||||
|
||||
## When to Use
|
||||
|
||||
**Use frequently at key moments**:
|
||||
- **Start**: Analyze the question, understand what's needed
|
||||
- **Before major decisions**: Which tool to use? What query to run?
|
||||
- **After tool calls**: Evaluate results, decide next step
|
||||
- **Before answering**: Organize information, check completeness
|
||||
|
||||
## What to Think About
|
||||
|
||||
### At Start
|
||||
- What is the user really asking?
|
||||
- What information do I need?
|
||||
- What's my search strategy?
|
||||
|
||||
### After Search Results
|
||||
- Are results relevant? Complete?
|
||||
- Do I need more context (get_related_chunks)?
|
||||
- Should I search more or answer now?
|
||||
|
||||
### Before Answering
|
||||
- Do I have enough information?
|
||||
- Are all sources cited?
|
||||
- Is the structure clear?
|
||||
|
||||
|
||||
## Tips
|
||||
|
||||
- Use before important decisions
|
||||
- Keep thoughts focused and actionable
|
||||
- End with clear next step
|
||||
- Don't overthink simple queries`
|
||||
|
||||
return &ThinkingTool{
|
||||
BaseTool: NewBaseTool(
|
||||
"thinking",
|
||||
description,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters returns the JSON schema for the tool's parameters
|
||||
func (t *ThinkingTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"thought": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "Your thinking process and reasoning content",
|
||||
},
|
||||
},
|
||||
"required": []string{"thought"},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute executes the thinking tool
|
||||
func (t *ThinkingTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
logger.Infof(ctx, "[Tool][Thinking] Execute started")
|
||||
|
||||
thought, ok := args["thought"].(string)
|
||||
if !ok {
|
||||
thought = "Thought content not provided"
|
||||
logger.Warnf(ctx, "[Tool][Thinking] No thought content provided")
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][Thinking] Thought length: %d characters", len(thought))
|
||||
logger.Debugf(ctx, "[Tool][Thinking] Thought content:\n%s", thought)
|
||||
|
||||
// This is a no-op tool - it just logs the thought
|
||||
// The thought itself is valuable for transparency and decision-making
|
||||
|
||||
// Format output for better display
|
||||
output := "Thought process recorded:\n\n"
|
||||
output += thought
|
||||
|
||||
logger.Infof(ctx, "[Tool][Thinking] Execute completed")
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: output,
|
||||
Data: map[string]interface{}{
|
||||
"thought": thought,
|
||||
"display_type": "thinking",
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
@@ -25,172 +25,121 @@ type PlanStep struct {
|
||||
|
||||
// NewTodoWriteTool creates a new todo_write tool instance
|
||||
func NewTodoWriteTool() *TodoWriteTool {
|
||||
description := `Use this tool to create a structured, actionable plan for complex research tasks. This helps you organize multi-step investigations, track progress, and ensure comprehensive coverage.
|
||||
|
||||
## Critical Thinking Integration
|
||||
**IMPORTANT**: When working with complex research questions, you should typically use the **think tool** for deep analysis BEFORE creating your plan. This ensures:
|
||||
|
||||
- **Problem Analysis**: Use think tool to analyze the research question, identify key dimensions, and explore different angles
|
||||
- **Strategic Planning**: Use think tool to consider what information is needed, which knowledge bases to search, and potential challenges
|
||||
- **Scope Definition**: Use think tool to determine the depth and breadth of research required
|
||||
|
||||
The think tool helps ensure your plan is comprehensive, well-structured, and addresses all aspects of the research question effectively.
|
||||
description := `Use this tool to create and manage a structured task list for your current coding session. This helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
|
||||
It also helps the user understand the progress of the task and overall progress of their requests.
|
||||
|
||||
## When to Use This Tool
|
||||
|
||||
Use this tool proactively in these scenarios:
|
||||
|
||||
1. **Complex multi-dimensional questions** - Questions requiring investigation of multiple aspects or dimensions
|
||||
2. **Comparison tasks** - When you need to compare multiple systems, approaches, or solutions systematically
|
||||
3. **Deep research tasks** - Questions requiring exploration of multiple knowledge areas or documents
|
||||
4. **Architecture analysis** - Tasks involving system design, architecture review, or technical deep-dives
|
||||
5. **User requests explicit planning** - When users ask for structured analysis or step-by-step investigation
|
||||
1. Complex multi-step tasks - When a task requires 3 or more distinct steps or actions
|
||||
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
|
||||
3. User explicitly requests todo list - When the user directly asks you to use the todo list
|
||||
4. User provides multiple tasks - When users provide a list of things to be done (numbered or comma-separated)
|
||||
5. After receiving new instructions - Immediately capture user requirements as todos
|
||||
6. When you start working on a task - Mark it as in_progress BEFORE beginning work. Ideally you should only have one todo as in_progress at a time
|
||||
7. After completing a task - Mark it as completed and add any new follow-up tasks discovered during implementation
|
||||
|
||||
## When NOT to Use This Tool
|
||||
|
||||
Skip using this tool when:
|
||||
1. There is only a single, straightforward task
|
||||
2. The task is trivial and tracking it provides no organizational benefit
|
||||
3. The task is purely conversational or informational
|
||||
|
||||
1. **Simple, direct queries** - Questions with straightforward answers (e.g., "What is a vector database?")
|
||||
2. **Single-step searches** - When you already know exactly what to search for
|
||||
3. **Mid-execution** - Don't create plans after you've already started searching
|
||||
4. **Trivial lookups** - Simple fact-finding that requires one tool call
|
||||
NOTE that you should not use this tool if there is only one trivial task to do. In this case you are better off just doing the task directly.
|
||||
|
||||
NOTE: If the question can be answered with 1-2 simple searches, skip planning and search directly.
|
||||
|
||||
## Examples of When to Use
|
||||
## Examples of When to Use the Todo List
|
||||
|
||||
<example>
|
||||
User: "如何设计一个高可用的微服务架构?需要考虑哪些方面?"
|
||||
Assistant: This is a complex, multi-dimensional question. Let me first think through the key aspects and then create a structured research plan.
|
||||
*Uses think tool to analyze: architecture patterns, reliability concerns, deployment strategies, monitoring needs*
|
||||
Assistant: Based on my analysis, let me create a research plan covering the main dimensions.
|
||||
*Creates plan with steps for:*
|
||||
1. Search microservices architecture patterns and best practices
|
||||
2. Investigate high availability strategies (load balancing, failover, redundancy)
|
||||
3. Research service mesh and communication patterns
|
||||
4. Explore monitoring and observability solutions
|
||||
5. Investigate deployment and scaling strategies
|
||||
*Begins executing the plan*
|
||||
User: I need to implement these features for my e-commerce site: user registration, product catalog, shopping cart, and checkout flow.
|
||||
Assistant: I'll help implement these features for your e-commerce site. Let me first think through the architecture and dependencies between these features to create an optimal implementation plan.
|
||||
*Uses think tool to analyze the e-commerce architecture, identify dependencies between features (user auth needed for cart, catalog needed for checkout), consider database design, security requirements, and implementation order*
|
||||
Assistant: After analyzing the system architecture and feature dependencies, let me create a strategic todo list that accounts for the interconnected nature of these features.
|
||||
*Creates a todo list breaking down each feature into specific tasks based on the project architecture and dependencies*
|
||||
Assistant: Let's start with user registration since it's foundational for the shopping cart and checkout features. This will involve creating database models, API endpoints, and frontend forms that integrate with your existing authentication system.
|
||||
|
||||
<reasoning>
|
||||
The assistant used both think and todo_write tools because:
|
||||
1. First used think tool to analyze the multi-dimensional nature of the question
|
||||
2. Identified key areas: architecture, availability, communication, monitoring, deployment
|
||||
3. Created a structured plan to ensure systematic coverage
|
||||
4. The plan helps avoid missing critical aspects of high availability
|
||||
1. First used think tool to analyze the complex e-commerce architecture and feature dependencies
|
||||
2. Considered the interconnected nature of features (user auth → cart → checkout)
|
||||
3. Analyzed security requirements, database design, and optimal implementation order
|
||||
4. Then created a strategic todo list that accounts for these dependencies
|
||||
5. This approach ensures features are implemented in the correct order with proper foundations
|
||||
</reasoning>
|
||||
</example>
|
||||
|
||||
<example>
|
||||
User: "对比Redis、Memcached和Hazelcast这三种缓存系统的性能、成本和适用场景"
|
||||
Assistant: This is a structured comparison task. Let me think through the comparison dimensions and create a systematic research plan.
|
||||
*Uses think tool to identify: performance metrics, cost factors, use case categories, comparison criteria*
|
||||
Assistant: I'll create a research plan to ensure fair, comprehensive comparison across all three systems.
|
||||
*Creates plan with steps:*
|
||||
1. Search Redis characteristics (performance, features, use cases)
|
||||
2. Search Memcached characteristics (performance, features, use cases)
|
||||
3. Search Hazelcast characteristics (performance, features, use cases)
|
||||
4. Search direct performance comparisons between these systems
|
||||
5. Investigate cost considerations and deployment complexity
|
||||
*Executes searches systematically*
|
||||
User: Can you help optimize my React application? It's rendering slowly and has performance issues.</user>
|
||||
Assistant: I'll help optimize your React application. First, let me examine your codebase to identify potential performance bottlenecks.
|
||||
*Reviews component structure, render patterns, state management, and data fetching*
|
||||
Assistant: After analyzing your codebase, I've identified several performance issues. Let me create a todo list to track our optimization efforts.
|
||||
*Creates todo list with items like: 1) Implement memoization for expensive calculations in ProductList, 2) Add virtualization for long lists in Dashboard, 3) Optimize image loading in Gallery component, 4) Fix state update loops in ShoppingCart, 5) Review bundle size and implement code splitting*
|
||||
Let's start by implementing memoization for the expensive calculations in your ProductList component.</assistant>
|
||||
|
||||
<reasoning>
|
||||
The assistant used todo_write because:
|
||||
1. Comparison tasks benefit from structured, parallel research
|
||||
2. The plan ensures each system is investigated equally
|
||||
3. Structured approach prevents bias toward any particular system
|
||||
4. Makes it easier to synthesize structured comparison at the end
|
||||
The assistant used the todo list because:
|
||||
1. First, the assistant examined the codebase to identify specific performance issues
|
||||
2. Based on this analysis, it identified multiple optimization opportunities
|
||||
3. Performance optimization is a non-trivial task requiring multiple steps
|
||||
4. The todo list helps methodically track improvements across different components
|
||||
5. This systematic approach ensures all performance bottlenecks are addressed
|
||||
</reasoning>
|
||||
</example>
|
||||
|
||||
## Examples of When NOT to Use
|
||||
## Examples of When NOT to Use the Todo List
|
||||
|
||||
<example>
|
||||
User: "向量数据库的主要用途是什么?"
|
||||
Assistant: Let me search for information about vector database use cases.
|
||||
*Uses knowledge_search directly without planning*
|
||||
User: How do I print 'Hello World' in Python?
|
||||
Assistant: In Python, you can print "Hello World" with this simple code:
|
||||
|
||||
print("Hello World")
|
||||
|
||||
This will output the text "Hello World" to the console when executed.</assistant>
|
||||
|
||||
<reasoning>
|
||||
The assistant skipped todo_write because:
|
||||
1. This is a simple, direct question
|
||||
2. One well-crafted search will likely provide the answer
|
||||
3. No need to organize multiple research steps
|
||||
4. Planning would add unnecessary overhead
|
||||
The assistant did not use the todo list because this is a single, trivial task that can be completed in one step. There's no need to track multiple tasks or steps for such a straightforward request.
|
||||
</reasoning>
|
||||
</example>
|
||||
|
||||
<example>
|
||||
User: "Kubernetes是什么?"
|
||||
Assistant: Let me search for information about Kubernetes.
|
||||
*Uses knowledge_search directly*
|
||||
User: What does the git status command do?
|
||||
Assistant: The git status command shows the current state of your working directory and staging area. It displays which changes have been staged, which haven't, and which files aren't being tracked by Git. This is a fundamental command for understanding the current state of your repository before making commits.
|
||||
|
||||
<reasoning>
|
||||
Simple definitional question - just search directly without planning.
|
||||
The assistant did not use the todo list because this is an informational request with no actual coding task to complete. The user is simply asking for an explanation, not for the assistant to perform multiple steps or tasks.
|
||||
</reasoning>
|
||||
</example>
|
||||
|
||||
## Standard Workflow
|
||||
## Task States and Management
|
||||
|
||||
The recommended workflow when using this tool:
|
||||
1. **Task States**: Use these states to track progress:
|
||||
- pending: Task not yet started
|
||||
- in_progress: Currently working on (limit to ONE task at a time)
|
||||
- completed: Task finished successfully
|
||||
|
||||
` + "```" + `
|
||||
Step 1: User asks complex question
|
||||
↓
|
||||
Step 2: Use think tool (analyze problem, identify dimensions, consider approaches)
|
||||
↓
|
||||
Step 3: Use todo_write tool (create structured plan with steps, tools, priorities) [OPTIONAL]
|
||||
↓
|
||||
Step 4: Execute plan steps (use search tools, mark progress)
|
||||
↓
|
||||
Step 5: Use think tool (evaluate results, identify gaps)
|
||||
↓
|
||||
Step 6: Adjust plan or execute remaining steps
|
||||
↓
|
||||
Step 7: Synthesize comprehensive answer with citations
|
||||
` + "```" + `
|
||||
2. **Task Management**:
|
||||
- Update task status in real-time as you work
|
||||
- Mark tasks complete IMMEDIATELY after finishing (don't batch completions)
|
||||
- Only have ONE task in_progress at any time
|
||||
- Complete current tasks before starting new ones
|
||||
- Remove tasks that are no longer relevant from the list entirely
|
||||
|
||||
## Plan Structure
|
||||
3. **Task Completion Requirements**:
|
||||
- ONLY mark a task as completed when you have FULLY accomplished it
|
||||
- If you encounter errors, blockers, or cannot finish, keep the task as in_progress
|
||||
- When blocked, create a new task describing what needs to be resolved
|
||||
- Never mark a task as completed if:
|
||||
- Tests are failing
|
||||
- Implementation is partial
|
||||
- You encountered unresolved errors
|
||||
- You couldn't find necessary files or dependencies
|
||||
|
||||
Your plan should include steps with:
|
||||
- **ID**: Unique identifier for each step (e.g., "step1", "step2")
|
||||
- **Description**: Clear description of what to investigate
|
||||
- **Tools to Use**: Which tools to use (e.g., "knowledge_search", "get_related_chunks")
|
||||
- **Status**: Current status (pending, in_progress, completed, skipped)
|
||||
4. **Task Breakdown**:
|
||||
- Create specific, actionable items
|
||||
- Break complex tasks into smaller, manageable steps
|
||||
- Use clear, descriptive task names
|
||||
|
||||
## Step Status Management
|
||||
|
||||
1. **Status Values**:
|
||||
- **pending**: Step not yet started (default for new steps)
|
||||
- **in_progress**: Currently executing this step
|
||||
- **completed**: Step finished successfully with results
|
||||
- **skipped**: Step determined to be unnecessary based on findings
|
||||
|
||||
2. **Status Management Best Practices**:
|
||||
- Start with all steps as "pending"
|
||||
- Mark one step as "in_progress" before executing it
|
||||
- Update to "completed" immediately after finishing
|
||||
- Mark as "skipped" if findings make a step unnecessary
|
||||
|
||||
## Parameters
|
||||
|
||||
- **task** (required): The complex task or question you need to create a plan for
|
||||
- Be specific about what needs to be accomplished
|
||||
- Include the user's actual question or research goal
|
||||
|
||||
- **steps** (required): Array of plan steps, each containing:
|
||||
- **id**: Unique identifier (e.g., "step1", "step2")
|
||||
- **description**: What to investigate or accomplish
|
||||
- **tools_to_use**: Suggested tools for this step
|
||||
- **status**: Current status (pending, in_progress, completed, skipped)
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Think First**: Always use think tool before creating a plan to ensure thorough analysis
|
||||
2. **Be Specific**: Each step should have a clear, actionable objective
|
||||
3. **Stay Flexible**: Adjust the plan based on findings - some steps may become unnecessary
|
||||
4. **Track Progress**: Update step status as you work through the plan
|
||||
5. **Don't Over-plan**: 3-7 steps is usually sufficient; more suggests over-complexity
|
||||
`
|
||||
When in doubt, use this tool. Being proactive with task management demonstrates attentiveness and ensures you complete all requirements successfully.`
|
||||
|
||||
return &TodoWriteTool{
|
||||
BaseTool: NewBaseTool("todo_write", description),
|
||||
@@ -229,8 +178,8 @@ func (t *TodoWriteTool) Parameters() map[string]interface{} {
|
||||
},
|
||||
"status": map[string]interface{}{
|
||||
"type": "string",
|
||||
"enum": []string{"pending", "in_progress", "completed", "skipped"},
|
||||
"description": "Current status: pending (not started), in_progress (executing), completed (finished), skipped (unnecessary)",
|
||||
"enum": []string{"pending", "in_progress", "completed"},
|
||||
"description": "Current status: pending (not started), in_progress (executing), completed (finished)",
|
||||
},
|
||||
},
|
||||
"required": []string{"id", "description", "status"},
|
||||
|
||||
@@ -0,0 +1,564 @@
|
||||
package tools
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/PuerkitoBio/goquery"
|
||||
"github.com/chromedp/chromedp"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
const (
|
||||
webFetchTimeout = 60 * time.Second
|
||||
webFetchMaxChars = 100000
|
||||
)
|
||||
|
||||
type webFetchParams struct {
|
||||
URL string
|
||||
Prompt string
|
||||
}
|
||||
|
||||
type webFetchItemResult struct {
|
||||
output string
|
||||
data map[string]interface{}
|
||||
err error
|
||||
}
|
||||
|
||||
// WebFetchTool 拉取网页内容并根据提示执行总结
|
||||
type WebFetchTool struct {
|
||||
BaseTool
|
||||
client *http.Client
|
||||
chatModel chat.Chat
|
||||
}
|
||||
|
||||
// NewWebFetchTool 创建 web_fetch 工具实例
|
||||
func NewWebFetchTool(chatModel chat.Chat) *WebFetchTool {
|
||||
description := `Fetch web content from previously discovered URLs and analyze it with an LLM.
|
||||
|
||||
## 流程
|
||||
- 接收一个或多个 {url, prompt} 组合
|
||||
- 抓取网页内容并转换为 Markdown 文本
|
||||
- 使用提示词调用小模型进行分析与总结(若模型可用)
|
||||
- 返回总结结果与原始内容片段
|
||||
|
||||
## 使用场景
|
||||
- 对 web_search 返回的链接做进一步深入阅读
|
||||
- 从网页中提取结构化信息或关键信息
|
||||
|
||||
## 参数
|
||||
- items (必填): 数组,元素为 { "url": "...", "prompt": "..." }
|
||||
`
|
||||
|
||||
return &WebFetchTool{
|
||||
BaseTool: NewBaseTool("web_fetch", description),
|
||||
client: &http.Client{
|
||||
Timeout: webFetchTimeout,
|
||||
},
|
||||
chatModel: chatModel,
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters 返回工具参数的 JSON Schema
|
||||
func (t *WebFetchTool) Parameters() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"items": map[string]interface{}{
|
||||
"type": "array",
|
||||
"description": "批量抓取任务,每项包含 url 与 prompt",
|
||||
"items": map[string]interface{}{
|
||||
"type": "object",
|
||||
"properties": map[string]interface{}{
|
||||
"url": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "待抓取的网页 URL,需来自 web_search 结果",
|
||||
},
|
||||
"prompt": map[string]interface{}{
|
||||
"type": "string",
|
||||
"description": "分析该网页内容时使用的提示词",
|
||||
},
|
||||
},
|
||||
"required": []string{"url", "prompt"},
|
||||
},
|
||||
"minItems": 1,
|
||||
},
|
||||
},
|
||||
"required": []string{"items"},
|
||||
}
|
||||
}
|
||||
|
||||
// Execute 执行 web_fetch 工具
|
||||
func (t *WebFetchTool) Execute(ctx context.Context, args map[string]interface{}) (*types.ToolResult, error) {
|
||||
logger.Infof(ctx, "[Tool][WebFetch] Execute started")
|
||||
|
||||
rawItems, ok := args["items"]
|
||||
if !ok {
|
||||
logger.Errorf(ctx, "[Tool][WebFetch] 参数缺失: items")
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "missing required parameter: items",
|
||||
}, nil
|
||||
}
|
||||
|
||||
itemsSlice, ok := rawItems.([]interface{})
|
||||
if !ok || len(itemsSlice) == 0 {
|
||||
logger.Errorf(ctx, "[Tool][WebFetch] items 解析失败或为空: %#v", rawItems)
|
||||
return &types.ToolResult{
|
||||
Success: false,
|
||||
Error: "'items' must be a non-empty array",
|
||||
}, nil
|
||||
}
|
||||
|
||||
results := make([]*webFetchItemResult, len(itemsSlice))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(len(itemsSlice))
|
||||
|
||||
for idx := range itemsSlice {
|
||||
i := idx
|
||||
itemAny := itemsSlice[i]
|
||||
|
||||
params := t.parseParams(itemAny)
|
||||
|
||||
go func(index int, p webFetchParams) {
|
||||
defer wg.Done()
|
||||
|
||||
if err := t.validateParams(p); err != nil {
|
||||
results[index] = &webFetchItemResult{
|
||||
err: err,
|
||||
data: map[string]interface{}{
|
||||
"url": p.URL,
|
||||
"prompt": p.Prompt,
|
||||
"error": err.Error(),
|
||||
},
|
||||
output: fmt.Sprintf("URL: %s\n错误: %v\n\n", p.URL, err),
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
output, data, err := t.executeFetch(ctx, p)
|
||||
results[index] = &webFetchItemResult{
|
||||
output: output,
|
||||
data: data,
|
||||
err: err,
|
||||
}
|
||||
}(i, params)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
var builder strings.Builder
|
||||
builder.WriteString("=== Web Fetch Results ===\n\n")
|
||||
|
||||
aggregated := make([]map[string]interface{}, 0, len(results))
|
||||
success := true
|
||||
var firstErr error
|
||||
|
||||
for idx, res := range results {
|
||||
if res == nil {
|
||||
success = false
|
||||
if firstErr == nil {
|
||||
firstErr = fmt.Errorf("fetch item %d returned nil", idx)
|
||||
}
|
||||
builder.WriteString(fmt.Sprintf("#%d: 无结果(内部错误)\n\n", idx+1))
|
||||
continue
|
||||
}
|
||||
|
||||
builder.WriteString(fmt.Sprintf("#%d:\n%s", idx+1, res.output))
|
||||
if !strings.HasSuffix(res.output, "\n") {
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
builder.WriteString("\n")
|
||||
|
||||
if res.data != nil {
|
||||
aggregated = append(aggregated, res.data)
|
||||
}
|
||||
|
||||
if res.err != nil {
|
||||
success = false
|
||||
if firstErr == nil {
|
||||
firstErr = res.err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"results": aggregated,
|
||||
"count": len(aggregated),
|
||||
"display_type": "web_fetch_results",
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "[Tool][WebFetch] Completed with success=%v, items=%d", success, len(aggregated))
|
||||
|
||||
return &types.ToolResult{
|
||||
Success: success,
|
||||
Output: builder.String(),
|
||||
Data: data,
|
||||
Error: func() string {
|
||||
if firstErr != nil {
|
||||
return firstErr.Error()
|
||||
}
|
||||
return ""
|
||||
}(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) parseParams(item interface{}) webFetchParams {
|
||||
params := webFetchParams{}
|
||||
if m, ok := item.(map[string]interface{}); ok {
|
||||
if v, ok := m["url"].(string); ok {
|
||||
params.URL = strings.TrimSpace(v)
|
||||
}
|
||||
if v, ok := m["prompt"].(string); ok {
|
||||
params.Prompt = strings.TrimSpace(v)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) validateParams(p webFetchParams) error {
|
||||
if p.URL == "" {
|
||||
return fmt.Errorf("url is required")
|
||||
}
|
||||
if p.Prompt == "" {
|
||||
return fmt.Errorf("prompt is required")
|
||||
}
|
||||
if !strings.HasPrefix(p.URL, "http://") && !strings.HasPrefix(p.URL, "https://") {
|
||||
return fmt.Errorf("invalid URL format")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) executeFetch(ctx context.Context, params webFetchParams) (string, map[string]interface{}, error) {
|
||||
logger.Infof(ctx, "[Tool][WebFetch] Fetching URL: %s", params.URL)
|
||||
|
||||
finalURL := t.normalizeGitHubURL(params.URL)
|
||||
|
||||
htmlContent, method, err := t.fetchHTMLContent(ctx, finalURL)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "[Tool][WebFetch] 获取页面失败 url=%s err=%v", finalURL, err)
|
||||
return fmt.Sprintf("URL: %s\n错误: %v\n", params.URL, err),
|
||||
map[string]interface{}{
|
||||
"url": params.URL,
|
||||
"prompt": params.Prompt,
|
||||
"error": err.Error(),
|
||||
}, err
|
||||
}
|
||||
|
||||
textContent := t.convertHTMLToText(htmlContent)
|
||||
|
||||
resultData := map[string]interface{}{
|
||||
"url": params.URL,
|
||||
"prompt": params.Prompt,
|
||||
"raw_content": textContent,
|
||||
"content_length": len(textContent),
|
||||
"method": method,
|
||||
}
|
||||
var summary string
|
||||
var summaryErr error
|
||||
summary, summaryErr = t.processWithLLM(ctx, params, textContent)
|
||||
if summaryErr != nil {
|
||||
logger.Warnf(ctx, "[Tool][WebFetch] LLM 处理失败 url=%s err=%v", params.URL, summaryErr)
|
||||
} else if summary != "" {
|
||||
resultData["summary"] = summary
|
||||
}
|
||||
|
||||
output := t.buildOutputText(params, textContent, summary, summaryErr)
|
||||
|
||||
return output, resultData, summaryErr
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) normalizeGitHubURL(source string) string {
|
||||
if strings.Contains(source, "github.com") && strings.Contains(source, "/blob/") {
|
||||
source = strings.Replace(source, "github.com", "raw.githubusercontent.com", 1)
|
||||
source = strings.Replace(source, "/blob/", "/", 1)
|
||||
}
|
||||
return source
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) processWithLLM(ctx context.Context, params webFetchParams, content string) (string, error) {
|
||||
if t.chatModel == nil {
|
||||
return "", fmt.Errorf("chat model not available for web_fetch")
|
||||
}
|
||||
|
||||
systemMessage := "你是一名擅长阅读网页内容的智能助手,请根据提供的网页文本回答用户需求,严禁编造未在文本中出现的信息。"
|
||||
userTemplate := `用户请求:
|
||||
%s
|
||||
|
||||
网页内容:
|
||||
%s`
|
||||
|
||||
messages := []chat.Message{
|
||||
{
|
||||
Role: "system",
|
||||
Content: systemMessage,
|
||||
},
|
||||
{
|
||||
Role: "user",
|
||||
Content: fmt.Sprintf(userTemplate, params.Prompt, content),
|
||||
},
|
||||
}
|
||||
|
||||
response, err := t.chatModel.Chat(ctx, messages, &chat.ChatOptions{
|
||||
Temperature: 0.3,
|
||||
MaxTokens: 1024,
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return strings.TrimSpace(response.Content), nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) buildOutputText(params webFetchParams, content string, summary string, summaryErr error) string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
|
||||
builder.WriteString(fmt.Sprintf("Prompt: %s\n", params.Prompt))
|
||||
|
||||
if summaryErr == nil && summary != "" {
|
||||
builder.WriteString("Summary:\n")
|
||||
builder.WriteString(summary)
|
||||
builder.WriteString("\n")
|
||||
} else {
|
||||
builder.WriteString("Content Preview:\n")
|
||||
builder.WriteString(content)
|
||||
builder.WriteString("\n")
|
||||
}
|
||||
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) fetchHTMLContent(ctx context.Context, targetURL string) (string, string, error) {
|
||||
html, err := t.fetchWithChromedp(ctx, targetURL)
|
||||
if err == nil && strings.TrimSpace(html) != "" {
|
||||
return html, "chromedp", nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取失败 url=%s err=%v,尝试直接请求", targetURL, err)
|
||||
}
|
||||
|
||||
html, httpErr := t.fetchWithHTTP(ctx, targetURL)
|
||||
if httpErr != nil {
|
||||
if err != nil {
|
||||
return "", "", fmt.Errorf("chromedp error: %v; http error: %w", err, httpErr)
|
||||
}
|
||||
return "", "", httpErr
|
||||
}
|
||||
|
||||
return html, "http", nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) fetchWithChromedp(ctx context.Context, targetURL string) (string, error) {
|
||||
logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取开始 url=%s", targetURL)
|
||||
|
||||
opts := append(chromedp.DefaultExecAllocatorOptions[:],
|
||||
chromedp.Flag("headless", true),
|
||||
chromedp.Flag("disable-setuid-sandbox", true),
|
||||
chromedp.Flag("disable-dev-shm-usage", true),
|
||||
chromedp.Flag("disable-gpu", true),
|
||||
chromedp.Flag("disable-blink-features", "AutomationControlled"),
|
||||
chromedp.Flag("disable-features", "VizDisplayCompositor"),
|
||||
chromedp.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"),
|
||||
)
|
||||
|
||||
allocCtx, cancel := chromedp.NewExecAllocator(ctx, opts...)
|
||||
defer cancel()
|
||||
|
||||
ctx, cancel = chromedp.NewContext(allocCtx)
|
||||
defer cancel()
|
||||
|
||||
ctx, cancel = context.WithTimeout(ctx, webFetchTimeout)
|
||||
defer cancel()
|
||||
|
||||
var html string
|
||||
err := chromedp.Run(ctx,
|
||||
chromedp.Navigate(targetURL),
|
||||
chromedp.WaitReady("body", chromedp.ByQuery),
|
||||
chromedp.OuterHTML("html", &html),
|
||||
)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("chromedp run failed: %w", err)
|
||||
}
|
||||
|
||||
logger.Debugf(ctx, "[Tool][WebFetch] Chromedp 抓取成功 url=%s", targetURL)
|
||||
return html, nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) fetchWithHTTP(ctx context.Context, targetURL string) (string, error) {
|
||||
resp, err := t.fetchWithTimeout(ctx, targetURL)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("request failed with status %d %s", resp.StatusCode, resp.Status)
|
||||
}
|
||||
|
||||
limitedReader := io.LimitReader(resp.Body, webFetchMaxChars*2)
|
||||
htmlBytes, err := io.ReadAll(limitedReader)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
return string(htmlBytes), nil
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) fetchWithTimeout(ctx context.Context, targetURL string) (*http.Response, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; WebFetchTool/1.0)")
|
||||
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8")
|
||||
req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8")
|
||||
req.Header.Set("Cache-Control", "no-cache")
|
||||
|
||||
return t.client.Do(req)
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) convertHTMLToText(html string) string {
|
||||
doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
|
||||
if err != nil {
|
||||
return t.basicTextExtraction(html)
|
||||
}
|
||||
|
||||
doc.Find("script, style, nav, footer, header").Remove()
|
||||
|
||||
var markdown strings.Builder
|
||||
doc.Find("body").Each(func(i int, body *goquery.Selection) {
|
||||
t.processNode(body, &markdown)
|
||||
})
|
||||
|
||||
result := markdown.String()
|
||||
result = regexp.MustCompile(`\n{3,}`).ReplaceAllString(result, "\n\n")
|
||||
return strings.TrimSpace(result)
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) processNode(s *goquery.Selection, markdown *strings.Builder) {
|
||||
s.Contents().Each(func(i int, node *goquery.Selection) {
|
||||
nodeName := goquery.NodeName(node)
|
||||
|
||||
switch nodeName {
|
||||
case "h1", "h2", "h3", "h4", "h5", "h6":
|
||||
headerLevel := int(nodeName[1] - '0')
|
||||
markdown.WriteString("\n")
|
||||
markdown.WriteString(strings.Repeat("#", headerLevel))
|
||||
markdown.WriteString(" ")
|
||||
markdown.WriteString(strings.TrimSpace(node.Text()))
|
||||
markdown.WriteString("\n\n")
|
||||
case "p":
|
||||
t.processNode(node, markdown)
|
||||
markdown.WriteString("\n\n")
|
||||
case "a":
|
||||
href, exists := node.Attr("href")
|
||||
text := strings.TrimSpace(node.Text())
|
||||
if exists && text != "" {
|
||||
markdown.WriteString("[")
|
||||
markdown.WriteString(text)
|
||||
markdown.WriteString("](")
|
||||
markdown.WriteString(href)
|
||||
markdown.WriteString(")")
|
||||
} else if text != "" {
|
||||
markdown.WriteString(text)
|
||||
}
|
||||
case "img":
|
||||
src, _ := node.Attr("src")
|
||||
alt, _ := node.Attr("alt")
|
||||
if src != "" {
|
||||
markdown.WriteString("
|
||||
markdown.WriteString(src)
|
||||
markdown.WriteString(")\n\n")
|
||||
}
|
||||
case "ul", "ol":
|
||||
markdown.WriteString("\n")
|
||||
isOrdered := nodeName == "ol"
|
||||
node.Find("li").Each(func(idx int, li *goquery.Selection) {
|
||||
if isOrdered {
|
||||
markdown.WriteString(fmt.Sprintf("%d. ", idx+1))
|
||||
} else {
|
||||
markdown.WriteString("- ")
|
||||
}
|
||||
markdown.WriteString(strings.TrimSpace(li.Text()))
|
||||
markdown.WriteString("\n")
|
||||
})
|
||||
markdown.WriteString("\n")
|
||||
case "br":
|
||||
markdown.WriteString("\n")
|
||||
case "code":
|
||||
parent := node.Parent()
|
||||
if goquery.NodeName(parent) == "pre" {
|
||||
markdown.WriteString("\n```\n")
|
||||
markdown.WriteString(node.Text())
|
||||
markdown.WriteString("\n```\n\n")
|
||||
} else {
|
||||
markdown.WriteString("`")
|
||||
markdown.WriteString(node.Text())
|
||||
markdown.WriteString("`")
|
||||
}
|
||||
case "blockquote":
|
||||
lines := strings.Split(strings.TrimSpace(node.Text()), "\n")
|
||||
for _, line := range lines {
|
||||
markdown.WriteString("> ")
|
||||
markdown.WriteString(strings.TrimSpace(line))
|
||||
markdown.WriteString("\n")
|
||||
}
|
||||
markdown.WriteString("\n")
|
||||
case "strong", "b":
|
||||
markdown.WriteString("**")
|
||||
markdown.WriteString(strings.TrimSpace(node.Text()))
|
||||
markdown.WriteString("**")
|
||||
case "em", "i":
|
||||
markdown.WriteString("*")
|
||||
markdown.WriteString(strings.TrimSpace(node.Text()))
|
||||
markdown.WriteString("*")
|
||||
case "hr":
|
||||
markdown.WriteString("\n---\n\n")
|
||||
case "table":
|
||||
markdown.WriteString("\n")
|
||||
node.Find("tr").Each(func(idx int, tr *goquery.Selection) {
|
||||
tr.Find("th, td").Each(func(i int, cell *goquery.Selection) {
|
||||
markdown.WriteString("| ")
|
||||
markdown.WriteString(strings.TrimSpace(cell.Text()))
|
||||
markdown.WriteString(" ")
|
||||
})
|
||||
markdown.WriteString("|\n")
|
||||
if idx == 0 {
|
||||
tr.Find("th").Each(func(i int, _ *goquery.Selection) {
|
||||
markdown.WriteString("|---")
|
||||
})
|
||||
markdown.WriteString("|\n")
|
||||
}
|
||||
})
|
||||
markdown.WriteString("\n")
|
||||
case "#text":
|
||||
text := node.Text()
|
||||
if strings.TrimSpace(text) != "" {
|
||||
markdown.WriteString(text)
|
||||
}
|
||||
default:
|
||||
t.processNode(node, markdown)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (t *WebFetchTool) basicTextExtraction(html string) string {
|
||||
re := regexp.MustCompile(`<[^>]*>`)
|
||||
text := re.ReplaceAllString(html, " ")
|
||||
text = regexp.MustCompile(`\s+`).ReplaceAllString(text, " ")
|
||||
return strings.TrimSpace(text)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/event"
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/mcp"
|
||||
"github.com/Tencent/WeKnora/internal/models/chat"
|
||||
"github.com/Tencent/WeKnora/internal/models/rerank"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
@@ -97,7 +98,7 @@ func (s *agentService) CreateAgentEngine(
|
||||
toolRegistry := tools.NewToolRegistry(s.knowledgeBaseService, s.knowledgeService, s.chunkService, s.db)
|
||||
|
||||
// Register tools
|
||||
if err := s.registerTools(ctx, toolRegistry, config, rerankModel, sessionID, sessionService); err != nil {
|
||||
if err := s.registerTools(ctx, toolRegistry, config, rerankModel, chatModel, sessionID, sessionService); err != nil {
|
||||
return nil, fmt.Errorf("failed to register tools: %w", err)
|
||||
}
|
||||
|
||||
@@ -147,8 +148,10 @@ func (s *agentService) CreateAgentEngine(
|
||||
}
|
||||
}
|
||||
|
||||
// Get system prompt template from config (use default if empty)
|
||||
systemPromptTemplate := config.SystemPrompt
|
||||
systemPromptTemplate := agent.DefaultSystemPromptTemplate
|
||||
if config.UseCustomSystemPrompt && config.SystemPrompt != "" {
|
||||
systemPromptTemplate = config.SystemPrompt
|
||||
}
|
||||
|
||||
// Create engine with provided EventBus and contextManager
|
||||
engine := agent.NewAgentEngine(
|
||||
@@ -172,6 +175,7 @@ func (s *agentService) registerTools(
|
||||
registry *tools.ToolRegistry,
|
||||
config *types.AgentConfig,
|
||||
rerankModel rerank.Reranker,
|
||||
chatModel chat.Chat,
|
||||
sessionID string,
|
||||
sessionService interfaces.SessionService,
|
||||
) error {
|
||||
@@ -186,6 +190,7 @@ func (s *agentService) registerTools(
|
||||
// If web search is enabled, add web_search to allowedTools
|
||||
if config.WebSearchEnabled {
|
||||
allowedTools = append(allowedTools, "web_search")
|
||||
allowedTools = append(allowedTools, "web_fetch")
|
||||
}
|
||||
|
||||
// Get tenant ID from context
|
||||
@@ -199,7 +204,7 @@ func (s *agentService) registerTools(
|
||||
for _, toolName := range allowedTools {
|
||||
switch toolName {
|
||||
case "thinking":
|
||||
registry.RegisterTool(tools.NewThinkingTool())
|
||||
registry.RegisterTool(tools.NewSequentialThinkingTool())
|
||||
case "todo_write":
|
||||
registry.RegisterTool(tools.NewTodoWriteTool())
|
||||
case "knowledge_search":
|
||||
@@ -223,6 +228,10 @@ func (s *agentService) registerTools(
|
||||
))
|
||||
logger.Infof(ctx, "Registered web_search tool for session: %s, maxResults: %d", sessionID, config.WebSearchMaxResults)
|
||||
|
||||
case "web_fetch":
|
||||
registry.RegisterTool(tools.NewWebFetchTool(chatModel))
|
||||
logger.Infof(ctx, "Registered web_fetch tool for session: %s", sessionID)
|
||||
|
||||
default:
|
||||
logger.Warnf(ctx, "Unknown tool: %s", toolName)
|
||||
}
|
||||
|
||||
@@ -67,6 +67,11 @@ type knowledgeService struct {
|
||||
graphEngine interfaces.RetrieveGraphRepository
|
||||
}
|
||||
|
||||
const (
|
||||
manualContentMaxLength = 200000
|
||||
manualFileExtension = ".md"
|
||||
)
|
||||
|
||||
// NewKnowledgeService creates a new knowledge service instance
|
||||
func NewKnowledgeService(
|
||||
config *config.Config,
|
||||
@@ -364,6 +369,91 @@ func (s *knowledgeService) CreateKnowledgeFromPassageSync(ctx context.Context,
|
||||
return s.createKnowledgeFromPassageInternal(ctx, kbID, passage, true)
|
||||
}
|
||||
|
||||
// CreateKnowledgeFromManual creates or saves manual Markdown knowledge content.
|
||||
func (s *knowledgeService) CreateKnowledgeFromManual(ctx context.Context,
|
||||
kbID string, payload *types.ManualKnowledgePayload,
|
||||
) (*types.Knowledge, error) {
|
||||
logger.Info(ctx, "Start creating manual knowledge entry")
|
||||
|
||||
if payload == nil {
|
||||
return nil, werrors.NewBadRequestError("请求内容不能为空")
|
||||
}
|
||||
|
||||
cleanContent := secutils.CleanMarkdown(payload.Content)
|
||||
if strings.TrimSpace(cleanContent) == "" {
|
||||
return nil, werrors.NewValidationError("内容不能为空")
|
||||
}
|
||||
if len([]rune(cleanContent)) > manualContentMaxLength {
|
||||
return nil, werrors.NewValidationError(fmt.Sprintf("内容长度超出限制(最多%d个字符)", manualContentMaxLength))
|
||||
}
|
||||
|
||||
safeTitle, ok := secutils.ValidateInput(payload.Title)
|
||||
if !ok {
|
||||
return nil, werrors.NewValidationError("标题包含非法字符或超出长度限制")
|
||||
}
|
||||
|
||||
status := strings.ToLower(strings.TrimSpace(payload.Status))
|
||||
if status == "" {
|
||||
status = types.ManualKnowledgeStatusDraft
|
||||
}
|
||||
if status != types.ManualKnowledgeStatusDraft && status != types.ManualKnowledgeStatusPublish {
|
||||
return nil, werrors.NewValidationError("状态仅支持 draft 或 publish")
|
||||
}
|
||||
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
now := time.Now()
|
||||
title := safeTitle
|
||||
if title == "" {
|
||||
title = fmt.Sprintf("手工知识-%s", now.Format("20060102-150405"))
|
||||
}
|
||||
|
||||
fileName := ensureManualFileName(title)
|
||||
meta := types.NewManualKnowledgeMetadata(cleanContent, status, 1)
|
||||
|
||||
knowledge := &types.Knowledge{
|
||||
TenantID: tenantID,
|
||||
KnowledgeBaseID: kbID,
|
||||
Type: types.KnowledgeTypeManual,
|
||||
Title: title,
|
||||
Description: "",
|
||||
Source: types.KnowledgeTypeManual,
|
||||
ParseStatus: types.ManualKnowledgeStatusDraft,
|
||||
EnableStatus: "disabled",
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
EmbeddingModelID: kb.EmbeddingModelID,
|
||||
FileName: fileName,
|
||||
FileType: types.KnowledgeTypeManual,
|
||||
}
|
||||
if err := knowledge.SetManualMetadata(meta); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set manual metadata: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
knowledge.EnsureManualDefaults()
|
||||
|
||||
if status == types.ManualKnowledgeStatusPublish {
|
||||
knowledge.ParseStatus = "pending"
|
||||
}
|
||||
|
||||
if err := s.repo.CreateKnowledge(ctx, knowledge); err != nil {
|
||||
logger.Errorf(ctx, "Failed to create manual knowledge record: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if status == types.ManualKnowledgeStatusPublish {
|
||||
logger.Infof(ctx, "Manual knowledge created, scheduling indexing, ID: %s", knowledge.ID)
|
||||
s.triggerManualProcessing(ctx, kb, knowledge, cleanContent, false)
|
||||
}
|
||||
|
||||
return knowledge, nil
|
||||
}
|
||||
|
||||
// createKnowledgeFromPassageInternal consolidates the common logic for creating knowledge from passages.
|
||||
// When syncMode is true, chunk processing is performed synchronously; otherwise, it's processed asynchronously.
|
||||
func (s *knowledgeService) createKnowledgeFromPassageInternal(ctx context.Context,
|
||||
@@ -1381,6 +1471,112 @@ func (s *knowledgeService) UpdateKnowledge(ctx context.Context, knowledge *types
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateManualKnowledge updates manual Markdown knowledge content.
|
||||
func (s *knowledgeService) UpdateManualKnowledge(ctx context.Context,
|
||||
knowledgeID string, payload *types.ManualKnowledgePayload,
|
||||
) (*types.Knowledge, error) {
|
||||
logger.Info(ctx, "Start updating manual knowledge entry")
|
||||
if payload == nil {
|
||||
return nil, werrors.NewBadRequestError("请求内容不能为空")
|
||||
}
|
||||
|
||||
cleanContent := secutils.CleanMarkdown(payload.Content)
|
||||
if strings.TrimSpace(cleanContent) == "" {
|
||||
return nil, werrors.NewValidationError("内容不能为空")
|
||||
}
|
||||
if len([]rune(cleanContent)) > manualContentMaxLength {
|
||||
return nil, werrors.NewValidationError(fmt.Sprintf("内容长度超出限制(最多%d个字符)", manualContentMaxLength))
|
||||
}
|
||||
|
||||
safeTitle, ok := secutils.ValidateInput(payload.Title)
|
||||
if !ok {
|
||||
return nil, werrors.NewValidationError("标题包含非法字符或超出长度限制")
|
||||
}
|
||||
|
||||
status := strings.ToLower(strings.TrimSpace(payload.Status))
|
||||
if status == "" {
|
||||
status = types.ManualKnowledgeStatusDraft
|
||||
}
|
||||
if status != types.ManualKnowledgeStatusDraft && status != types.ManualKnowledgeStatusPublish {
|
||||
return nil, werrors.NewValidationError("状态仅支持 draft 或 publish")
|
||||
}
|
||||
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint)
|
||||
existing, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to load knowledge: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
if !existing.IsManual() {
|
||||
return nil, werrors.NewBadRequestError("仅支持手工知识的在线编辑")
|
||||
}
|
||||
|
||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, existing.KnowledgeBaseID)
|
||||
if err != nil {
|
||||
logger.Errorf(ctx, "Failed to get knowledge base for manual update: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var version int
|
||||
if meta, err := existing.ManualMetadata(); err == nil && meta != nil {
|
||||
version = meta.Version + 1
|
||||
} else {
|
||||
version = 1
|
||||
}
|
||||
|
||||
meta := types.NewManualKnowledgeMetadata(cleanContent, status, version)
|
||||
if err := existing.SetManualMetadata(meta); err != nil {
|
||||
logger.Errorf(ctx, "Failed to set manual metadata during update: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if safeTitle != "" {
|
||||
existing.Title = safeTitle
|
||||
} else if existing.Title == "" {
|
||||
existing.Title = fmt.Sprintf("手工知识-%s", time.Now().Format("20060102-150405"))
|
||||
}
|
||||
existing.FileName = ensureManualFileName(existing.Title)
|
||||
existing.FileType = types.KnowledgeTypeManual
|
||||
existing.Type = types.KnowledgeTypeManual
|
||||
existing.Source = types.KnowledgeTypeManual
|
||||
existing.EnableStatus = "disabled"
|
||||
existing.UpdatedAt = time.Now()
|
||||
|
||||
if err := s.cleanupKnowledgeResources(ctx, existing); err != nil {
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
})
|
||||
return nil, err
|
||||
}
|
||||
|
||||
existing.EmbeddingModelID = kb.EmbeddingModelID
|
||||
|
||||
if status == types.ManualKnowledgeStatusDraft {
|
||||
existing.ParseStatus = types.ManualKnowledgeStatusDraft
|
||||
existing.Description = ""
|
||||
existing.ProcessedAt = nil
|
||||
|
||||
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
|
||||
logger.Errorf(ctx, "Failed to persist manual draft: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
existing.ParseStatus = "pending"
|
||||
existing.Description = ""
|
||||
existing.ProcessedAt = nil
|
||||
|
||||
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
|
||||
logger.Errorf(ctx, "Failed to persist manual knowledge before indexing: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Manual knowledge updated, scheduling indexing, ID: %s", existing.ID)
|
||||
s.triggerManualProcessing(ctx, kb, existing, cleanContent, false)
|
||||
return existing, nil
|
||||
}
|
||||
|
||||
// isValidFileType checks if a file type is supported
|
||||
func isValidFileType(filename string) bool {
|
||||
switch strings.ToLower(getFileType(filename)) {
|
||||
@@ -1825,6 +2021,110 @@ func (s *knowledgeService) CloneChunk(ctx context.Context, src, dst *types.Knowl
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureManualFileName(title string) string {
|
||||
if title == "" {
|
||||
return fmt.Sprintf("manual-%s%s", time.Now().Format("20060102-150405"), manualFileExtension)
|
||||
}
|
||||
trimmed := strings.TrimSpace(title)
|
||||
if strings.HasSuffix(strings.ToLower(trimmed), manualFileExtension) {
|
||||
return trimmed
|
||||
}
|
||||
return trimmed + manualFileExtension
|
||||
}
|
||||
|
||||
func splitManualContent(content string) []string {
|
||||
clean := strings.TrimSpace(content)
|
||||
if clean == "" {
|
||||
return []string{}
|
||||
}
|
||||
normalized := strings.ReplaceAll(clean, "\r\n", "\n")
|
||||
segments := strings.Split(normalized, "\n\n")
|
||||
results := make([]string, 0, len(segments))
|
||||
for _, seg := range segments {
|
||||
part := strings.TrimSpace(seg)
|
||||
if part != "" {
|
||||
results = append(results, part)
|
||||
}
|
||||
}
|
||||
if len(results) == 0 {
|
||||
results = append(results, clean)
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
func (s *knowledgeService) triggerManualProcessing(ctx context.Context,
|
||||
kb *types.KnowledgeBase, knowledge *types.Knowledge, content string, sync bool,
|
||||
) {
|
||||
passages := splitManualContent(content)
|
||||
if len(passages) == 0 {
|
||||
passages = []string{content}
|
||||
}
|
||||
|
||||
if sync {
|
||||
s.processDocumentFromPassage(ctx, kb, knowledge, passages)
|
||||
return
|
||||
}
|
||||
|
||||
newCtx := logger.CloneContext(ctx)
|
||||
go s.processDocumentFromPassage(newCtx, kb, knowledge, passages)
|
||||
}
|
||||
|
||||
func (s *knowledgeService) cleanupKnowledgeResources(ctx context.Context, knowledge *types.Knowledge) error {
|
||||
logger.GetLogger(ctx).Infof("Cleaning knowledge resources before manual update, knowledge ID: %s", knowledge.ID)
|
||||
|
||||
var cleanupErr error
|
||||
|
||||
if knowledge.ParseStatus == types.ManualKnowledgeStatusDraft && knowledge.StorageSize == 0 {
|
||||
// Draft without indexed data, skip cleanup.
|
||||
return nil
|
||||
}
|
||||
|
||||
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
|
||||
if knowledge.EmbeddingModelID != "" {
|
||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.RetrieverEngines.Engines)
|
||||
if err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Error("Failed to init retrieve engine during cleanup")
|
||||
cleanupErr = errors.Join(cleanupErr, err)
|
||||
} else {
|
||||
embeddingModel, modelErr := s.modelService.GetEmbeddingModel(ctx, knowledge.EmbeddingModelID)
|
||||
if modelErr != nil {
|
||||
logger.GetLogger(ctx).WithField("error", modelErr).Error("Failed to get embedding model during cleanup")
|
||||
cleanupErr = errors.Join(cleanupErr, modelErr)
|
||||
} else {
|
||||
if err := retrieveEngine.DeleteByKnowledgeIDList(ctx, []string{knowledge.ID}, embeddingModel.GetDimensions()); err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Error("Failed to delete manual knowledge index")
|
||||
cleanupErr = errors.Join(cleanupErr, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.chunkService.DeleteChunksByKnowledgeID(ctx, knowledge.ID); err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Error("Failed to delete manual knowledge chunks")
|
||||
cleanupErr = errors.Join(cleanupErr, err)
|
||||
}
|
||||
|
||||
namespace := types.NameSpace{KnowledgeBase: knowledge.KnowledgeBaseID, Knowledge: knowledge.ID}
|
||||
if err := s.graphEngine.DelGraph(ctx, []types.NameSpace{namespace}); err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Error("Failed to delete manual knowledge graph data")
|
||||
cleanupErr = errors.Join(cleanupErr, err)
|
||||
}
|
||||
|
||||
if knowledge.StorageSize > 0 {
|
||||
tenantInfo.StorageUsed -= knowledge.StorageSize
|
||||
if tenantInfo.StorageUsed < 0 {
|
||||
tenantInfo.StorageUsed = 0
|
||||
}
|
||||
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, -knowledge.StorageSize); err != nil {
|
||||
logger.GetLogger(ctx).WithField("error", err).Error("Failed to adjust storage usage during manual cleanup")
|
||||
cleanupErr = errors.Join(cleanupErr, err)
|
||||
}
|
||||
knowledge.StorageSize = 0
|
||||
}
|
||||
|
||||
return cleanupErr
|
||||
}
|
||||
|
||||
func IsImageType(fileType string) bool {
|
||||
switch fileType {
|
||||
case "jpg", "jpeg", "png", "gif", "webp", "bmp", "svg", "tiff":
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/agent"
|
||||
chatpipline "github.com/Tencent/WeKnora/internal/application/service/chat_pipline"
|
||||
llmcontext "github.com/Tencent/WeKnora/internal/application/service/llmcontext"
|
||||
"github.com/Tencent/WeKnora/internal/config"
|
||||
@@ -805,6 +806,12 @@ func (s *sessionService) AgentQA(ctx context.Context, session *types.Session, qu
|
||||
WebSearchEnabled: session.AgentConfig.WebSearchEnabled, // Web search enabled from session config
|
||||
}
|
||||
|
||||
if tenantInfo.AgentConfig.UseCustomSystemPrompt {
|
||||
agentConfig.SystemPrompt = tenantInfo.AgentConfig.SystemPrompt
|
||||
} else {
|
||||
agentConfig.SystemPrompt = agent.DefaultSystemPromptTemplate
|
||||
}
|
||||
|
||||
// Set web search max results from tenant config (default: 5)
|
||||
agentConfig.WebSearchMaxResults = 5
|
||||
if tenantInfo.WebSearchConfig != nil && tenantInfo.WebSearchConfig.MaxResults > 0 {
|
||||
|
||||
@@ -196,6 +196,44 @@ func (h *KnowledgeHandler) CreateKnowledgeFromURL(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// CreateManualKnowledge handles manual Markdown knowledge creation
|
||||
func (h *KnowledgeHandler) CreateManualKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start creating manual knowledge")
|
||||
|
||||
_, kbID, err := h.validateKnowledgeBaseAccess(c)
|
||||
if err != nil {
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
var req types.ManualKnowledgePayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse manual knowledge request", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
knowledge, err := h.kgService.CreateKnowledgeFromManual(ctx, kbID, &req)
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"kb_id": kbID,
|
||||
})
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Manual knowledge created successfully, knowledge ID: %s", knowledge.ID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": knowledge,
|
||||
})
|
||||
}
|
||||
|
||||
// GetKnowledge retrieves a knowledge entry by its ID
|
||||
func (h *KnowledgeHandler) GetKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
@@ -430,6 +468,45 @@ func (h *KnowledgeHandler) UpdateKnowledge(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateManualKnowledge handles manual Markdown knowledge updates
|
||||
func (h *KnowledgeHandler) UpdateManualKnowledge(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
logger.Info(ctx, "Start updating manual knowledge")
|
||||
|
||||
knowledgeID := c.Param("id")
|
||||
if knowledgeID == "" {
|
||||
logger.Error(ctx, "Knowledge ID is empty")
|
||||
c.Error(errors.NewBadRequestError("Knowledge ID cannot be empty"))
|
||||
return
|
||||
}
|
||||
|
||||
var req types.ManualKnowledgePayload
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
logger.Error(ctx, "Failed to parse manual knowledge update request", err)
|
||||
c.Error(errors.NewBadRequestError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
knowledge, err := h.kgService.UpdateManualKnowledge(ctx, knowledgeID, &req)
|
||||
if err != nil {
|
||||
if appErr, ok := errors.IsAppError(err); ok {
|
||||
c.Error(appErr)
|
||||
return
|
||||
}
|
||||
logger.ErrorWithFields(ctx, err, map[string]interface{}{
|
||||
"knowledge_id": knowledgeID,
|
||||
})
|
||||
c.Error(errors.NewInternalServerError(err.Error()))
|
||||
return
|
||||
}
|
||||
|
||||
logger.Infof(ctx, "Manual knowledge updated successfully, knowledge ID: %s", knowledge.ID)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": knowledge,
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateImageInfo updates a chunk's properties
|
||||
func (h *KnowledgeHandler) UpdateImageInfo(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
|
||||
+40
-27
@@ -237,6 +237,7 @@ type AgentConfigRequest struct {
|
||||
ThinkingModelID string `json:"thinking_model_id"`
|
||||
RerankModelID string `json:"rerank_model_id"`
|
||||
SystemPrompt string `json:"system_prompt,omitempty"` // System prompt template with placeholders (optional)
|
||||
UseCustomPrompt *bool `json:"use_custom_system_prompt"`
|
||||
}
|
||||
|
||||
// GetTenantAgentConfig retrieves the agent configuration for a tenant
|
||||
@@ -277,15 +278,16 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"max_iterations": agent.DefaultAgentMaxIterations,
|
||||
"reflection_enabled": agent.DefaultAgentReflectionEnabled,
|
||||
"allowed_tools": agenttools.DefaultAllowedTools(),
|
||||
"temperature": agent.DefaultAgentTemperature,
|
||||
"thinking_model_id": "",
|
||||
"rerank_model_id": "",
|
||||
"system_prompt": agent.DefaultSystemPromptTemplate,
|
||||
"available_tools": availableTools,
|
||||
"available_placeholders": availablePlaceholders,
|
||||
"max_iterations": agent.DefaultAgentMaxIterations,
|
||||
"reflection_enabled": agent.DefaultAgentReflectionEnabled,
|
||||
"allowed_tools": agenttools.DefaultAllowedTools(),
|
||||
"temperature": agent.DefaultAgentTemperature,
|
||||
"thinking_model_id": "",
|
||||
"rerank_model_id": "",
|
||||
"system_prompt": agent.DefaultSystemPromptTemplate,
|
||||
"use_custom_system_prompt": false,
|
||||
"available_tools": availableTools,
|
||||
"available_placeholders": availablePlaceholders,
|
||||
},
|
||||
})
|
||||
return
|
||||
@@ -293,6 +295,10 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
|
||||
|
||||
// Get system prompt, use default if empty
|
||||
systemPrompt := tenant.AgentConfig.SystemPrompt
|
||||
useCustomPrompt := tenant.AgentConfig.UseCustomSystemPrompt
|
||||
if !useCustomPrompt && systemPrompt != "" && systemPrompt != agent.DefaultSystemPromptTemplate {
|
||||
useCustomPrompt = true
|
||||
}
|
||||
if systemPrompt == "" {
|
||||
systemPrompt = agent.DefaultSystemPromptTemplate
|
||||
}
|
||||
@@ -301,16 +307,17 @@ func (h *TenantHandler) GetTenantAgentConfig(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"data": gin.H{
|
||||
"enabled": tenant.AgentConfig.Enabled,
|
||||
"max_iterations": tenant.AgentConfig.MaxIterations,
|
||||
"reflection_enabled": tenant.AgentConfig.ReflectionEnabled,
|
||||
"allowed_tools": tenant.AgentConfig.AllowedTools,
|
||||
"temperature": tenant.AgentConfig.Temperature,
|
||||
"thinking_model_id": tenant.AgentConfig.ThinkingModelID,
|
||||
"rerank_model_id": tenant.AgentConfig.RerankModelID,
|
||||
"system_prompt": systemPrompt,
|
||||
"available_tools": availableTools,
|
||||
"available_placeholders": availablePlaceholders,
|
||||
"enabled": tenant.AgentConfig.Enabled,
|
||||
"max_iterations": tenant.AgentConfig.MaxIterations,
|
||||
"reflection_enabled": tenant.AgentConfig.ReflectionEnabled,
|
||||
"allowed_tools": tenant.AgentConfig.AllowedTools,
|
||||
"temperature": tenant.AgentConfig.Temperature,
|
||||
"thinking_model_id": tenant.AgentConfig.ThinkingModelID,
|
||||
"rerank_model_id": tenant.AgentConfig.RerankModelID,
|
||||
"system_prompt": systemPrompt,
|
||||
"use_custom_system_prompt": useCustomPrompt,
|
||||
"available_tools": availableTools,
|
||||
"available_placeholders": availablePlaceholders,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -354,15 +361,21 @@ func (h *TenantHandler) updateTenantAgentConfigInternal(c *gin.Context) {
|
||||
}
|
||||
|
||||
// Update agent configuration
|
||||
useCustomPrompt := tenant.AgentConfig.UseCustomSystemPrompt
|
||||
if req.UseCustomPrompt != nil {
|
||||
useCustomPrompt = *req.UseCustomPrompt
|
||||
}
|
||||
|
||||
tenant.AgentConfig = &types.AgentConfig{
|
||||
Enabled: req.Enabled,
|
||||
MaxIterations: req.MaxIterations,
|
||||
ReflectionEnabled: req.ReflectionEnabled,
|
||||
AllowedTools: req.AllowedTools,
|
||||
Temperature: req.Temperature,
|
||||
ThinkingModelID: req.ThinkingModelID,
|
||||
RerankModelID: req.RerankModelID,
|
||||
SystemPrompt: req.SystemPrompt,
|
||||
Enabled: req.Enabled,
|
||||
MaxIterations: req.MaxIterations,
|
||||
ReflectionEnabled: req.ReflectionEnabled,
|
||||
AllowedTools: req.AllowedTools,
|
||||
Temperature: req.Temperature,
|
||||
ThinkingModelID: req.ThinkingModelID,
|
||||
RerankModelID: req.RerankModelID,
|
||||
SystemPrompt: req.SystemPrompt,
|
||||
UseCustomSystemPrompt: useCustomPrompt,
|
||||
}
|
||||
|
||||
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
|
||||
|
||||
@@ -364,7 +364,25 @@ func (c *RemoteAPIChat) ChatStream(ctx context.Context,
|
||||
defer close(streamChan)
|
||||
defer stream.Close()
|
||||
|
||||
var collectedToolCalls []types.LLMToolCall
|
||||
toolCallMap := make(map[int]*types.LLMToolCall)
|
||||
lastFunctionName := make(map[int]string)
|
||||
nameNotified := make(map[int]bool)
|
||||
|
||||
buildOrderedToolCalls := func() []types.LLMToolCall {
|
||||
if len(toolCallMap) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make([]types.LLMToolCall, 0, len(toolCallMap))
|
||||
for i := 0; i < len(toolCallMap); i++ {
|
||||
if tc, ok := toolCallMap[i]; ok && tc != nil {
|
||||
result = append(result, *tc)
|
||||
}
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
for {
|
||||
response, err := stream.Recv()
|
||||
@@ -374,7 +392,7 @@ func (c *RemoteAPIChat) ChatStream(ctx context.Context,
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "",
|
||||
Done: true,
|
||||
ToolCalls: collectedToolCalls,
|
||||
ToolCalls: buildOrderedToolCalls(),
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -391,27 +409,57 @@ func (c *RemoteAPIChat) ChatStream(ctx context.Context,
|
||||
if tc.Index != nil {
|
||||
toolCallIndex = *tc.Index
|
||||
}
|
||||
if toolCallIndex >= len(collectedToolCalls) {
|
||||
// 新建 tool call
|
||||
collectedToolCalls = append(collectedToolCalls, types.LLMToolCall{
|
||||
ID: tc.ID,
|
||||
toolCallEntry, exists := toolCallMap[toolCallIndex]
|
||||
if !exists || toolCallEntry == nil {
|
||||
toolCallEntry = &types.LLMToolCall{
|
||||
Type: string(tc.Type),
|
||||
Function: types.FunctionCall{
|
||||
Name: tc.Function.Name,
|
||||
Arguments: tc.Function.Arguments,
|
||||
Name: "",
|
||||
Arguments: "",
|
||||
},
|
||||
})
|
||||
} else {
|
||||
// 追加参数到已有的 tool call
|
||||
collectedToolCalls[toolCallIndex].Function.Arguments += tc.Function.Arguments
|
||||
// 更新 ID 和名称(如果提供了)
|
||||
if tc.ID != "" {
|
||||
collectedToolCalls[toolCallIndex].ID = tc.ID
|
||||
}
|
||||
if tc.Function.Name != "" {
|
||||
collectedToolCalls[toolCallIndex].Function.Name = tc.Function.Name
|
||||
}
|
||||
toolCallMap[toolCallIndex] = toolCallEntry
|
||||
}
|
||||
|
||||
// 更新 ID、类型
|
||||
if tc.ID != "" {
|
||||
toolCallEntry.ID = tc.ID
|
||||
}
|
||||
if tc.Type != "" {
|
||||
toolCallEntry.Type = string(tc.Type)
|
||||
}
|
||||
|
||||
// 累积函数名称(可能分多次返回)
|
||||
if tc.Function.Name != "" {
|
||||
toolCallEntry.Function.Name += tc.Function.Name
|
||||
}
|
||||
|
||||
// 累积参数(可能为部分 JSON)
|
||||
argsUpdated := false
|
||||
if tc.Function.Arguments != "" {
|
||||
toolCallEntry.Function.Arguments += tc.Function.Arguments
|
||||
argsUpdated = true
|
||||
}
|
||||
|
||||
currName := toolCallEntry.Function.Name
|
||||
if currName != "" &&
|
||||
currName == lastFunctionName[toolCallIndex] &&
|
||||
argsUpdated &&
|
||||
!nameNotified[toolCallIndex] &&
|
||||
toolCallEntry.ID != "" {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeToolCall,
|
||||
Content: "",
|
||||
Done: false,
|
||||
Data: map[string]interface{}{
|
||||
"tool_name": currName,
|
||||
"tool_call_id": toolCallEntry.ID,
|
||||
},
|
||||
}
|
||||
nameNotified[toolCallIndex] = true
|
||||
}
|
||||
|
||||
lastFunctionName[toolCallIndex] = currName
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,17 +469,17 @@ func (c *RemoteAPIChat) ChatStream(ctx context.Context,
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: delta.Content,
|
||||
Done: isDone,
|
||||
ToolCalls: collectedToolCalls,
|
||||
ToolCalls: buildOrderedToolCalls(),
|
||||
}
|
||||
}
|
||||
|
||||
// 如果是最后一次响应,确保发送包含所有 tool calls 的响应
|
||||
if isDone && len(collectedToolCalls) > 0 {
|
||||
if isDone && len(toolCallMap) > 0 {
|
||||
streamChan <- types.StreamResponse{
|
||||
ResponseType: types.ResponseTypeAnswer,
|
||||
Content: "",
|
||||
Done: true,
|
||||
ToolCalls: collectedToolCalls,
|
||||
ToolCalls: buildOrderedToolCalls(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +121,8 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
|
||||
kb.POST("/file", handler.CreateKnowledgeFromFile)
|
||||
// 从URL创建知识
|
||||
kb.POST("/url", handler.CreateKnowledgeFromURL)
|
||||
// 手工 Markdown 录入
|
||||
kb.POST("/manual", handler.CreateManualKnowledge)
|
||||
// 获取知识库下的知识列表
|
||||
kb.GET("", handler.ListKnowledge)
|
||||
}
|
||||
@@ -136,6 +138,8 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl
|
||||
k.DELETE("/:id", handler.DeleteKnowledge)
|
||||
// 更新知识
|
||||
k.PUT("/:id", handler.UpdateKnowledge)
|
||||
// 更新手工 Markdown 知识
|
||||
k.PUT("/manual/:id", handler.UpdateManualKnowledge)
|
||||
// 获取知识文件
|
||||
k.GET("/:id/download", handler.DownloadKnowledgeFile)
|
||||
// 更新图像分块信息
|
||||
|
||||
+12
-11
@@ -10,17 +10,18 @@ import (
|
||||
// AgentConfig represents the full agent configuration (used at tenant level and runtime)
|
||||
// This includes all configuration parameters for agent execution
|
||||
type AgentConfig struct {
|
||||
Enabled bool `json:"enabled"` // Whether agent mode is enabled
|
||||
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
|
||||
ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection
|
||||
AllowedTools []string `json:"allowed_tools"` // List of allowed tool names
|
||||
Temperature float64 `json:"temperature"` // LLM temperature for agent
|
||||
ThinkingModelID string `json:"thinking_model_id"` // Model ID for reasoning
|
||||
RerankModelID string `json:"rerank_model_id"` // Model ID for reranking search results
|
||||
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
|
||||
SystemPrompt string `json:"system_prompt,omitempty"` // System prompt template with placeholders (optional)
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
|
||||
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
|
||||
Enabled bool `json:"enabled"` // Whether agent mode is enabled
|
||||
MaxIterations int `json:"max_iterations"` // Maximum number of ReAct iterations
|
||||
ReflectionEnabled bool `json:"reflection_enabled"` // Whether to enable reflection
|
||||
AllowedTools []string `json:"allowed_tools"` // List of allowed tool names
|
||||
Temperature float64 `json:"temperature"` // LLM temperature for agent
|
||||
ThinkingModelID string `json:"thinking_model_id"` // Model ID for reasoning
|
||||
RerankModelID string `json:"rerank_model_id"` // Model ID for reranking search results
|
||||
KnowledgeBases []string `json:"knowledge_bases"` // Accessible knowledge base IDs
|
||||
SystemPrompt string `json:"system_prompt,omitempty"` // System prompt template with placeholders (optional)
|
||||
UseCustomSystemPrompt bool `json:"use_custom_system_prompt"` // Whether to use custom system prompt instead of default
|
||||
WebSearchEnabled bool `json:"web_search_enabled"` // Whether web search tool is enabled
|
||||
WebSearchMaxResults int `json:"web_search_max_results"` // Maximum number of web search results (default: 5)
|
||||
}
|
||||
|
||||
// SessionAgentConfig represents session-level agent configuration
|
||||
|
||||
@@ -24,6 +24,8 @@ type KnowledgeService interface {
|
||||
CreateKnowledgeFromPassage(ctx context.Context, kbID string, passage []string) (*types.Knowledge, error)
|
||||
// CreateKnowledgeFromPassageSync creates knowledge from text passages and waits until chunks are indexed.
|
||||
CreateKnowledgeFromPassageSync(ctx context.Context, kbID string, passage []string) (*types.Knowledge, error)
|
||||
// CreateKnowledgeFromManual creates or saves manual Markdown knowledge content.
|
||||
CreateKnowledgeFromManual(ctx context.Context, kbID string, payload *types.ManualKnowledgePayload) (*types.Knowledge, error)
|
||||
// GetKnowledgeByID retrieves knowledge by ID.
|
||||
GetKnowledgeByID(ctx context.Context, id string) (*types.Knowledge, error)
|
||||
// GetKnowledgeBatch retrieves a batch of knowledge by IDs.
|
||||
@@ -42,6 +44,8 @@ type KnowledgeService interface {
|
||||
GetKnowledgeFile(ctx context.Context, id string) (io.ReadCloser, string, error)
|
||||
// UpdateKnowledge updates knowledge information.
|
||||
UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
|
||||
// UpdateManualKnowledge updates manual Markdown knowledge content.
|
||||
UpdateManualKnowledge(ctx context.Context, knowledgeID string, payload *types.ManualKnowledgePayload) (*types.Knowledge, error)
|
||||
// CloneKnowledgeBase clones knowledge to another knowledge base.
|
||||
CloneKnowledgeBase(ctx context.Context, srcID, dstID string) error
|
||||
// UpdateImageInfo updates image information for a knowledge chunk.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -8,6 +9,16 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
KnowledgeTypeManual = "manual"
|
||||
)
|
||||
|
||||
const (
|
||||
ManualKnowledgeFormatMarkdown = "markdown"
|
||||
ManualKnowledgeStatusDraft = "draft"
|
||||
ManualKnowledgeStatusPublish = "publish"
|
||||
)
|
||||
|
||||
// Knowledge represents a knowledge entity in the system.
|
||||
// It contains metadata about the knowledge source, its processing status,
|
||||
// and references to the physical file if applicable.
|
||||
@@ -77,6 +88,118 @@ func (k *Knowledge) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ManualKnowledgeMetadata stores metadata for manual Markdown knowledge content.
|
||||
type ManualKnowledgeMetadata struct {
|
||||
Content string `json:"content"`
|
||||
Format string `json:"format"`
|
||||
Status string `json:"status"`
|
||||
Version int `json:"version"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// ManualKnowledgePayload represents the payload for manual knowledge operations.
|
||||
type ManualKnowledgePayload struct {
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// NewManualKnowledgeMetadata creates a new ManualKnowledgeMetadata instance.
|
||||
func NewManualKnowledgeMetadata(content, status string, version int) *ManualKnowledgeMetadata {
|
||||
if version <= 0 {
|
||||
version = 1
|
||||
}
|
||||
return &ManualKnowledgeMetadata{
|
||||
Content: content,
|
||||
Format: ManualKnowledgeFormatMarkdown,
|
||||
Status: status,
|
||||
Version: version,
|
||||
UpdatedAt: time.Now().UTC().Format(time.RFC3339),
|
||||
}
|
||||
}
|
||||
|
||||
// ToJSON converts the metadata to JSON type.
|
||||
func (m *ManualKnowledgeMetadata) ToJSON() (JSON, error) {
|
||||
if m == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if m.Format == "" {
|
||||
m.Format = ManualKnowledgeFormatMarkdown
|
||||
}
|
||||
if m.Status == "" {
|
||||
m.Status = ManualKnowledgeStatusDraft
|
||||
}
|
||||
if m.Version <= 0 {
|
||||
m.Version = 1
|
||||
}
|
||||
if m.UpdatedAt == "" {
|
||||
m.UpdatedAt = time.Now().UTC().Format(time.RFC3339)
|
||||
}
|
||||
bytes, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return JSON(bytes), nil
|
||||
}
|
||||
|
||||
// ManualMetadata parses and returns manual knowledge metadata.
|
||||
func (k *Knowledge) ManualMetadata() (*ManualKnowledgeMetadata, error) {
|
||||
if len(k.Metadata) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var metadata ManualKnowledgeMetadata
|
||||
if err := json.Unmarshal(k.Metadata, &metadata); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if metadata.Format == "" {
|
||||
metadata.Format = ManualKnowledgeFormatMarkdown
|
||||
}
|
||||
if metadata.Version <= 0 {
|
||||
metadata.Version = 1
|
||||
}
|
||||
return &metadata, nil
|
||||
}
|
||||
|
||||
// SetManualMetadata sets manual knowledge metadata onto the knowledge instance.
|
||||
func (k *Knowledge) SetManualMetadata(meta *ManualKnowledgeMetadata) error {
|
||||
if meta == nil {
|
||||
k.Metadata = nil
|
||||
return nil
|
||||
}
|
||||
jsonValue, err := meta.ToJSON()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k.Metadata = jsonValue
|
||||
return nil
|
||||
}
|
||||
|
||||
// IsManual returns true if the knowledge item is manual Markdown knowledge.
|
||||
func (k *Knowledge) IsManual() bool {
|
||||
return k != nil && k.Type == KnowledgeTypeManual
|
||||
}
|
||||
|
||||
// EnsureManualDefaults sets default values for manual knowledge entries.
|
||||
func (k *Knowledge) EnsureManualDefaults() {
|
||||
if k == nil {
|
||||
return
|
||||
}
|
||||
if k.Type == "" {
|
||||
k.Type = KnowledgeTypeManual
|
||||
}
|
||||
if k.FileType == "" {
|
||||
k.FileType = KnowledgeTypeManual
|
||||
}
|
||||
if k.Source == "" {
|
||||
k.Source = KnowledgeTypeManual
|
||||
}
|
||||
}
|
||||
|
||||
// IsDraft returns whether the payload should be saved as draft.
|
||||
func (p ManualKnowledgePayload) IsDraft() bool {
|
||||
return p.Status == "" || p.Status == ManualKnowledgeStatusDraft
|
||||
}
|
||||
|
||||
// KnowledgeCheckParams defines parameters used to check if knowledge already exists.
|
||||
type KnowledgeCheckParams struct {
|
||||
// File parameters
|
||||
|
||||
Reference in New Issue
Block a user