-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
bingserpapi.ts
78 lines (61 loc) · 2.05 KB
/
bingserpapi.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
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Tool } from "@langchain/core/tools";
/**
* A tool for web search functionality using Bing's search engine. It
* extends the base `Tool` class and implements the `_call` method to
* perform the search operation. Requires an API key for Bing's search
* engine, which can be set in the environment variables. Also accepts
* additional parameters for the search query.
*/
class BingSerpAPI extends Tool {
static lc_name() {
return "BingSerpAPI";
}
/**
* Not implemented. Will throw an error if called.
*/
toJSON() {
return this.toJSONNotImplemented();
}
name = "bing-search";
description =
"a search engine. useful for when you need to answer questions about current events. input should be a search query.";
key: string;
params: Record<string, string>;
constructor(
apiKey: string | undefined = getEnvironmentVariable("BingApiKey"),
params: Record<string, string> = {}
) {
super(...arguments);
if (!apiKey) {
throw new Error(
"BingSerpAPI API key not set. You can set it as BingApiKey in your .env file."
);
}
this.key = apiKey;
this.params = params;
}
/** @ignore */
async _call(input: string): Promise<string> {
const headers = { "Ocp-Apim-Subscription-Key": this.key };
const params = { q: input, textDecorations: "true", textFormat: "HTML" };
const searchUrl = new URL("https://api.bing.microsoft.com/v7.0/search");
Object.entries(params).forEach(([key, value]) => {
searchUrl.searchParams.append(key, value);
});
const response = await fetch(searchUrl, { headers });
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const res = await response.json();
const results: [] = res.webPages.value;
if (results.length === 0) {
return "No good results found.";
}
const snippets = results
.map((result: { snippet: string }) => result.snippet)
.join(" ");
return snippets;
}
}
export { BingSerpAPI };