-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathrequests.ts
98 lines (82 loc) · 2.71 KB
/
requests.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
import { Tool } from "@langchain/core/tools";
export interface Headers {
[key: string]: string;
}
/**
* Interface for HTTP request tools. Contains properties for headers and
* maximum output length.
*/
export interface RequestTool {
headers: Headers;
maxOutputLength: number;
}
/**
* Class for making GET requests. Extends the Tool class and implements
* the RequestTool interface. The input should be a URL string, and the
* output will be the text response of the GET request.
*/
export class RequestsGetTool extends Tool implements RequestTool {
static lc_name() {
return "RequestsGetTool";
}
name = "requests_get";
maxOutputLength = 2000;
constructor(
public headers: Headers = {},
{ maxOutputLength }: { maxOutputLength?: number } = {}
) {
super(...arguments);
this.maxOutputLength = maxOutputLength ?? this.maxOutputLength;
}
/** @ignore */
async _call(input: string) {
const res = await fetch(input, {
headers: this.headers,
});
const text = await res.text();
return text.slice(0, this.maxOutputLength);
}
description = `A portal to the internet. Use this when you need to get specific content from a website.
Input should be a url string (i.e. "https://www.google.com"). The output will be the text response of the GET request.`;
}
/**
* Class for making POST requests. Extends the Tool class and implements
* the RequestTool interface. The input should be a JSON string with two
* keys: 'url' and 'data'. The output will be the text response of the
* POST request.
*/
export class RequestsPostTool extends Tool implements RequestTool {
static lc_name() {
return "RequestsPostTool";
}
name = "requests_post";
maxOutputLength = Infinity;
constructor(
public headers: Headers = {},
{ maxOutputLength }: { maxOutputLength?: number } = {}
) {
super(...arguments);
this.maxOutputLength = maxOutputLength ?? this.maxOutputLength;
}
/** @ignore */
async _call(input: string) {
try {
const { url, data } = JSON.parse(input);
const res = await fetch(url, {
method: "POST",
headers: this.headers,
body: JSON.stringify(data),
});
const text = await res.text();
return text.slice(0, this.maxOutputLength);
} catch (error) {
return `${error}`;
}
}
description = `Use this when you want to POST to a website.
Input should be a json string with two keys: "url" and "data".
The value of "url" should be a string, and the value of "data" should be a dictionary of
key-value pairs you want to POST to the url as a JSON body.
Be careful to always use double quotes for strings in the json string
The output will be the text response of the POST request.`;
}