|
| 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(); |
0 commit comments