Open source file-system and knowledge based agent template. Build AI agents that stay up to date with your knowledge base
use events tools
Hugo Richard5dcc9698bda8
diff --git a/apps/chat/app/components/ToolCallItem.vue b/apps/chat/app/components/ToolCallItem.vueindex 66a7a74..51c7915 100644--- a/apps/chat/app/components/ToolCallItem.vue+++ b/apps/chat/app/components/ToolCallItem.vue@@ -10,24 +10,8 @@ const props = defineProps<{const isExpanded = ref(false)const displayedLabel = ref('')-const adminToolLabels: Record<string, { loading: string, done: string }> = {- query_stats: { loading: 'Querying usage statistics', done: 'Queried usage statistics' },- list_users: { loading: 'Listing users', done: 'Listed users' },- list_sources: { loading: 'Listing sources', done: 'Listed sources' },- query_chats: { loading: 'Querying chats', done: 'Queried chats' },- run_sql: { loading: 'Running SQL query', done: 'Ran SQL query' },- get_agent_config: { loading: 'Fetching agent config', done: 'Fetched agent config' },- chart: { loading: 'Generating chart', done: 'Generated chart' },-}-const fullLabel = computed(() => {const { toolName, args, state } = props.tool-- const adminLabel = adminToolLabels[toolName]- if (adminLabel) {- return state === 'loading' ? adminLabel.loading : adminLabel.done- }-const commands = args?.commands as string[] || (args?.command ? [args.command as string] : [])if (toolName === 'search_and_read') {@@ -74,8 +58,8 @@ function summarizeCommand(cmd: string): string {return `ls ${dirName}`}- const [cmdName] = firstPart.split(/\s+/)- return cmdName || 'command'+ // For non-shell commands (e.g. admin tool labels), return the full text+ return firstPart.length > 60 ? `${firstPart.slice(0, 60)}…` : firstPart || 'command'}let typewriterTimeout: ReturnType<typeof setTimeout> | null = null@@ -118,6 +102,14 @@ watch(() => props.tool.state, (newState, oldState) => {if (newState === 'loading' && oldState !== 'loading') {startExpand()} else if (newState === 'done' && oldState === 'loading') {+ // If loading was too brief for the 150ms expand timer to fire, expand now+ if (!isExpanded.value) {+ isExpanded.value = true+ }+ startCollapse()+ } else if (newState === 'done' && oldState === undefined) {+ // Tool arrived with loading+done batched in the same tick (fast admin tools)+ isExpanded.value = truestartCollapse()}}, { immediate: true })@@ -200,14 +192,15 @@ function truncateOutput(text: string, maxLines = 8): string {<AnimatePresence><motion.div- v-if="isExpanded && commandsToShow.length"+ v-if="isExpanded && canExpand"+ key="expanded":initial="{ height: 0, opacity: 0 }":animate="{ height: 'auto', opacity: 1 }":exit="{ height: 0, opacity: 0 }":transition="{ duration: 0.3, ease: [0.25, 0.1, 0.25, 1] }"class="overflow-hidden">- <div class="ml-2.5 pl-1.5 border-l border-muted/15 mt-0.5 mb-1 space-y-1">+ <div v-if="commandsToShow.length" class="ml-2.5 pl-1.5 border-l border-muted/15 mt-0.5 mb-1 space-y-1"><divv-for="(cmd, idx) in commandsToShow":key="idx"diff --git a/apps/chat/app/pages/chat/[id].vue b/apps/chat/app/pages/chat/[id].vueindex 35a2853..6c3a5e2 100644--- a/apps/chat/app/pages/chat/[id].vue+++ b/apps/chat/app/pages/chat/[id].vue@@ -187,7 +187,7 @@ function getMessageToolCalls(message: UIMessage): ToolCall[] {if (!message?.parts) return []return (message.parts as Array<{ type: string, data?: ToolCall }>).filter(p => p.type === 'data-tool-call')- .map(p => p.data!)+ .map(p => ({ ...p.data! })).filter(Boolean)}diff --git a/apps/chat/app/pages/shared/[token].vue b/apps/chat/app/pages/shared/[token].vueindex b44cd43..20e5b0b 100644--- a/apps/chat/app/pages/shared/[token].vue+++ b/apps/chat/app/pages/shared/[token].vue@@ -100,7 +100,7 @@ definePageMeta({class="pt-4 sm:pt-6 pb-4 sm:pb-6"><template #content="{ message }">- <template v-for="(part, index) in message.parts.filter(p => p.type !== 'data-sources')" :key="`${message.id}-${part.type}-${index}`">+ <template v-for="(part, index) in message.parts.filter(p => p.type !== 'data-sources')" :key="`${message.id}-${part.type}-${index}-${part.type.startsWith('tool-') ? (part as any).state ?? '' : ''}`"><Reasoningv-if="part.type === 'reasoning'":text="part.text"diff --git a/apps/chat/server/api/chats/[id].post.ts b/apps/chat/server/api/chats/[id].post.tsindex bada84d..b572d41 100644--- a/apps/chat/server/api/chats/[id].post.ts+++ b/apps/chat/server/api/chats/[id].post.ts@@ -20,6 +20,25 @@ defineRouteMeta({},})+/** Build a human-readable label for an admin tool call (used as `command`). */+function adminToolLabel(toolName: string, args: Record<string, unknown>): string {+ switch (toolName) {+ case 'run_sql': {+ const q = String(args?.query || '').trim()+ return q.length > 80 ? `${q.slice(0, 80)}…` : q || 'SQL query'+ }+ case 'query_stats': return 'Query stats'+ case 'list_users': return 'List users'+ case 'list_sources': return 'List sources'+ case 'query_chats': return 'Query chats'+ case 'get_agent_config': return 'Get agent config'+ case 'query_logs': return 'Query logs'+ case 'log_stats': return 'Log stats'+ case 'query_errors': return 'Query errors'+ default: return toolName.replace(/_/g, ' ')+ }+}+export default defineEventHandler(async (event) => {const requestLog = useLogger(event)const requestId = crypto.randomUUID().slice(0, 8)@@ -124,13 +143,79 @@ export default defineEventHandler(async (event) => {let routingResult: RoutingResult | undefinedlet effectiveModel = model+ // Wrap admin tools to emit loading/done events using the same format as SDK tools.+ // Exclude 'chart' which has its own native UI via tool-chart parts.+ const wrappedAdminTools = isAdminChat+ ? Object.fromEntries(+ Object.entries(adminTools).map(([name, t]) => {+ if (name === 'chart') return [name, t]+ return [+ name,+ {+ ...(t as Record<string, unknown>),+ execute: (args: Record<string, unknown>, options: { toolCallId: string }) => {+ const label = adminToolLabel(name, args)++ // Emit loading event (same shape as SDK tools)+ if (streamWriter) {+ streamWriter.write({+ type: 'data-tool-call',+ id: options.toolCallId,+ data: {+ toolCallId: options.toolCallId,+ toolName: name,+ args: { command: label },+ state: 'loading',+ },+ })+ }++ const start = Date.now()+ const promise = (t as any).execute(args, options) as Promise<unknown>++ // Emit done event with result as stdout (same shape as SDK tools)+ return promise.then((output: unknown) => {+ if (streamWriter) {+ streamWriter.write({+ type: 'data-tool-call',+ id: options.toolCallId,+ data: {+ toolCallId: options.toolCallId,+ toolName: name,+ args: { command: label },+ state: 'done',+ result: {+ success: true,+ durationMs: Date.now() - start,+ commands: [+ {+ command: label,+ stdout: JSON.stringify(output, null, 2),+ stderr: '',+ exitCode: 0,+ success: true,+ },+ ],+ },+ },+ })+ }+ return output+ })+ },+ },+ ]+ }),+ )+ : undefined+const agent = createAgent({tools: savoir.tools,route: () => routeQuestion(messages, requestId),buildPrompt: (routerConfig, agentConfig) => applyComplexity(buildChatSystemPrompt(agentConfig), routerConfig),resolveModel: (_, agentConfig) => agentConfig.defaultModel || model,- admin: isAdminChat- ? { tools: adminTools, systemPrompt: ADMIN_SYSTEM_PROMPT }+ admin: wrappedAdminTools+ ? { tools: wrappedAdminTools, systemPrompt: ADMIN_SYSTEM_PROMPT }: undefined,onRouted: (routed) => {routingResult = routed@@ -153,26 +238,8 @@ export default defineEventHandler(async (event) => {const tools = stepResult.toolCalls.map((c: { toolName: string }) => c.toolName).join(', ')log.info('chat', `[${requestId}] Step ${stepCount}: ${tools} (${stepDurationMs}ms)`)- // Emit tool call events for admin tools (SDK tools handle this via onToolCall)- if (isAdminChat && streamWriter) {- for (const tc of stepResult.toolCalls) {- streamWriter.write({- type: 'data-tool-call',- id: tc.toolCallId,- data: {- toolCallId: tc.toolCallId,- toolName: tc.toolName,- args: tc.args,- state: 'done',- result: {- success: true,- durationMs: stepDurationMs,- commands: [],- },- },- })- }- }+ // Admin tool call events (loading + done) are emitted from the tool wrapper itself,+ // so no additional emission is needed here.} else {log.info('chat', `[${requestId}] Step ${stepCount}: response (${stepDurationMs}ms)`)}diff --git a/apps/chat/server/utils/chat/admin-tools/index.ts b/apps/chat/server/utils/chat/admin-tools/index.tsindex b5921cc..35527a3 100644--- a/apps/chat/server/utils/chat/admin-tools/index.ts+++ b/apps/chat/server/utils/chat/admin-tools/index.ts@@ -4,6 +4,9 @@ import { listSourcesTool } from './list-sources'import { queryChatsTool } from './query-chats'import { runSqlTool } from './run-sql'import { getAgentConfigTool } from './get-agent-config'+import { queryLogsTool } from './query-logs'+import { logStatsTool } from './log-stats'+import { queryErrorsTool } from './query-errors'import { chartTool } from '~~/shared/utils/tools/chart'export const adminTools = {@@ -13,5 +16,8 @@ export const adminTools = {query_chats: queryChatsTool,run_sql: runSqlTool,get_agent_config: getAgentConfigTool,+ query_logs: queryLogsTool,+ log_stats: logStatsTool,+ query_errors: queryErrorsTool,chart: chartTool,}diff --git a/apps/chat/server/utils/prompts/chat.ts b/apps/chat/server/utils/prompts/chat.tsindex 0c50bd5..d7c06d7 100644--- a/apps/chat/server/utils/prompts/chat.ts+++ b/apps/chat/server/utils/prompts/chat.ts@@ -12,6 +12,9 @@ You have access to admin tools that query the application's internal data:- **query_chats**: Browse recent chats to understand user questions and topics- **run_sql**: Execute read-only SQL queries for custom data analysis- **get_agent_config**: Check the current assistant configuration+- **query_logs**: Browse and search recent production logs. Filter by level, path, status, method, or keyword.+- **log_stats**: Get aggregated log statistics — error rates, latency percentiles, top endpoints, status distribution.+- **query_errors**: Error-focused analysis with recent errors, error groups, and hourly error trends.- **chart**: Create line chart visualizations to display data trends. Use this to visualize time-series data, usage trends, token consumption over time, etc.## Guidelines@@ -19,8 +22,19 @@ You have access to admin tools that query the application's internal data:- Use tools to fetch real data before answering. Never guess or make up numbers.- When asked about usage or stats, use query_stats first to get an overview.- For user-related questions, use list_users to get actual data.+- For app health, errors, or latency questions, use log_stats and query_errors to get real production data.- Use run_sql for complex queries that other tools can't handle.-- **When data has a time dimension (daily stats, trends, etc.), use the chart tool** to create a visual representation. This provides much better readability than raw numbers. ALWAYS provide startDate and endDate to define the full date range (e.g., for "last 30 days", set startDate to 30 days ago and endDate to today).++### Visualize everything you can++- **ALWAYS use the chart tool when data has a time dimension** (daily stats, trends, hourly patterns, etc.). Charts are far more readable than tables of numbers.+- ALWAYS provide startDate and endDate to define the full date range (e.g., for "last 30 days", set startDate to 30 days ago and endDate to today).+- Combine multiple data series in a single chart when it makes sense (e.g., tokens by model, errors vs requests).+- When showing stats, lead with a chart then follow with key numbers. Don't dump raw tables when a chart tells the story better.+- For error trends, latency over time, usage growth — always chart first, summarize second.++### Response style+- Present data clearly with tables, lists, or summaries as appropriate.- Use markdown formatting for readability.- Be concise but thorough in your analysis.