agsamantha/node_modules/@langchain/community/dist/tools/brave_search.cjs

67 lines
2.4 KiB
JavaScript
Raw Normal View History

2024-10-02 20:15:21 +00:00
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BraveSearch = void 0;
const env_1 = require("@langchain/core/utils/env");
const tools_1 = require("@langchain/core/tools");
/**
* Class for interacting with the Brave Search engine. It extends the Tool
* class and requires an API key to function. The API key can be passed in
* during instantiation or set as an environment variable named
* 'BRAVE_SEARCH_API_KEY'.
*/
class BraveSearch extends tools_1.Tool {
static lc_name() {
return "BraveSearch";
}
constructor(fields = {
apiKey: (0, env_1.getEnvironmentVariable)("BRAVE_SEARCH_API_KEY"),
}) {
super();
Object.defineProperty(this, "name", {
enumerable: true,
configurable: true,
writable: true,
value: "brave-search"
});
Object.defineProperty(this, "description", {
enumerable: true,
configurable: true,
writable: true,
value: "a search engine. useful for when you need to answer questions about current events. input should be a search query."
});
Object.defineProperty(this, "apiKey", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
if (!fields.apiKey) {
throw new Error(`Brave API key not set. Please pass it in or set it as an environment variable named "BRAVE_SEARCH_API_KEY".`);
}
this.apiKey = fields.apiKey;
}
/** @ignore */
async _call(input) {
const headers = {
"X-Subscription-Token": this.apiKey,
Accept: "application/json",
};
const searchUrl = new URL(`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(input)}`);
const response = await fetch(searchUrl, { headers });
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const parsedResponse = await response.json();
const webSearchResults = parsedResponse.web?.results;
const finalResults = Array.isArray(webSearchResults)
? webSearchResults.map((item) => ({
title: item.title,
link: item.url,
snippet: item.description,
}))
: [];
return JSON.stringify(finalResults);
}
}
exports.BraveSearch = BraveSearch;