Skip to content

Commit ffc9b8b

Browse files
committed
brung back memory
1 parent c9d4d93 commit ffc9b8b

File tree

8 files changed

+98
-15
lines changed

8 files changed

+98
-15
lines changed

apps/api/src/ai/agents.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
import { Agent } from "@ai-sdk-tools/agents";
22
import type { AppContext } from "./config/context";
33

4+
import {
5+
extendedMemoryConfig,
6+
maxMemoryConfig,
7+
minimalMemoryConfig,
8+
standardMemoryConfig,
9+
} from "./config/memory";
410
import { models } from "./config/models";
511
import { buildAnalyticsInstructions } from "./prompts/analytics";
612
import { buildReflectionInstructions } from "./prompts/reflection";
@@ -66,6 +72,7 @@ export function createAnalyticsAgent(
6672
temperature: 0.3,
6773
instructions: buildAnalyticsInstructions,
6874
tools,
75+
memory: standardMemoryConfig,
6976
modelSettings: {
7077
failureMode: {
7178
maxAttempts: 2,
@@ -94,14 +101,17 @@ export const createReflectionAgent = (
94101
standard: {
95102
model: models.advanced,
96103
maxTurns: 15,
104+
memory: extendedMemoryConfig, // 30 messages for Sonnet
97105
},
98106
haiku: {
99107
model: models.analytics,
100108
maxTurns: 15,
109+
memory: standardMemoryConfig, // 20 messages for Haiku
101110
},
102111
max: {
103112
model: models.advanced,
104113
maxTurns: 20,
114+
memory: maxMemoryConfig, // 40 messages for deep investigations
105115
},
106116
}[variant];
107117

@@ -139,6 +149,7 @@ export function createTriageAgent(
139149
model: models.triage,
140150
temperature: 0.1,
141151
instructions: buildTriageInstructions,
152+
memory: minimalMemoryConfig,
142153
modelSettings: {
143154
toolChoice: {
144155
type: "tool",

apps/api/src/ai/config/memory.ts

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { RedisProvider } from "@ai-sdk-tools/memory/redis";
2+
import { redis } from "@databuddy/redis";
3+
import type { RedisClientType } from "redis";
4+
5+
/**
6+
* Shared memory provider for all agents.
7+
* Uses Redis for persistent conversation history.
8+
*/
9+
export const memoryProvider = new RedisProvider(
10+
redis as unknown as RedisClientType
11+
);
12+
13+
/**
14+
* Memory configurations for different agent types.
15+
* Higher-capability models get more memory to support complex, multi-step reasoning.
16+
*/
17+
18+
/** Minimal memory for simple routing (triage) */
19+
export const minimalMemoryConfig = {
20+
provider: memoryProvider,
21+
history: {
22+
enabled: true,
23+
limit: 10, // ~5 turns - just enough for context
24+
},
25+
} as const;
26+
27+
/** Standard memory for typical analytical queries */
28+
export const standardMemoryConfig = {
29+
provider: memoryProvider,
30+
history: {
31+
enabled: true,
32+
limit: 20, // ~10 turns - good for most conversations
33+
},
34+
} as const;
35+
36+
/** Extended memory for complex multi-step investigations */
37+
export const extendedMemoryConfig = {
38+
provider: memoryProvider,
39+
history: {
40+
enabled: true,
41+
limit: 30, // ~15 turns - deep analysis sessions
42+
},
43+
} as const;
44+
45+
/** Maximum memory for advanced reasoning with Sonnet */
46+
export const maxMemoryConfig = {
47+
provider: memoryProvider,
48+
history: {
49+
enabled: true,
50+
limit: 40, // ~20 turns - complex multi-step workflows
51+
},
52+
} as const;

apps/api/src/ai/config/models.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,15 @@ export const openrouter = createOpenRouter({
1717
* Centralized here for easy switching and environment-based overrides.
1818
*/
1919

20+
// const overrideModel = 'z-ai/glm-4.6'
21+
const overrideModel = null;
22+
2023
const modelNames = {
21-
triage: "anthropic/claude-haiku-4.5",
22-
analytics: "anthropic/claude-haiku-4.5",
24+
triage: overrideModel || "anthropic/claude-haiku-4.5",
25+
analytics: overrideModel || "anthropic/claude-haiku-4.5",
2326
// triage: "z-ai/glm-4.6",
2427
// analytics: "z-ai/glm-4.6",
25-
advanced: "anthropic/claude-sonnet-4.5",
28+
advanced: overrideModel || "anthropic/claude-sonnet-4.5",
2629
// advanced: "z-ai/glm-4.6",
2730
perplexity: "perplexity/sonar-pro",
2831
} as const;

apps/api/src/ai/prompts/analytics.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ import { COMMON_AGENT_RULES } from "./shared";
77
* Analytics-specific rules for data analysis and presentation.
88
*/
99
const ANALYTICS_RULES = `<agent-specific-rules>
10+
**CRITICAL DATA INTEGRITY RULES:**
11+
- NEVER make up, invent, fabricate, or hallucinate any analytics data
12+
- NEVER provide fake numbers, metrics, page views, visitor counts, or any analytics without calling tools first
13+
- NEVER respond to questions like "what's my top page", "how many visitors", "traffic data" without calling the appropriate tool
14+
- If a user asks about ANY analytics data, you MUST call get_top_pages, execute_query_builder, or execute_sql_query BEFORE responding
15+
- Only use real data returned from tool calls - never use example data, placeholder numbers, or made-up metrics
16+
- If you don't have tool results, you MUST call the tool first - never guess or estimate
17+
1018
**Data Analysis:**
1119
- Lead with key metrics and insights
1220
- Always include time context (e.g., "in the last 7 days", "yesterday vs last week")
@@ -20,7 +28,6 @@ const ANALYTICS_RULES = `<agent-specific-rules>
2028
- Use execute_query_builder for pre-built analytics queries (PREFERRED - use this for common queries like traffic, sessions, pages, devices, geo, errors, performance, etc.)
2129
- Use execute_sql_query ONLY for custom SQL queries that aren't covered by query builders
2230
- Use competitor_analysis for real-time competitor insights, market trends, and industry analysis with citations
23-
- Use memory tools (search_memory, add_memory) to remember user preferences and past analysis patterns
2431
- Use funnels tools when users ask about funnels, conversion paths, or user journeys:
2532
- list_funnels: List all funnels for a website (use when user asks "show me my funnels", "what funnels do I have", etc.)
2633
- get_funnel_by_id: Get details of a specific funnel by ID
@@ -54,15 +61,15 @@ const ANALYTICS_RULES = `<agent-specific-rules>
5461
* Builds the instruction prompt for the analytics agent.
5562
*/
5663
export function buildAnalyticsInstructions(ctx: AppContext): string {
57-
return `You are Databunny, an analytics assistant for ${ctx.websiteDomain}. Your goal is to analyze website traffic, user behavior, and performance metrics.
58-
59-
<background-data>
60-
${formatContextForLLM(ctx)}
61-
</background-data>
64+
return `You are Databunny, an analytics assistant for ${ctx.websiteDomain}. Your goal is to analyze website traffic, user behavior, and performance metrics.
6265
6366
${COMMON_AGENT_RULES}
6467
6568
${ANALYTICS_RULES}
6669
70+
<background-data>
71+
${formatContextForLLM(ctx)}
72+
</background-data>
73+
6774
${CLICKHOUSE_SCHEMA_DOCS}`;
6875
}

apps/api/src/ai/prompts/reflection.ts

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ analytics: Website traffic analysis, page views, visitors, performance metrics,
1313
* Reflection and orchestration rules.
1414
*/
1515
const REFLECTION_RULES = `<reflection-rules>
16+
**CRITICAL: NEVER make up, invent, or fabricate analytics data. Always hand off to analytics agent to get real data first.**
17+
1618
Your primary role is to reflect on responses and orchestrate multi-step investigations:
1719
1820
1. **Response Analysis**: When you receive a response from another agent or tool:
@@ -24,6 +26,7 @@ Your primary role is to reflect on responses and orchestrate multi-step investig
2426
- If the response is complete and clear → Explain it to the user in a helpful, synthesized way
2527
- If more data is needed → Hand off to the analytics agent with specific instructions
2628
- If the response needs clarification → Ask follow-up questions or request specific data
29+
- NEVER provide analytics data without handing off to analytics agent first
2730
2831
3. **Multi-Step Workflows**: For complex questions, break them down:
2932
- First, gather initial data (e.g., "check for errors")
@@ -47,6 +50,7 @@ Your primary role is to reflect on responses and orchestrate multi-step investig
4750
- Ask clarifying questions when the request is ambiguous
4851
- Proactively suggest related insights worth investigating
4952
- CRITICAL: Never respond before tool calls complete. Always wait for actual tool results before generating your response
53+
- CRITICAL: Never make up analytics data - always hand off to analytics agent to get real data
5054
</reflection-rules>`;
5155

5256
/**
@@ -98,19 +102,19 @@ User: "Create a funnel for signup" or "I want to track the checkout process"
98102
* Builds the instruction prompt for the reflection agent.
99103
*/
100104
export function buildReflectionInstructions(ctx: AppContext): string {
101-
return `You are Databunny, an analytics assistant for ${ctx.websiteDomain}. Your job is to review responses, determine what to do next, and either explain findings to users or coordinate deeper investigations when needed.
105+
return `You are Databunny, an analytics assistant for ${ctx.websiteDomain}. Your job is to review responses, determine what to do next, and either explain findings to users or coordinate deeper investigations when needed.
102106
103-
<background-data>
104-
${formatContextForLLM(ctx)}
105-
</background-data>
107+
${COMMON_AGENT_RULES}
106108
107109
${AGENT_CAPABILITIES}
108110
109111
${REFLECTION_RULES}
110112
111113
${WORKFLOW_EXAMPLES}
112114
113-
${COMMON_AGENT_RULES}
115+
<background-data>
116+
${formatContextForLLM(ctx)}
117+
</background-data>
114118
115119
<important-notes>
116120
- You are the orchestrator - use other agents to gather data, then synthesize and explain
@@ -120,5 +124,6 @@ ${COMMON_AGENT_RULES}
120124
- If a response is incomplete or unclear, investigate further before responding to the user
121125
- Consider the business context and primary goal when framing insights
122126
- Be data-driven but acknowledge limitations (small samples, short time periods, data gaps)
127+
- NEVER make up analytics data - always hand off to analytics agent to get real data first
123128
</important-notes>`;
124129
}

apps/api/src/ai/prompts/shared.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,11 @@
55
export const COMMON_AGENT_RULES = `<behavior_rules>
66
- Call tools immediately without explanatory text
77
- CRITICAL: NEVER generate a response before tool calls complete. Always wait for tool results before responding to the user
8+
- CRITICAL: NEVER make up, invent, or fabricate data. NEVER provide fake numbers, metrics, or analytics. If you don't have real data from tools, you MUST call the appropriate tool first
9+
- CRITICAL: If a user asks about analytics data (page views, visitors, traffic, etc.), you MUST call the appropriate tool (get_top_pages, execute_query_builder, execute_sql_query) BEFORE responding. Never respond with made-up data
810
- If you need data to answer a question, call the tool first, then respond based on the actual results
911
- Do not speculate or guess what tool results will be - wait for actual data
12+
- Do not provide example data or placeholder responses - only use real data from tool calls
1013
- Use parallel tool calls when possible
1114
- Provide specific numbers and actionable insights
1215
- Lead with the most important information first

apps/api/src/ai/prompts/triage.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { AppContext } from "../config/context";
22
import { formatContextForLLM } from "../config/context";
3+
import { COMMON_AGENT_RULES } from "./shared";
34

45
/**
56
* Single-model capabilities.
@@ -25,6 +26,8 @@ const ROUTING_RULES = `<routing-rules>
2526
export function buildTriageInstructions(ctx: AppContext): string {
2627
return `You are Databunny, an analytics assistant for ${ctx.websiteDomain}. Handle analytics requests directly.
2728
29+
${COMMON_AGENT_RULES}
30+
2831
<background-data>
2932
${formatContextForLLM(ctx)}
3033

apps/api/src/routes/agent.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@ function toUIMessage(msg: IncomingMessage): UIMessage {
5353
};
5454
}
5555

56-
// Extract text from content or text field
5756
const text = msg.content ?? msg.text ?? "";
5857

5958
return {

0 commit comments

Comments
 (0)