Skip to content

Commit 108dc8d

Browse files
authored
Make AutoRAG optional and improve thread summary fallback (#1888)
# READ CAREFULLY THEN REMOVE Remove bullet points that are not relevant. PLEASE REFRAIN FROM USING AI TO WRITE YOUR CODE AND PR DESCRIPTION. IF YOU DO USE AI TO WRITE YOUR CODE PLEASE PROVIDE A DESCRIPTION AND REVIEW IT CAREFULLY. MAKE SURE YOU UNDERSTAND THE CODE YOU ARE SUBMITTING USING AI. - Pull requests that do not follow these guidelines will be closed without review or comment. - If you use AI to write your PR description your pr will be close without review or comment. - If you are unsure about anything, feel free to ask for clarification. ## Description Please provide a clear description of your changes. --- ## Type of Change Please delete options that are not relevant. - [ ] 🐛 Bug fix (non-breaking change which fixes an issue) - [ ] ✨ New feature (non-breaking change which adds functionality) - [ ] 💥 Breaking change (fix or feature with breaking changes) - [ ] 📝 Documentation update - [ ] 🎨 UI/UX improvement - [ ] 🔒 Security enhancement - [ ] ⚡ Performance improvement ## Areas Affected Please check all that apply: - [ ] Email Integration (Gmail, IMAP, etc.) - [ ] User Interface/Experience - [ ] Authentication/Authorization - [ ] Data Storage/Management - [ ] API Endpoints - [ ] Documentation - [ ] Testing Infrastructure - [ ] Development Workflow - [ ] Deployment/Infrastructure ## Testing Done Describe the tests you've done: - [ ] Unit tests added/updated - [ ] Integration tests added/updated - [ ] Manual testing performed - [ ] Cross-browser testing (if UI changes) - [ ] Mobile responsiveness verified (if UI changes) ## Security Considerations For changes involving data or authentication: - [ ] No sensitive data is exposed - [ ] Authentication checks are in place - [ ] Input validation is implemented - [ ] Rate limiting is considered (if applicable) ## Checklist - [ ] I have read the [CONTRIBUTING](https://github.com/Mail-0/Zero/blob/staging/.github/CONTRIBUTING.md) document - [ ] My code follows the project's style guidelines - [ ] I have performed a self-review of my code - [ ] I have commented my code, particularly in complex areas - [ ] I have updated the documentation - [ ] My changes generate no new warnings - [ ] I have added tests that prove my fix/feature works - [ ] All tests pass locally - [ ] Any dependent changes are merged and published ## Additional Notes Add any other context about the pull request here. ## Screenshots/Recordings Add screenshots or recordings here if applicable. --- _By submitting this pull request, I confirm that my contribution is made under the terms of the project's license._ <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Made AutoRAG optional so it only runs when configured, and improved thread summary fallback to always return basic info if a summary is missing. - **Bug Fixes** - Thread summary now returns subject, sender, and date even if no summary is found. - AutoRAG is only used when enabled, with a proper fallback to raw search results. <!-- End of auto-generated description by cubic. --> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Introduced a new inbox search tool supporting natural language queries with configurable result limits. * Enabled conditional use of advanced search features based on environment settings. * **Improvements** * Clarified tool parameter descriptions. * Enhanced tool registration to accept dynamic header values. * **Refactor** * Improved internal handling of request headers and tool configuration. * **Chores** * Removed default fallback server URL in tool registration scripts. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent a34028c commit 108dc8d

File tree

4 files changed

+57
-21
lines changed

4 files changed

+57
-21
lines changed

apps/server/src/routes/agent/index.ts

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1371,21 +1371,29 @@ export class ZeroDriver extends Agent<ZeroEnv> {
13711371
}).then((r) => r.threads.map((t) => t.id)),
13721372
).pipe(Effect.catchAll(() => Effect.succeed([])));
13731373

