113 lines
3.9 KiB
JavaScript
113 lines
3.9 KiB
JavaScript
import { tool } from "@langchain/core/tools";
|
|
import { z } from "zod";
|
|
import { safeFetch } from './http_client.js';
|
|
|
|
const BAIDU_MAP_HOST = 'api.map.baidu.com';
|
|
const BAIDU_MAP_TOKEN_ENV = 'BAIDU_MAP_AUTH_TOKEN';
|
|
|
|
/**
|
|
* 拼查询参数。统一用 URLSearchParams,避免模型手工拼接导致中文/特殊字符未编码。
|
|
*/
|
|
function buildRequestUrl(url, params) {
|
|
if (!params) return url;
|
|
const parsed = new URL(url);
|
|
for (const [key, value] of Object.entries(params)) {
|
|
if (value === undefined || value === null) continue;
|
|
parsed.searchParams.append(key, String(value));
|
|
}
|
|
return parsed.toString();
|
|
}
|
|
|
|
/**
|
|
* 百度地图 Agent Plan 鉴权由运行时注入,不把 token 暴露给模型。
|
|
* 仅对 https://api.map.baidu.com/agent_plan/ 生效,其他地址不附加凭证。
|
|
*/
|
|
function applyBaiduAuthorization(url, headers = {}) {
|
|
const parsed = new URL(url);
|
|
// 只给 Agent Plan 接口附加凭证,避免 token 被带到百度地图的其他接口
|
|
if (
|
|
parsed.protocol !== 'https:'
|
|
|| parsed.hostname !== BAIDU_MAP_HOST
|
|
|| !parsed.pathname.startsWith('/agent_plan/')
|
|
) {
|
|
return headers;
|
|
}
|
|
|
|
const token = process.env[BAIDU_MAP_TOKEN_ENV];
|
|
if (!token) return headers;
|
|
|
|
const next = { ...headers };
|
|
const authorizationKey = Object.keys(next)
|
|
.find((key) => key.toLowerCase() === 'authorization');
|
|
const key = authorizationKey || 'Authorization';
|
|
|
|
// 兼容旧 skill 中写占位符的调用方式;模型不应主动传真实 token
|
|
if (!authorizationKey || !String(next[key] ?? '').trim()) {
|
|
next[key] = `Bearer ${token}`;
|
|
return next;
|
|
}
|
|
next[key] = String(next[key])
|
|
.replace(/\$\{BAIDU_MAP_AUTH_TOKEN\}|\$BAIDU_MAP_AUTH_TOKEN/g, token);
|
|
return next;
|
|
}
|
|
|
|
export { buildRequestUrl, applyBaiduAuthorization };
|
|
|
|
export const httpGetTool = tool(
|
|
async ({ url, params, headers = {}, timeout = 15000 }) => {
|
|
try {
|
|
const requestUrl = buildRequestUrl(url, params);
|
|
// 校验(含 DNS)、重定向控制、超时夹紧、响应体截断统一在 safeFetch 内完成
|
|
const response = await safeFetch(requestUrl, {
|
|
headers: {
|
|
'User-Agent': 'XAgent-Bot/1.0',
|
|
...applyBaiduAuthorization(requestUrl, headers)
|
|
},
|
|
timeout
|
|
});
|
|
|
|
const contentType = response.headers['content-type'] || '';
|
|
let body;
|
|
|
|
if (contentType.includes('application/json')) {
|
|
try {
|
|
body = JSON.parse(response.text);
|
|
} catch (e) {
|
|
// 服务端声明 json 但返回非法内容时退回原文,避免工具直接抛错中断对话
|
|
body = response.text;
|
|
}
|
|
} else if (contentType.includes('text/') || contentType.includes('application/javascript')) {
|
|
body = response.text;
|
|
} else {
|
|
body = response.buffer.toString('base64');
|
|
}
|
|
|
|
return JSON.stringify({
|
|
success: true,
|
|
status: response.status,
|
|
statusText: response.statusText,
|
|
headers: response.headers,
|
|
truncated: response.truncated,
|
|
body
|
|
});
|
|
} catch (error) {
|
|
if (error.name === 'AbortError') {
|
|
return JSON.stringify({ success: false, error: 'Request timed out' });
|
|
}
|
|
return JSON.stringify({ success: false, error: error.message });
|
|
}
|
|
},
|
|
{
|
|
name: 'http_get',
|
|
description: 'Send HTTP GET request and return response content. Query params are URL-encoded automatically; Baidu Map Agent Plan auth is injected server-side. Response body is capped at 2MB.',
|
|
schema: z.object({
|
|
url: z.string().describe('Request URL'),
|
|
params: z.record(
|
|
z.string(),
|
|
z.union([z.string(), z.number(), z.boolean()])
|
|
).optional().describe('Query parameters, encoded automatically'),
|
|
headers: z.record(z.string(), z.string()).optional().describe('Request headers'),
|
|
timeout: z.number().optional().describe('Timeout in milliseconds, clamped to 1s-15s')
|
|
})
|
|
}
|
|
); |