feat: 工具调用链改造

This commit is contained in:
digua
2025-12-06 01:33:36 +08:00
parent 14c93bbed3
commit 5618bf7be4
7 changed files with 320 additions and 194 deletions
+3 -122
View File
@@ -243,134 +243,15 @@ watch(
<div ref="messagesContainer" class="min-h-0 flex-1 overflow-y-auto p-4">
<div class="mx-auto max-w-3xl space-y-4">
<template v-for="msg in messages" :key="msg.id">
<!-- 聊天消息 -->
<!-- 聊天消息支持 contentBlocks 混合渲染 -->
<ChatMessage
v-if="msg.role === 'user' || msg.content"
v-if="msg.role === 'user' || msg.content || (msg.contentBlocks && msg.contentBlocks.length > 0)"
:role="msg.role"
:content="msg.content"
:timestamp="msg.timestamp"
:is-streaming="msg.isStreaming"
:content-blocks="msg.contentBlocks"
/>
<!-- 工具调用链显示在用户消息后面 -->
<div
v-if="msg.role === 'user' && msg.toolCalls && msg.toolCalls.length > 0"
class="ml-11 space-y-2 rounded-lg border border-gray-200 bg-gray-50/80 px-3 py-2 dark:border-gray-700 dark:bg-gray-800/50"
>
<!-- 工具链标题 -->
<div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
<UIcon name="i-heroicons-wrench-screwdriver" class="h-3.5 w-3.5" />
<span>工具调用</span>
</div>
<!-- 工具列表 -->
<div class="space-y-1.5">
<div v-for="(tool, idx) in msg.toolCalls" :key="tool.name + idx" class="flex items-start gap-2">
<!-- 状态图标 -->
<UIcon
:name="
tool.status === 'running'
? 'i-heroicons-arrow-path'
: tool.status === 'done'
? 'i-heroicons-check-circle'
: 'i-heroicons-x-circle'
"
class="mt-0.5 h-4 w-4 shrink-0"
:class="[
tool.status === 'running'
? 'animate-spin text-pink-500'
: tool.status === 'done'
? 'text-green-500'
: 'text-red-500',
]"
/>
<div class="min-w-0 flex-1">
<!-- 工具名称 -->
<span class="text-sm font-medium text-gray-700 dark:text-gray-300">
{{ tool.displayName }}
</span>
<!-- 参数详情 -->
<div v-if="tool.params" class="mt-0.5 space-y-0.5 text-xs text-gray-500 dark:text-gray-400">
<template v-if="tool.name === 'search_messages' && tool.params.keywords">
<div>
<span class="text-gray-400">关键词:</span>
<span
v-for="(kw, kwIdx) in tool.params.keywords as string[]"
:key="kwIdx"
class="ml-1 inline-flex rounded bg-pink-100 px-1.5 py-0.5 text-pink-700 dark:bg-pink-900/40 dark:text-pink-300"
>
{{ kw }}
</span>
</div>
<!-- 时间范围LLM 指定的年/ -->
<div v-if="tool.params.year" class="text-gray-400">
<span>时间范围:</span>
<span class="ml-1 text-gray-600 dark:text-gray-300">
{{ tool.params.year }}{{ tool.params.month ? `${tool.params.month}` : '' }}
</span>
</div>
<!-- 时间范围用户筛选 -->
<div v-else-if="tool.params._timeFilter" class="text-gray-400">
<span>时间范围:</span>
<span class="ml-1 text-gray-600 dark:text-gray-300">
{{ formatTimestamp((tool.params._timeFilter as { startTs: number }).startTs) }}
</span>
<span class="mx-1"></span>
<span class="text-gray-600 dark:text-gray-300">
{{ formatTimestamp((tool.params._timeFilter as { endTs: number }).endTs) }}
</span>
</div>
<div v-else class="text-gray-400">
<span>时间范围:</span>
<span class="ml-1 text-gray-600 dark:text-gray-300">全部时间</span>
</div>
</template>
<template v-else-if="tool.name === 'get_recent_messages'">
<div>
<span class="text-gray-400">获取</span>
<span class="ml-1 text-gray-600 dark:text-gray-300">{{ tool.params.limit || 100 }}</span>
<span class="text-gray-400">条消息</span>
</div>
<!-- 时间范围LLM 指定的年/ -->
<div v-if="tool.params.year" class="text-gray-400">
<span>时间范围:</span>
<span class="ml-1 text-gray-600 dark:text-gray-300">
{{ tool.params.year }}{{ tool.params.month ? `${tool.params.month}` : '' }}
</span>
</div>
<!-- 时间范围用户筛选 -->
<div v-else-if="tool.params._timeFilter" class="text-gray-400">
<span>时间范围:</span>
<span class="ml-1 text-gray-600 dark:text-gray-300">
{{ formatTimestamp((tool.params._timeFilter as { startTs: number }).startTs) }}
</span>
<span class="mx-1"></span>
<span class="text-gray-600 dark:text-gray-300">
{{ formatTimestamp((tool.params._timeFilter as { endTs: number }).endTs) }}
</span>
</div>
</template>
<template v-else-if="tool.name === 'get_member_stats'">
<span class="text-gray-400">查询成员统计</span>
<span class="mx-0.5 text-gray-600 dark:text-gray-300">{{ tool.params.top_n || 10 }}</span>
<span class="text-gray-400"></span>
</template>
<template v-else-if="tool.name === 'get_time_stats'">
<span class="text-gray-400">统计类型:</span>
<span class="ml-1 text-gray-600 dark:text-gray-300">
{{
tool.params.type === 'hourly'
? '按小时'
: tool.params.type === 'weekday'
? '按星期'
: '按日期'
}}
</span>
</template>
</div>
</div>
</div>
</div>
</div>
</template>
<!-- AI 思考中指示器 -->
+145 -19
View File
@@ -3,6 +3,7 @@ import { computed } from 'vue'
import dayjs from 'dayjs'
import MarkdownIt from 'markdown-it'
import userAvatar from '@/assets/images/momo.png'
import type { ContentBlock } from '@/composables/useAIChat'
// Props
const props = defineProps<{
@@ -10,6 +11,8 @@ const props = defineProps<{
content: string
timestamp: number
isStreaming?: boolean
/** AI 消息的混合内容块(按时序排列的文本和工具调用) */
contentBlocks?: ContentBlock[]
}>()
// 格式化时间
@@ -28,11 +31,69 @@ const md = new MarkdownIt({
typographer: true, // 启用排版优化
})
// 渲染后的 HTML
// 渲染 Markdown 文本
function renderMarkdown(text: string): string {
if (!text) return ''
return md.render(text)
}
// 渲染后的 HTML(用于用户消息或纯文本 AI 消息)
const renderedContent = computed(() => {
if (!props.content) return ''
return md.render(props.content)
})
// 是否使用 contentBlocks 渲染(AI 消息且有 contentBlocks
const useBlocksRendering = computed(() => {
return props.role === 'assistant' && props.contentBlocks && props.contentBlocks.length > 0
})
// 格式化工具参数显示
function formatToolParams(tool: ContentBlock extends { type: 'tool'; tool: infer T } ? T : never): string {
if (!tool.params) return ''
const name = tool.name
const params = tool.params
if (name === 'search_messages' && params.keywords) {
const keywords = params.keywords as string[]
let result = `关键词: ${keywords.join(', ')}`
if (params.year) {
result += ` | 时间: ${params.year}${params.month ? `${params.month}` : ''}`
}
return result
}
if (name === 'get_recent_messages') {
let result = `获取 ${params.limit || 100} 条消息`
if (params.year) {
result += ` | ${params.year}${params.month ? `${params.month}` : ''}`
}
return result
}
if (name === 'get_member_stats') {
return `${params.top_n || 10} 名成员`
}
if (name === 'get_time_stats') {
const typeMap: Record<string, string> = {
hourly: '按小时',
weekday: '按星期',
daily: '按日期',
}
return typeMap[params.type as string] || String(params.type)
}
if (name === 'get_group_members') {
if (params.search) {
return `搜索: ${params.search}`
}
return '获取成员列表'
}
return ''
}
</script>
<template>
@@ -43,31 +104,96 @@ const renderedContent = computed(() => {
</div>
<div
v-else
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-pink-500 to-pink-600"
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-linear-to-br from-pink-500 to-pink-600"
>
<UIcon name="i-heroicons-sparkles" class="h-4 w-4 text-white" />
</div>
<!-- 消息内容 -->
<div class="max-w-[80%] min-w-0">
<div
class="rounded-2xl px-4 py-3"
:class="[
isUser
? 'rounded-tr-sm bg-blue-500 text-white'
: 'rounded-tl-sm bg-gray-100 text-gray-900 dark:bg-gray-800 dark:text-gray-100',
]"
>
<!-- 消息内容 -->
<div
class="prose prose-sm max-w-none leading-relaxed"
:class="[isUser ? 'prose-invert' : 'dark:prose-invert']"
v-html="renderedContent"
/>
<!-- 用户消息简单气泡 -->
<template v-if="isUser">
<div class="rounded-2xl rounded-tr-sm bg-blue-500 px-4 py-3 text-white">
<div class="prose prose-sm prose-invert max-w-none leading-relaxed" v-html="renderedContent" />
</div>
</template>
<!-- 流式输出光标 -->
<span v-if="isStreaming" class="ml-1 inline-block h-4 w-1.5 animate-pulse rounded-sm bg-pink-500" />
</div>
<!-- AI 消息混合内容块布局 -->
<template v-else-if="useBlocksRendering">
<div class="space-y-3">
<template v-for="(block, idx) in contentBlocks" :key="idx">
<!-- 文本块 -->
<div
v-if="block.type === 'text'"
class="rounded-2xl rounded-tl-sm bg-gray-100 px-4 py-3 text-gray-900 dark:bg-gray-800 dark:text-gray-100"
>
<div
class="prose prose-sm dark:prose-invert max-w-none leading-relaxed"
v-html="renderMarkdown(block.text)"
/>
<!-- 流式输出光标只在最后一个文本块显示 -->
<span
v-if="isStreaming && idx === contentBlocks!.length - 1"
class="ml-1 inline-block h-4 w-1.5 animate-pulse rounded-sm bg-pink-500"
/>
</div>
<!-- 工具块 -->
<div
v-else-if="block.type === 'tool'"
class="flex items-center gap-2 rounded-lg border px-3 py-2 text-sm"
:class="[
block.tool.status === 'running'
? 'border-pink-200 bg-pink-50 dark:border-pink-800/50 dark:bg-pink-900/20'
: block.tool.status === 'done'
? 'border-green-200 bg-green-50 dark:border-green-800/50 dark:bg-green-900/20'
: 'border-red-200 bg-red-50 dark:border-red-800/50 dark:bg-red-900/20',
]"
>
<!-- 状态图标 -->
<UIcon
:name="
block.tool.status === 'running'
? 'i-heroicons-arrow-path'
: block.tool.status === 'done'
? 'i-heroicons-check-circle'
: 'i-heroicons-x-circle'
"
class="h-4 w-4 shrink-0"
:class="[
block.tool.status === 'running'
? 'animate-spin text-pink-500'
: block.tool.status === 'done'
? 'text-green-500'
: 'text-red-500',
]"
/>
<!-- 工具信息 -->
<div class="min-w-0 flex-1">
<!-- 调用前缀 -->
<span class="text-xs text-gray-400 dark:text-gray-500 mr-1">调用</span>
<span class="font-medium text-gray-700 dark:text-gray-300">
{{ block.tool.displayName }}
</span>
<span
v-if="formatToolParams(block.tool)"
class="ml-2 text-xs text-gray-500 dark:text-gray-400"
>
{{ formatToolParams(block.tool) }}
</span>
</div>
</div>
</template>
</div>
</template>
<!-- AI 消息传统纯文本渲染向后兼容 -->
<template v-else>
<div class="rounded-2xl rounded-tl-sm bg-gray-100 px-4 py-3 text-gray-900 dark:bg-gray-800 dark:text-gray-100">
<div class="prose prose-sm dark:prose-invert max-w-none leading-relaxed" v-html="renderedContent" />
<span v-if="isStreaming" class="ml-1 inline-block h-4 w-1.5 animate-pulse rounded-sm bg-pink-500" />
</div>
</template>
<!-- 时间戳 -->
<div class="mt-1 px-1" :class="[isUser ? 'text-right' : '']">
+107 -43
View File
@@ -17,6 +17,19 @@ export interface ToolCallRecord {
params?: Record<string, unknown>
}
// 内容块类型(用于 AI 消息的流式混合渲染)
export type ContentBlock =
| { type: 'text'; text: string }
| {
type: 'tool'
tool: {
name: string
displayName: string
status: 'running' | 'done' | 'error'
params?: Record<string, unknown>
}
}
// 消息类型
export interface ChatMessage {
id: string
@@ -27,8 +40,10 @@ export interface ChatMessage {
toolsUsed: string[]
toolRounds: number
}
/** 工具调用记录(用户消息后显示) */
/** @deprecated 使用 contentBlocks 替代 */
toolCalls?: ToolCallRecord[]
/** AI 消息的内容块数组(按时序排列的文本和工具调用) */
contentBlocks?: ContentBlock[]
isStreaming?: boolean
}
@@ -151,7 +166,7 @@ export function useAIChat(
const thisRequestId = currentRequestId
console.log('[AI] 开始 Agent 处理...', { requestId: thisRequestId })
// 创建 AI 响应消息占位符
// 创建 AI 响应消息占位符(使用 contentBlocks 数组)
const aiMessageId = generateId('ai')
const aiMessage: ChatMessage = {
id: aiMessageId,
@@ -159,10 +174,67 @@ export function useAIChat(
content: '',
timestamp: Date.now(),
isStreaming: true,
contentBlocks: [], // 初始化内容块数组
}
messages.value.push(aiMessage)
const aiMessageIndex = messages.value.length - 1
// 辅助函数:更新 AI 消息
const updateAIMessage = (updates: Partial<ChatMessage>) => {
messages.value[aiMessageIndex] = {
...messages.value[aiMessageIndex],
...updates,
}
}
// 辅助函数:获取或创建当前文本块
const appendTextToBlocks = (text: string) => {
const blocks = messages.value[aiMessageIndex].contentBlocks || []
const lastBlock = blocks[blocks.length - 1]
if (lastBlock && lastBlock.type === 'text') {
// 追加到现有文本块
lastBlock.text += text
} else {
// 创建新文本块
blocks.push({ type: 'text', text })
}
updateAIMessage({
contentBlocks: [...blocks],
content: messages.value[aiMessageIndex].content + text, // 同时更新 content 用于向后兼容和数据库存储
})
}
// 辅助函数:添加工具块
const addToolBlock = (toolName: string, params?: Record<string, unknown>) => {
const blocks = messages.value[aiMessageIndex].contentBlocks || []
blocks.push({
type: 'tool',
tool: {
name: toolName,
displayName: TOOL_DISPLAY_NAMES[toolName] || toolName,
status: 'running',
params,
},
})
updateAIMessage({ contentBlocks: [...blocks] })
}
// 辅助函数:更新工具块状态
const updateToolBlockStatus = (toolName: string, status: 'done' | 'error') => {
const blocks = messages.value[aiMessageIndex].contentBlocks || []
// 找到最后一个匹配的 running 状态的工具块
for (let i = blocks.length - 1; i >= 0; i--) {
const block = blocks[i]
if (block.type === 'tool' && block.tool.name === toolName && block.tool.status === 'running') {
block.tool.status = status
break
}
}
updateAIMessage({ contentBlocks: [...blocks] })
}
try {
// 调用 Agent API
const context = {
@@ -202,28 +274,18 @@ export function useAIChat(
switch (chunk.type) {
case 'content':
// 流式内容更新
// 流式内容更新 - 追加到 contentBlocks
if (chunk.content) {
// 清除工具状态,开始显示内容
currentToolStatus.value = null
messages.value[aiMessageIndex] = {
...messages.value[aiMessageIndex],
content: messages.value[aiMessageIndex].content + chunk.content,
}
appendTextToBlocks(chunk.content)
}
break
case 'tool_start':
// 工具开始执行 - 更新状态并记录到用户消息(包含参数)
// 工具开始执行 - 添加工具块到 contentBlocks
console.log('[AI] 工具开始执行:', chunk.toolName, chunk.toolParams)
if (chunk.toolName) {
const toolRecord: ToolCallRecord = {
name: chunk.toolName,
displayName: TOOL_DISPLAY_NAMES[chunk.toolName] || chunk.toolName,
status: 'running',
timestamp: Date.now(),
params: chunk.toolParams as Record<string, unknown>,
}
const toolParams = chunk.toolParams as Record<string, unknown> | undefined
currentToolStatus.value = {
name: chunk.toolName,
displayName: TOOL_DISPLAY_NAMES[chunk.toolName] || chunk.toolName,
@@ -231,43 +293,23 @@ export function useAIChat(
}
toolsUsedInCurrentRound.value.push(chunk.toolName)
// 更新用户消息的工具调用记录
const userMsg = messages.value[userMessageIndex]
if (userMsg.toolCalls) {
userMsg.toolCalls = [...userMsg.toolCalls, toolRecord]
} else {
userMsg.toolCalls = [toolRecord]
}
messages.value[userMessageIndex] = { ...userMsg }
// 添加工具块到 AI 消息的 contentBlocks
addToolBlock(chunk.toolName, toolParams)
}
break
case 'tool_result':
// 工具执行结果 - 更新工具状态为完成
// 工具执行结果 - 更新工具状态
console.log('[AI] 工具执行结果:', chunk.toolName, chunk.toolResult)
if (chunk.toolName) {
// 更新 currentToolStatus
if (currentToolStatus.value?.name === chunk.toolName) {
currentToolStatus.value = {
...currentToolStatus.value,
status: 'done',
}
}
// 更新用户消息中的工具调用状态
const userMsg = messages.value[userMessageIndex]
if (userMsg.toolCalls) {
const toolIndex = userMsg.toolCalls.findIndex(
(t) => t.name === chunk.toolName && t.status === 'running'
)
if (toolIndex >= 0) {
userMsg.toolCalls[toolIndex] = {
...userMsg.toolCalls[toolIndex],
status: 'done',
}
messages.value[userMessageIndex] = { ...userMsg }
}
}
// 更新 contentBlocks 中的工具块状态
updateToolBlockStatus(chunk.toolName, 'done')
}
isLoadingSource.value = false
break
@@ -286,6 +328,8 @@ export function useAIChat(
...currentToolStatus.value,
status: 'error',
}
// 更新对应工具块状态为错误
updateToolBlockStatus(currentToolStatus.value.name, 'error')
}
break
}
@@ -372,13 +416,23 @@ export function useAIChat(
// 保存用户消息
await window.aiApi.addMessage(currentConversationId.value, 'user', userMsg.content)
// 保存 AI 消息
// 保存 AI 消息(包含 contentBlocks
// 注意:需要深拷贝 contentBlocks 以确保可序列化(避免 Vue 响应式代理对象)
const serializableContentBlocks = aiMsg.contentBlocks
? JSON.parse(JSON.stringify(aiMsg.contentBlocks))
: undefined
console.log('[AI] 保存 AI 消息:', {
contentLength: aiMsg.content?.length,
hasContentBlocks: !!serializableContentBlocks,
contentBlocksLength: serializableContentBlocks?.length,
})
await window.aiApi.addMessage(
currentConversationId.value,
'assistant',
aiMsg.content,
undefined, // 不再保存关键词
undefined
undefined,
serializableContentBlocks // 保存内容块(已序列化)
)
console.log('[AI] 消息保存完成')
} catch (error) {
@@ -395,11 +449,21 @@ export function useAIChat(
const history = await window.aiApi.getMessages(conversationId)
currentConversationId.value = conversationId
console.log('[AI] 从数据库加载的原始消息:', history.map((m) => ({
id: m.id,
role: m.role,
contentLength: m.content?.length,
hasContentBlocks: !!m.contentBlocks,
contentBlocksLength: m.contentBlocks?.length,
})))
messages.value = history.map((msg) => ({
id: msg.id,
role: msg.role,
content: msg.content,
timestamp: msg.timestamp * 1000,
// 加载保存的 contentBlocks(如果有)
contentBlocks: msg.contentBlocks as ContentBlock[] | undefined,
}))
console.log('[AI] 加载完成,messages.value 数量:', messages.value.length)
} catch (error) {