1374+
const effects: Effect.Effect<string[]>[] = [rawEffect];
1375+
if (this.env.AUTORAG_ID) effects.unshift(ragEffect as Effect.Effect<string[]>);
1376+
13741377
// Run both in parallel and wait for results
1375-
const results = await Effect.runPromise(
1376-
Effect.all([ragEffect, rawEffect], { concurrency: 'unbounded' }),
1377-
);
1378+
const results = await Effect.runPromise(Effect.all(effects, { concurrency: 'unbounded' }));
1379+
if (this.env.AUTORAG_ID) {
1380+
const [ragIds, rawIds] = results;
13781381

1379-
const [ragIds, rawIds] = results;
1382+
// Return InboxRag results if found, otherwise fallback to raw
1383+
if (ragIds.length > 0) {
1384+
return {
1385+
threadIds: ragIds,
1386+
source: 'autorag' as const,
1387+
};
1388+
}
13801389

1381-
// Return InboxRag results if found, otherwise fallback to raw
1382-
if (ragIds.length > 0) {
13831390
return {
1384-
threadIds: ragIds,
1385-
source: 'autorag' as const,
1391+
threadIds: rawIds,
1392+
source: 'raw' as const,
1393+
nextPageToken: pageToken,
13861394
};
13871395
}
1388-
1396+
const [rawIds] = results;
13891397
return {
13901398
threadIds: rawIds,
13911399
source: 'raw' as const,

apps/server/src/routes/agent/tools.ts

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,9 @@ const getThreadSummary = (connectionId: string) =>
136136
const thread = await driver.getThread(id);
137137
if (response.length && response?.[0]?.metadata?.['summary'] && thread?.latest?.subject) {
138138
const result = response[0].metadata as { summary: string; connection: string };
139-
if (result.connection !== connectionId) return null;
139+
if (result.connection !== connectionId) {
140+
return null;
141+
}
140142
const shortResponse = await env.AI.run('@cf/facebook/bart-large-cnn', {
141143
input_text: result.summary,
142144
});
@@ -147,7 +149,11 @@ const getThreadSummary = (connectionId: string) =>
147149
date: thread.latest?.receivedOn,
148150
};
149151
}
150-
return null;
152+
return {
153+
subject: thread.latest?.subject,
154+
sender: thread.latest?.sender,
155+
date: thread.latest?.receivedOn,
156+
};
151157
},
152158
});
153159

@@ -448,8 +454,8 @@ export const webSearch = () =>
448454
},
449455
});
450456

