Skip to content

Commit

Permalink
✨ add image search
Browse files Browse the repository at this point in the history
  • Loading branch information
JohannLai committed Jan 29, 2024
1 parent ac76320 commit eb55490
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export { createGoogleCustomSearch } from './tools/googleCustomSearch';
export { createBingCustomSearch } from './tools/bingCustomSearch';
export { createSerpApiCustomSearch } from './tools/serpApiCustomSearch';
export { createSerperCustomSearch } from './tools/serperCustomSearch';
export { createSerperImagesSearch } from './tools/serperImagesSearch';
export { createClock } from './tools/clock';
export { createWebBrowser } from './tools/webbrowser';
export { createReadFileTool, createWriteFileTool } from './tools/fs';
Expand Down
51 changes: 51 additions & 0 deletions tools/serperImagesSearch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Tool } from './tool';
import { z } from 'zod';

function createSerperImagesSearch({ apiKey }: { apiKey: string }) {
if (!apiKey) {
throw new Error('Serper key must be set.');
}

const paramsSchema = z.object({
input: z.string(),
});
const name = 'serperImagesSearch';
const description = 'Useful for searching images. Input should be a search query. Outputs a JSON array of image results.';

const execute = async ({ input }: z.infer<typeof paramsSchema>) => {
try {
const res = await fetch(
'https://google.serper.dev/images',
{
method: 'POST',
headers: {
'X-API-KEY': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({ q: input })
}
);

if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}

const data = await res.json();

const results =
data.images?.map((item: any) => ({
title: item.title,
imageUrl: item.imageUrl,
imageWidth: item.imageWidth,
imageHeight: item.imageHeight,
})) ?? [];
return JSON.stringify(results);
} catch (error) {
throw new Error(`Error in SerperImagesSearch: ${error}`);
}
};

return new Tool(paramsSchema, name, description, execute).tool;
}

export { createSerperImagesSearch };

0 comments on commit eb55490

Please sign in to comment.