-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathchart.ts
More file actions
144 lines (125 loc) · 4.44 KB
/
chart.ts
File metadata and controls
144 lines (125 loc) · 4.44 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
// Copyright (c) 2025 The Linux Foundation and each contributor.
// SPDX-License-Identifier: MIT
import { Pool } from 'pg';
import { generateChartConfig, modifyChartConfig } from '../../../lib/chat/chart/generator';
import { ChatRepository } from '../../repo/chat.repo';
import { Result, Config, DataMapping } from '../../../lib/chat/chart/types';
import { getBucketIdForProject } from '../../data/tinybird/bucket-cache';
import { fetchFromTinybird } from '../../data/tinybird/tinybird';
import { PipeInstructions } from '~~/lib/chat/types';
export const maxDuration = 30;
// Helper function to get router reasoning from conversation
async function getRouterReasoningFromConversation(
pool: Pool,
conversationId?: string,
): Promise<string | undefined> {
if (!conversationId) return undefined;
try {
const chatRepo = new ChatRepository(pool);
const latestResponse = await chatRepo.getLatestChatResponseByConversation(conversationId);
return latestResponse?.routerReason || undefined;
} catch (error) {
console.error('Error fetching router reasoning from conversation:', error);
return undefined;
}
}
interface IChartRequestBody {
results?: Result[];
userQuery?: string;
currentConfig?: Config;
instructions?: string;
pipeInstructions?: PipeInstructions;
conversationId?: string;
}
interface ChartConfigResponse {
success: boolean;
isModification: boolean;
config?: Config | null;
dataMapping?: DataMapping[] | null;
isMetric?: boolean;
}
export default defineEventHandler(async (event): Promise<ChartConfigResponse | Error> => {
try {
const { results, userQuery, currentConfig, instructions, pipeInstructions, conversationId } =
await readBody<IChartRequestBody>(event);
// Get router reasoning from conversation
const routerReasoning = await getRouterReasoningFromConversation(
event.context.insightsDbPool as Pool,
conversationId,
);
// If pipe instructions are provided, execute them first to get results
if (pipeInstructions && !results) {
const { executePipeInstructions } = await import('../../../lib/chat/instructions');
try {
const project = pipeInstructions.pipes[0]?.inputs?.project as string | undefined;
const bucketId = project ? await getBucketIdForProject(project, fetchFromTinybird) : null;
const executedResults = await executePipeInstructions(pipeInstructions, bucketId);
if (!userQuery) {
return createError({
statusCode: 400,
statusMessage: 'User query is required for chart generation',
});
}
const chartGeneration = await generateChartConfig(
executedResults as Result[],
userQuery,
routerReasoning,
);
return {
success: true,
isMetric: chartGeneration.isMetric,
config: chartGeneration.config,
dataMapping: chartGeneration.dataMapping,
isModification: false,
};
} catch (pipeError) {
console.error('Pipe execution error:', pipeError);
return createError({
statusCode: 500,
statusMessage: 'Failed to execute pipe instructions',
});
}
}
if (!results || !Array.isArray(results)) {
return createError({
statusCode: 400,
statusMessage: 'Results array or pipe instructions are required',
});
}
// If we have a current config and instructions, this is a modification request
if (currentConfig && instructions) {
const updatedConfig = await modifyChartConfig(
currentConfig as Config,
results as Result[],
instructions,
);
return {
success: true,
config: updatedConfig.config,
isModification: true,
};
}
// Otherwise, generate a new chart config
if (!userQuery) {
return createError({
statusCode: 400,
statusMessage: 'User query is required for chart generation',
});
}
const chartGeneration = await generateChartConfig(
results as Result[],
userQuery,
routerReasoning,
);
return {
success: true,
isMetric: chartGeneration.isMetric,
config: chartGeneration.config,
dataMapping: chartGeneration.dataMapping,
isModification: false,
};
} catch (error) {
console.error('Chart generation/modification error:', error);
return createError({ statusCode: 500, statusMessage: 'Failed to process chart request' });
}
});