451-
export const tools = async (connectionId: string) => {
452-
return {
457+
export const tools = async (connectionId: string, ragEffect: boolean = false) => {
458+
const _tools = {
453459
[Tools.GetThread]: getEmail(),
454460
[Tools.GetThreadSummary]: getThreadSummary(connectionId),
455461
[Tools.ComposeEmail]: composeEmailTool(connectionId),
@@ -464,6 +470,23 @@ export const tools = async (connectionId: string) => {
464470
[Tools.DeleteLabel]: deleteLabel(connectionId),
465471
[Tools.BuildGmailSearchQuery]: buildGmailSearchQuery(),
466472
[Tools.GetCurrentDate]: getCurrentDate(),
473+
[Tools.InboxRag]: tool({
474+
description:
475+
'Search the inbox for emails using natural language. Returns only an array of threadIds.',
476+
parameters: z.object({
477+
query: z.string().describe('The query to search the inbox for'),
478+
maxResults: z.number().describe('The maximum number of results to return').default(10),
479+
}),
480+
execute: async ({ query, maxResults }) => {
481+
const agent = await getZeroAgent(connectionId);
482+
const res = await agent.searchThreads({ query, maxResults });
483+
return res.threadIds;
484+
},
485+
}),
486+
};
487+
if (ragEffect) return _tools;
488+
return {
489+
..._tools,
467490
[Tools.InboxRag]: tool({
468491
description:
469492
'Search the inbox for emails using natural language. Returns only an array of threadIds.',

apps/server/src/routes/ai.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { systemPrompt } from '../services/call-service/system-prompt';
22
import { openai } from '@ai-sdk/openai';
33
import { tools } from './agent/tools';
44
import { generateText } from 'ai';
5+
import { Tools } from '../types';
56
import { createDb } from '../db';
67
import { env } from '../env';
78
import { Hono } from 'hono';
@@ -28,11 +29,12 @@ aiRouter.post('/do/:action', async (c) => {
2829
// if (env.DISABLE_CALLS) return c.json({ success: false, error: 'Not implemented' }, 400);
2930
if (env.VOICE_SECRET !== c.req.header('X-Voice-Secret'))
3031
return c.json({ success: false, error: 'Unauthorized' }, 401);
31-
if (!c.req.header('X-Caller')) return c.json({ success: false, error: 'Unauthorized' }, 401);
32+
const caller = c.req.header('X-Caller');
33+
if (!caller) return c.json({ success: false, error: 'Unauthorized' }, 401);
3234
const { db, conn } = createDb(env.HYPERDRIVE.connectionString);
3335
const user = await db.query.user.findFirst({
3436
where: (user, { eq, and }) =>
35-
and(eq(user.phoneNumber, c.req.header('X-Caller')!), eq(user.phoneNumberVerified, true)),
37+
and(eq(user.phoneNumber, caller), eq(user.phoneNumberVerified, true)),
3638
});
3739
if (!user) return c.json({ success: false, error: 'Unauthorized' }, 401);
3840

@@ -44,12 +46,12 @@ aiRouter.post('/do/:action', async (c) => {
4446
if (!connection) return c.json({ success: false, error: 'Unauthorized' }, 401);
4547

4648
try {
47-
const action = c.req.param('action');
49+
const action = c.req.param('action') as keyof ToolsReturnType;
4850
const body = await c.req.json();
4951
console.log('[DEBUG] action', action, body);
5052

5153
// Get all tools for this connection
52-
const toolset: ToolsReturnType = await tools(connection.id);
54+
const toolset: ToolsReturnType = await tools(connection.id, action === Tools.InboxRag);
5355
const tool = toolset[action as keyof ToolsReturnType];
5456

5557
if (!tool) {

scripts/register-elevenlabs-tools.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ export const toolDefinitions: ToolDefinition[] = [
4040
name: Tools.GetThreadSummary,
4141
description: 'Get the summary of a specific email thread',
4242
parameters: z.object({
43-
id: z.string().describe('The ID of the email thread to get the summary of'),
43+
id: z.string().describe('The threadId of the email thread to get the summary of'),
4444
}),
4545
},
4646
{
@@ -189,6 +189,7 @@ export const toolDefinitions: ToolDefinition[] = [
189189
'Search the inbox for emails using natural language. Returns only an array of threadIds.',
190190
parameters: z.object({
191191
query: z.string().describe('The query to search the inbox for'),
192+
maxResults: z.number().describe('The maximum number of results to return').default(10),
192193
}),
193194
},
194195
];
@@ -206,7 +207,7 @@ interface ElevenLabsToolRequest {
206207
properties: any;
207208
required?: string[];
208209
};
209-
request_headers: Record<string, string>;
210+
request_headers: Record<string, string | { variable_name: string }>;
210211
};
211212
};
212213
}
@@ -477,7 +478,7 @@ async function updateAgent(apiKey: string, agentId: string, toolIds: string[]):
477478

478479
async function main() {
479480
const apiKey = process.env.ELEVENLABS_API_KEY;
480-
const serverUrl = process.env.SERVER_URL || 'https://staging.0.email';
481+
const serverUrl = process.env.SERVER_URL;
481482
const voiceSecret = process.env.VOICE_SECRET;
482483
const agentId = process.env.ELEVENLABS_AGENT_ID;
483484

@@ -557,7 +558,9 @@ async function main() {
557558
request_headers: {
558559
'Content-Type': 'application/json',
559560
'X-Voice-Secret': voiceSecret,
560-
'X-Caller': 'system__caller_id',
561+
'X-Caller': {
562+
variable_name: 'system__caller_id',
563+
},
561564
},
562565
},
563566
},

0 commit comments

Comments
 (0)