-
Notifications
You must be signed in to change notification settings - Fork 0
/
javascript-function-call-transformation.ts
148 lines (133 loc) · 6.29 KB
/
javascript-function-call-transformation.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
138
139
140
141
142
143
144
145
146
147
148
import OpenAIApi from 'openai';
import { FunctionAgentJsonResponse } from '@/types';
import BaseAgent from '@/agents/base-agent';
/**
* JavaScriptFunctionCallTransformationAgent Class
*
* This class serves as an interface between a JavaScript function definition and the OpenAI API.
* It takes in JavaScript function code as a string and outputs a JSON object adhering to the OpenAI Function Calling Schema.
* The class uses a pre-defined system message to set the context for the OpenAI model.
*
* Usage:
* const agent = new JavaScriptFunctionCallTransformationAgent(apiKey, model, systemMessage);
* const response: FunctionAgentJsonResponse = await agent.run('function add(a, b) { return a + b; }');
*
* @example
*
* const agent = new JavaScriptFunctionCallTransformationAgent('openai-api-key', 'gpt-4-0613');
* const response = await agent.run('function add(a, b) { return a + b; }');
*/
class JavaScriptFunctionCallTransformationAgent extends BaseAgent {
private systemMessage: string;
constructor(
openai_api_key: string,
model: string,
systemMessage: string = 'You are a JavaScript interpreter agent. You take in JavaScript function code. Your task is to take the function and output in the form of a JSON object matching the OpenAI Function Calling schema using only the interpreterFunction. Do not add any commentary or ask any questions. Strictly run the interpreterFunction and return the JSON object.'
) {
super(openai_api_key, model);
this.systemMessage = systemMessage;
}
async run(userMessage: string): Promise<FunctionAgentJsonResponse> {
if (!userMessage) {
throw new Error('Missing user message');
}
console.log('JavaScriptFunctionCallTransformationAgent invoked with function code and arguments:', userMessage, '\n');
const startTime = Date.now();
try {
const messages: OpenAIApi.Chat.ChatCompletionMessage[] = [
{
role: 'system',
content: this.systemMessage,
},
{
role: 'user',
content: userMessage,
},
];
const interpreterFunction: OpenAIApi.Chat.ChatCompletionCreateParams.Function = {
name: 'interpreterFunction',
description: 'Interprets JavaScript function and returns OpenAI Function Calling Schema.',
parameters: {
type: 'object',
properties: {
functionName: {
type: 'string',
description: 'The JavaScript function name to be called',
},
functionDescription: {
type: 'string',
description: 'The description of the JavaScript function',
},
functionArguments: {
type: 'array',
description: 'The JavaScript function arguments to be passed to the function',
items: {
type: 'object',
properties: {
name: {
type: 'string',
description: 'The name of the JavaScript function argument',
},
type: {
type: 'string',
description: 'The type of the JavaScript function argument',
},
description: {
type: 'string',
description: 'The description of the JavaScript function argument',
},
},
},
},
},
required: ['functionName', 'functionDescription', 'functionArguments'],
},
};
const response: OpenAIApi.Chat.ChatCompletion = await this.openai.chat.completions.create({
model: this.model,
messages,
functions: [interpreterFunction],
temperature: 0,
});
if (!response.choices[0].message?.function_call?.name || !response.choices[0].message?.function_call?.arguments) {
throw new Error(`No function call found in response: ${JSON.stringify(response)}`);
}
const args = JSON.parse(response.choices[0].message.function_call.arguments);
type FunctionArgument = {
name: string;
type: string;
description: string;
};
const json: OpenAIApi.Chat.ChatCompletionCreateParams.Function = {
name: args.functionName,
description: args.functionDescription,
parameters: {
type: 'object',
properties: args.functionArguments.reduce((acc: any, arg: FunctionArgument) => {
acc[arg.name] = {
type: arg.type,
description: arg.description,
};
return acc;
}, {}),
required: args.functionArguments.map((arg: FunctionArgument) => arg.name),
},
};
console.log('JavaScriptFunctionCallTransformationAgent successfully completed in ', Date.now() - startTime, 'ms\n');
return {
json,
success: true,
duration: Date.now() - startTime, // duration in ms
};
} catch (error) {
console.log('JavaScriptFunctionCallTransformationAgent failed in ', Date.now() - startTime, 'ms\n');
return {
json: {},
success: false,
error: JSON.stringify(error),
duration: Date.now() - startTime, // duration in ms
};
}
}
}
export default JavaScriptFunctionCallTransformationAgent;