-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
137 lines (110 loc) · 3.64 KB
/
main.ts
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
import { GoogleGenerativeAI } from "@google/generative-ai";
import { queryGoogleAnalyticsData, getQueryGoogleAnalyticsDataFunctionDeclaration } from './queryGoogleAnalyticsData';
import { config } from './config.js';
const API_KEY = 'API_KEY';
const PATH_TO_JSON_KEY = 'PATH_TO_JSON_KEY';
const PROJECT_ID = 'PROJECT_ID';
interface Message {
role: 'user' | 'model';
content: string;
}
interface Completion {
Content: string;
TokenUsage?: number;
}
interface ErrorCompletion {
Error: string;
}
type ConnectorResponse = {
Completions: Array<Completion | ErrorCompletion>;
ModelType?: string;
};
type Function = (...args: any[]) => Promise<any>;
interface AvailableFunctions {
[key: string]: Function;
}
const mapErrorToCompletion = (error: unknown): ErrorCompletion => {
const errorMessage = error instanceof Error ? error.message : JSON.stringify(error);
return {
Error: errorMessage,
};
};
async function main(
model: string,
prompts: string[],
properties: Record<string, unknown>,
settings: Record<string, unknown>,
): Promise<ConnectorResponse> {
try {
const { ...restProperties } = properties;
const genAI = new GoogleGenerativeAI(settings?.[API_KEY] as string);
const pathToJsonKey = settings?.[PATH_TO_JSON_KEY] as string;
const projectId = settings?.[PROJECT_ID] as string;
const geminiModel = genAI.getGenerativeModel({
model: model,
tools: [{
functionDeclarations: [getQueryGoogleAnalyticsDataFunctionDeclaration],
}],
...restProperties
});
const outputs: Array<Completion | ErrorCompletion> = [];
let chatHistory: Message[] = [];
let chat = geminiModel.startChat({
history: chatHistory.map((msg) => ({
role: msg.role,
parts: [{ text: msg.content }],
})),
});
for (const prompt of prompts) {
try {
chatHistory.push({ role: 'user', content: prompt });
const result = await chat.sendMessage(prompt);
const response = result.response;
const functionCalls = result.response.functionCalls();
console.log('Function calls:', functionCalls);
const call = functionCalls ? functionCalls[0] : undefined;
let text = '';
if (call) {
// Call the executable function named in the function call
// with the arguments specified in the function call and
// let it call the hypothetical API.
const availableFunctions: AvailableFunctions = {
queryGoogleAnalyticsData: queryGoogleAnalyticsData,
};
const functionToCall = availableFunctions[call.name];
const functionResponse = await functionToCall(
pathToJsonKey,
projectId,
...Object.values(call.args),
);
const result2 = await chat.sendMessage([{
functionResponse: {
name: call.name,
response: functionResponse[0]
}
}]);
const response2 = result2.response;
text = response2.text();
} else {
text = response.text();
}
// Count tokens
const { totalTokens } = await geminiModel.countTokens(prompt);
chatHistory.push({ role: 'model', content: text });
outputs.push({ Content: text, TokenUsage: totalTokens });
} catch (error) {
const completionWithError = mapErrorToCompletion(error);
outputs.push(completionWithError);
}
}
return {
Completions: outputs,
};
} catch (error) {
console.error('Error in main function:', error);
return {
Completions: [mapErrorToCompletion(error)],
};
}
}
export { main, config };