Skip to content

📈 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!

Ask AI feature

Blue Mouse96e11f13bb2b
diff --git a/backend/.env.example b/backend/.env.example
index b69ee6bd6..4251955b3 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -97,3 +97,6 @@ EMAIL_ACTION_ENCRYPTION_KEY=
# Swetrix Enterprise (Cloud)
SWETRIX_LICENSE_KEY=
+
+# OpenRouter API key for AI features
+OPENROUTER_API_KEY=
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.ts
new file mode 100644
index 000000000..8ca949763
--- /dev/null
+++ b/backend/apps/cloud/src/ai/ai.controller.ts
@@ -0,0 +1,157 @@
+import {
+ Controller,
+ Post,
+ Body,
+ Param,
+ Res,
+ NotFoundException,
+ ForbiddenException,
+ HttpException,
+ HttpStatus,
+} from '@nestjs/common'
+import { Response } from 'express'
+import {
+ ApiTags,
+ ApiBearerAuth,
+ ApiResponse,
+ ApiOperation,
+} from '@nestjs/swagger'
+import _isEmpty from 'lodash/isEmpty'
+
+import { Auth } from '../auth/decorators'
+import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'
+import { ProjectService } from '../project/project.service'
+import { AppLoggerService } from '../logger/logger.service'
+import { AiService } from './ai.service'
+import { ChatDto } from './dto/chat.dto'
+
+@ApiTags('AI')
+@Controller(['ai', 'v1/ai'])
+export class AiController {
+ constructor(
+ private readonly aiService: AiService,
+ private readonly projectService: ProjectService,
+ private readonly logger: AppLoggerService,
+ ) {}
+
+ @ApiBearerAuth()
+ @Post(':pid/chat')
+ @Auth()
+ @ApiOperation({ summary: 'Chat with AI about project analytics' })
+ @ApiResponse({ status: 200, description: 'SSE stream of AI response' })
+ async chat(
+ @Param('pid') pid: string,
+ @Body() chatDto: ChatDto,
+ @CurrentUserId() uid: string,
+ @Res() res: Response,
+ ) {
+ this.logger.log({ uid, pid }, 'POST /ai/:pid/chat')
+
+ // Check if OpenRouter API key is configured
+ if (!process.env.OPENROUTER_API_KEY) {
+ throw new HttpException(
+ 'AI features are not configured. Please set OPENROUTER_API_KEY.',
+ HttpStatus.SERVICE_UNAVAILABLE,
+ )
+ }
+
+ // Get and validate project access
+ const project = await this.projectService.getFullProject(pid)
+
+ if (_isEmpty(project)) {
+ throw new NotFoundException('Project not found')
+ }
+
+ this.projectService.allowedToView(project, uid)
+
+ // Check billing status
+ if (project.admin?.dashboardBlockReason) {
+ throw new ForbiddenException(
+ 'The account that owns this project is currently suspended due to a billing issue.',
+ )
+ }
+
+ try {
+ // Set up SSE headers
+ res.setHeader('Content-Type', 'text/event-stream')
+ res.setHeader('Cache-Control', 'no-cache')
+ res.setHeader('Connection', 'keep-alive')
+ res.setHeader('X-Accel-Buffering', 'no')
+ res.flushHeaders()
+
+ // Convert messages to CoreMessage format, filtering out empty messages
+ const messages = chatDto.messages
+ .filter(m => m.content && m.content.trim().length > 0)
+ .map(m => ({
+ role: m.role as 'user' | 'assistant',
+ content: m.content,
+ }))
+
+ if (messages.length === 0) {
+ throw new HttpException(
+ 'At least one message with content is required',
+ HttpStatus.BAD_REQUEST,
+ )
+ }
+
+ // Get streaming response from AI
+ const result = await this.aiService.chat(
+ project,
+ messages,
+ chatDto.timezone || 'UTC',
+ )
+
+ // 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
+ res.write(
+ `data: ${JSON.stringify({
+ type: 'tool-result',
+ toolName: part.toolName,
+ result: part.result,
+ })}\n\n`,
+ )
+ } else if (part.type === 'reasoning') {
+ // Stream reasoning/thinking tokens if available
+ res.write(
+ `data: ${JSON.stringify({ type: 'reasoning', content: part.textDelta })}\n\n`,
+ )
+ }
+ }
+
+ // Send done event
+ res.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`)
+ res.end()
+ } catch (error) {
+ this.logger.error({ error, pid, uid }, 'Error in AI chat')
+
+ // If headers not sent yet, throw error
+ if (!res.headersSent) {
+ throw new HttpException(
+ 'Failed to process AI request',
+ HttpStatus.INTERNAL_SERVER_ERROR,
+ )
+ }
+
+ // If streaming already started, send error event
+ res.write(
+ `data: ${JSON.stringify({ type: 'error', content: 'An error occurred while processing your request' })}\n\n`,
+ )
+ res.end()
+ }
+ }
+}
diff --git a/backend/apps/cloud/src/ai/ai.module.ts b/backend/apps/cloud/src/ai/ai.module.ts
new file mode 100644
index 000000000..cdda34cb7
--- /dev/null
+++ b/backend/apps/cloud/src/ai/ai.module.ts
@@ -0,0 +1,15 @@
+import { Module } from '@nestjs/common'
+
+import { ProjectModule } from '../project/project.module'
+import { AppLoggerModule } from '../logger/logger.module'
+import { AnalyticsModule } from '../analytics/analytics.module'
+import { GoalModule } from '../goal/goal.module'
+import { AiService } from './ai.service'
+import { AiController } from './ai.controller'
+
+@Module({
+ imports: [ProjectModule, AppLoggerModule, AnalyticsModule, GoalModule],
+ providers: [AiService],
+ controllers: [AiController],
+})
+export class AiModule {}
diff --git a/backend/apps/cloud/src/ai/ai.service.ts b/backend/apps/cloud/src/ai/ai.service.ts
new file mode 100644
index 000000000..42b6e9a80
--- /dev/null
+++ b/backend/apps/cloud/src/ai/ai.service.ts
@@ -0,0 +1,858 @@
+import { Injectable } from '@nestjs/common'
+import { createOpenAI } from '@ai-sdk/openai'
+import { streamText, tool, CoreMessage } from 'ai'
+import { z } from 'zod'
+import _isEmpty from 'lodash/isEmpty'
+import _map from 'lodash/map'
+import _pick from 'lodash/pick'
+import dayjs from 'dayjs'
+
+import { ProjectService } from '../project/project.service'
+import {
+ AnalyticsService,
+ getLowestPossibleTimeBucket,
+} from '../analytics/analytics.service'
+import { GoalService } from '../goal/goal.service'
+import { AppLoggerService } from '../logger/logger.service'
+import { clickhouse } from '../common/integrations/clickhouse'
+import { Project } from '../project/entity/project.entity'
+import { TimeBucketType } from '../analytics/dto/getData.dto'
+
+const OPENROUTER_BASE_URL = 'https://openrouter.ai/api/v1'
+
+@Injectable()
+export class AiService {
+ private openrouter: ReturnType<typeof createOpenAI>
+
+ constructor(
+ private readonly projectService: ProjectService,
+ private readonly analyticsService: AnalyticsService,
+ private readonly goalService: GoalService,
+ private readonly logger: AppLoggerService,
+ ) {
+ this.openrouter = createOpenAI({
+ baseURL: OPENROUTER_BASE_URL,
+ apiKey: process.env.OPENROUTER_API_KEY,
+ })
+ }
+
+ async chat(
+ project: Project,
+ messages: CoreMessage[],
+ timezone: string = 'UTC',
+ ) {
+ const systemPrompt = this.buildSystemPrompt(project, timezone)
+
+ const result = streamText({
+ model: this.openrouter('openai/gpt-oss-120b'),
+ system: systemPrompt,
+ messages,
+ tools: this.buildTools(project, timezone),
+ maxSteps: 10,
+ })
+
+ return result
+ }
+
+ private buildSystemPrompt(project: Project, timezone: string): string {
+ const currentDate = dayjs().tz(timezone).format('YYYY-MM-DD HH:mm:ss')
+
+ return `You are an AI assistant for Swetrix, a privacy-focused web analytics platform. You help users understand their website analytics data.
+
+Current context:
+- Project: "${project.name}" (ID: ${project.id})
+- Current date/time: ${currentDate} (timezone: ${timezone})
+
+You have access to tools that can query analytics data for this project. Use them to answer user questions about:
+- Traffic and pageviews
+- Visitors and sessions
+- Performance metrics
+- Custom events
+- Goals and conversions
+- Errors
+- Geographic data
+- Device and browser statistics
+- Referrer sources
+
+Guidelines:
+1. Always use tools to fetch real data before answering questions about analytics
+2. When presenting data, be clear and concise
+3. If the user asks for charts or visualizations, include a chart in your response using the special JSON format
+4. Use appropriate time periods based on context (default to last 7 days if not specified)
+5. Round percentages and large numbers for readability
+6. Explain trends and provide actionable insights when relevant
+
+To include a chart in your response, use this exact JSON format on its own line:
+{"type":"chart","chartType":"line","title":"Chart Title","data":{"x":["2024-01-01","2024-01-02"],"pageviews":[100,150],"visitors":[80,120]}}
+
+Supported chart types: "line", "bar", "area"
+The data object should have "x" for x-axis labels and named arrays for each series.`
+ }
+
+ private buildTools(project: Project, timezone: string) {
+ return {
+ getProjectInfo: tool({
+ description:
+ 'Get basic information about the current project including name, settings, and available funnels/goals',
+ parameters: z.object({}),
+ execute: async () => {
+ return this.getProjectInfo(project)
+ },
+ }),
+
+ getData: tool({
+ description: `Query analytics data for the project. Returns chart data and panel breakdowns (top pages, countries, browsers, etc.).
+
+Available columns for filters:
+- pg: page path
+- cc: country code (2-letter ISO)
+- rg: region
+- ct: city
+- br: browser name
+- os: operating system
+- dv: device type (desktop, mobile, tablet)
+- ref: referrer
+- so: source
+- me: medium
+- ca: campaign
+- lc: locale/language
+- host: hostname`,
+ parameters: z.object({
+ dataType: z
+ .enum(['analytics', 'performance', 'captcha', 'errors'])
+ .describe('Type of data to query'),
+ period: z
+ .string()
+ .optional()
+ .describe(
+ 'Time period: 1h, today, yesterday, 1d, 7d, 4w, 3M, 12M, 24M',
+ ),
+ from: z
+ .string()
+ .optional()
+ .describe('Start date (YYYY-MM-DD format)'),
+ to: z.string().optional().describe('End date (YYYY-MM-DD format)'),
+ timeBucket: z
+ .enum(['minute', 'hour', 'day', 'month'])
+ .optional()
+ .describe('Time bucket for chart aggregation'),
+ filters: z
+ .array(
+ z.object({
+ column: z.string().describe('Column to filter'),
+ filter: z.string().describe('Filter value'),
+ isExclusive: z
+ .boolean()
+ .optional()
+ .describe('If true, exclude this value'),
+ }),
+ )
+ .optional()
+ .describe('Filters to apply'),
+ measure: z
+ .enum(['average', 'median', 'p95'])
+ .optional()
+ .describe('Measure type for performance data'),
+ }),
+ execute: async params => {
+ if (!params.dataType) {
+ return { error: 'dataType is required' }
+ }
+ return this.getData(
+ project.id,
+ { ...params, dataType: params.dataType },
+ timezone,
+ )
+ },
+ }),
+
+ getGoalStats: tool({
+ description:
+ 'Get goal conversion statistics including conversions, conversion rate, and trends',
+ parameters: z.object({
+ goalId: z
+ .string()
+ .optional()
+ .describe('Specific goal ID, or omit to get all goals'),
+ period: z.string().optional().describe('Time period (default: 7d)'),
+ from: z
+ .string()
+ .optional()
+ .describe('Start date (YYYY-MM-DD format)'),
+ to: z.string().optional().describe('End date (YYYY-MM-DD format)'),
+ }),
+ execute: async params => {
+ return this.getGoalStats(project.id, params, timezone)
+ },
+ }),
+
+ getFunnelData: tool({
+ description:
+ 'Get funnel analysis data showing step-by-step conversions',
+ parameters: z.object({
+ funnelId: z.string().describe('Funnel ID to query'),
+ period: z.string().optional().describe('Time period (default: 7d)'),
+ from: z
+ .string()
+ .optional()
+ .describe('Start date (YYYY-MM-DD format)'),
+ to: z.string().optional().describe('End date (YYYY-MM-DD format)'),
+ }),
+ execute: async params => {
+ if (!params.funnelId) {
+ return { error: 'funnelId is required' }
+ }
+ return this.getFunnelData(
+ project.id,
+ { ...params, funnelId: params.funnelId },
+ timezone,
+ )
+ },
+ }),
+ }
+ }
+
+ private async getProjectInfo(project: Project) {
+ // Get funnels
+ const funnels = await this.projectService.getFunnels(project.id)
+
+ // Get goals
+ const goals = await this.goalService.find({
+ where: { project: { id: project.id }, active: true },
+ order: { name: 'ASC' },
+ })
+
+ return {
+ id: project.id,
+ name: project.name,
+ created: project.created,
+ isAnalyticsProject: project.isAnalyticsProject,
+ captchaEnabled: !!project.captchaSecretKey,
+ funnels: _map(funnels, f => ({ id: f.id, name: f.name, steps: f.steps })),
+ goals: _map(goals, g => ({
+ id: g.id,
+ name: g.name,
+ type: g.type,
+ value: g.value,
+ })),
+ }
+ }
+
+ private async getData(
+ pid: string,
+ params: {
+ dataType: 'analytics' | 'performance' | 'captcha' | 'errors'
+ period?: string
+ from?: string
+ to?: string
+ timeBucket?: string
+ filters?: Array<{
+ column?: string
+ filter?: string
+ isExclusive?: boolean
+ }>
+ measure?: 'average' | 'median' | 'p95'
+ },
+ timezone: string,
+ ) {
+ const {
+ dataType,
+ period = '7d',
+ from,
+ to,
+ timeBucket: requestedTimeBucket,
+ filters: rawFilters = [],
+ measure = 'median',
+ } = params
+
+ // Filter out invalid filter entries
+ const filters = rawFilters.filter(
+ (f): f is { column: string; filter: string; isExclusive?: boolean } =>
+ typeof f.column === 'string' && typeof f.filter === 'string',
+ )
+
+ try {
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const timeBucket =
+ (requestedTimeBucket as TimeBucketType) ||
+ getLowestPossibleTimeBucket(period, from, to)
+
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ timeBucket,
+ period,
+ safeTimezone,
+ )
+
+ if (dataType === 'analytics') {
+ return this.getAnalyticsData(
+ pid,
+ groupFromUTC,
+ groupToUTC,
+ timeBucket,
+ safeTimezone,
+ filters,
+ )
+ }
+
+ if (dataType === 'performance') {
+ return this.getPerformanceData(
+ pid,
+ groupFromUTC,
+ groupToUTC,
+ timeBucket,
+ safeTimezone,
+ filters,
+ measure,
+ )
+ }
+
+ if (dataType === 'errors') {
+ return this.getErrorsData(pid, groupFromUTC, groupToUTC, safeTimezone)
+ }
+
+ return { error: 'Unsupported data type' }
+ } catch (error) {
+ this.logger.error({ error, pid, params }, 'Error fetching data for AI')
+ return { error: 'Failed to fetch data' }
+ }
+ }
+
+ private async getAnalyticsData(
+ pid: string,
+ groupFrom: string,
+ groupTo: string,
+ timeBucket: TimeBucketType,
+ timezone: string,
+ filters: Array<{
+ column: string
+ filter: string
+ isExclusive?: boolean
+ }>,
+ ) {
+ const filterConditions = this.buildFilterConditions(filters)
+
+ // Get overall stats
+ const overallQuery = `
+ SELECT
+ count(*) as pageviews,
+ uniqExact(psid) as sessions,
+ uniqExact(uid) as visitors,
+ countIf(unique = 1) as uniquePageviews,
+ round(avg(sdur), 2) as avgSessionDuration,
+ round(countIf(unique = 1 AND sdur <= 0) * 100.0 / nullIf(countIf(unique = 1), 0), 2) as bounceRate
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filterConditions.where}
+ `
+
+ const { data: overallData } = await clickhouse
+ .query({
+ query: overallQuery,
+ query_params: {
+ pid,
+ groupFrom,
+ groupTo,
+ ...filterConditions.params,
+ },
+ })
+ .then(r => r.json())
+
+ // Get chart data
+ const chartQuery = `
+ SELECT
+ ${this.getTimeBucketSelect(timeBucket, timezone)} as date,
+ count(*) as pageviews,
+ uniqExact(psid) as sessions,
+ uniqExact(uid) as visitors
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filterConditions.where}
+ GROUP BY date
+ ORDER BY date
+ `
+
+ const { data: chartData } = await clickhouse
+ .query({
+ query: chartQuery,
+ query_params: {
+ pid,
+ groupFrom,
+ groupTo,
+ timezone,
+ ...filterConditions.params,
+ },
+ })
+ .then(r => r.json())
+
+ // Get top pages
+ const pagesQuery = `
+ SELECT pg as name, count(*) as count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filterConditions.where}
+ GROUP BY pg
+ ORDER BY count DESC
+ LIMIT 10
+ `
+
+ const { data: topPages } = await clickhouse
+ .query({
+ query: pagesQuery,
+ query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
+ })
+ .then(r => r.json())
+
+ // Get top countries
+ const countriesQuery = `
+ SELECT cc as name, uniqExact(psid) as count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND cc IS NOT NULL AND cc != ''
+ ${filterConditions.where}
+ GROUP BY cc
+ ORDER BY count DESC
+ LIMIT 10
+ `
+
+ const { data: topCountries } = await clickhouse
+ .query({
+ query: countriesQuery,
+ query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
+ })
+ .then(r => r.json())
+
+ // Get top referrers
+ const referrersQuery = `
+ SELECT ref as name, uniqExact(psid) as count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND ref IS NOT NULL AND ref != ''
+ ${filterConditions.where}
+ GROUP BY ref
+ ORDER BY count DESC
+ LIMIT 10
+ `
+
+ const { data: topReferrers } = await clickhouse
+ .query({
+ query: referrersQuery,
+ query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
+ })
+ .then(r => r.json())
+
+ // Get browsers
+ const browsersQuery = `
+ SELECT br as name, uniqExact(psid) as count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND br IS NOT NULL AND br != ''
+ ${filterConditions.where}
+ GROUP BY br
+ ORDER BY count DESC
+ LIMIT 10
+ `
+
+ const { data: topBrowsers } = await clickhouse
+ .query({
+ query: browsersQuery,
+ query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
+ })
+ .then(r => r.json())
+
+ // Get devices
+ const devicesQuery = `
+ SELECT dv as name, uniqExact(psid) as count
+ FROM analytics
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ AND dv IS NOT NULL AND dv != ''
+ ${filterConditions.where}
+ GROUP BY dv
+ ORDER BY count DESC
+ `
+
+ const { data: devices } = await clickhouse
+ .query({
+ query: devicesQuery,
+ query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
+ })
+ .then(r => r.json())
+
+ return {
+ overall: overallData[0] || {},
+ chart: {
+ x: _map(chartData, (d: any) => d.date),
+ pageviews: _map(chartData, (d: any) => d.pageviews),
+ sessions: _map(chartData, (d: any) => d.sessions),
+ visitors: _map(chartData, (d: any) => d.visitors),
+ },
+ topPages,
+ topCountries,
+ topReferrers,
+ topBrowsers,
+ devices,
+ period: { from: groupFrom, to: groupTo },
+ }
+ }
+
+ private async getPerformanceData(
+ pid: string,
+ groupFrom: string,
+ groupTo: string,
+ timeBucket: TimeBucketType,
+ timezone: string,
+ filters: Array<{
+ column: string
+ filter: string
+ isExclusive?: boolean
+ }>,
+ measure: string,
+ ) {
+ const filterConditions = this.buildFilterConditions(filters)
+ const measureFn =
+ measure === 'average'
+ ? 'avg'
+ : measure === 'p95'
+ ? 'quantileExact(0.95)'
+ : 'median'
+
+ // Get overall performance stats
+ const overallQuery = `
+ SELECT
+ round(${measureFn}(pageLoad) / 1000, 2) as pageLoad,
+ round(${measureFn}(dns) / 1000, 2) as dns,
+ round(${measureFn}(tls) / 1000, 2) as tls,
+ round(${measureFn}(conn) / 1000, 2) as connection,
+ round(${measureFn}(response) / 1000, 2) as response,
+ round(${measureFn}(render) / 1000, 2) as render,
+ round(${measureFn}(domLoad) / 1000, 2) as domLoad,
+ round(${measureFn}(ttfb) / 1000, 2) as ttfb
+ FROM performance
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filterConditions.where}
+ `
+
+ const { data: overallData } = await clickhouse
+ .query({
+ query: overallQuery,
+ query_params: {
+ pid,
+ groupFrom,
+ groupTo,
+ ...filterConditions.params,
+ },
+ })
+ .then(r => r.json())
+
+ // Get chart data
+ const chartQuery = `
+ SELECT
+ ${this.getTimeBucketSelect(timeBucket, timezone)} as date,
+ round(${measureFn}(pageLoad) / 1000, 2) as pageLoad,
+ round(${measureFn}(ttfb) / 1000, 2) as ttfb
+ FROM performance
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ ${filterConditions.where}
+ GROUP BY date
+ ORDER BY date
+ `
+
+ const { data: chartData } = await clickhouse
+ .query({
+ query: chartQuery,
+ query_params: {
+ pid,
+ groupFrom,
+ groupTo,
+ timezone,
+ ...filterConditions.params,
+ },
+ })
+ .then(r => r.json())
+
+ return {
+ overall: overallData[0] || {},
+ chart: {
+ x: _map(chartData, (d: any) => d.date),
+ pageLoad: _map(chartData, (d: any) => d.pageLoad),
+ ttfb: _map(chartData, (d: any) => d.ttfb),
+ },
+ measure,
+ period: { from: groupFrom, to: groupTo },
+ }
+ }
+
+ private async getErrorsData(
+ pid: string,
+ groupFrom: string,
+ groupTo: string,
+ _timezone: string,
+ ) {
+ // Get error counts
+ const overallQuery = `
+ SELECT
+ count(*) as totalErrors,
+ uniqExact(eid) as uniqueErrors
+ FROM errors
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ const { data: overallData } = await clickhouse
+ .query({
+ query: overallQuery,
+ query_params: { pid, groupFrom, groupTo },
+ })
+ .then(r => r.json())
+
+ // Get top errors
+ const topErrorsQuery = `
+ SELECT
+ name,
+ message,
+ count(*) as count,
+ max(created) as lastSeen
+ FROM errors
+ WHERE pid = {pid:FixedString(12)}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ GROUP BY name, message
+ ORDER BY count DESC
+ LIMIT 10
+ `
+
+ const { data: topErrors } = await clickhouse
+ .query({
+ query: topErrorsQuery,
+ query_params: { pid, groupFrom, groupTo },
+ })
+ .then(r => r.json())
+
+ return {
+ overall: overallData[0] || {},
+ topErrors,
+ period: { from: groupFrom, to: groupTo },
+ }
+ }
+
+ private async getGoalStats(
+ pid: string,
+ params: {
+ goalId?: string
+ period?: string
+ from?: string
+ to?: string
+ },
+ timezone: string,
+ ) {
+ const { goalId, period = '7d', from, to } = params
+
+ try {
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const timeBucket = getLowestPossibleTimeBucket(period, from, to)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ timeBucket,
+ period,
+ safeTimezone,
+ )
+
+ if (goalId) {
+ const goal = await this.goalService.findOne({ where: { id: goalId } })
+ if (!goal) {
+ return { error: 'Goal not found' }
+ }
+
+ // Query specific goal stats
+ const table = goal.type === 'custom_event' ? 'customEV' : 'analytics'
+ const matchCondition =
+ goal.matchType === 'exact'
+ ? goal.type === 'custom_event'
+ ? `ev = {goalValue:String}`
+ : `pg = {goalValue:String}`
+ : goal.type === 'custom_event'
+ ? `ev ILIKE concat('%', {goalValue:String}, '%')`
+ : `pg ILIKE concat('%', {goalValue:String}, '%')`
+
+ const query = `
+ SELECT
+ count(*) as conversions,
+ uniqExact(psid) as uniqueSessions
+ FROM ${table}
+ WHERE pid = {pid:FixedString(12)}
+ AND ${matchCondition}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: {
+ pid,
+ goalValue: goal.value || '',
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ },
+ })
+ .then(r => r.json())
+
+ return {
+ goal: { id: goal.id, name: goal.name, type: goal.type },
+ stats: data[0] || { conversions: 0, uniqueSessions: 0 },
+ period: { from: groupFromUTC, to: groupToUTC },
+ }
+ }
+
+ // Get all goals for the project
+ const goals = await this.goalService.find({
+ where: { project: { id: pid }, active: true },
+ })
+
+ const results = await Promise.all(
+ goals.map(async goal => {
+ const table = goal.type === 'custom_event' ? 'customEV' : 'analytics'
+ const matchCondition =
+ goal.matchType === 'exact'
+ ? goal.type === 'custom_event'
+ ? `ev = {goalValue:String}`
+ : `pg = {goalValue:String}`
+ : goal.type === 'custom_event'
+ ? `ev ILIKE concat('%', {goalValue:String}, '%')`
+ : `pg ILIKE concat('%', {goalValue:String}, '%')`
+
+ const query = `
+ SELECT count(*) as conversions
+ FROM ${table}
+ WHERE pid = {pid:FixedString(12)}
+ AND ${matchCondition}
+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: {
+ pid,
+ goalValue: goal.value || '',
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ },
+ })
+ .then(r => r.json())
+
+ return {
+ id: goal.id,
+ name: goal.name,
+ type: goal.type,
+ conversions: (data[0] as any)?.conversions || 0,
+ }
+ }),
+ )
+
+ return {
+ goals: results,
+ period: { from: groupFromUTC, to: groupToUTC },
+ }
+ } catch (error) {
+ this.logger.error({ error, pid, params }, 'Error fetching goal stats')
+ return { error: 'Failed to fetch goal stats' }
+ }
+ }
+
+ private async getFunnelData(
+ pid: string,
+ params: {
+ funnelId: string
+ period?: string
+ from?: string
+ to?: string
+ },
+ timezone: string,
+ ) {
+ const { funnelId, period = '7d', from, to } = params
+
+ try {
+ const funnel = await this.projectService.getFunnel(funnelId, pid)
+ if (!funnel) {
+ return { error: 'Funnel not found' }
+ }
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const timeBucket = getLowestPossibleTimeBucket(period, from, to)
+ const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ timeBucket,
+ period,
+ safeTimezone,
+ )
+
+ const funnelData = await this.analyticsService.getFunnel(funnel.steps, {
+ pid,
+ groupFrom: groupFromUTC,
+ groupTo: groupToUTC,
+ })
+
+ return {
+ funnel: {
+ id: funnel.id,
+ name: funnel.name,
+ steps: funnel.steps,
+ },
+ data: funnelData,
+ period: { from: groupFromUTC, to: groupToUTC },
+ }
+ } catch (error) {
+ this.logger.error({ error, pid, params }, 'Error fetching funnel data')
+ return { error: 'Failed to fetch funnel data' }
+ }
+ }
+
+ private getTimeBucketSelect(timeBucket: TimeBucketType, timezone: string) {
+ const conversionMap: Record<TimeBucketType, string> = {
+ minute: `formatDateTime(toStartOfMinute(toTimeZone(created, '${timezone}')), '%Y-%m-%d %H:%M:00')`,
+ hour: `formatDateTime(toStartOfHour(toTimeZone(created, '${timezone}')), '%Y-%m-%d %H:00:00')`,
+ day: `formatDateTime(toStartOfDay(toTimeZone(created, '${timezone}')), '%Y-%m-%d')`,
+ month: `formatDateTime(toStartOfMonth(toTimeZone(created, '${timezone}')), '%Y-%m')`,
+ year: `formatDateTime(toStartOfYear(toTimeZone(created, '${timezone}')), '%Y')`,
+ }
+ return conversionMap[timeBucket] || conversionMap.day
+ }
+
+ private buildFilterConditions(
+ filters: Array<{
+ column: string
+ filter: string
+ isExclusive?: boolean
+ }>,
+ ): { where: string; params: Record<string, string> } {
+ if (_isEmpty(filters)) {
+ return { where: '', params: {} }
+ }
+
+ const conditions: string[] = []
+ const params: Record<string, string> = {}
+
+ filters.forEach((f, index) => {
+ const paramName = `filter_${index}`
+ params[paramName] = f.filter
+ const operator = f.isExclusive ? '!=' : '='
+ conditions.push(`${f.column} ${operator} {${paramName}:String}`)
+ })
+
+ return {
+ where: conditions.length > 0 ? `AND ${conditions.join(' AND ')}` : '',
+ params,
+ }
+ }
+}
diff --git a/backend/apps/cloud/src/ai/dto/chat.dto.ts b/backend/apps/cloud/src/ai/dto/chat.dto.ts
new file mode 100644
index 000000000..5f6f529b1
--- /dev/null
+++ b/backend/apps/cloud/src/ai/dto/chat.dto.ts
@@ -0,0 +1,46 @@
+import { ApiProperty } from '@nestjs/swagger'
+import {
+ IsArray,
+ IsNotEmpty,
+ IsString,
+ ValidateNested,
+ IsIn,
+ IsOptional,
+} from 'class-validator'
+import { Type } from 'class-transformer'
+
+export class ChatMessageDto {
+ @ApiProperty({
+ enum: ['user', 'assistant'],
+ description: 'The role of the message sender',
+ })
+ @IsNotEmpty()
+ @IsIn(['user', 'assistant'])
+ role: 'user' | 'assistant'
+
+ @ApiProperty({
+ description: 'The content of the message',
+ })
+ @IsNotEmpty()
+ @IsString()
+ content: string
+}
+
+export class ChatDto {
+ @ApiProperty({
+ type: [ChatMessageDto],
+ description: 'Array of chat messages',
+ })
+ @IsArray()
+ @ValidateNested({ each: true })
+ @Type(() => ChatMessageDto)
+ messages: ChatMessageDto[]
+
+ @ApiProperty({
+ required: false,
+ description: 'Timezone for date/time context',
+ })
+ @IsOptional()
+ @IsString()
+ timezone?: string
+}
diff --git a/backend/apps/cloud/src/app.module.ts b/backend/apps/cloud/src/app.module.ts
index 890cb697f..e3944eefc 100644
--- a/backend/apps/cloud/src/app.module.ts
+++ b/backend/apps/cloud/src/app.module.ts
@@ -21,6 +21,7 @@ import { PingModule } from './ping/ping.module'
import { MarketplaceModule } from './marketplace/marketplace.module'
import { AlertModule } from './alert/alert.module'
import { GoalModule } from './goal/goal.module'
+import { AiModule } from './ai/ai.module'
import { getI18nConfig } from './configs'
import { AuthModule } from './auth/auth.module'
import { CaptchaModule } from './captcha/captcha.module'
@@ -79,6 +80,7 @@ const modules = [
MarketplaceModule,
AlertModule,
GoalModule,
+ AiModule,
AuthModule,
CaptchaModule,
OgImageModule,
diff --git a/backend/package-lock.json b/backend/package-lock.json
index dab123577..51aa7e8b0 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -6,6 +6,7 @@
"": {
"license": "AGPL-3.0",
"dependencies": {
+ "@ai-sdk/openai": "^1.3.22",
"@clickhouse/client": "^1.14.0",
"@faker-js/faker": "^10.1.0",
"@nestjs-modules/mailer": "^2.0.2",
@@ -27,6 +28,7 @@
"@sentry/nestjs": "^10.27.0",
"@sentry/profiling-node": "^10.27.0",
"@ua-parser-js/pro-business": "^2.0.6",
+ "ai": "^4.3.16",
"axios": "^1.13.2",
"bcrypt": "^6.0.0",
"body-parser": "^2.2.1",
@@ -68,7 +70,8 @@
"sns-payload-validator": "^2.1.0",
"telegraf": "^4.16.3",
"typeorm": "^0.3.27",
- "validator": "^13.15.23"
+ "validator": "^13.15.23",
+ "zod": "^3.24.4"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
@@ -100,6 +103,92 @@
"node": ">=22"
}
},
+ "node_modules/@ai-sdk/openai": {
+ "version": "1.3.24",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/openai/-/openai-1.3.24.tgz",
+ "integrity": "sha512-GYXnGJTHRTZc4gJMSmFRgEQudjqd4PUN0ZjQhPwOAYH1yOAvQoG/Ikqs+HyISRbLPCrhbZnPKCNHuRU4OfpW0Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "1.1.3",
+ "@ai-sdk/provider-utils": "2.2.8"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.0.0"
+ }
+ },
+ "node_modules/@ai-sdk/provider": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-1.1.3.tgz",
+ "integrity": "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "json-schema": "^0.4.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@ai-sdk/provider-utils": {
+ "version": "2.2.8",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-2.2.8.tgz",
+ "integrity": "sha512-fqhG+4sCVv8x7nFzYnFo19ryhAa3w096Kmc3hWxMQfW/TubPOmt3A6tYZhl4mUfQWWQMsuSkLrtjlWuXBVSGQA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "1.1.3",
+ "nanoid": "^3.3.8",
+ "secure-json-parse": "^2.7.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.23.8"
+ }
+ },
+ "node_modules/@ai-sdk/react": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/react/-/react-1.2.12.tgz",
+ "integrity": "sha512-jK1IZZ22evPZoQW3vlkZ7wvjYGYF+tRBKXtrcolduIkQ/m/sOAVcVeVDUDvh1T91xCnWCdUGCPZg2avZ90mv3g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider-utils": "2.2.8",
+ "@ai-sdk/ui-utils": "1.2.11",
+ "swr": "^2.2.5",
+ "throttleit": "2.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "react": "^18 || ^19 || ^19.0.0-rc",
+ "zod": "^3.23.8"
+ },
+ "peerDependenciesMeta": {
+ "zod": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@ai-sdk/ui-utils": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@ai-sdk/ui-utils/-/ui-utils-1.2.11.tgz",
+ "integrity": "sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "1.1.3",
+ "@ai-sdk/provider-utils": "2.2.8",
+ "zod-to-json-schema": "^3.24.1"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "zod": "^3.23.8"
+ }
+ },
"node_modules/@angular-devkit/core": {
"version": "19.2.17",
"resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-19.2.17.tgz",
@@ -4736,6 +4825,12 @@
"@types/express": "*"
}
},
+ "node_modules/@types/diff-match-patch": {
+ "version": "1.0.36",
+ "resolved": "https://registry.npmjs.org/@types/diff-match-patch/-/diff-match-patch-1.0.36.tgz",
+ "integrity": "sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg==",
+ "license": "MIT"
+ },
"node_modules/@types/ejs": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/@types/ejs/-/ejs-3.1.5.tgz",
@@ -5629,6 +5724,32 @@
"node": ">= 6.0.0"
}
},
+ "node_modules/ai": {
+ "version": "4.3.19",
+ "resolved": "https://registry.npmjs.org/ai/-/ai-4.3.19.tgz",
+ "integrity": "sha512-dIE2bfNpqHN3r6IINp9znguYdhIOheKW2LDigAMrgt/upT3B8eBGPSCblENvaZGoq+hxaN9fSMzjWpbqloP+7Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@ai-sdk/provider": "1.1.3",
+ "@ai-sdk/provider-utils": "2.2.8",
+ "@ai-sdk/react": "1.2.12",
+ "@ai-sdk/ui-utils": "1.2.11",
+ "@opentelemetry/api": "1.9.0",
+ "jsondiffpatch": "0.6.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "react": "^18 || ^19 || ^19.0.0-rc",
+ "zod": "^3.23.8"
+ },
+ "peerDependenciesMeta": {
+ "react": {
+ "optional": true
+ }
+ }
+ },
"node_modules/ajv": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
@@ -6449,6 +6570,18 @@
],
"license": "CC-BY-4.0"
},
+ "node_modules/chalk": {
+ "version": "5.6.2",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz",
+ "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==",
+ "license": "MIT",
+ "engines": {
+ "node": "^12.17.0 || ^14.13 || >=16.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/chalk?sponsor=1"
+ }
+ },
"node_modules/character-parser": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/character-parser/-/character-parser-2.2.0.tgz",
@@ -7175,6 +7308,15 @@
"node": ">= 0.8"
}
},
+ "node_modules/dequal": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
+ "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/detect-europe-js": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/detect-europe-js/-/detect-europe-js-0.1.2.tgz",
@@ -7237,6 +7379,12 @@
"integrity": "sha512-vhE6eymDQSKWUXwwA37NtTTVEzjtGVfDr3pRbsWEQ5onH/Snp2c+2xZHWJJawG/0hCCJLRGt4xVtEVUVILol4w==",
"license": "BSD-3-Clause"
},
+ "node_modules/diff-match-patch": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/diff-match-patch/-/diff-match-patch-1.0.5.tgz",
+ "integrity": "sha512-IayShXAgj/QMXgB0IWmKx+rOPuGMhqm5w6jvFxmVenXKIzRqTAAsbBPT3kWQeGANj3jGgvcvv4yK6SxqYmikgw==",
+ "license": "Apache-2.0"
+ },
"node_modules/display-notification": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/display-notification/-/display-notification-2.0.0.tgz",
@@ -10032,6 +10180,12 @@
"integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
"license": "MIT"
},
+ "node_modules/json-schema": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
+ "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",
+ "license": "(AFL-2.1 OR BSD-3-Clause)"
+ },
"node_modules/json-schema-traverse": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
@@ -10066,6 +10220,23 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/jsondiffpatch": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/jsondiffpatch/-/jsondiffpatch-0.6.0.tgz",
+ "integrity": "sha512-3QItJOXp2AP1uv7waBkao5nCvhEv+QmJAd38Ybq7wNI74Q+BBmnLn4EDKz6yI9xGAIQoUF87qHt+kc1IVxB4zQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/diff-match-patch": "^1.0.36",
+ "chalk": "^5.3.0",
+ "diff-match-patch": "^1.0.5"
+ },
+ "bin": {
+ "jsondiffpatch": "bin/jsondiffpatch.js"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ }
+ },
"node_modules/jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
@@ -11522,6 +11693,24 @@
"node": ">=12.0.0"
}
},
+ "node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
"node_modules/natural-compare": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz",
@@ -13164,6 +13353,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/react": {
+ "version": "19.2.1",
+ "resolved": "https://registry.npmjs.org/react/-/react-19.2.1.tgz",
+ "integrity": "sha512-DGrYcCWK7tvYMnWh79yrPHt+vdx9tY+1gPZa7nJQtO/p8bLTDaHp4dzwEhQB7pZ4Xe3ok4XKuEPrVuc+wlpkmw==",
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
@@ -13629,6 +13828,12 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/secure-json-parse": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-2.7.0.tgz",
+ "integrity": "sha512-6aU+Rwsezw7VR8/nyvKTx8QpWH9FrcYiXXlqC4z5d5XQBDRqtbfsRjnwGyqbi3gddNtWHuEk9OANUotL26qKUw==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/selderee": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/selderee/-/selderee-0.11.0.tgz",
@@ -14215,6 +14420,19 @@
"@scarf/scarf": "=1.4.0"
}
},
+ "node_modules/swr": {
+ "version": "2.3.7",
+ "resolved": "https://registry.npmjs.org/swr/-/swr-2.3.7.tgz",
+ "integrity": "sha512-ZEquQ82QvalqTxhBVv/DlAg2mbmUjF4UgpPg9wwk4ufb9rQnZXh1iKyyKBqV6bQGu1Ie7L1QwSYO07qFIa1p+g==",
+ "license": "MIT",
+ "dependencies": {
+ "dequal": "^2.0.3",
+ "use-sync-external-store": "^1.4.0"
+ },
+ "peerDependencies": {
+ "react": "^16.11.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/symbol-observable": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/symbol-observable/-/symbol-observable-4.0.0.tgz",
@@ -14427,6 +14645,18 @@
"node": ">=0.2.6"
}
},
+ "node_modules/throttleit": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/throttleit/-/throttleit-2.1.0.tgz",
+ "integrity": "sha512-nt6AMGKW1p/70DF/hGBdJB57B8Tspmbp5gfJ8ilhLnt7kkr2ye7hzD6NVG8GGErk2HWF34igrL2CXmNIkzKqKw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/tiny-lru": {
"version": "11.4.5",
"resolved": "https://registry.npmjs.org/tiny-lru/-/tiny-lru-11.4.5.tgz",
@@ -15077,6 +15307,15 @@
"integrity": "sha512-XdVKMF4SJ0nP/O7XIPB0JwAEuT9lDIYnNsK8yGVe43y0AWoKeJNdv3ZNWh7ksJ6KqQFjOO6ox/VEitLnaVNufw==",
"license": "BSD"
},
+ "node_modules/use-sync-external-store": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
+ "integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
+ "license": "MIT",
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ }
+ },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
@@ -15706,6 +15945,15 @@
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
+ },
+ "node_modules/zod-to-json-schema": {
+ "version": "3.25.0",
+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.0.tgz",
+ "integrity": "sha512-HvWtU2UG41LALjajJrML6uQejQhNJx+JBO9IflpSja4R03iNWfKXrj6W2h7ljuLyc1nKS+9yDyL/9tD1U/yBnQ==",
+ "license": "ISC",
+ "peerDependencies": {
+ "zod": "^3.25 || ^4"
+ }
}
}
}
diff --git a/backend/package.json b/backend/package.json
index 4ec4beeb1..26a1dfc2b 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -26,6 +26,7 @@
"knip": "knip"
},
"dependencies": {
+ "@ai-sdk/openai": "^1.3.22",
"@clickhouse/client": "^1.14.0",
"@faker-js/faker": "^10.1.0",
"@nestjs-modules/mailer": "^2.0.2",
@@ -47,6 +48,7 @@
"@sentry/nestjs": "^10.27.0",
"@sentry/profiling-node": "^10.27.0",
"@ua-parser-js/pro-business": "^2.0.6",
+ "ai": "^4.3.16",
"axios": "^1.13.2",
"bcrypt": "^6.0.0",
"body-parser": "^2.2.1",
@@ -88,7 +90,8 @@
"sns-payload-validator": "^2.1.0",
"telegraf": "^4.16.3",
"typeorm": "^0.3.27",
- "validator": "^13.15.23"
+ "validator": "^13.15.23",
+ "zod": "^3.24.4"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index 1b8149209..9735455a8 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -1808,3 +1808,99 @@ export const getGSCKeywords = (
.catch((error) => {
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
+
+// AI Chat API with SSE streaming
+export interface AIChatMessage {
+ role: 'user' | 'assistant'
+ content: string
+}
+
+export interface AIStreamCallbacks {
+ onText: (chunk: string) => void
+ onToolCall?: (toolName: string, args: unknown) => void
+ onToolResult?: (toolName: string, result: unknown) => void
+ onReasoning?: (chunk: string) => void
+ onComplete: () => void
+ onError: (error: Error) => void
+}
+
+export const askAI = async (
+ pid: string,
+ messages: AIChatMessage[],
+ timezone: string,
+ callbacks: AIStreamCallbacks,
+ signal?: AbortSignal,
+) => {
+ const token = getAccessToken()
+
+ try {
+ const response = await fetch(`${API_URL}ai/${pid}/chat`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: token ? `Bearer ${token}` : '',
+ },
+ body: JSON.stringify({ messages, timezone }),
+ signal,
+ })
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}))
+ throw new Error(errorData.message || `HTTP error! status: ${response.status}`)
+ }
+
+ const reader = response.body?.getReader()
+ if (!reader) {
+ throw new Error('No response body')
+ }
+
+ const decoder = new TextDecoder()
+ let buffer = ''
+
+ while (true) {
+ const { done, value } = await reader.read()
+
+ if (done) {
+ callbacks.onComplete()
+ break
+ }
+
+ buffer += decoder.decode(value, { stream: true })
+
+ // Process SSE events
+ const lines = buffer.split('\n')
+ buffer = lines.pop() || ''
+
+ for (const line of lines) {
+ if (line.startsWith('data: ')) {
+ const data = line.slice(6)
+ try {
+ const parsed = JSON.parse(data)
+ if (parsed.type === 'text') {
+ callbacks.onText(parsed.content)
+ } else if (parsed.type === 'tool-call') {
+ callbacks.onToolCall?.(parsed.toolName, parsed.args)
+ } else if (parsed.type === 'tool-result') {
+ callbacks.onToolResult?.(parsed.toolName, parsed.result)
+ } else if (parsed.type === 'reasoning') {
+ callbacks.onReasoning?.(parsed.content)
+ } else if (parsed.type === 'error') {
+ callbacks.onError(new Error(parsed.content))
+ } else if (parsed.type === 'done') {
+ callbacks.onComplete()
+ return
+ }
+ } catch {
+ // Ignore parsing errors for incomplete JSON
+ }
+ }
+ }
+ }
+ } catch (error) {
+ if ((error as Error).name === 'AbortError') {
+ callbacks.onComplete()
+ return
+ }
+ callbacks.onError(error as Error)
+ }
+}
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index e7f896112..32e35e430 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -405,6 +405,7 @@ const SELFHOSTED_PROJECT_TABS = {
sessions: 'sessions',
errors: 'errors',
goals: 'goals',
+ askAi: 'askAi',
} as const
const PRODUCTION_PROJECT_TABS = {
@@ -417,6 +418,7 @@ const PRODUCTION_PROJECT_TABS = {
goals: 'goals',
alerts: 'alerts',
captcha: 'captcha',
+ askAi: 'askAi',
} as const
export const PROJECT_TABS = (
diff --git a/web/app/pages/Project/AskAI/AIChart.tsx b/web/app/pages/Project/AskAI/AIChart.tsx
new file mode 100644
index 000000000..245264bc8
--- /dev/null
+++ b/web/app/pages/Project/AskAI/AIChart.tsx
@@ -0,0 +1,243 @@
+import type { ChartOptions } from 'billboard.js'
+import { line, area, bar, spline } from 'billboard.js'
+import dayjs from 'dayjs'
+import _isEmpty from 'lodash/isEmpty'
+import _keys from 'lodash/keys'
+import _map from 'lodash/map'
+import _size from 'lodash/size'
+import _filter from 'lodash/filter'
+import React, { useMemo } from 'react'
+
+import BillboardChart from '~/ui/BillboardChart'
+
+interface AIChartData {
+ type: 'chart'
+ chartType: 'line' | 'bar' | 'area' | 'spline'
+ title?: string
+ data: {
+ x: string[]
+ [key: string]: number[] | string[]
+ }
+}
+
+interface AIChartProps {
+ chart: AIChartData
+}
+
+// Generate nice colors for chart series
+const CHART_COLORS = [
+ '#2563EB', // blue-600
+ '#16a34a', // green-600
+ '#dc2626', // red-600
+ '#9333ea', // purple-600
+ '#ea580c', // orange-600
+ '#0891b2', // cyan-600
+ '#4f46e5', // indigo-600
+ '#db2777', // pink-600
+]
+
+// Calculate optimal Y axis ticks
+const calculateOptimalTicks = (data: number[], targetCount: number = 6): number[] => {
+ const validData = data.filter((n) => n !== undefined && n !== null && Number.isFinite(n))
+
+ if (validData.length === 0) {
+ return [0, 1]
+ }
+
+ const min = Math.min(...validData)
+ const max = Math.max(...validData)
+
+ if (min === max) {
+ return max === 0 ? [0, 1] : [0, max * 1.2]
+ }
+
+ const upperBound = Math.ceil(max * 1.2)
+ const roughStep = upperBound / (targetCount - 1)
+
+ let niceStep: number
+ if (roughStep <= 1) niceStep = 1
+ else if (roughStep <= 2) niceStep = 2
+ else if (roughStep <= 5) niceStep = 5
+ else if (roughStep <= 10) niceStep = 10
+ else if (roughStep <= 20) niceStep = 20
+ else if (roughStep <= 25) niceStep = 25
+ else if (roughStep <= 50) niceStep = 50
+ else {
+ const magnitude = Math.pow(10, Math.floor(Math.log10(roughStep)))
+ const normalized = roughStep / magnitude
+ if (normalized <= 2) niceStep = 2 * magnitude
+ else if (normalized <= 5) niceStep = 5 * magnitude
+ else niceStep = 10 * magnitude
+ }
+
+ const ticks: number[] = []
+ for (let i = 0; i <= upperBound; i += niceStep) {
+ ticks.push(i)
+ }
+
+ if (ticks[ticks.length - 1] < max) {
+ ticks.push(ticks[ticks.length - 1] + niceStep)
+ }
+
+ return ticks
+}
+
+const getChartType = (type: string) => {
+ switch (type) {
+ case 'bar':
+ return bar()
+ case 'area':
+ return area()
+ case 'spline':
+ return spline()
+ case 'line':
+ default:
+ return line()
+ }
+}
+
+const AIChart: React.FC<AIChartProps> = ({ chart }) => {
+ const chartOptions = useMemo<ChartOptions>(() => {
+ if (_isEmpty(chart.data) || _isEmpty(chart.data.x)) {
+ return {}
+ }
+
+ const xData = chart.data.x
+ const seriesKeys = _filter(_keys(chart.data), (key) => key !== 'x')
+
+ // Build columns
+ const columns: any[] = [['x', ..._map(xData, (el) => (dayjs(el).isValid() ? dayjs(el).toDate() : el))]]
+
+ const types: Record<string, ReturnType<typeof line | typeof bar | typeof area | typeof spline>> = {}
+ const colors: Record<string, string> = {}
+
+ seriesKeys.forEach((key, idx) => {
+ columns.push([key, ...chart.data[key]])
+ types[key] = getChartType(chart.chartType)
+ colors[key] = CHART_COLORS[idx % CHART_COLORS.length]
+ })
+
+ // Calculate optimal Y axis ticks from all series data
+ const allYValues: number[] = []
+ seriesKeys.forEach((key) => {
+ const values = chart.data[key]
+ if (Array.isArray(values)) {
+ values.forEach((v) => {
+ if (typeof v === 'number') {
+ allYValues.push(v)
+ }
+ })
+ }
+ })
+
+ const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+
+ // Determine if x-axis looks like dates
+ const isDateAxis = xData.length > 0 && dayjs(xData[0]).isValid()
+
+ return {
+ data: {
+ x: 'x',
+ columns,
+ types,
+ colors,
+ },
+ grid: {
+ y: {
+ show: true,
+ },
+ },
+ transition: {
+ duration: 200,
+ },
+ resize: {
+ auto: true,
+ },
+ axis: {
+ x: {
+ type: isDateAxis ? 'timeseries' : 'category',
+ tick: {
+ fit: true,
+ rotate: xData.length > 10 ? 45 : 0,
+ format: isDateAxis
+ ? (x: Date) => {
+ const d = dayjs(x)
+ // Auto-format based on data range
+ if (xData.length <= 24) {
+ return d.format('HH:mm')
+ } else if (xData.length <= 31) {
+ return d.format('MMM D')
+ } else {
+ return d.format('MMM D')
+ }
+ }
+ : undefined,
+ },
+ },
+ y: {
+ tick: {
+ values: optimalTicks,
+ format: (d: number) => {
+ if (d >= 1000000) return `${(d / 1000000).toFixed(1)}M`
+ if (d >= 1000) return `${(d / 1000).toFixed(1)}K`
+ return d.toFixed(0)
+ },
+ },
+ min: 0,
+ padding: { bottom: 0 },
+ },
+ },
+ point: {
+ r: 3,
+ focus: {
+ expand: {
+ r: 5,
+ },
+ },
+ },
+ legend: {
+ show: seriesKeys.length > 1,
+ position: 'bottom',
+ inset: {
+ anchor: 'top-right',
+ x: 10,
+ y: 10,
+ step: 1,
+ },
+ },
+ tooltip: {
+ format: {
+ title: (x: Date | string) => {
+ if (x instanceof Date) {
+ return dayjs(x).format('MMM D, YYYY HH:mm')
+ }
+ return String(x)
+ },
+ value: (value: number) => {
+ if (value >= 1000000) return `${(value / 1000000).toFixed(2)}M`
+ if (value >= 1000) return `${(value / 1000).toFixed(2)}K`
+ return value.toLocaleString()
+ },
+ },
+ },
+ padding: {
+ right: 20,
+ },
+ }
+ }, [chart])
+
+ if (_isEmpty(chart.data) || _isEmpty(chart.data.x)) {
+ return null
+ }
+
+ return (
+ <div className='rounded-lg border border-gray-200 bg-white p-3 dark:border-slate-600 dark:bg-slate-800'>
+ {chart.title && <h4 className='mb-2 text-sm font-medium text-gray-700 dark:text-gray-300'>{chart.title}</h4>}
+ <div className='h-[200px] w-full'>
+ <BillboardChart options={chartOptions} className='h-full w-full' />
+ </div>
+ </div>
+ )
+}
+
+export default AIChart
diff --git a/web/app/pages/Project/AskAI/AskAIView.tsx b/web/app/pages/Project/AskAI/AskAIView.tsx
new file mode 100644
index 000000000..ebf458506
--- /dev/null
+++ b/web/app/pages/Project/AskAI/AskAIView.tsx
@@ -0,0 +1,529 @@
+import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'
+import { useTranslation } from 'react-i18next'
+import cx from 'clsx'
+import {
+ SendIcon,
+ SparklesIcon,
+ ChevronDownIcon,
+ ChevronRightIcon,
+ Loader2Icon,
+ StopCircleIcon,
+ AlertCircleIcon,
+ ThumbsUpIcon,
+ ThumbsDownIcon,
+ RotateCcwIcon,
+} from 'lucide-react'
+import _isEmpty from 'lodash/isEmpty'
+import _map from 'lodash/map'
+import _filter from 'lodash/filter'
+import _sample from 'lodash/sample'
+import { marked } from 'marked'
+import sanitizeHtml from 'sanitize-html'
+
+import { askAI } from '~/api'
+import AIChart from './AIChart'
+
+interface Message {
+ id: string
+ role: 'user' | 'assistant'
+ content: string
+ reasoning?: string
+ toolCalls?: Array<{ toolName: string; args: unknown }>
+}
+
+interface AskAIViewProps {
+ projectId: string
+}
+
+// Configure marked for safe rendering
+marked.setOptions({
+ breaks: true,
+ gfm: true,
+})
+
+// Parse chart JSON from AI response
+const parseCharts = (content: string): { text: string; charts: any[] } => {
+ const chartRegex = /\{"type":"chart"[^}]+\}/g
+ const charts: any[] = []
+ let text = content
+
+ const matches = content.match(chartRegex)
+ if (matches) {
+ for (const match of matches) {
+ try {
+ const chartData = JSON.parse(match)
+ if (chartData.type === 'chart') {
+ charts.push(chartData)
+ text = text.replace(match, '')
+ }
+ } catch {
+ // Not valid JSON, keep as text
+ }
+ }
+ }
+
+ return { text: text.trim(), charts }
+}
+
+// Render markdown safely
+const renderMarkdown = (content: string): string => {
+ const html = marked.parse(content) as string
+ return sanitizeHtml(html, {
+ allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
+ allowedAttributes: {
+ ...sanitizeHtml.defaults.allowedAttributes,
+ code: ['class'],
+ pre: ['class'],
+ span: ['class'],
+ },
+ })
+}
+
+// Thinking messages that rotate
+const THINKING_MESSAGES = [
+ 'Thinking...',
+ 'Analyzing data...',
+ 'Processing...',
+ 'Querying analytics...',
+ 'Crunching numbers...',
+ 'Gathering insights...',
+]
+
+// Tool name to human-readable description
+const getToolDescription = (toolName: string): string => {
+ const descriptions: Record<string, string> = {
+ getProjectInfo: 'Getting project information',
+ getData: 'Querying analytics data',
+ getGoalStats: 'Fetching goal statistics',
+ getFunnelData: 'Loading funnel data',
+ }
+ return descriptions[toolName] || `Running ${toolName}`
+}
+
+const ThinkingIndicator = () => {
+ const [messageIndex, setMessageIndex] = useState(0)
+
+ useEffect(() => {
+ const interval = setInterval(() => {
+ setMessageIndex((prev) => (prev + 1) % THINKING_MESSAGES.length)
+ }, 3000)
+ return () => clearInterval(interval)
+ }, [])
+
+ return (
+ <div className='flex items-center gap-2 text-sm text-gray-500 dark:text-gray-400'>
+ <Loader2Icon className='h-4 w-4 animate-spin' />
+ <span>{THINKING_MESSAGES[messageIndex]}</span>
+ </div>
+ )
+}
+
+const ThoughtProcess = ({
+ reasoning,
+ toolCalls,
+ isExpanded,
+ onToggle,
+}: {
+ reasoning?: string
+ toolCalls?: Array<{ toolName: string; args: unknown }>
+ isExpanded: boolean
+ onToggle: () => void
+}) => {
+ const hasContent = reasoning || (toolCalls && toolCalls.length > 0)
+
+ if (!hasContent) return null
+
+ return (
+ <div className='mb-2'>
+ <button
+ type='button'
+ onClick={onToggle}
+ className='flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300'
+ >
+ <Loader2Icon className='h-3.5 w-3.5' />
+ <span>Thought</span>
+ {isExpanded ? <ChevronDownIcon className='h-3.5 w-3.5' /> : <ChevronRightIcon className='h-3.5 w-3.5' />}
+ </button>
+ {isExpanded && (
+ <div className='mt-2 border-l-2 border-gray-200 pl-3 text-sm text-gray-600 dark:border-gray-700 dark:text-gray-400'>
+ {toolCalls && toolCalls.length > 0 && (
+ <div className='mb-2 space-y-1'>
+ {_map(toolCalls, (call, idx) => (
+ <div key={idx} className='text-xs text-gray-500'>
+ 🔧 {getToolDescription(call.toolName)}
+ </div>
+ ))}
+ </div>
+ )}
+ {reasoning && <div className='whitespace-pre-wrap'>{reasoning}</div>}
+ </div>
+ )}
+ </div>
+ )
+}
+
+const MessageContent = ({ content, isStreaming }: { content: string; isStreaming?: boolean }) => {
+ const { text, charts } = parseCharts(content)
+
+ return (
+ <>
+ {text && (
+ <div
+ className='prose prose-sm max-w-none dark:prose-invert prose-p:my-2 prose-ol:my-2 prose-ul:my-2 prose-li:my-0.5 prose-table:text-sm'
+ dangerouslySetInnerHTML={{ __html: renderMarkdown(text) }}
+ />
+ )}
+ {isStreaming && <span className='ml-1 inline-block h-4 w-0.5 animate-pulse bg-gray-400' />}
+ {!_isEmpty(charts) && (
+ <div className='mt-4 space-y-4'>
+ {_map(charts, (chart, idx) => (
+ <AIChart key={idx} chart={chart} />
+ ))}
+ </div>
+ )}
+ </>
+ )
+}
+
+const AssistantMessage = ({
+ message,
+ isStreaming,
+ onRegenerate,
+}: {
+ message: Message
+ isStreaming?: boolean
+ onRegenerate?: () => void
+}) => {
+ const [isThoughtExpanded, setIsThoughtExpanded] = useState(false)
+
+ return (
+ <div className='group'>
+ <ThoughtProcess
+ reasoning={message.reasoning}
+ toolCalls={message.toolCalls}
+ isExpanded={isThoughtExpanded}
+ onToggle={() => setIsThoughtExpanded(!isThoughtExpanded)}
+ />
+ <MessageContent content={message.content} isStreaming={isStreaming} />
+ {!isStreaming && message.content && (
+ <div className='mt-2 flex items-center gap-2 opacity-0 transition-opacity group-hover:opacity-100'>
+ <button
+ type='button'
+ className='rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300'
+ title='Good response'
+ >
+ <ThumbsUpIcon className='h-4 w-4' />
+ </button>
+ <button
+ type='button'
+ className='rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300'
+ title='Bad response'
+ >
+ <ThumbsDownIcon className='h-4 w-4' />
+ </button>
+ {onRegenerate && (
+ <button
+ type='button'
+ onClick={onRegenerate}
+ className='rounded p-1 text-gray-400 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-slate-800 dark:hover:text-gray-300'
+ title='Regenerate response'
+ >
+ <RotateCcwIcon className='h-4 w-4' />
+ </button>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
+
+const UserMessage = ({ content }: { content: string }) => {
+ return (
+ <div className='flex justify-end'>
+ <div className='max-w-[85%] rounded-2xl bg-indigo-600 px-4 py-2.5 text-white'>
+ <p className='text-sm'>{content}</p>
+ </div>
+ </div>
+ )
+}
+
+const AskAIView = ({ projectId }: AskAIViewProps) => {
+ const { t } = useTranslation('common')
+ const [messages, setMessages] = useState<Message[]>([])
+ const [input, setInput] = useState('')
+ const [isLoading, setIsLoading] = useState(false)
+ const [isWaitingForResponse, setIsWaitingForResponse] = useState(false)
+ const [streamingMessage, setStreamingMessage] = useState<Message | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const messagesContainerRef = useRef<HTMLDivElement>(null)
+ const inputRef = useRef<HTMLTextAreaElement>(null)
+ const abortControllerRef = useRef<AbortController | null>(null)
+
+ // Refs to track streaming content
+ const streamingContentRef = useRef('')
+ const streamingReasoningRef = useRef('')
+ const streamingToolCallsRef = useRef<Array<{ toolName: string; args: unknown }>>([])
+
+ const scrollToBottom = useCallback(() => {
+ if (messagesContainerRef.current) {
+ messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight
+ }
+ }, [])
+
+ // Scroll on new messages
+ useEffect(() => {
+ scrollToBottom()
+ }, [messages, scrollToBottom])
+
+ const generateMessageId = () => `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
+
+ const handleSubmit = async (e?: React.FormEvent) => {
+ e?.preventDefault()
+ if (!input.trim() || isLoading) return
+
+ setError(null)
+ const userMessage: Message = { id: generateMessageId(), role: 'user', content: input.trim() }
+ const newMessages = [...messages, userMessage]
+ setMessages(newMessages)
+ setInput('')
+ setIsLoading(true)
+ setIsWaitingForResponse(true)
+
+ // Reset streaming refs
+ streamingContentRef.current = ''
+ streamingReasoningRef.current = ''
+ streamingToolCallsRef.current = []
+
+ // Create abort controller for cancellation
+ abortControllerRef.current = new AbortController()
+
+ try {
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
+
+ // Filter out messages with empty content and convert to API format
+ const messagesToSend = _filter(newMessages, (msg) => msg.content.trim().length > 0).map((msg) => ({
+ role: msg.role,
+ content: msg.content,
+ }))
+
+ await askAI(
+ projectId,
+ messagesToSend,
+ timezone,
+ {
+ onText: (chunk) => {
+ setIsWaitingForResponse(false)
+ streamingContentRef.current += chunk
+ setStreamingMessage({
+ id: generateMessageId(),
+ role: 'assistant',
+ content: streamingContentRef.current,
+ reasoning: streamingReasoningRef.current,
+ toolCalls: [...streamingToolCallsRef.current],
+ })
+ },
+ onToolCall: (toolName, args) => {
+ setIsWaitingForResponse(false)
+ streamingToolCallsRef.current.push({ toolName, args })
+ setStreamingMessage((prev) =>
+ prev
+ ? { ...prev, toolCalls: [...streamingToolCallsRef.current] }
+ : {
+ id: generateMessageId(),
+ role: 'assistant',
+ content: '',
+ toolCalls: [...streamingToolCallsRef.current],
+ },
+ )
+ },
+ onReasoning: (chunk) => {
+ setIsWaitingForResponse(false)
+ streamingReasoningRef.current += chunk
+ setStreamingMessage((prev) =>
+ prev
+ ? { ...prev, reasoning: streamingReasoningRef.current }
+ : {
+ id: generateMessageId(),
+ role: 'assistant',
+ content: '',
+ reasoning: streamingReasoningRef.current,
+ },
+ )
+ },
+ onComplete: () => {
+ const finalContent = streamingContentRef.current
+ if (finalContent.trim() || streamingToolCallsRef.current.length > 0) {
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: generateMessageId(),
+ role: 'assistant',
+ content: finalContent,
+ reasoning: streamingReasoningRef.current,
+ toolCalls: streamingToolCallsRef.current,
+ },
+ ])
+ }
+ setStreamingMessage(null)
+ setIsLoading(false)
+ setIsWaitingForResponse(false)
+ },
+ onError: (err) => {
+ console.error('AI chat error:', err)
+ setError(err.message || t('askAi.error'))
+ setStreamingMessage(null)
+ setIsLoading(false)
+ setIsWaitingForResponse(false)
+ },
+ },
+ abortControllerRef.current.signal,
+ )
+ } catch (err) {
+ console.error('AI chat error:', err)
+ setError((err as Error).message || t('askAi.error'))
+ setIsLoading(false)
+ setIsWaitingForResponse(false)
+ }
+ }
+
+ const handleStop = () => {
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort()
+ setIsLoading(false)
+ setIsWaitingForResponse(false)
+ const finalContent = streamingContentRef.current
+ if (finalContent.trim()) {
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: generateMessageId(),
+ role: 'assistant',
+ content: finalContent,
+ reasoning: streamingReasoningRef.current,
+ toolCalls: streamingToolCallsRef.current,
+ },
+ ])
+ }
+ setStreamingMessage(null)
+ }
+ }
+
+ const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault()
+ handleSubmit()
+ }
+ }
+
+ // Auto-resize textarea
+ useEffect(() => {
+ if (inputRef.current) {
+ inputRef.current.style.height = 'auto'
+ inputRef.current.style.height = `${Math.min(inputRef.current.scrollHeight, 200)}px`
+ }
+ }, [input])
+
+ const suggestions = useMemo(() => [t('askAi.suggestion1'), t('askAi.suggestion2'), t('askAi.suggestion3')], [t])
+
+ return (
+ <div className='flex h-[calc(100vh-200px)] min-h-[600px] flex-col'>
+ {/* Error Banner */}
+ {error && (
+ <div className='mb-4 flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 dark:border-red-800 dark:bg-red-900/20'>
+ <AlertCircleIcon className='h-5 w-5 shrink-0 text-red-500' />
+ <p className='flex-1 text-sm text-red-700 dark:text-red-400'>{error}</p>
+ <button
+ type='button'
+ onClick={() => setError(null)}
+ className='text-sm font-medium text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300'
+ >
+ Dismiss
+ </button>
+ </div>
+ )}
+
+ {/* Messages Area */}
+ <div ref={messagesContainerRef} className='flex-1 overflow-y-auto'>
+ {_isEmpty(messages) && !streamingMessage ? (
+ <div className='flex h-full flex-col items-center justify-center px-4'>
+ <div className='mb-6 flex h-16 w-16 items-center justify-center rounded-full bg-linear-to-br from-violet-500/10 to-purple-600/10'>
+ <SparklesIcon className='h-8 w-8 text-violet-600 dark:text-violet-400' />
+ </div>
+ <h2 className='mb-2 text-xl font-semibold text-gray-900 dark:text-white'>{t('askAi.welcomeTitle')}</h2>
+ <p className='mb-8 max-w-lg text-center text-gray-500 dark:text-gray-400'>
+ {t('askAi.welcomeDescription')}
+ </p>
+ <div className='flex flex-wrap justify-center gap-2'>
+ {_map(suggestions, (suggestion, idx) => (
+ <button
+ key={idx}
+ type='button'
+ onClick={() => setInput(suggestion)}
+ className='rounded-full border border-gray-200 bg-white px-4 py-2 text-sm text-gray-700 shadow-sm transition-all hover:border-gray-300 hover:shadow dark:border-slate-700 dark:bg-slate-800 dark:text-gray-300 dark:hover:border-slate-600'
+ >
+ {suggestion}
+ </button>
+ ))}
+ </div>
+ </div>
+ ) : (
+ <div className='mx-auto max-w-3xl space-y-6 px-4 py-6'>
+ {_map(messages, (msg) =>
+ msg.role === 'user' ? (
+ <UserMessage key={msg.id} content={msg.content} />
+ ) : (
+ <AssistantMessage key={msg.id} message={msg} />
+ ),
+ )}
+ {isWaitingForResponse && (
+ <div className='py-2'>
+ <ThinkingIndicator />
+ </div>
+ )}
+ {streamingMessage && <AssistantMessage message={streamingMessage} isStreaming />}
+ </div>
+ )}
+ </div>
+
+ {/* Input Area */}
+ <div className='border-t border-gray-200 bg-white px-4 py-4 dark:border-slate-700 dark:bg-slate-900'>
+ <div className='mx-auto max-w-3xl'>
+ <form onSubmit={handleSubmit} className='relative'>
+ <textarea
+ ref={inputRef}
+ value={input}
+ onChange={(e) => setInput(e.target.value)}
+ onKeyDown={handleKeyDown}
+ placeholder={t('askAi.placeholder')}
+ disabled={isLoading}
+ rows={1}
+ className='w-full resize-none rounded-xl border border-gray-300 bg-white py-3 pr-12 pl-4 text-sm text-gray-900 placeholder-gray-500 shadow-sm transition-colors focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-slate-600 dark:bg-slate-800 dark:text-white dark:placeholder-gray-400 dark:focus:border-indigo-400 dark:focus:ring-indigo-400'
+ />
+ <div className='absolute right-2 bottom-2'>
+ {isLoading ? (
+ <button
+ type='button'
+ onClick={handleStop}
+ className='flex h-8 w-8 items-center justify-center rounded-lg bg-red-600 text-white transition-colors hover:bg-red-700'
+ >
+ <StopCircleIcon className='h-4 w-4' />
+ </button>
+ ) : (
+ <button
+ type='submit'
+ disabled={!input.trim()}
+ className='flex h-8 w-8 items-center justify-center rounded-lg bg-indigo-600 text-white transition-colors hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-50'
+ >
+ <SendIcon className='h-4 w-4' />
+ </button>
+ )}
+ </div>
+ </form>
+ <p className='mt-2 text-center text-xs text-gray-400 dark:text-gray-500'>{t('askAi.disclaimer')}</p>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default AskAIView
diff --git a/web/app/pages/Project/AskAI/index.tsx b/web/app/pages/Project/AskAI/index.tsx
new file mode 100644
index 000000000..3b59ac6bf
--- /dev/null
+++ b/web/app/pages/Project/AskAI/index.tsx
@@ -0,0 +1 @@
+export { default } from './AskAIView'
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index f412a191a..cbe4cd80d 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -40,6 +40,7 @@ import {
KeyboardIcon,
TargetIcon,
PuzzleIcon,
+ SparklesIcon,
} from 'lucide-react'
import React, {
useState,
@@ -167,6 +168,7 @@ import routes from '~/utils/routes'
import { useCurrentProject, useProjectPassword } from '../../../providers/CurrentProjectProvider'
import ProjectAlertsView from '../Alerts/View'
+import AskAIView from '../AskAI'
import GoalsView from '../Goals/View'
import AddAViewModal from './components/AddAViewModal'
@@ -1505,6 +1507,11 @@ const ViewProjectContent = () => {
label: t('dashboard.goals'),
icon: TargetIcon,
},
+ {
+ id: PROJECT_TABS.askAi,
+ label: t('dashboard.askAi'),
+ icon: SparklesIcon,
+ },
]
const adminTabs = allowedToManage
@@ -4309,6 +4316,7 @@ const ViewProjectContent = () => {
timezone={timezone}
/>
) : null}
+ {activeTab === PROJECT_TABS.askAi ? <AskAIView projectId={id} /> : null}
{activeTab === PROJECT_TABS.captcha ? <CaptchaView projectId={id} /> : null}
{analyticsLoading &&
(activeTab === PROJECT_TABS.traffic || activeTab === PROJECT_TABS.performance) ? (
diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsx
index ab38d5075..59d4892b0 100644
--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx
+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx
@@ -13,6 +13,8 @@ import routes from '~/utils/routes'
type ProjectTabKey = keyof typeof PROJECT_TABS | 'settings'
const ICON_COLORS: Record<string, string> = {
+ // Ask AI
+ askAi: 'text-violet-500',
// Web Analytics
traffic: 'text-blue-500',
performance: 'text-amber-500',
@@ -156,6 +158,11 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
}) => {
const { t } = useTranslation('common')
+ // Find Ask AI tab (standalone, not in a group)
+ const askAiTab = useMemo(() => {
+ return tabs.find((tab) => tab.id === PROJECT_TABS.askAi)
+ }, [tabs])
+
// Group tabs by category
const tabGroups = useMemo<TabGroup[]>(() => {
const groups: TabGroup[] = []
@@ -217,6 +224,46 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
{/* Tabs area */}
<div className='flex-1 px-2 py-3'>
+ {/* Ask AI - standalone tab above groups */}
+ {askAiTab && (
+ <div className='mb-3'>
+ {(() => {
+ const isCurrent = askAiTab.id === activeTab
+ const TabIcon = askAiTab.icon
+ const iconColorClass = ICON_COLORS[askAiTab.id] || 'text-gray-500'
+
+ const handleClick = (e: React.MouseEvent) => {
+ e.preventDefault()
+ if (!dataLoading) {
+ onTabChange(askAiTab.id as keyof typeof PROJECT_TABS)
+ }
+ }
+
+ const newSearchParams = new URLSearchParams(searchParams.toString())
+ newSearchParams.set('tab', askAiTab.id)
+
+ return (
+ <Link
+ to={{ search: newSearchParams.toString() }}
+ onClick={handleClick}
+ className={cx('group flex items-center gap-2 rounded-md px-2.5 py-2 transition-colors', {
+ 'bg-linear-to-r from-violet-500/10 to-purple-500/10 dark:from-violet-500/20 dark:to-purple-500/20':
+ isCurrent,
+ 'hover:bg-gray-50 dark:hover:bg-slate-800/50': !isCurrent,
+ 'cursor-wait': dataLoading,
+ })}
+ aria-current={isCurrent ? 'page' : undefined}
+ >
+ <TabIcon className={cx('size-4 shrink-0', iconColorClass)} strokeWidth={1.5} aria-hidden='true' />
+ <Text as='span' size='sm' weight='medium' truncate className='max-w-full'>
+ {askAiTab.label}
+ </Text>
+ </Link>
+ )
+ })()}
+ </div>
+ )}
+
{_map(tabGroups, (group) => (
<CollapsibleGroup
key={group.id}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 1cd89c5bf..113e0cd35 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -884,6 +884,7 @@
"alertsDesc": "Automated alerts is a powerful tool that notifies you when some events occur on your website.\nWe can automatically monitor your project for traffic spikes and notify you via Telegram, Slack or Discord.",
"goals": "Goals",
"goalsDesc": "Conversion goals help you track important user actions on your website.\nDefine pageview goals or custom event goals to measure how many visitors complete specific actions.",
+ "askAi": "Ask AI",
"webAnalytics": "Web analytics",
"productAnalytics": "Product analytics",
"revenueAnalytics": "Revenue analytics",
@@ -1737,5 +1738,17 @@
"imprint": "Legal notice",
"cloudEdition": "Cloud edition",
"starOnGithub": "Star us on GitHub"
+ },
+ "askAi": {
+ "title": "Ask AI",
+ "subtitle": "Ask questions about your analytics data",
+ "welcomeTitle": "How can I help you?",
+ "welcomeDescription": "Ask me anything about your website analytics, traffic patterns, visitor behavior, or performance metrics.",
+ "placeholder": "Ask anything about your analytics...",
+ "suggestion1": "What are my top pages this week?",
+ "suggestion2": "How is my traffic trending compared to last month?",
+ "suggestion3": "Which countries are my visitors from?",
+ "error": "Sorry, something went wrong. Please try again.",
+ "disclaimer": "AI responses may not always be accurate. Verify important data."
}
}