Created
April 20, 2023 10:45
-
-
Save spd789562/52fed6344b8c1513e079d6b1e3d473b0 to your computer and use it in GitHub Desktop.
Langchain tool for google search, is basicly just copy bingSerpAPI and change part of code useing google custom search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Tool } from 'langchain/tools'; | |
import { google } from 'googleapis'; | |
class GoogleSerpAPI extends Tool { | |
private apiKey: string; | |
private engineId: string; | |
private count = 5; | |
name = 'google-search'; | |
description = | |
'a search engine. useful for when you need to answer questions about current events. input should be a search query.'; | |
constructor(apiKey: string = process.env.GoogleAPIKey ?? '', engineId: string = process.env.GoogleEngineId ?? '') { | |
super(); | |
if (!apiKey || !engineId) { | |
throw new Error( | |
'either GoogleSerpAPI API key nor GoogleEngineId not set. You can set it as GoogleAPIKey and GoogleEngineId in your .env file.' | |
); | |
} | |
this.apiKey = apiKey; | |
this.engineId = engineId; | |
} | |
async _call(input: string): Promise<string> { | |
const customsearch = google.customsearch('v1'); | |
const res = await customsearch.cse.list({ | |
auth: this.apiKey, | |
q: input, | |
cx: this.engineId, | |
}); | |
if (!res.data.items || (res.data.items && res.data.items.length === 0)) { | |
return 'No good results found.'; | |
} | |
const snippets = res.data.items | |
// get the first 5 results | |
.slice(0, this.count) | |
.map((item) => item.snippet); | |
console.log( | |
`gpt trigger search query:${input}, result snippets: ${snippets}` | |
); | |
return snippets.join(' '); | |
} | |
} | |
export { GoogleSerpAPI }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment