#1345 Add API endpoint for web search interaction

This commit is contained in:
Cohee 2023-11-14 00:16:41 +02:00
parent 61764a9a21
commit 5fe8f70eb1
4 changed files with 44 additions and 0 deletions

View File

@ -12,6 +12,7 @@ export const SECRET_KEYS = {
AI21: 'api_key_ai21',
SCALE_COOKIE: 'scale_cookie',
PALM: 'api_key_palm',
SERPAPI: 'api_key_serpapi',
}
const INPUT_MAP = {

View File

@ -3528,6 +3528,9 @@ require('./src/classify').registerEndpoints(app, jsonParser);
// Image captioning
require('./src/caption').registerEndpoints(app, jsonParser);
// Web search extension
require('./src/serpapi').registerEndpoints(app, jsonParser);
const tavernUrl = new URL(
(cliArguments.ssl ? 'https://' : 'http://') +
(listen ? '0.0.0.0' : '127.0.0.1') +

View File

@ -21,6 +21,7 @@ const SECRET_KEYS = {
ONERING_URL: 'oneringtranslator_url',
DEEPLX_URL: 'deeplx_url',
PALM: 'api_key_palm',
SERPAPI: 'api_key_serpapi',
}
/**

39
src/serpapi.js Normal file
View File

@ -0,0 +1,39 @@
const fetch = require('node-fetch').default;
const { readSecret } = require('./secrets');
/**
* Registers the SerpApi endpoints.
* @param {import("express").Express} app
* @param {any} jsonParser
*/
function registerEndpoints(app, jsonParser) {
app.post('/api/serpapi/search', jsonParser, async (request, response) => {
try {
const key = readSecret('serpapi_key');
if (!key) {
console.log('No SerpApi key found');
return response.sendStatus(401);
}
const { query } = request.body;
const result = await fetch(`https://serpapi.com/search.json?q=${encodeURIComponent(query)}&api_key=${key}`);
if (!result.ok) {
const text = await result.text();
console.log('SerpApi request failed', result.statusText, text);
return response.status(500).send(text);
}
const data = await result.json();
return response.json(data);
} catch (error) {
console.log(error);
return response.sendStatus(500);
}
});
}
module.exports = {
registerEndpoints,
};