diff --git a/apps/rag-knowledge-agent/src/app/api/chat/route.ts b/apps/rag-knowledge-agent/src/app/api/chat/route.ts index 47443a2..1520b41 100644 --- a/apps/rag-knowledge-agent/src/app/api/chat/route.ts +++ b/apps/rag-knowledge-agent/src/app/api/chat/route.ts @@ -134,10 +134,14 @@ export async function POST(request: NextRequest) { .map((i) => i.stackone_account_id) .filter((id): id is string => Boolean(id)) - logger.log('Chat API - Starting agent loop', { - documentIds: documentIds.length, + console.log('[Chat API] Starting agent loop', { + integrationIdsFromAgent: integrationIds.length, + integrationsFound: integrations.length, accountIds: accountIds.length, + accountIdPreviews: accountIds.map(id => id.slice(0, 12) + '...'), + documentIds: documentIds.length, documentContext: documentContext.length, + hasStackOneApiKey: !!process.env.STACKONE_API_KEY, }) let fullResponse = '' diff --git a/apps/rag-knowledge-agent/src/lib/chat/vercel-agent.ts b/apps/rag-knowledge-agent/src/lib/chat/vercel-agent.ts index ea7b786..332584e 100644 --- a/apps/rag-knowledge-agent/src/lib/chat/vercel-agent.ts +++ b/apps/rag-knowledge-agent/src/lib/chat/vercel-agent.ts @@ -52,9 +52,24 @@ export async function* runVercelAgent( const ragService = new RAGService() // StackOne utility tools (tool_search + tool_execute): model discovers tools via search, then executes by name + console.log('[Agent] Loading utility tools', { accountIds: accountIds.length, hasApiKey: !!process.env.STACKONE_API_KEY }) + if (accountIds.length === 0) { + console.warn( + '[Agent] No StackOne account IDs for this agent — tool_search/tool_execute are disabled. Link integrations to the agent (with a connected StackOne account) and ensure STACKONE_API_KEY is set.' + ) + } + const aiSdkUtilityTools = accountIds.length > 0 ? await getStackOneUtilityToolsForAISDK(accountIds) : {} - const systemPrompt = `You are a helpful AI assistant with access to the following tools. Use each when appropriate: + const hasActionTools = Object.keys(aiSdkUtilityTools).length > 0 + console.log('[Agent] Utility tools result', { hasActionTools, toolNames: Object.keys(aiSdkUtilityTools) }) + if (accountIds.length > 0 && !hasActionTools) { + console.error( + '[Agent] StackOne utility tools failed to load (empty tool_search/tool_execute). Check STACKONE_API_KEY, STACKONE_BASE_URL, and server logs from getStackOneUtilityToolsForAISDK.' + ) + } + + const systemPromptWithActions = `You are a helpful AI assistant with access to the following tools. Use each when appropriate: **getInformationFromRAG** – Use when the user asks a question about their documents, when you need to read or search document content, or when you need a document identifier (remote_document_id) or current content to perform an action. Do not use when the request does not involve the user's documents or when you already have the needed content or ids from context. @@ -66,6 +81,16 @@ export async function* runVercelAgent( Respond in natural language. After using tools, summarize outcomes for the user. If a tool returns an error, report it clearly and suggest what the user can check or try.` + const systemPromptRagOnly = `You are a helpful AI assistant with access to **getInformationFromRAG** only (search/read indexed documents). You do **not** have tools to update Google Docs, Drive, or other live apps in this session. + +**getInformationFromRAG** – Use when the user asks about their documents, needs content or quotes, or needs a remote_document_id from indexed material. + +If the user asks to update, edit, or change a live document in a connected app, explain clearly that realtime actions require this agent to have StackOne integrations linked (with an active connection) and STACKONE_API_KEY configured on the server; you can still help using retrieved document content where applicable. + +Respond in natural language. If a tool returns an error, report it clearly.` + + const systemPrompt = hasActionTools ? systemPromptWithActions : systemPromptRagOnly + // Add document context to system prompt if available let enhancedSystemPrompt = systemPrompt if (documentContext.length > 0) { diff --git a/apps/rag-knowledge-agent/src/lib/stackone/meta-tools.ts b/apps/rag-knowledge-agent/src/lib/stackone/meta-tools.ts index 1467aee..c5fb226 100644 --- a/apps/rag-knowledge-agent/src/lib/stackone/meta-tools.ts +++ b/apps/rag-knowledge-agent/src/lib/stackone/meta-tools.ts @@ -238,16 +238,18 @@ export interface UtilityToolsResult { */ async function getToolsForAccounts(accountIds: string[]) { if (!process.env.STACKONE_API_KEY) { + console.error('[StackOne tools] STACKONE_API_KEY is not configured') throw new Error('STACKONE_API_KEY is not configured') } - const toolset = new StackOneToolSet({ - baseUrl: process.env.STACKONE_BASE_URL ?? 'https://api.stackone.com', - }) + const baseUrl = process.env.STACKONE_BASE_URL ?? 'https://api.stackone.com' + console.log('[StackOne tools] fetchTools starting', { accountCount: accountIds.length, baseUrl }) + const toolset = new StackOneToolSet({ baseUrl }) const tools = await toolset.fetchTools({ accountIds }) const accountIdsForLog = accountIds.map((id) => id.slice(0, 12) + '...') - logger.log('[StackOne tools] fetchTools:', { accountCount: accountIds.length, accountIdsForLog, toolCount: tools.toArray().length }) + const toolCount = tools.toArray().length + console.log('[StackOne tools] fetchTools result:', { accountIdsForLog, toolCount }) return tools } @@ -261,12 +263,16 @@ async function getToolsForAccounts(accountIds: string[]) { export async function getStackOneUtilityToolsForAISDK(accountIds: string[]) { if (accountIds.length === 0) return {} try { + console.log('[StackOne tools] getStackOneUtilityToolsForAISDK: fetching tools...') const tools = await getToolsForAccounts(accountIds) + console.log('[StackOne tools] getStackOneUtilityToolsForAISDK: calling utilityTools()...') const utilityTools = await tools.utilityTools() + console.log('[StackOne tools] getStackOneUtilityToolsForAISDK: getting tool_search and tool_execute...') const searchTool = utilityTools.getTool('tool_search') const executeTool = utilityTools.getTool('tool_execute') + console.log('[StackOne tools] getStackOneUtilityToolsForAISDK:', { hasSearchTool: !!searchTool, hasExecuteTool: !!executeTool }) if (!searchTool || !executeTool) { - logger.warn('[StackOne tools] tool_search or tool_execute not available') + console.error('[StackOne tools] tool_search or tool_execute not available from utilityTools()') return {} } @@ -306,7 +312,7 @@ export async function getStackOneUtilityToolsForAISDK(accountIds: string[]) { } return requiredNext as JsonObject } catch (error) { - logger.log('[StackOne tools] tool_search (AI SDK) error:', error instanceof Error ? error.message : error) + console.error('[StackOne tools] tool_search (AI SDK) error:', error instanceof Error ? error.message : error) return { error: error instanceof Error ? error.message : String(error) } } }, @@ -343,9 +349,9 @@ export async function getStackOneUtilityToolsForAISDK(accountIds: string[]) { } return result } catch (error) { - logger.log('[StackOne tools] tool_execute (AI SDK) error:', { toolName, error: error instanceof Error ? error.message : String(error) }) + console.error('[StackOne tools] tool_execute (AI SDK) error:', { toolName, error: error instanceof Error ? error.message : String(error) }) if (debugPayloads) { - logger.log('[StackOne tools] tool_execute (AI SDK) error detail:', error) + console.error('[StackOne tools] tool_execute (AI SDK) error detail:', error) } return { error: error instanceof Error ? error.message : String(error) } } @@ -357,7 +363,7 @@ export async function getStackOneUtilityToolsForAISDK(accountIds: string[]) { tool_execute: toolExecuteAISDK, } } catch (error) { - logger.error('[StackOne tools] Failed to get utility tools for AI SDK:', error) + console.error('[StackOne tools] Failed to get utility tools for AI SDK:', error instanceof Error ? { message: error.message, stack: error.stack } : error) return {} } } diff --git a/apps/rag-knowledge-agent/src/utils/logger.ts b/apps/rag-knowledge-agent/src/utils/logger.ts index b7e48fd..28efb27 100644 --- a/apps/rag-knowledge-agent/src/utils/logger.ts +++ b/apps/rag-knowledge-agent/src/utils/logger.ts @@ -3,25 +3,20 @@ * Set DEBUG=1 or DEBUG_CHAT=1 in .env.local to enable verbose logging. */ -const isDevelopment = process.env.NODE_ENV === 'development'; -const isDebug = isDevelopment && (process.env.DEBUG === '1' || process.env.DEBUG === 'true' || process.env.DEBUG_CHAT === '1' || process.env.DEBUG_CHAT === 'true'); +const isDebug = process.env.DEBUG === '1' || process.env.DEBUG === 'true' || process.env.DEBUG_CHAT === '1' || process.env.DEBUG_CHAT === 'true'; export const logger = { - /** Only logs when DEBUG or DEBUG_CHAT is set (in dev). Use for verbose/trace. */ + /** Only logs when DEBUG or DEBUG_CHAT is set. Use for verbose/trace. */ log: (...args: unknown[]) => { if (isDebug) { console.log(...args); } }, warn: (...args: unknown[]) => { - if (isDevelopment) { - console.warn(...args); - } + console.warn(...args); }, error: (...args: unknown[]) => { - if (isDevelopment) { - console.error(...args); - } + console.error(...args); }, info: (...args: unknown[]) => { if (isDebug) {