89 lines
2.7 KiB
JavaScript
89 lines
2.7 KiB
JavaScript
import { tool } from "@langchain/core/tools";
|
|
import z from "zod";
|
|
|
|
const httpPostTool = tool(
|
|
async ({ url, body, headers = {}, contentType = 'json', timeout = 30000 }) => {
|
|
try {
|
|
new URL(url);
|
|
} catch (e) {
|
|
return { success: false, error: `Invalid URL: ${url}` };
|
|
}
|
|
|
|
let requestBody;
|
|
const requestHeaders = {
|
|
'User-Agent': 'XAgent-Bot/1.0',
|
|
...headers
|
|
};
|
|
|
|
switch (contentType) {
|
|
case 'json':
|
|
requestHeaders['Content-Type'] = 'application/json';
|
|
requestBody = typeof body === 'string' ? body : JSON.stringify(body);
|
|
break;
|
|
case 'form':
|
|
requestHeaders['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
if (typeof body === 'object') {
|
|
requestBody = new URLSearchParams(body).toString();
|
|
} else {
|
|
requestBody = body;
|
|
}
|
|
break;
|
|
case 'text':
|
|
requestHeaders['Content-Type'] = 'text/plain';
|
|
requestBody = typeof body === 'string' ? body : JSON.stringify(body);
|
|
break;
|
|
default:
|
|
requestBody = typeof body === 'string' ? body : JSON.stringify(body);
|
|
}
|
|
|
|
try {
|
|
const controller = new AbortController();
|
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
|
|
const response = await fetch(url, {
|
|
method: 'POST',
|
|
headers: requestHeaders,
|
|
body: requestBody,
|
|
signal: controller.signal
|
|
});
|
|
|
|
clearTimeout(timeoutId);
|
|
|
|
const responseContentType = response.headers.get('content-type') || '';
|
|
let responseBody;
|
|
|
|
if (responseContentType.includes('application/json')) {
|
|
responseBody = await response.json();
|
|
} else {
|
|
responseBody = await response.text();
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
headers: Object.fromEntries(response.headers.entries()),
|
|
body: responseBody
|
|
};
|
|
} catch (error) {
|
|
if (error.name === 'AbortError') {
|
|
return { success: false, error: `Request timed out after ${timeout}ms` };
|
|
}
|
|
return { success: false, error: error.message };
|
|
}
|
|
},
|
|
{
|
|
name: "http_post",
|
|
description: "Send HTTP POST request. Supports JSON and form data.",
|
|
schema: z.object({
|
|
url: z.string().describe("Request URL"),
|
|
body: z.union([z.string(), z.object({})]).describe("Request body, can be string or JSON object"),
|
|
headers: z.record(z.string()).optional().describe("Request headers"),
|
|
contentType: z.enum(['json', 'form', 'text', 'raw']).optional().describe("Content type, default json"),
|
|
timeout: z.number().optional().describe("Timeout in milliseconds, default 30000")
|
|
}),
|
|
},
|
|
);
|
|
|
|
export { httpPostTool };
|