Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

feat: easier access to ai filters

Carl-Gerhard Lindesvärde7f131c540fc
diff --git a/apps/api/src/agents/app.ts b/apps/api/src/agents/app.ts
index 5178cea39..9c0bdf977 100644
--- a/apps/api/src/agents/app.ts
+++ b/apps/api/src/agents/app.ts
@@ -1,6 +1,11 @@
import { betterAgent, defineAgent } from '@better-agent/core';
import { type ChatAgentContext, chatContextSchema } from './context';
-import { ALLOWED_MODELS, type ChatModelEntry, openaiProvider, resolveModel } from './models';
+import {
+ ALLOWED_MODELS,
+ type ChatModelEntry,
+ openaiProvider,
+ resolveModel,
+} from '@openpanel/trpc/src/agents/models';
import { prismaConversationStore } from './persistence';
import { buildSystemPrompt } from './prompt';
import { composeChatTools } from './tools';
diff --git a/apps/start/src/components/overview/overview-ai-command.tsx b/apps/start/src/components/overview/overview-ai-command.tsx
new file mode 100644
index 000000000..b8701f4fb
--- /dev/null
+++ b/apps/start/src/components/overview/overview-ai-command.tsx
@@ -0,0 +1,133 @@
+import { useMutation } from '@tanstack/react-query';
+import { Loader2Icon, SparklesIcon } from 'lucide-react';
+import { useState } from 'react';
+import { toast } from 'sonner';
+import { chatToolHandlers } from '../chat/tool-handlers';
+import { Input } from '../ui/input';
+import { useOverviewOptions } from './useOverviewOptions';
+import { useAppParams } from '@/hooks/use-app-params';
+import {
+ useEventQueryFilters,
+ useEventQueryNamesFilter,
+} from '@/hooks/use-event-query-filters';
+import { handleError, useTRPC } from '@/integrations/trpc/react';
+import { cn } from '@/utils/cn';
+
+/**
+ * Inline AI command bar. Calls the `overview.runFilterCommand`
+ * mutation, then dispatches the returned URL-mutator actions through
+ * the same handlers the chat panel uses (`chatToolHandlers`).
+ *
+ * `className` controls layout — caller passes the width / responsive
+ * visibility it wants (e.g. compact `hidden w-[280px] md:block` in a
+ * page header, `w-full` inside a filter sheet).
+ */
+export function OverviewAICommand({ className }: { className?: string }) {
+ const { projectId, organizationId } = useAppParams();
+ const { range, startDate, endDate, interval } = useOverviewOptions();
+ const [eventNames] = useEventQueryNamesFilter();
+ const [eventFilters] = useEventQueryFilters();
+ const trpc = useTRPC();
+
+ const [value, setValue] = useState('');
+
+ const mutation = useMutation(
+ trpc.overview.runFilterCommand.mutationOptions({
+ onSuccess: async (result) => {
+ // Dispatch each non-null group through the existing client
+ // handlers — they own URL serialization + popstate plumbing.
+ // Strip null inner fields from applyFilters: the schema uses
+ // nullable for OpenAI strict-mode compatibility, but the chat
+ // handler expects undefined to mean "leave this alone".
+ let applied = 0;
+ if (result.applyFilters) {
+ const af = result.applyFilters;
+ await chatToolHandlers.apply_filters({
+ ...(af.range !== null ? { range: af.range } : {}),
+ ...(af.startDate !== null ? { startDate: af.startDate } : {}),
+ ...(af.endDate !== null ? { endDate: af.endDate } : {}),
+ ...(af.interval !== null ? { interval: af.interval } : {}),
+ });
+ applied += 1;
+ }
+ if (result.setPropertyFilters) {
+ await chatToolHandlers.set_property_filters(
+ result.setPropertyFilters
+ );
+ applied += 1;
+ }
+ if (result.setEventNamesFilter) {
+ await chatToolHandlers.set_event_names_filter(
+ result.setEventNamesFilter
+ );
+ applied += 1;
+ }
+
+ if (applied === 0) {
+ toast(
+ result.summary ||
+ "Couldn't translate that into a filter — try rephrasing."
+ );
+ } else if (result.summary) {
+ toast(result.summary);
+ }
+
+ setValue('');
+ },
+ onError: handleError,
+ })
+ );
+
+ function submit() {
+ const query = value.trim();
+ if (!query || mutation.isPending) {
+ return;
+ }
+ mutation.mutate({
+ projectId,
+ query,
+ pageContext: {
+ page: 'overview',
+ route: { projectId, organizationId },
+ filters: {
+ range,
+ startDate: startDate ?? undefined,
+ endDate: endDate ?? undefined,
+ interval: interval ?? undefined,
+ ...(eventNames.length > 0 ? { eventNames } : {}),
+ ...(eventFilters.length > 0 ? { eventFilters } : {}),
+ },
+ },
+ });
+ }
+
+ const pending = mutation.isPending;
+
+ return (
+ <div className={cn('relative', className)}>
+ <SparklesIcon
+ className={cn(
+ 'pointer-events-none absolute top-1/2 left-2.5 size-4 -translate-y-1/2 text-muted-foreground',
+ pending && 'opacity-0'
+ )}
+ />
+ {pending && (
+ <Loader2Icon className="absolute top-1/2 left-2.5 size-4 -translate-y-1/2 animate-spin text-muted-foreground" />
+ )}
+ <Input
+ aria-label="AI filter command"
+ className="pl-8"
+ disabled={pending}
+ onChange={(e) => setValue(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ submit();
+ }
+ }}
+ placeholder='Try: "last 7 days, mobile only"'
+ value={value}
+ />
+ </div>
+ );
+}
diff --git a/apps/start/src/modals/overview-filters.tsx b/apps/start/src/modals/overview-filters.tsx
index 9ca7bf4a1..99fcb6a43 100644
--- a/apps/start/src/modals/overview-filters.tsx
+++ b/apps/start/src/modals/overview-filters.tsx
@@ -8,7 +8,7 @@ import {
useEventQueryNamesFilter,
} from '@/hooks/use-event-query-filters';
import { useProfileValues } from '@/hooks/use-profile-values';
-import { FilterIcon, GanttChartIcon, GlobeIcon, LucideIcon, SlidersHorizontal, XIcon } from 'lucide-react';
+import { FilterIcon, GanttChartIcon, GlobeIcon, LucideIcon, SlidersHorizontal, SparklesIcon, XIcon } from 'lucide-react';
import type { Options as NuqsOptions } from 'nuqs';
import type {
@@ -18,6 +18,7 @@ import type {
} from '@openpanel/validation';
import { OriginFilter } from '@/components/overview/filters/origin-filter';
+import { OverviewAICommand } from '@/components/overview/overview-ai-command';
import { PropertiesCombobox } from '@/components/report/sidebar/PropertiesCombobox';
import { ComboboxEvents } from '@/components/ui/combobox-events';
import { useAppParams } from '@/hooks/use-app-params';
@@ -54,6 +55,9 @@ export default function OverviewFilters({
<SheetContent className="[&>button.absolute]:hidden">
<ModalHeader title="Filters" />
<div className="flex flex-col gap-4">
+ <Heading icon={SparklesIcon} title="Ask AI" />
+ <OverviewAICommand className="w-full" />
+ <Seperator />
<Heading icon={GlobeIcon} title="Origins" />
<OriginFilter />
<Seperator />
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx
index 7fe6ac7bb..c89425b2c 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.index.tsx
@@ -5,6 +5,7 @@ import {
OverviewFilterButton,
OverviewFiltersButtons,
} from '@/components/overview/filters/overview-filters-buttons';
+import { OverviewAICommand } from '@/components/overview/overview-ai-command';
import { LiveCounter } from '@/components/overview/live-counter';
import OverviewInsights from '@/components/overview/overview-insights';
import { OverviewInterval } from '@/components/overview/overview-interval';
@@ -45,6 +46,7 @@ function ProjectDashboard() {
<OverviewRange />
<OverviewInterval />
<OverviewFilterButton mode="events" />
+ <OverviewAICommand className="hidden w-[280px] md:block" />
</div>
<div className="flex gap-2">
<LiveCounter projectId={projectId} />
diff --git a/packages/trpc/package.json b/packages/trpc/package.json
index 5c13808a1..a5c0f6aa9 100644
--- a/packages/trpc/package.json
+++ b/packages/trpc/package.json
@@ -8,6 +8,8 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
+ "@better-agent/core": "^0.1.0-beta.3",
+ "@better-agent/providers": "^0.1.0-beta.3",
"@openpanel/auth": "workspace:^",
"@openpanel/common": "workspace:*",
"@openpanel/constants": "workspace:*",
diff --git a/packages/trpc/src/agents/filter-command.ts b/packages/trpc/src/agents/filter-command.ts
new file mode 100644
index 000000000..5bac271b9
--- /dev/null
+++ b/packages/trpc/src/agents/filter-command.ts
@@ -0,0 +1,388 @@
+import {
+ type AgentToolDefinition,
+ betterAgent,
+ defineAgent,
+ defineTool,
+ type ToolRunContext,
+} from '@better-agent/core';
+import { intervals, operators, timeWindows } from '@openpanel/constants';
+import {
+ getDatesFromRange,
+ getTopPagesCore,
+ getTrafficBreakdownCore,
+ listEventNamesCore,
+ resolveDateRange as resolveDateRangeCore,
+} from '@openpanel/db';
+import {
+ CHAT_MODELS,
+ type ChatModelEntry,
+ type IChartEventFilter,
+ type IChartRange,
+ objectToZodEnums,
+ type PageContext,
+ zRange,
+} from '@openpanel/validation';
+import { z } from 'zod';
+import { resolveModel } from './models';
+
+const operatorEnum = z.enum(objectToZodEnums(operators));
+const rangeEnum = zRange;
+const intervalEnum = z.enum(objectToZodEnums(intervals));
+
+export const filterCommandOutputSchema = z.object({
+ applyFilters: z
+ .object({
+ range: rangeEnum.nullable(),
+ startDate: z.string().nullable().describe('YYYY-MM-DD or null'),
+ endDate: z.string().nullable().describe('YYYY-MM-DD or null'),
+ interval: intervalEnum.nullable(),
+ })
+ .nullable()
+ .describe(
+ 'Date range / interval. Null = no change. Either set `range` to a preset (and null both dates) OR set `startDate`+`endDate` for a custom window (and null `range`) — never both.',
+ ),
+ setPropertyFilters: z
+ .object({
+ filters: z.array(
+ z.object({
+ name: z
+ .string()
+ .describe(
+ 'Property key. Common: country, region, city, device, browser, os, referrer_name, referrer_type, path, origin, utm_source, utm_medium, utm_campaign.',
+ ),
+ operator: operatorEnum,
+ value: z
+ .array(z.string())
+ .describe(
+ "Values to match (OR'd). Use [] for isNull / isNotNull.",
+ ),
+ }),
+ ),
+ })
+ .nullable()
+ .describe(
+ 'REPLACES the active property-filter set. Null = no change. To ADD to existing filters, include the current ones (see "Current view"). Empty filters array clears all property filters.',
+ ),
+ setEventNamesFilter: z
+ .object({ eventNames: z.array(z.string()) })
+ .nullable()
+ .describe(
+ 'REPLACES the event-name filter. Null = no change. Empty array shows all events. Verify names with list_event_names if unsure.',
+ ),
+ summary: z
+ .string()
+ .describe(
+ 'One-line confirmation in 8-15 words. No preamble, no markdown. If ambiguous and you applied no changes, explain what you need.',
+ ),
+});
+
+export type FilterCommandResult = z.infer<typeof filterCommandOutputSchema>;
+
+const filterCommandContextSchema = z.object({
+ projectId: z.string(),
+ timezone: z.string(),
+ pageContext: z
+ .object({
+ filters: z
+ .object({
+ range: z.string().optional(),
+ startDate: z.string().optional(),
+ endDate: z.string().optional(),
+ interval: z.string().optional(),
+ eventNames: z.array(z.string()).optional(),
+ eventFilters: z.array(z.record(z.string(), z.unknown())).optional(),
+ })
+ .optional(),
+ })
+ .optional(),
+});
+
+type FilterCommandContext = z.infer<typeof filterCommandContextSchema>;
+
+const PREFERRED_MODEL_IDS = ['claude-haiku-4-5', 'gpt-4-1-mini'] as const;
+
+function pickModel(): ChatModelEntry {
+ const haveOpenai = Boolean(process.env.OPENAI_API_KEY);
+ const haveAnthropic = Boolean(process.env.ANTHROPIC_API_KEY);
+ const available = (entry: ChatModelEntry) =>
+ (entry.group === 'OpenAI' && haveOpenai) ||
+ (entry.group === 'Anthropic' && haveAnthropic);
+
+ for (const id of PREFERRED_MODEL_IDS) {
+ const entry = CHAT_MODELS.find((m) => m.id === id);
+ if (entry && available(entry)) return entry;
+ }
+ const fallback = CHAT_MODELS.find(available);
+ if (!fallback) {
+ throw new Error(
+ 'filter-command: no model available — set OPENAI_API_KEY or ANTHROPIC_API_KEY.',
+ );
+ }
+ return fallback;
+}
+
+const PRESET_RANGES: ReadonlySet<IChartRange> = new Set(
+ (Object.keys(timeWindows) as IChartRange[]).filter((k) => k !== 'custom'),
+);
+
+function resolveRange(
+ filters: FilterCommandContext['pageContext'] extends infer T
+ ? T extends { filters?: infer F }
+ ? F
+ : undefined
+ : undefined,
+ timezone: string,
+): { startDate: string; endDate: string } {
+ if (filters?.startDate || filters?.endDate) {
+ return resolveDateRangeCore(filters.startDate, filters.endDate);
+ }
+ const range = filters?.range as IChartRange | undefined;
+ if (range && PRESET_RANGES.has(range)) {
+ return getDatesFromRange(range, timezone);
+ }
+ return resolveDateRangeCore(undefined, undefined);
+}
+
+function activeFilters(ctx: FilterCommandContext): IChartEventFilter[] {
+ const raw = ctx.pageContext?.filters?.eventFilters;
+ if (!Array.isArray(raw)) return [];
+ return raw.filter(
+ (f): f is IChartEventFilter =>
+ typeof (f as { name?: unknown })?.name === 'string',
+ );
+}
+
+function defineServerTool<TSchema extends z.ZodTypeAny>(config: {
+ name: string;
+ description: string;
+ schema: TSchema;
+ handler: (
+ input: z.infer<TSchema>,
+ ctx: FilterCommandContext,
+ ) => Promise<unknown>;
+}): AgentToolDefinition {
+ // biome-ignore lint/suspicious/noExplicitAny: Zod schema instantiation depth — same dodge as apps/api/src/agents/tools/ui.ts
+ const contract: any = defineTool({
+ name: config.name,
+ description: config.description,
+ schema: config.schema,
+ });
+ return contract.server(async (input: unknown, runCtx: ToolRunContext) =>
+ config.handler(
+ input as z.infer<TSchema>,
+ runCtx.context as FilterCommandContext,
+ ),
+ ) as AgentToolDefinition;
+}
+
+const listEventNamesTool = defineServerTool({
+ name: 'list_event_names',
+ description:
+ 'Top 50 event names tracked in this project. Use BEFORE setting `setEventNamesFilter`.',
+ schema: z.object({}),
+ handler: async (_input, ctx) => ({
+ event_names: await listEventNamesCore(ctx.projectId),
+ }),
+});
+
+const getTopReferrersTool = defineServerTool({
+ name: 'get_top_referrers',
+ description:
+ "Top traffic sources by `referrer_name` ('Google', 'GitHub', 'Direct') in the user's current date range. Use to translate vague names into exact filter values.",
+ schema: z.object({}),
+ handler: async (_input, ctx) => {
+ const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);
+ const rows = await getTrafficBreakdownCore({
+ projectId: ctx.projectId,
+ startDate: range.startDate,
+ endDate: range.endDate,
+ column: 'referrer_name',
+ filters: activeFilters(ctx),
+ });
+ return { rows: rows.slice(0, 30) };
+ },
+});
+
+const getTopCountriesTool = defineServerTool({
+ name: 'get_top_countries',
+ description: "Top countries (ISO-2 codes) in the user's current date range.",
+ schema: z.object({}),
+ handler: async (_input, ctx) => {
+ const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);
+ const rows = await getTrafficBreakdownCore({
+ projectId: ctx.projectId,
+ startDate: range.startDate,
+ endDate: range.endDate,
+ column: 'country',
+ filters: activeFilters(ctx),
+ });
+ return { rows: rows.slice(0, 50) };
+ },
+});
+
+const getTopDevicesTool = defineServerTool({
+ name: 'get_top_devices',
+ description:
+ "Device classes seen in the user's current date range (mobile, desktop, tablet, …).",
+ schema: z.object({}),
+ handler: async (_input, ctx) => {
+ const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);
+ const rows = await getTrafficBreakdownCore({
+ projectId: ctx.projectId,
+ startDate: range.startDate,
+ endDate: range.endDate,
+ column: 'device',
+ filters: activeFilters(ctx),
+ });
+ return { rows: rows.slice(0, 20) };
+ },
+});
+
+const getTopPagesTool = defineServerTool({
+ name: 'get_top_pages',
+ description:
+ "Top pages (paths like '/blog/foo', '/pricing', '/') in the user's current date range. Use to discover the path shape so you can pick the right operator (`startsWith` for sections like /blog, `is` for an exact page, `contains` for fuzzy matching).",
+ schema: z.object({}),
+ handler: async (_input, ctx) => {
+ const range = resolveRange(ctx.pageContext?.filters, ctx.timezone);
+ const rows = await getTopPagesCore({
+ projectId: ctx.projectId,
+ startDate: range.startDate,
+ endDate: range.endDate,
+ filters: activeFilters(ctx),
+ limit: 50,
+ });
+ return { rows };
+ },
+});
+
+const FILTER_COMMAND_TOOLS: AgentToolDefinition[] = [
+ listEventNamesTool,
+ getTopReferrersTool,
+ getTopCountriesTool,
+ getTopDevicesTool,
+ getTopPagesTool,
+];
+
+function buildInstruction(ctx: FilterCommandContext): string {
+ const today = new Date();
+ const todayIso = today.toISOString().slice(0, 10);
+ const dayName = today.toLocaleDateString('en-US', {
+ weekday: 'long',
+ timeZone: 'UTC',
+ });
+
+ return [
+ "You are the OpenPanel filter command bar. Convert the user's short request into a structured filter update, then output a single short confirmation sentence in `summary`.",
+ '',
+ `Today is **${dayName}, ${todayIso}** (UTC). Use it for relative date math.`,
+ '',
+ '# Rules',
+ '- For date ranges, prefer presets when they match exactly. Anything that does not map to a preset MUST go through `startDate`+`endDate` (YYYY-MM-DD).',
+ '- "last week", explicit calendar windows ("Q1 2026", "august last year", "May 24-28") → ALWAYS compute `startDate`+`endDate` manually relative to today.',
+ '- For property filters: REPLACE semantics. To ADD to the existing set, include the current filters (listed under "Current view") in your output.',
+ '- When the user names a source ("google", "twitter", "hackernews") that may not be an exact known referrer, call `get_top_referrers` first and pick the matching `referrer_name` value(s). Same for countries (`get_top_countries`) and devices (`get_top_devices`).',
+ '- Prefer `referrer_name` for source filtering (e.g. "Google", "GitHub"), not the raw URL.',
+ '',
+ '# Page / path filtering',
+ '- When the user asks about a page or section ("blog posts", "the pricing page", "anything under /docs", "homepage only"), filter on the `path` property.',
+ '- Pick the operator that matches intent:',
+ ' - "blog posts" / "anything under /blog" / "the docs section" → `startsWith` with value like `["/blog"]` or `["/docs"]`',
+ ' - "pages with `pricing` in the URL" / fuzzy match → `contains`',
+ ' - exact page ("the homepage", "the pricing page") → `is` with the exact path (`["/"]` or `["/pricing"]`)',
+ ' - "anything ending in .pdf" → `endsWith`',
+ '- If you are not sure what paths exist (e.g. user says "blog" but the project might use `/posts/*` instead), call `get_top_pages` FIRST to see real paths, then pick the right prefix.',
+ '- Never invent event names — call `list_event_names` if unsure.',
+ '- Set `applyFilters` / `setPropertyFilters` / `setEventNamesFilter` to `null` when the user did not ask to change them. Do not over-apply.',
+ '- If the request is ambiguous, leave all three groups null and put a clarification in `summary`.',
+ '',
+ buildPageContextSection(ctx),
+ ].join('\n');
+}
+
+function buildPageContextSection(ctx: FilterCommandContext): string {
+ const pc = ctx.pageContext;
+ const lines: string[] = ['# Current view'];
+
+ if (!pc?.filters) {
+ lines.push('No filters currently active.');
+ return lines.join('\n');
+ }
+
+ if (pc.filters.range) {
+ const resolved = resolveRange(pc.filters, ctx.timezone);
+ const interval = pc.filters.interval ?? 'day';
+ lines.push(
+ `Date range: ${pc.filters.range} (${resolved.startDate} to ${resolved.endDate}), interval: ${interval}.`,
+ );
+ } else {
+ lines.push('Date range: default (no `range` set).');
+ }
+
+ if (pc.filters.eventNames && pc.filters.eventNames.length > 0) {
+ lines.push(
+ `Active event-name filter: ${JSON.stringify(pc.filters.eventNames)}`,
+ );
+ } else {
+ lines.push('No event-name filter active.');
+ }
+
+ if (pc.filters.eventFilters && pc.filters.eventFilters.length > 0) {
+ lines.push(
+ `Active property filters: ${JSON.stringify(pc.filters.eventFilters)}`,
+ );
+ } else {
+ lines.push('No property filters active.');
+ }
+
+ return lines.join('\n');
+}
+
+const filterCommandOutputJsonSchema = z.toJSONSchema(
+ filterCommandOutputSchema,
+ { target: 'draft-07' },
+);
+
+let _app: ReturnType<typeof betterAgent> | null = null;
+function getApp() {
+ if (_app) return _app;
+ const agent = defineAgent({
+ name: 'filter-command',
+ description: 'OpenPanel filter command bar (one-shot, no persistence).',
+ model: resolveModel(pickModel()),
+ contextSchema: filterCommandContextSchema,
+ outputSchema: {
+ schema: filterCommandOutputJsonSchema,
+ name: 'filter_command_output',
+ strict: true,
+ },
+ instruction: (ctx: FilterCommandContext) => buildInstruction(ctx),
+ tools: () => FILTER_COMMAND_TOOLS,
+ maxSteps: 6,
+ // biome-ignore lint/suspicious/noExplicitAny: same dodge as apps/api/src/agents/app.ts
+ } as any);
+ _app = betterAgent({ agents: [agent] });
+ return _app;
+}
+
+export async function runFilterCommand(input: {
+ query: string;
+ projectId: string;
+ pageContext?: PageContext;
+ timezone: string;
+}): Promise<FilterCommandResult> {
+ const result = (await getApp().run('filter-command', {
+ input: input.query,
+ context: {
+ projectId: input.projectId,
+ timezone: input.timezone,
+ pageContext: input.pageContext as FilterCommandContext['pageContext'],
+ },
+ // biome-ignore lint/suspicious/noExplicitAny: same dodge as apps/api/src/agents/app.ts
+ } as any)) as { structured?: FilterCommandResult };
+
+ if (!result.structured) {
+ throw new Error('filter-command agent returned no structured output');
+ }
+ return result.structured;
+}
diff --git a/apps/api/src/agents/models.ts b/packages/trpc/src/agents/models.ts
similarity index 59%
rename from apps/api/src/agents/models.ts
rename to packages/trpc/src/agents/models.ts
index f13ec84e0..7ec6c17ca 100644
--- a/apps/api/src/agents/models.ts
+++ b/packages/trpc/src/agents/models.ts
@@ -5,16 +5,9 @@ import { CHAT_MODELS, type ChatModelEntry } from '@openpanel/validation';
export { CHAT_MODELS as ALLOWED_MODELS } from '@openpanel/validation';
export type { ChatModelEntry } from '@openpanel/validation';
-// ────────────────────────────────────────────────────────────────────
-// Provider clients (lazy-built singletons)
-// ────────────────────────────────────────────────────────────────────
-
function requireEnv(name: string, provider: string): string {
const value = process.env[name];
if (!value) {
- // Don't throw here — the agent is built eagerly at import time and
- // we still want startup to succeed so the user can pick a model
- // whose key IS set. We throw when the agent actually runs.
console.warn(
`[chat] ${name} is not set. Models routed through ${provider} will fail with "x-api-key required" until you add it to the API's env.`,
);
@@ -25,9 +18,7 @@ function requireEnv(name: string, provider: string): string {
let _openai: ReturnType<typeof createOpenAI> | null = null;
function openai() {
if (!_openai) {
- _openai = createOpenAI({
- apiKey: requireEnv('OPENAI_API_KEY', 'OpenAI'),
- });
+ _openai = createOpenAI({ apiKey: requireEnv('OPENAI_API_KEY', 'OpenAI') });
}
return _openai;
}
@@ -42,16 +33,9 @@ function anthropic() {
return _anthropic;
}
-/**
- * Exposed for the titler agent in `app.ts`. Same singleton as the one
- * used by the chat agents so we don't duplicate API-key wiring.
- */
export const openaiProvider = openai;
+export const anthropicProvider = anthropic;
-/**
- * Resolve a model entry to the provider's model instance.
- * Used by the agent factory.
- */
export function resolveModel(entry: ChatModelEntry) {
switch (entry.group) {
case 'OpenAI':
diff --git a/packages/trpc/src/routers/overview.ts b/packages/trpc/src/routers/overview.ts
index e43dde515..e4329c6db 100644
--- a/packages/trpc/src/routers/overview.ts
+++ b/packages/trpc/src/routers/overview.ts
@@ -19,12 +19,18 @@ import {
zGetTopPagesInput,
zGetUserJourneyInput,
} from '@openpanel/db';
-import { type IChartRange, zRange } from '@openpanel/validation';
+import { pageContextSchema, type IChartRange, zRange } from '@openpanel/validation';
import { format } from 'date-fns';
import { z } from 'zod';
import { getProjectAccess } from '../access';
+import { runFilterCommand } from '../agents/filter-command';
import { TRPCAccessError } from '../errors';
-import { cacheMiddleware, createTRPCRouter, publicProcedure } from '../trpc';
+import {
+ cacheMiddleware,
+ createTRPCRouter,
+ protectedProcedure,
+ publicProcedure,
+} from '../trpc';
const cacher = cacheMiddleware((input, opts) => {
const range = input.range as IChartRange;
@@ -453,6 +459,28 @@ export const overviewRouter = createTRPCRouter({
return current;
}),
+ // One-shot AI command bar — converts natural-language requests
+ // ("show 7 aug to 11 aug", "from google", "mobile only for august
+ // last year") into structured filter changes the dashboard can apply
+ // through the same handlers the chat panel uses.
+ runFilterCommand: protectedProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ query: z.string().min(1).max(500),
+ pageContext: pageContextSchema.optional(),
+ }),
+ )
+ .mutation(async ({ input }) => {
+ const { timezone } = await getSettingsForProject(input.projectId);
+ return runFilterCommand({
+ query: input.query,
+ projectId: input.projectId,
+ pageContext: input.pageContext,
+ timezone: timezone || 'UTC',
+ });
+ }),
+
map: overviewProcedure
.input(
zGetMapDataInput.omit({ startDate: true, endDate: true }).extend({
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 86157e4d8..ef0a31af5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1779,6 +1779,12 @@ importers:
packages/trpc:
dependencies:
+ '@better-agent/core':
+ specifier: ^0.1.0-beta.3
+ version: 0.1.0-beta.3
+ '@better-agent/providers':
+ specifier: ^0.1.0-beta.3
+ version: 0.1.0-beta.3(@better-agent/[email protected])
'@openpanel/auth':
specifier: workspace:^
version: link:../auth
@@ -26926,7 +26932,7 @@ snapshots:
'@radix-ui/[email protected]':
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/[email protected]': {}
@@ -27052,7 +27058,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
react: 19.2.3
@@ -27069,7 +27075,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
react: 19.2.3
@@ -27142,7 +27148,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/primitive': 1.0.0
'@radix-ui/react-compose-refs': 1.0.0([email protected])
'@radix-ui/react-primitive': 1.0.0([email protected]([email protected]))([email protected])
@@ -27181,7 +27187,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
react: 19.2.3
@@ -27192,7 +27198,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/react-compose-refs': 1.0.0([email protected])
'@radix-ui/react-primitive': 1.0.0([email protected]([email protected]))([email protected])
'@radix-ui/react-use-callback-ref': 1.0.0([email protected])
@@ -27212,7 +27218,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/react-use-layout-effect': 1.0.0([email protected])
react: 19.2.3
@@ -27323,7 +27329,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/react-primitive': 1.0.0([email protected]([email protected]))([email protected])
react: 19.2.3
react-dom: 19.2.3([email protected])
@@ -27340,7 +27346,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/react-compose-refs': 1.0.0([email protected])
'@radix-ui/react-use-layout-effect': 1.0.0([email protected])
react: 19.2.3
@@ -27358,7 +27364,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/react-slot': 1.0.0([email protected])
react: 19.2.3
react-dom: 19.2.3([email protected])
@@ -27521,7 +27527,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/react-compose-refs': 1.0.0([email protected])
react: 19.2.3
@@ -27645,7 +27651,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
react: 19.2.3
@@ -27662,7 +27668,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/react-use-callback-ref': 1.0.0([email protected])
react: 19.2.3
@@ -27690,7 +27696,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
'@radix-ui/react-use-callback-ref': 1.0.0([email protected])
react: 19.2.3
@@ -27710,7 +27716,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
react: 19.2.3
@@ -30976,7 +30982,7 @@ snapshots:
dependencies:
fast-deep-equal: 3.1.3
- fast-uri: 3.0.6
+ fast-uri: 3.1.0
json-schema-traverse: 1.0.0
require-from-string: 2.0.2
@@ -32913,7 +32919,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
csstype: 3.2.3
@@ -35912,7 +35918,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
ts-algebra: 2.0.0
@@ -39340,7 +39346,7 @@ snapshots:
dependencies:
- '@babel/runtime': 7.23.9
+ '@babel/runtime': 7.29.2
dom-helpers: 5.2.1
loose-envify: 1.4.0
prop-types: 15.8.1