📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
add some logging
Blue Mouse7e50f77f1718
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.tsindex e96e56342..836c60f14 100644--- a/backend/apps/cloud/src/ai/ai.controller.ts+++ b/backend/apps/cloud/src/ai/ai.controller.ts@@ -94,6 +94,11 @@ export class AiController {)}+ this.logger.log(+ { pid, uid, messageCount: messages.length },+ 'Starting AI chat stream',+ )+// Get streaming response from AIconst result = await this.aiService.chat(project,@@ -102,46 +107,87 @@ export class AiController {)// Stream the full response including tool calls and reasoning- for await (const part of result.fullStream) {- if (part.type === 'text-delta') {- res.write(- `data: ${JSON.stringify({ type: 'text', content: part.textDelta })}\n\n`,- )- } else if (part.type === 'tool-call') {- // Send tool call info for UI feedback- res.write(- `data: ${JSON.stringify({- type: 'tool-call',- toolName: part.toolName,- args: part.args,- })}\n\n`,- )- } else if (part.type === 'tool-result') {- // Send tool result for transparency (limit result size to avoid huge payloads)- const resultPreview =- typeof part.result === 'object'- ? JSON.stringify(part.result).slice(0, 1000)- : String(part.result).slice(0, 1000)- res.write(- `data: ${JSON.stringify({- type: 'tool-result',- toolName: part.toolName,- result: resultPreview,- })}\n\n`,- )- } else if (part.type === 'reasoning') {- // Stream reasoning/thinking tokens if available+ // Wrap in try-catch to handle provider errors gracefully+ let hasContent = false+ try {+ for await (const part of result.fullStream) {+ if (part.type === 'text-delta') {+ hasContent = true+ res.write(+ `data: ${JSON.stringify({ type: 'text', content: part.textDelta })}\n\n`,+ )+ this.logger.debug(+ { pid, textLength: part.textDelta.length },+ 'AI text delta',+ )+ } else if (part.type === 'tool-call') {+ hasContent = true+ // Send tool call info for UI feedback+ res.write(+ `data: ${JSON.stringify({+ type: 'tool-call',+ toolName: part.toolName,+ args: part.args,+ })}\n\n`,+ )+ this.logger.log(+ { pid, toolName: part.toolName, args: part.args },+ 'AI tool call',+ )+ } else if (part.type === 'tool-result') {+ // Send tool result for transparency (limit result size to avoid huge payloads)+ const resultPreview =+ typeof part.result === 'object'+ ? JSON.stringify(part.result).slice(0, 1000)+ : String(part.result).slice(0, 1000)+ res.write(+ `data: ${JSON.stringify({+ type: 'tool-result',+ toolName: part.toolName,+ result: resultPreview,+ })}\n\n`,+ )+ this.logger.log(+ {+ pid,+ toolName: part.toolName,+ resultLength: resultPreview.length,+ },+ 'AI tool result',+ )+ } else if (part.type === 'reasoning') {+ hasContent = true+ // Stream reasoning/thinking tokens if available+ res.write(+ `data: ${JSON.stringify({ type: 'reasoning', content: part.textDelta })}\n\n`,+ )+ } else if (part.type === 'error') {+ // Handle errors during streaming (emitted by AI SDK)+ this.logger.error(+ { error: part.error, pid, uid },+ 'Error event during AI stream',+ )+ // Don't end the stream on error events - the provider may continue+ res.write(+ `data: ${JSON.stringify({ type: 'error', content: 'A temporary error occurred, continuing...' })}\n\n`,+ )+ }+ }+ } catch (streamError) {+ // Handle errors thrown during stream iteration (e.g., malformed provider responses)+ this.logger.error(+ { error: streamError, pid, uid },+ 'Exception during AI stream iteration',+ )++ // If we already have some content, send what we have with an error notice+ if (hasContent) {res.write(- `data: ${JSON.stringify({ type: 'reasoning', content: part.textDelta })}\n\n`,- )- } else if (part.type === 'error') {- // Handle errors during streaming- this.logger.error(- { error: part.error, pid, uid },- 'Error during AI stream',+ `data: ${JSON.stringify({ type: 'error', content: 'The response was interrupted due to a provider error.' })}\n\n`,)+ } else {res.write(- `data: ${JSON.stringify({ type: 'error', content: 'An error occurred while processing your request' })}\n\n`,+ `data: ${JSON.stringify({ type: 'error', content: 'Failed to get a response from the AI provider. Please try again.' })}\n\n`,)}}@@ -149,6 +195,8 @@ export class AiController {// Send done eventres.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`)res.end()++ this.logger.log({ pid, uid }, 'AI chat stream completed')} catch (error) {this.logger.error({ error, pid, uid }, 'Error in AI chat')diff --git a/backend/apps/cloud/src/ai/ai.service.ts b/backend/apps/cloud/src/ai/ai.service.tsindex e3fb0b0d3..7abb3e323 100644--- a/backend/apps/cloud/src/ai/ai.service.ts+++ b/backend/apps/cloud/src/ai/ai.service.ts@@ -1,6 +1,6 @@import { Injectable } from '@nestjs/common'import { createOpenAI } from '@ai-sdk/openai'-import { streamText, tool, CoreMessage } from 'ai'+import { streamText, tool, CoreMessage, StreamTextResult } from 'ai'import { z } from 'zod'import _isEmpty from 'lodash/isEmpty'import _map from 'lodash/map'@@ -40,9 +40,24 @@ export class AiService {project: Project,messages: CoreMessage[],timezone: string = 'UTC',- ) {+ ): Promise<+ StreamTextResult<+ typeof this.buildTools extends (...args: any[]) => infer R ? R : never,+ never+ >+ > {const systemPrompt = this.buildSystemPrompt(project, timezone)+ this.logger.log(+ {+ pid: project.id,+ messageCount: messages.length,+ lastMessage: messages[messages.length - 1]?.content?.slice(0, 100),+ timezone,+ },+ 'AI chat request',+ )+const result = streamText({model: this.openrouter('openai/gpt-oss-120b'),system: systemPrompt,@@ -105,8 +120,20 @@ The data object should have "x" for x-axis labels and named arrays for each seri'Get basic information about the current project including name, settings, and available funnels/goals',parameters: z.object({}),execute: async () => {+ this.logger.log({ pid: project.id }, 'Tool: getProjectInfo called')+try {- return await this.getProjectInfo(project)+ const result = await this.getProjectInfo(project)++ this.logger.log(+ {+ pid: project.id,+ funnelCount: result.funnels?.length,+ goalCount: result.goals?.length,+ },+ 'Tool: getProjectInfo completed',+ )+ return result} catch (error) {this.logger.error({ error, pid: project.id },@@ -175,12 +202,30 @@ Available columns for filters:if (!params.dataType) {return { error: 'dataType is required' }}+ this.logger.log(+ {+ pid: project.id,+ dataType: params.dataType,+ period: params.period,+ filters: params.filters,+ },+ 'Tool: getData called',+ )try {- return await this.getData(+ const result = await this.getData(project.id,{ ...params, dataType: params.dataType },timezone,)+ this.logger.log(+ {+ pid: project.id,+ dataType: params.dataType,+ hasData: !!result,+ },+ 'Tool: getData completed',+ )+ return result} catch (error) {this.logger.error({ error, pid: project.id }, 'Tool getData failed')return {@@ -207,8 +252,17 @@ Available columns for filters:to: z.string().optional().describe('End date (YYYY-MM-DD format)'),}),execute: async params => {+ this.logger.log(+ { pid: project.id, goalId: params.goalId, period: params.period },+ 'Tool: getGoalStats called',+ )try {- return await this.getGoalStats(project.id, params, timezone)+ const result = await this.getGoalStats(project.id, params, timezone)+ this.logger.log(+ { pid: project.id, hasData: !!result && !result.error },+ 'Tool: getGoalStats completed',+ )+ return result} catch (error) {this.logger.error({ error, pid: project.id },@@ -238,12 +292,29 @@ Available columns for filters:if (!params.funnelId) {return { error: 'funnelId is required' }}+ this.logger.log(+ {+ pid: project.id,+ funnelId: params.funnelId,+ period: params.period,+ },+ 'Tool: getFunnelData called',+ )try {- return await this.getFunnelData(+ const result = await this.getFunnelData(project.id,{ ...params, funnelId: params.funnelId },timezone,)+ this.logger.log(+ {+ pid: project.id,+ funnelId: params.funnelId,+ hasData: !!result,+ },+ 'Tool: getFunnelData completed',+ )+ return result} catch (error) {this.logger.error({ error, pid: project.id },@@ -332,6 +403,19 @@ Available columns for filters:safeTimezone,)+ this.logger.log(+ {+ pid,+ dataType,+ period,+ from: groupFromUTC,+ to: groupToUTC,+ timeBucket,+ filterCount: filters.length,+ },+ 'getData: Querying data',+ )+if (dataType === 'analytics') {return this.getAnalyticsData(pid,