Skip to content

Commit 79a229b

Browse files
committed
feat: add fetch tool
1 parent 3adf208 commit 79a229b

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,7 @@
118118
"mime-types": "^2.1.35",
119119
"minimatch": "^9.0.4",
120120
"mustache": "^4.2.0",
121+
"turndown": "^7.2.0",
121122
"url-parse": "^1.5.10",
122123
"vanilla-picker": "^2.12.3",
123124
"yargs": "^17.7.2",
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { StructuredTool } from "@langchain/core/tools";
2+
import TurndownService from "turndown";
3+
import { z } from "zod";
4+
5+
/**
6+
* Tool for fetching content from a URL
7+
*/
8+
class FetchTool extends StructuredTool {
9+
name = "fetch";
10+
description = "Fetches a URL and returns the content as Markdown.";
11+
schema = z.object({
12+
url: z.string().describe("The url to fetch."),
13+
});
14+
15+
async _call({ url }) {
16+
if (!url.startsWith("http://") && !url.startsWith("https://")) {
17+
url = `https://${url}`;
18+
}
19+
20+
return new Promise((resolve, reject) => {
21+
cordova.plugin.http.sendRequest(
22+
url,
23+
{
24+
method: "get",
25+
},
26+
(response) => {
27+
const contentType =
28+
response.headers["content-type"] ||
29+
response.headers["Content-Type"] ||
30+
"";
31+
32+
if (contentType.includes("text/html")) {
33+
// Convert HTML to Markdown
34+
const markdown = this.htmlToMarkdown(response.data);
35+
resolve(markdown);
36+
} else if (contentType.includes("application/json")) {
37+
// Return JSON as string
38+
const jsonString =
39+
typeof response.data === "string"
40+
? response.data
41+
: JSON.stringify(response.data);
42+
resolve(jsonString);
43+
} else {
44+
// Return as plain text
45+
resolve(response.data);
46+
}
47+
},
48+
(error) => {
49+
console.error(error);
50+
reject(error);
51+
},
52+
);
53+
});
54+
}
55+
56+
htmlToMarkdown(html) {
57+
const turndownService = new TurndownService();
58+
return turndownService.turndown(html);
59+
}
60+
}
61+
62+
export const fetchTool = new FetchTool();
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
import { fetchTool } from "./fetch";
12
import { readFile } from "./readFile";
23

34
// Export all tools as a single object
45
export const allTools = {
56
readFile,
7+
fetchTool,
68
};

0 commit comments

Comments
 (0)