62 lines
1.9 KiB
JavaScript
62 lines
1.9 KiB
JavaScript
import { tool } from 'langchain';
|
|
import * as z from 'zod';
|
|
|
|
export const httpGetTool = tool(
|
|
async ({ url, headers = {}, timeout = 30000 }) => {
|
|
try {
|
|
new URL(url);
|
|
} catch (e) {
|
|
return JSON.stringify({ success: false, error: `Invalid URL: ${url}` });
|
|
}
|
|
|
|
try {
|
|
const controller = new AbortController();
|
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
|
|
const response = await fetch(url, {
|
|
method: 'GET',
|
|
headers: {
|
|
'User-Agent': 'XAgent-Bot/1.0',
|
|
...headers
|
|
},
|
|
signal: controller.signal
|
|
});
|
|
|
|
clearTimeout(timeoutId);
|
|
|
|
const contentType = response.headers.get('content-type') || '';
|
|
let body;
|
|
|
|
if (contentType.includes('application/json')) {
|
|
body = await response.json();
|
|
} else if (contentType.includes('text/') || contentType.includes('application/javascript')) {
|
|
body = await response.text();
|
|
} else {
|
|
const buffer = await response.arrayBuffer();
|
|
body = Buffer.from(buffer).toString('base64');
|
|
}
|
|
|
|
return JSON.stringify({
|
|
success: true,
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
headers: Object.fromEntries(response.headers.entries()),
|
|
body
|
|
});
|
|
} catch (error) {
|
|
if (error.name === 'AbortError') {
|
|
return JSON.stringify({ success: false, error: `Request timed out after ${timeout}ms` });
|
|
}
|
|
return JSON.stringify({ success: false, error: error.message });
|
|
}
|
|
},
|
|
{
|
|
name: 'http_get',
|
|
description: 'Send HTTP GET request and return response content. Supports custom headers and timeout settings.',
|
|
schema: z.object({
|
|
url: z.string().describe('Request URL'),
|
|
headers: z.record(z.string(), z.string()).optional().describe('Request headers'),
|
|
timeout: z.number().optional().describe('Timeout in milliseconds, default 30000')
|
|
})
|
|
}
|
|
); |