-
Notifications
You must be signed in to change notification settings - Fork 137
/
openLibrary.ts
101 lines (89 loc) · 2.63 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import {
BaseToolOptions,
BaseToolRunOptions,
Tool,
ToolInput,
JSONToolOutput,
ToolError,
ToolEmitter,
} from "bee-agent-framework/tools/base";
import { z } from "zod";
import { createURLParams } from "bee-agent-framework/internals/fetcher";
import { GetRunContext } from "bee-agent-framework/context";
import { Callback, Emitter } from "bee-agent-framework/emitter/emitter";
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();
}
public readonly emitter: ToolEmitter<
ToolInput<this>,
OpenLibraryToolOutput,
{
beforeFetch: Callback<{ request: { url: string; options: RequestInit } }>;
afterFetch: Callback<{ data: OpenLibraryResponse }>;
}
> = Emitter.root.child({
namespace: ["tool", "search", "openLibrary"],
creator: this,
});
static {
this.register();
}
protected async _run(
input: ToolInput<this>,
_options: Partial<ToolRunOptions>,
run: GetRunContext<this>,
) {
const request = {
url: `https://openlibrary.org?${createURLParams({
searchon: input,
})}`,
options: { signal: run.signal } as RequestInit,
};
await run.emitter.emit("beforeFetch", { request });
const response = await fetch(request.url, request.options);
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;
}
await run.emitter.emit("afterFetch", { data: json });
return new OpenLibraryToolOutput(json);
}
}