forked from i-am-bee/bee-agent-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenLibrary.ts
83 lines (73 loc) · 2.03 KB
/
openLibrary.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
79
80
81
82
83
import {
BaseToolOptions,
BaseToolRunOptions,
Tool,
ToolInput,
JSONToolOutput,
ToolError,
} from "bee-agent-framework/tools/base";
import { z } from "zod";
import { createURLParams } from "bee-agent-framework/internals/fetcher";
import { RunContext } from "bee-agent-framework/context";
type ToolOptions = BaseToolOptions & { maxResults?: number };
type ToolRunOptions = BaseToolRunOptions;
export interface OpenLibraryResponse {
numFound: number;
start: number;
numFoundExact: boolean;
q: string;
offset: number;
docs: Record<string, any>[];
}
export class OpenLibraryToolOutput extends JSONToolOutput<OpenLibraryResponse> {
isEmpty(): boolean {
return !this.result || this.result.numFound === 0 || this.result.docs.length === 0;
}
}
export class OpenLibraryTool extends Tool<OpenLibraryToolOutput, ToolOptions, ToolRunOptions> {
name = "OpenLibrary";
description =
"Provides access to a library of books with information about book titles, authors, contributors, publication dates, publisher and isbn.";
inputSchema() {
return z
.object({
title: z.string(),
author: z.string(),
isbn: z.string(),
subject: z.string(),
place: z.string(),
person: z.string(),
publisher: z.string(),
})
.partial();
}
static {
this.register();
}
protected async _run(
input: ToolInput<this>,
_options: ToolRunOptions | undefined,
run: RunContext<this>,
) {
const query = createURLParams({
searchon: input,
});
const response = await fetch(`https://openlibrary.org?${query}`, {
signal: run.signal,
});
if (!response.ok) {
throw new ToolError(
"Request to Open Library API has failed!",
[new Error(await response.text())],
{
context: { input },
},
);
}
const json: OpenLibraryResponse = await response.json();
if (this.options.maxResults) {
json.docs.length = this.options.maxResults;
}
return new OpenLibraryToolOutput(json);
}
}