-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathdata-copilot.ts
More file actions
1255 lines (1148 loc) · 39.2 KB
/
data-copilot.ts
File metadata and controls
1255 lines (1148 loc) · 39.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 The Linux Foundation and each contributor.
// SPDX-License-Identifier: MIT
/* eslint-disable @typescript-eslint/no-explicit-any */
import { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';
import { experimental_createMCPClient as createMCPClient, type LanguageModelV1 } from 'ai';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import type { Pool } from 'pg';
import type { ChatResponse, IChatResponseDb } from '../../server/repo/chat.repo';
import { ChatRepository } from '../../server/repo/chat.repo';
import { TextToSqlAgent, PipeAgent, RouterAgent, AuditorAgent } from './agents';
import { executePipeInstructions, executeTextToSqlInstructions } from './instructions';
import type {
AgentResponseCompleteParams,
AuditorAgentInput,
ChatMessage,
DataCopilotQueryInput,
PipeAgentInput,
PipeAgentStreamInput,
PipeInstructions,
RouterAgentInput,
RouterOutput,
TextToSqlAgentInput,
TextToSqlAgentStreamInput,
} from './types';
import { RouterDecisionAction, StreamDataStatus, StreamDataType } from './enums';
import { generateDataSummary } from './utils/data-summary';
const bedrock = createAmazonBedrock({
accessKeyId: process.env.NUXT_AWS_BEDROCK_ACCESS_KEY_ID,
secretAccessKey: process.env.NUXT_AWS_BEDROCK_SECRET_ACCESS_KEY,
region: process.env.NUXT_AWS_BEDROCK_REGION,
});
type MCPClient = Awaited<ReturnType<typeof createMCPClient>>;
type TbTools = Record<
string,
{
description?: string;
meta?: { description?: string };
inputSchema?: unknown;
parameters?: unknown;
schema?: unknown;
[key: string]: unknown; // Allow additional properties
}
>;
export class DataCopilot {
/** MCP client for communicating with Tinybird services */
private mcpClient!: MCPClient;
/** Available Tinybird tools loaded from MCP server */
private tbTools: TbTools = {};
/** Human-readable overview of tools for router agent decision making */
private toolsOverview: string = '';
/** Tinybird MCP server URL */
private tbMcpUrl: string = '';
/** Amazon Bedrock language model instance */
private model: LanguageModelV1;
/** Bedrock model identifier */
private readonly BEDROCK_MODEL_ID = 'us.anthropic.claude-opus-4-6-v1';
/** Maximum number of auditor retry attempts */
private readonly MAX_AUDITOR_RETRIES = 1;
/** Maximum number of SQL execution retry attempts */
private readonly MAX_SQL_RETRIES = 2;
constructor() {
this.model = bedrock(this.BEDROCK_MODEL_ID);
this.tbMcpUrl = `https://mcp.tinybird.co?token=${process.env.NUXT_INSIGHTS_DATA_COPILOT_TINYBIRD_TOKEN}&host=${process.env.NUXT_TINYBIRD_BASE_URL}`;
}
/**
* Initialize MCP client connection and load Tinybird tools
*/
async initialize(): Promise<void> {
const url = new URL(this.tbMcpUrl);
this.mcpClient = await createMCPClient({
transport: new StreamableHTTPClientTransport(url, {
sessionId: `session_${Date.now()}`,
}),
});
this.tbTools = await this.mcpClient.tools({});
this.buildToolsOverview();
}
/**
* Build human-readable overview of available tools for the router agent
*/
private buildToolsOverview(): void {
const excludedFromOverview = new Set([
'explore_data',
'text_to_sql',
'list_endpoints',
'list_service_datasources',
]);
this.toolsOverview = Object.entries(this.tbTools)
.filter(([name]) => !excludedFromOverview.has(name))
.map(([name, def]: [string, TbTools[string]]) => {
try {
const description = def?.description || def?.meta?.description || '';
const inputSchema = def?.inputSchema || def?.parameters || def?.schema || undefined;
const params = inputSchema ? JSON.stringify(inputSchema, null, 2) : undefined;
return [`- ${name}: ${description}`, params ? ` params: ${params}` : undefined]
.filter(Boolean)
.join('\n');
} catch {
return `- ${name}`;
}
})
.join('\n');
}
/**
* Save chat response to database
*/
private async saveChatResponse(
response: ChatResponse,
insightsDbPool: Pool,
userEmail: string,
): Promise<string> {
const chatRepo = new ChatRepository(insightsDbPool);
return await chatRepo.saveChatResponse(response, userEmail);
}
/**
* Create initial chat response early to get ID for tracking agent steps
*/
private async createInitialChatResponse(
userPrompt: string,
insightsDbPool: Pool,
userEmail: string,
conversationId?: string,
): Promise<string> {
const chatRepo = new ChatRepository(insightsDbPool);
return await chatRepo.createInitialChatResponse(userPrompt, userEmail, conversationId);
}
/**
* Update chat response with final data
*/
private async updateChatResponse(
chatResponseId: string,
response: Omit<ChatResponse, 'userPrompt'>,
insightsDbPool: Pool,
): Promise<void> {
const chatRepo = new ChatRepository(insightsDbPool);
return await chatRepo.updateChatResponse(chatResponseId, response);
}
/**
* Track an agent execution step
*/
private async trackAgentStep(
chatResponseId: string,
agent: 'ROUTER' | 'PIPE' | 'TEXT_TO_SQL' | 'AUDITOR' | 'CHART' | 'EXECUTE_INSTRUCTIONS',
response: any | undefined,
responseTimeSeconds: number,
insightsDbPool: Pool,
errorMessage?: string,
instructions?: string,
): Promise<void> {
const chatRepo = new ChatRepository(insightsDbPool);
await chatRepo.saveAgentStep({
chatResponseId,
agent,
model: agent === 'EXECUTE_INSTRUCTIONS' ? undefined : this.BEDROCK_MODEL_ID,
response,
inputTokens: response?.usage?.promptTokens || 0,
outputTokens: response?.usage?.completionTokens || 0,
responseTimeSeconds,
instructions,
errorMessage,
});
}
/**
* Executes the router agent to analyze user queries and determine the optimal processing strategy.
* The router acts as the decision-making component that routes requests to either SQL generation
* or data pipeline processing based on query complexity and intent.
*
* @param messages - User conversation history providing context for the query
* @param date - Current date string for time-based query filtering
* @param projectName - Project identifier for data scoping and access control
* @param pipe - Main data endpoint or pipeline identifier
* @param parametersString - Additional query parameters serialized as JSON
* @param segmentId - Data segment filter for multi-tenant data access
* @returns Router decision with next action, reasoning, and selected tools
*/
private async runRouterAgent({
messages,
date,
projectName,
pipe,
parametersString,
segmentId,
previousWasClarification,
}: Omit<RouterAgentInput, 'toolsOverview' | 'model' | 'tools'>) {
const agent = new RouterAgent();
return agent.execute({
model: this.model,
messages,
tools: this.tbTools,
toolsOverview: this.toolsOverview,
date,
projectName,
pipe,
parametersString,
segmentId,
previousWasClarification,
});
}
/**
* Executes the text-to-SQL agent to convert natural language questions into executable SQL queries.
* This agent understands database schemas, applies proper filtering, and generates optimized queries
* for direct data access when users need raw data rather than processed analytics.
*
* @param messages - Original conversation context for understanding query intent
* @param date - Current date for constructing time-based WHERE conditions
* @param projectName - Project context for database table scoping
* @param pipe - Data source identifier for table selection
* @param parametersString - Additional query parameters for filtering
* @param segmentId - Segment identifier for multi-tenant data filtering
* @param reformulatedQuestion - Clarified question from router agent for better SQL generation
* @returns SQL query string with explanation and token usage metrics
*/
private async runTextToSqlAgent({
messages,
date,
projectName,
pipe,
parametersString,
segmentId,
reformulatedQuestion,
}: TextToSqlAgentInput) {
const followUpTools = this.tbTools;
delete followUpTools['execute_query'];
const agent = new TextToSqlAgent();
return agent.execute({
model: this.model,
messages,
tools: followUpTools,
date,
projectName,
pipe,
parametersString,
segmentId,
reformulatedQuestion,
});
}
/**
* Executes the pipe agent to generate tinybird pipeline instructions.
* This agent designs multi-step workflows that use one or more tinybird pipes.
* Each pipe is used to answer specific parts of the user's analytical question.
*
* @param messages - Original conversation context for understanding analytical requirements
* @param date - Current date for time-based data filtering in pipeline steps
* @param projectName - Project identifier for data access and pipeline scoping
* @param pipe - Primary pipeline identifier for data source selection
* @param parametersString - Additional processing parameters for pipeline configuration
* @param segmentId - Segment filter for multi-tenant pipeline execution
* @param reformulatedQuestion - Refined analytical question from router agent
* @param toolNames - Selected Tinybird tools for pipeline construction (e.g., aggregation, transformation tools)
* @returns Pipeline instructions with processing steps, column definitions, and explanation
*/
private async runPipeAgent({
messages,
date,
projectName,
pipe,
parametersString,
segmentId,
reformulatedQuestion,
toolNames,
}: Omit<PipeAgentInput, 'model' | 'tools'>) {
const followUpTools: Record<string, unknown> = {};
for (const toolName of toolNames) {
if (this.tbTools[toolName]) {
followUpTools[toolName] = this.tbTools[toolName];
}
}
const agent = new PipeAgent();
return agent.execute({
model: this.model,
messages,
tools: followUpTools,
date,
projectName,
pipe,
parametersString,
segmentId,
reformulatedQuestion,
toolNames,
});
}
/**
* Executes the auditor agent to validate whether retrieved data actually answers the user's question.
* Uses statistical analysis of data structure and content without requiring full dataset transmission.
*
* @param messages - Conversation history for context
* @param originalQuestion - The user's original question
* @param reformulatedQuestion - Router's enhanced interpretation of the question
* @param data - Retrieved data to validate
* @param attemptNumber - Current retry attempt (0 for first attempt)
* @param previousFeedback - Feedback from previous auditor run if this is a retry
* @returns Validation result with summary or feedback for router
*/
private async runAuditorAgent({
messages,
originalQuestion,
reformulatedQuestion,
data,
attemptNumber,
previousFeedback,
}: Omit<AuditorAgentInput, 'model' | 'dataSummary'> & { data: any[] }) {
const dataSummary = generateDataSummary(data);
const agent = new AuditorAgent();
return agent.execute({
model: this.model,
messages,
originalQuestion,
reformulatedQuestion,
dataSummary,
attemptNumber,
previousFeedback,
});
}
/**
* Run execution and validation loop with auditor feedback
* Handles router execution, query/pipes execution, validation, and retries
*
* @returns Router action and results after validation
*/
private async runExecutionWithAuditorLoop({
messages,
currentQuestion,
date,
projectName,
pipe,
parametersString,
segmentId,
previousWasClarification,
dataStream,
responseData,
chatResponseId,
insightsDbPool,
}: {
messages: ChatMessage[];
currentQuestion: string;
date: string;
projectName: string;
pipe: string;
parametersString: string;
segmentId: string;
previousWasClarification: boolean;
dataStream: any;
responseData: ChatResponse;
chatResponseId: string;
insightsDbPool: Pool;
}): Promise<{
action: RouterDecisionAction;
routerOutput: RouterOutput;
sqlQuery?: string;
pipeInstructions?: PipeInstructions;
}> {
let attemptNumber = 0;
let previousFeedback: string | undefined = undefined;
let currentMessages = messages;
let routerOutput: RouterOutput;
let sqlQuery: string | undefined = undefined;
let pipeInstructions: PipeInstructions | undefined = undefined;
let explanation: string | undefined = undefined;
while (attemptNumber <= this.MAX_AUDITOR_RETRIES) {
// Run router agent - only stream status on first attempt
if (attemptNumber === 0) {
dataStream.writeData({
type: StreamDataType.ROUTER_STATUS,
status: StreamDataStatus.ANALYZING,
});
}
const routerStartTime = Date.now();
try {
routerOutput = await this.runRouterAgent({
messages: currentMessages,
date,
projectName,
pipe,
parametersString,
segmentId,
previousWasClarification: attemptNumber === 0 ? previousWasClarification : false,
});
const routerResponseTime = (Date.now() - routerStartTime) / 1000;
// Track router agent step
await this.trackAgentStep(
chatResponseId,
'ROUTER',
routerOutput,
routerResponseTime,
insightsDbPool,
);
} catch (error) {
const routerResponseTime = (Date.now() - routerStartTime) / 1000;
await this.trackAgentStep(
chatResponseId,
'ROUTER',
undefined,
routerResponseTime,
insightsDbPool,
error instanceof Error ? error.message : String(error),
);
throw error;
}
// Accumulate router token usage
if (routerOutput.usage) {
responseData.inputTokens += routerOutput.usage.promptTokens || 0;
responseData.outputTokens += routerOutput.usage.completionTokens || 0;
}
// Handle STOP and ASK_CLARIFICATION - no auditor needed
if (
routerOutput.next_action === RouterDecisionAction.STOP ||
routerOutput.next_action === RouterDecisionAction.ASK_CLARIFICATION
) {
return { action: routerOutput.next_action, routerOutput };
}
// Router decided on CREATE_QUERY or PIPES - only stream complete status on first attempt
if (attemptNumber === 0) {
dataStream.writeData({
type: StreamDataType.ROUTER_STATUS,
status: StreamDataStatus.COMPLETE,
reasoning: routerOutput.reasoning,
reformulatedQuestion: routerOutput.reformulated_question,
});
}
let data: any[] = [];
// Execute based on router decision
if (routerOutput.next_action === RouterDecisionAction.CREATE_QUERY) {
const result = await this.handleCreateQueryAction({
messages: currentMessages,
date,
projectName,
pipe,
parametersString,
segmentId,
reformulatedQuestion: routerOutput.reformulated_question,
dataStream,
chatResponseId,
insightsDbPool,
});
sqlQuery = result.sqlQuery;
explanation = result.explanation;
data = result.data;
} else if (routerOutput.next_action === RouterDecisionAction.PIPES) {
const result = await this.handlePipesAction({
messages: currentMessages,
date,
projectName,
pipe,
parametersString,
segmentId,
reformulatedQuestion: routerOutput.reformulated_question,
toolNames: routerOutput.tools,
dataStream,
responseData,
routerOutput,
chatResponseId,
insightsDbPool,
});
pipeInstructions = result.pipeInstructions;
explanation = result.explanation;
data = result.data;
}
// Stream auditor status
dataStream.writeData({
type: StreamDataType.AUDITOR_STATUS,
status: attemptNumber === 0 ? StreamDataStatus.VALIDATING : StreamDataStatus.RETRYING,
attempt: attemptNumber + 1,
maxAttempts: this.MAX_AUDITOR_RETRIES + 1,
});
// Run auditor validation
const auditorStartTime = Date.now();
let auditorResult;
try {
auditorResult = await this.runAuditorAgent({
messages: currentMessages,
originalQuestion: currentQuestion,
reformulatedQuestion: routerOutput.reformulated_question,
data,
attemptNumber,
previousFeedback,
});
const auditorResponseTime = (Date.now() - auditorStartTime) / 1000;
// Track auditor agent step
await this.trackAgentStep(
chatResponseId,
'AUDITOR',
auditorResult,
auditorResponseTime,
insightsDbPool,
undefined, // Feedback is not an error, it's part of the response
);
} catch (error) {
const auditorResponseTime = (Date.now() - auditorStartTime) / 1000;
await this.trackAgentStep(
chatResponseId,
'AUDITOR',
undefined,
auditorResponseTime,
insightsDbPool,
error instanceof Error ? error.message : String(error),
);
throw error;
}
// Accumulate auditor token usage
if (auditorResult.usage) {
responseData.inputTokens += auditorResult.usage.promptTokens || 0;
responseData.outputTokens += auditorResult.usage.completionTokens || 0;
}
if (auditorResult.is_valid) {
// Data is valid, stream summary and data
dataStream.writeData({
type: StreamDataType.AUDITOR_STATUS,
status: StreamDataStatus.VALIDATED,
summary: auditorResult.summary,
reasoning: auditorResult.reasoning,
});
// Stream data after auditor approval
if (routerOutput.next_action === RouterDecisionAction.CREATE_QUERY) {
dataStream.writeData({
type: StreamDataType.SQL_RESULT,
instructions: sqlQuery,
explanation,
data,
chatResponseId,
});
} else if (routerOutput.next_action === RouterDecisionAction.PIPES) {
dataStream.writeData({
type: StreamDataType.PIPE_RESULT,
instructions: pipeInstructions,
explanation,
data,
chatResponseId,
});
}
return { action: routerOutput.next_action, routerOutput, sqlQuery, pipeInstructions };
}
// Data is invalid
if (attemptNumber >= this.MAX_AUDITOR_RETRIES) {
// Max retries reached, send final status and stream data anyway
dataStream.writeData({
type: StreamDataType.AUDITOR_STATUS,
status: StreamDataStatus.MAX_RETRIES,
feedback: auditorResult.feedback_to_router,
reasoning: auditorResult.reasoning,
});
// Stream data even though validation failed (max retries reached)
if (routerOutput.next_action === RouterDecisionAction.CREATE_QUERY) {
dataStream.writeData({
type: StreamDataType.SQL_RESULT,
instructions: sqlQuery,
explanation,
data,
chatResponseId,
});
} else if (routerOutput.next_action === RouterDecisionAction.PIPES) {
dataStream.writeData({
type: StreamDataType.PIPE_RESULT,
instructions: pipeInstructions,
explanation,
data,
chatResponseId,
});
}
return { action: routerOutput.next_action, routerOutput, sqlQuery, pipeInstructions };
}
// Prepare for retry - add feedback to messages and loop
previousFeedback = auditorResult.feedback_to_router;
attemptNumber++;
dataStream.writeData({
type: StreamDataType.AUDITOR_STATUS,
status: StreamDataStatus.RETRYING,
feedback: previousFeedback,
attempt: attemptNumber + 1,
});
// Add feedback to conversation context for next iteration
currentMessages = [
...currentMessages,
{
role: 'system',
content: `Previous attempt did not produce valid results. Auditor feedback: ${previousFeedback}. \n
Please adjust your approach based on this feedback.`,
},
];
}
// This should never be reached, but TypeScript needs it
throw new Error('Auditor loop completed without returning a result');
}
/**
* Send keepalive message to prevent Cloudflare timeout
*/
private sendKeepalive(dataStream: any, message: string): void {
dataStream.writeData({
type: 'keepalive',
message,
timestamp: new Date().toISOString(),
});
}
/**
* Send progress update message
*/
private sendProgress(dataStream: any, status: string, message: string): void {
dataStream.writeData({
type: StreamDataType.ROUTER_STATUS,
status: 'progress',
message,
timestamp: new Date().toISOString(),
});
}
/**
* Build messages array from conversation history
* Handles clarification merging if the previous response was ASK_CLARIFICATION
*/
private async buildMessagesFromConversation(
currentQuestion: string,
conversationId: string | undefined,
insightsDbPool: Pool,
): Promise<{ messages: ChatMessage[]; previousWasClarification: boolean }> {
const chatRepo = new ChatRepository(insightsDbPool);
if (!conversationId) {
// No conversation history, just return the current question
return {
messages: [{ role: 'user', content: currentQuestion }],
previousWasClarification: false,
};
}
const previousChatResponses = await chatRepo.getChatResponsesByConversation(conversationId);
if (previousChatResponses.length === 0) {
// No previous responses in this conversation
return {
messages: [{ role: 'user', content: currentQuestion }],
previousWasClarification: false,
};
}
// Check if the latest response was ASK_CLARIFICATION
const latestResponse = previousChatResponses[
previousChatResponses.length - 1
] as IChatResponseDb;
const previousWasClarification =
latestResponse.router_response === RouterDecisionAction.ASK_CLARIFICATION;
if (previousWasClarification) {
// Merge the clarification: combine the ambiguous question with the clarification answer
const ambiguousQuestion = latestResponse.user_prompt;
const mergedQuestion = `Original question: ${ambiguousQuestion}\n\nClarification provided: ${currentQuestion}`;
// Build messages: [older history before clarification] + [merged question]
const messages = previousChatResponses.slice(0, -1).map((response) => ({
role: 'user' as const,
content: response.user_prompt,
}));
// Add the merged question as the current message
messages.push({
role: 'user',
content: mergedQuestion,
});
return { messages, previousWasClarification: true };
}
// Normal case: build messages from all previous responses + current question
const messages = previousChatResponses.map((response) => ({
role: 'user' as const,
content: response.user_prompt,
}));
// Add the current question
messages.push({
role: 'user',
content: currentQuestion,
});
return { messages, previousWasClarification: false };
}
/**
* Main streaming handler that orchestrates the entire AI agent workflow
*/
async streamingAgentRequestHandler({
currentQuestion,
segmentId,
projectName,
pipe,
parameters,
conversationId,
insightsDbPool,
userEmail,
dataStream,
}: DataCopilotQueryInput): Promise<void> {
const parametersString = JSON.stringify(parameters || {});
const date = new Date().toISOString().slice(0, 10);
// Build messages from conversation history
const { messages, previousWasClarification } = await this.buildMessagesFromConversation(
currentQuestion,
conversationId,
insightsDbPool,
);
// Create initial chat response early to get ID for tracking agent steps
const chatResponseId = await this.createInitialChatResponse(
currentQuestion,
insightsDbPool,
userEmail,
conversationId,
);
// Stream the chat response ID immediately
dataStream.writeData({
type: StreamDataType.CHAT_RESPONSE_ID,
id: chatResponseId,
conversationId: conversationId || '',
});
const responseData: ChatResponse = {
userPrompt: currentQuestion,
inputTokens: 0,
outputTokens: 0,
model: this.BEDROCK_MODEL_ID,
conversationId: conversationId || '',
routerResponse: RouterDecisionAction.STOP,
routerReason: '',
pipeInstructions: undefined as PipeInstructions | undefined,
sqlQuery: undefined as string | undefined,
};
try {
// Run execution with auditor loop (handles router, execution, validation, retries)
const { action, routerOutput, sqlQuery, pipeInstructions } =
await this.runExecutionWithAuditorLoop({
messages,
currentQuestion,
date,
projectName: projectName as string,
pipe,
parametersString,
segmentId: segmentId as string,
previousWasClarification,
dataStream,
responseData,
chatResponseId,
insightsDbPool,
});
// Handle STOP and ASK_CLARIFICATION actions
if (action === RouterDecisionAction.STOP) {
await this.handleStopAction(
chatResponseId,
routerOutput,
responseData,
dataStream,
insightsDbPool,
conversationId,
);
return;
}
if (action === RouterDecisionAction.ASK_CLARIFICATION) {
await this.handleAskClarificationAction(
chatResponseId,
routerOutput,
responseData,
dataStream,
insightsDbPool,
conversationId,
);
return;
}
// Handle completed execution (CREATE_QUERY or PIPES)
await this.handleResponseComplete({
chatResponseId,
responseData,
routerOutput,
pipeInstructions,
sqlQuery,
conversationId,
insightsDbPool,
dataStream,
});
} catch (error) {
dataStream.writeData({
type: 'router-status',
status: 'error',
error: error instanceof Error ? error.message : 'An error occurred',
});
throw error;
}
}
/**
* Handle router 'stop' action - send final response without further processing
*/
private async handleStopAction(
chatResponseId: string,
routerOutput: RouterOutput,
responseData: ChatResponse,
dataStream: any,
insightsDbPool: Pool,
conversationId?: string,
): Promise<void> {
dataStream.writeData({
type: StreamDataType.ROUTER_STATUS,
status: StreamDataStatus.COMPLETE,
reasoning: routerOutput.reasoning,
});
await this.updateChatResponse(
chatResponseId,
{
inputTokens: responseData.inputTokens,
outputTokens: responseData.outputTokens,
routerResponse: RouterDecisionAction.STOP,
routerReason: routerOutput.reasoning,
pipeInstructions: undefined,
sqlQuery: undefined,
model: this.BEDROCK_MODEL_ID,
conversationId: conversationId,
},
insightsDbPool,
);
}
/**
* Handle router 'ask_clarification' action - ask user for clarification
*/
private async handleAskClarificationAction(
chatResponseId: string,
routerOutput: RouterOutput,
responseData: ChatResponse,
dataStream: any,
insightsDbPool: Pool,
conversationId?: string,
): Promise<void> {
dataStream.writeData({
type: StreamDataType.ROUTER_STATUS,
status: StreamDataStatus.ASK_CLARIFICATION,
question: routerOutput.clarification_question,
reasoning: routerOutput.reasoning,
});
await this.updateChatResponse(
chatResponseId,
{
inputTokens: responseData.inputTokens,
outputTokens: responseData.outputTokens,
routerResponse: RouterDecisionAction.ASK_CLARIFICATION,
routerReason: routerOutput.reasoning,
clarificationQuestion: routerOutput.clarification_question || undefined,
pipeInstructions: undefined,
sqlQuery: undefined,
model: this.BEDROCK_MODEL_ID,
conversationId: conversationId,
},
insightsDbPool,
);
}
/**
* Handle router 'create_query' action - generate and execute SQL query with retry logic
*/
private async handleCreateQueryAction({
messages,
date,
projectName,
pipe,
parametersString,
segmentId,
reformulatedQuestion,
dataStream,
chatResponseId,
insightsDbPool,
}: TextToSqlAgentStreamInput & {
chatResponseId: string;
insightsDbPool: Pool;
}): Promise<{ sqlQuery: string; explanation: string; data: any[] }> {
let attemptNumber = 0;
let errorContext: import('./types').SqlErrorContext | undefined = undefined;
let lastGeneratedQuery = '';
// Set up keepalive interval during long operation
const keepaliveInterval = setInterval(() => {
this.sendKeepalive(dataStream, 'Processing SQL query generation...');
}, 15000); // Send keepalive every 15 seconds
try {
while (attemptNumber <= this.MAX_SQL_RETRIES) {
// Send status update
if (attemptNumber === 0) {
this.sendProgress(dataStream, 'progress', 'Analyzing database schema...');
dataStream.writeData({
type: StreamDataType.SQL_STATUS,
status: StreamDataStatus.EXECUTING,
attempt: attemptNumber + 1,
maxAttempts: this.MAX_SQL_RETRIES + 1,
});
} else {
dataStream.writeData({
type: StreamDataType.SQL_STATUS,
status: StreamDataStatus.RETRYING,
attempt: attemptNumber + 1,
maxAttempts: this.MAX_SQL_RETRIES + 1,
error: errorContext?.errorMessage,
});
}
try {
// Generate SQL query
const sqlStartTime = Date.now();
let textToSqlOutput;
try {
textToSqlOutput = await this.runTextToSqlAgent({
messages,
date,
projectName,
pipe,
parametersString,
segmentId,
reformulatedQuestion,
errorContext,
});
const sqlResponseTime = (Date.now() - sqlStartTime) / 1000;
lastGeneratedQuery = textToSqlOutput.instructions;
this.sendProgress(dataStream, 'progress', `SQL query generated! Executing...`);
// Track successful Text-to-SQL agent execution
await this.trackAgentStep(
chatResponseId,
'TEXT_TO_SQL',
textToSqlOutput,
sqlResponseTime,
insightsDbPool,
);
} catch (agentError: any) {
// Text-to-SQL agent itself failed
const sqlResponseTime = (Date.now() - sqlStartTime) / 1000;
await this.trackAgentStep(
chatResponseId,
'TEXT_TO_SQL',
undefined,
sqlResponseTime,
insightsDbPool,
agentError instanceof Error ? agentError.message : String(agentError),
);
throw agentError;
}