forked from continuedev/continue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GoogleContextProvider.ts
65 lines (53 loc) · 1.54 KB
/
GoogleContextProvider.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
import { BaseContextProvider } from "..";
import {
ContextItem,
ContextProviderDescription,
ContextProviderExtras,
} from "../..";
class GoogleContextProvider extends BaseContextProvider {
static description: ContextProviderDescription = {
title: "google",
displayTitle: "Google",
description: "Attach the results of a Google search",
type: "query",
};
private _serperApiKey: string;
constructor(options: { serperApiKey: string }) {
super(options);
this._serperApiKey = options.serperApiKey;
}
async getContextItems(
query: string,
extras: ContextProviderExtras
): Promise<ContextItem[]> {
const url = "https://google.serper.dev/search";
const payload = JSON.stringify({ q: query });
const headers = {
"X-API-KEY": this._serperApiKey,
"Content-Type": "application/json",
};
const response = await fetch(url, {
method: "POST",
headers: headers,
body: payload,
});
const results = await response.text();
let jsonResults = JSON.parse(results);
let content = `Google Search: ${query}\n\n`;
let answerBox = jsonResults["answerBox"];
if (answerBox) {
content += `Answer Box (${answerBox["title"]}): ${answerBox["answer"]}\n\n`;
}
for (let result of jsonResults["organic"]) {
content += `${result["title"]}\n${result["link"]}\n${result["snippet"]}\n\n`;
}
return [
{
content,
name: "Google Search",
description: "Google Search",
},
];
}
}
export default GoogleContextProvider;