Elffuss BraidHub

kikocis/continue public

4e263ad457a7 · 1.8 KiBRawPermalink
1import {
2 ContextItem,
3 ContextProviderDescription,
4 ContextProviderExtras,
5} from "../../index.js";
6import { BaseContextProvider } from "../index.js";
7
8class GoogleContextProvider extends BaseContextProvider {
9 static description: ContextProviderDescription = {
10 title: "google",
11 displayTitle: "Google",
12 description: "Attach the results of a Google search",
13 type: "query",
14 };
15
16 private _serperApiKey: string;
17
18 constructor(options: { serperApiKey: string }) {
19 super(options);
20 this._serperApiKey = options.serperApiKey;
21 }
22
23 async getContextItems(
24 query: string,
25 extras: ContextProviderExtras,
26 ): Promise<ContextItem[]> {
27 const url = "https://google.serper.dev/search";
28
29 const payload = JSON.stringify({ q: query });
30 const headers = {
31 "X-API-KEY": this._serperApiKey,
32 "Content-Type": "application/json",
33 };
34
35 const response = await extras.fetch(url, {
36 method: "POST",
37 headers: headers,
38 body: payload,
39 });
40
41 if (!response.ok) {
42 throw new Error(
43 `Failed to fetch Google search results: ${response.statusText}`,
44 );
45 }
46 const results = await response.text();
47 try {
48 const parsed = JSON.parse(results);
49 let content = `Google Search: ${query}\n\n`;
50 const answerBox = parsed.answerBox;
51
52 if (answerBox) {
53 content += `Answer Box (${answerBox.title}): ${answerBox.answer}\n\n`;
54 }
55
56 for (const result of parsed.organic) {
57 content += `${result.title}\n${result.link}\n${result.snippet}\n\n`;
58 }
59
60 return [
61 {
62 content,
63 name: "Google Search",
64 description: "Google Search",
65 },
66 ];
67 } catch (e) {
68 throw new Error(`Failed to parse Google search results: ${results}`);
69 }
70 }
71}
72
73export default GoogleContextProvider;