-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpenAI.js
333 lines (293 loc) · 10.5 KB
/
OpenAI.js
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
import OpenAI from 'openai';
import axios from 'axios';
import * as cheerio from 'cheerio';
import dotenv from 'dotenv';
dotenv.config();
const client = new OpenAI({ baseURL: 'https://api.openai.com/v1', apiKey: process.env.O_API_KEY });
const MODEL = 'gpt-4o-mini';
const tools = [
{
type: "function",
function: {
name: "web_search",
description: "Search the internet to find up-to-date information on a given topic.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "The query to search for."
}
},
required: ["query"],
additionalProperties: false
}
}
},
{
type: "function",
function: {
name: "search_webpage",
description: "Returns a string with all the content of a webpage. Some websites block this, so try a few different websites.",
parameters: {
type: "object",
properties: {
url: {
type: "string",
description: "The URL of the site to search."
}
},
required: ["url"],
additionalProperties: false
}
}
}
];
async function webSearch(args, id) {
const query = args.query;
try {
const result = await performSearch(query);
const function_call_result_message = {
role: "tool",
content: result,
tool_call_id: id
};
return function_call_result_message;
} catch (error) {
const errorMessage = `Error while performing web search: ${error}`;
console.error(errorMessage);
const function_call_result_message = {
role: "tool",
content: JSON.stringify({
error: errorMessage
}),
tool_call_id: id
};
return function_call_result_message;
}
}
async function searchWebpage(args, id) {
const url = args.url;
try {
const result = await searchWebpageContent(url);
const function_call_result_message = {
role: "tool",
content: result,
tool_call_id: id
};
return function_call_result_message;
} catch (error) {
const errorMessage = `Error while searching the site: ${error}`;
console.error(errorMessage);
const function_call_result_message = {
role: "tool",
content: JSON.stringify({
error: errorMessage
}),
tool_call_id: id
};
return function_call_result_message;
}
}
async function searchWebpageContent(url) {
const TIMEOUT = 5000; // 5 seconds
const MIN_CONTENT_LENGTH = 500; // Minimum length for valid content
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Request timed out after 5 seconds')), TIMEOUT)
);
try {
const response = await Promise.race([fetch(url), timeoutPromise]);
if (!response.ok) {
throw new Error(`Failed to fetch URL: ${response.statusText}`);
}
const html = await response.text();
const $ = cheerio.load(html);
$('script, style').remove();
let bodyText = $('body').text();
bodyText = bodyText.replace(/<[^>]*>?/gm, ''); // remove HTML tags
bodyText = bodyText.replace(/\s{6,}/g, ' '); // replace sequences of 6 or more whitespace characters with 2 spaces
bodyText = bodyText.replace(/(\r?\n){6,}/g, '\n\n'); // replace sequences of 6 or more line breaks with 2 line breaks
const trimmedBodyText = bodyText.trim();
/*
if (trimmedBodyText.length < MIN_CONTENT_LENGTH) {
throw new Error('Content is too short; less than 500 characters');
}
*/
return trimmedBodyText;
} catch (error) {
throw new Error(error.message || 'Could not search content from webpage');
}
}
async function performSearch(query) {
const url = `https://search.neuranet-ai.com/search?query=${encodeURIComponent(query)}&limit=5`;
const response = await axios.get(url)
.catch(error => {
throw new Error(`Failed to perform the search request: ${error.message}`);
});
const entries = response.data;
const resultObject = entries.slice(0, 5).map((entry, index) => {
const title = entry.title;
const result = entry.snippet;
const url = entry.link;
return { [`result_${index + 1}`]: { title, result, url } };
});
const note = {
"Note": "These are only the search results overview. Please use the Scrape Webpage tool to search further into the links."
};
return JSON.stringify(resultObject.reduce((acc, curr) => Object.assign(acc, curr), note), null, 2);
}
/*
async function performSearch(query) {
const url = 'https://websearch.plugsugar.com/api/plugins/websearch';
const response = await axios.post(url, { query: query })
.catch(error => {
throw new Error(`Failed to perform the initial search request: ${error.message}`);
});
const rawText = response.data.result;
const entries = rawText.trim().split('\n\n').slice(0, 5);
const resultObject = await Promise.all(entries.map(async (entry, index) => {
const lines = entry.split('\n');
const title = lines.find(line => line.startsWith('Title:')).replace('Title: ', '');
const result = lines.find(line => line.startsWith('Result:')).replace('Result: ', '');
const url = lines.find(line => line.startsWith('URL:')).replace('URL: ', '');
return { [`result_${index + 1}`]: { title, result, url } };
}));
const note = {
"Note": "These are only the search results overview. Please use the Scrape Webpage tool to search further into the links."
};
return JSON.stringify(resultObject.reduce((acc, curr) => Object.assign(acc, curr), note), null, 2);
}
async function performSearch(query) {
const url = 'https://websearch.plugsugar.com/api/plugins/websearch';
const response = await axios.post(url`, { query: query })
.catch(error => {
throw new Error(`Failed to perform the initial search request: ${error.message}`);
});
const rawText = response.data.result;
const entries = rawText.trim().split('\n\n').slice(0, 3);
const resultObject = await Promise.all(entries.map(async (entry, index) => {
const lines = entry.split('\n');
const title = lines.find(line => line.startsWith('Title:')).replace('Title: ', '');
let result = lines.find(line => line.startsWith('Result:')).replace('Result: ', '');
const url = lines.find(line => line.startsWith('URL:')).replace('URL: ', '');
try {
const searchedContent = await searchWebpageContent(url);
result = searchedContent;
} catch (error) {
console.error(`Failed to search content from ${url}:`, error);
}
return { [`result_${index + 1}`]: { title, result, url } };
}));
const note = {
"Note": "The search results contain raw searched website content, and you need to extract relevant information from this and present it to the user in a well-structured manner."
};
return JSON.stringify(resultObject.reduce((acc, curr) => Object.assign(acc, curr), note), null, 2);
}
*/
const systemPrompt = "You are Search GPT, a helpful assistant with the ability to perform web searches and view websites using the tools provided. When a user asks you a question, you can use web search to find up-to-date information on that topic. You can retrieve the content of webpages from search result links using the Search Website tool. Use several tool calls consecutively, performing deep searches and trying your best to extract relevant and helpful information before responding to the user.";
let mainMessages = [
{ role: "user", content: "Hi, can you search the web for me?" },
{ role: "assistant", content: "Hi there! I can help with that. Can you tell me a bit about your query?" }
];
async function getResponse(query) {
mainMessages.push({ role: "user", content: query });
let fullResponce = "";
async function sendRequest() {
const response = await client.chat.completions.create({
model: MODEL,
messages: [{ role: "system", content: systemPrompt }, ...mainMessages],
tools: tools
});
const toolCalls = response.choices[0].message?.tool_calls;
if (toolCalls) {
const toolCallsResults = [response.choices[0].message];
for (const toolCall of toolCalls) {
const result = await manageToolCall(toolCall);
toolCallsResults.push(result);
}
mainMessages.push(...toolCallsResults);
fullResponce = fullResponce.trim() + `\n\n- [TOOL CALLS: ${processToolCallsNames(response)}]\n\n` + (response.choices[0].message?.content || '');
return await sendRequest();
} else {
fullResponce = fullResponce.trim() + '\n\n' + response.choices[0].message?.content;
return fullResponce.trim();
}
}
return await sendRequest();
}
/*
{
finish_reason: 'tool_calls',
index: 0,
logprobs: null,
message: {
content: null,
role: 'assistant',
function_call: null,
tool_calls: [
{
id: 'call_62136354',
function: {
arguments: '{"query":"Latest sports news"}',
name: 'web_search'
},
type: 'function'
}
]
}
}
*/
async function manageToolCall(toolCall) {
const tool_calls_to_function = {
"web_search": webSearch,
"search_webpage": searchWebpage
}
const functionName = toolCall.function.name;
const func = tool_calls_to_function[functionName];
if (func) {
const args = JSON.parse(toolCall.function.arguments);
const result = await func(args, toolCall.id);
return result;
} else {
const errorMessage = `No function found for ${functionName}`;
console.error(errorMessage);
const function_call_result_message = {
role: "tool",
content: JSON.stringify({
error: errorMessage
}),
tool_call_id: toolCall.id
};
return function_call_result_message;
}
}
function processToolCallsNames(response) {
const toolCalls = response.choices[0].message.tool_calls;
return toolCalls
.map(tc => {
if (!tc || !tc.function || !tc.function.name) return '';
const formattedName = tc.function.name.split('_')
.map(word => {
if (isNaN(word)) {
return word.charAt(0).toUpperCase() + word.slice(1);
}
return word;
})
.join(' ');
let formattedArgs = '';
if (tc.function.arguments) {
try {
const argsObject = JSON.parse(tc.function.arguments);
formattedArgs = Object.entries(argsObject)
.map(([key, value]) => `${key}: ${value}`)
.join(', ');
} catch (e) {
console.error('Error parsing arguments:', e);
}
}
return formattedArgs ? `${formattedName} (${formattedArgs})` : formattedName;
})
.filter(name => name)
.join(', ');
}
console.log(await getResponse('Some news related to sports.'));