调整了agent
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import { TavilyExtract } from "@langchain/tavily";
|
||||
import { tool } from "@langchain/core/tools";
|
||||
import * as z from "zod"
|
||||
import { z } from "zod";
|
||||
import config from "../../../../config.js";
|
||||
|
||||
const webFetchTool = tool(
|
||||
@@ -20,14 +20,13 @@ const webFetchTool = tool(
|
||||
},
|
||||
{
|
||||
name: "web_fetch",
|
||||
description: "Run a web fetch",
|
||||
description:
|
||||
"抓取并提取指定网页的正文内容(默认 Markdown),适合阅读医院官网、政策公告、新闻等长文页面。",
|
||||
schema: z.object({
|
||||
extractDepth: z.enum(["basic", "advanced"]).default("basic"),
|
||||
includeImages: z.boolean().default(false),
|
||||
format: z
|
||||
.enum(["markdown", "json"])
|
||||
.default("markdown"),
|
||||
urls: z.array(z.string().describe("The urls")).default([]),
|
||||
urls: z.array(z.string()).min(1).max(5).describe("要抓取的网页 URL 列表(1-5 个)"),
|
||||
extractDepth: z.enum(["basic", "advanced"]).default("basic").describe("提取深度:basic 更快,advanced 更完整"),
|
||||
includeImages: z.boolean().default(false).describe("是否包含图片"),
|
||||
format: z.enum(["markdown", "json"]).default("markdown").describe("返回格式"),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
/**
|
||||
* Agent 出网 HTTP 客户端:统一承载 SSRF 校验、重定向控制、超时上限与响应体截断。
|
||||
*
|
||||
* http_get / http_post 只负责参数整理,真正的安全约束集中在这里,
|
||||
* 避免两个工具各写一套、修了一个漏掉另一个。
|
||||
* 目前只有 http_get 使用,安全约束集中在这里,避免工具各自实现一套。
|
||||
*
|
||||
* 约束:
|
||||
* - 每一跳都重新做同步 + DNS 校验,最多 3 跳(重定向可被用来绕过首次校验);
|
||||
* - POST 不跟随重定向(303/302 会改写成 GET,语义与安全性都不可控);
|
||||
* - 超时由服务端夹紧到 1s~15s,不接受模型传入的任意大值;
|
||||
* - 响应体最多读取 2MB,超出即截断并标记 truncated。
|
||||
*/
|
||||
@@ -63,17 +61,14 @@ async function readBodyLimited(response) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 发起受控的 HTTP 请求
|
||||
* 发起受控的 GET 请求
|
||||
* @param {string} url 目标地址
|
||||
* @param {Object} options
|
||||
* @param {string} [options.method] 请求方法
|
||||
* @param {Object} [options]
|
||||
* @param {Object} [options.headers] 请求头
|
||||
* @param {string} [options.body] 请求体
|
||||
* @param {number} [options.timeout] 超时毫秒数(会被夹紧)
|
||||
* @returns {Promise<{status:number,statusText:string,headers:Object,buffer:Buffer,text:string,truncated:boolean,url:string}>}
|
||||
*/
|
||||
async function safeFetch(url, options = {}) {
|
||||
const method = (options.method || "GET").toUpperCase();
|
||||
const timeout = clampTimeout(options.timeout);
|
||||
let currentUrl = url;
|
||||
|
||||
@@ -87,9 +82,8 @@ async function safeFetch(url, options = {}) {
|
||||
|
||||
try {
|
||||
const response = await fetch(currentUrl, {
|
||||
method,
|
||||
method: "GET",
|
||||
headers: options.headers,
|
||||
body: options.body,
|
||||
redirect: "manual",
|
||||
signal: controller.signal,
|
||||
});
|
||||
@@ -98,7 +92,6 @@ async function safeFetch(url, options = {}) {
|
||||
const location = response.headers.get("location");
|
||||
await response.body?.cancel().catch(() => {});
|
||||
if (!location) throw new Error(`Redirect without location: ${response.status}`);
|
||||
if (method !== "GET") throw new Error("Redirects are not followed for non-GET requests");
|
||||
currentUrl = new URL(location, currentUrl).toString();
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -2,15 +2,66 @@ import { tool } from 'langchain';
|
||||
import * as 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, headers = {}, timeout = 15000 }) => {
|
||||
async ({ url, params, headers = {}, timeout = 15000 }) => {
|
||||
try {
|
||||
const requestUrl = buildRequestUrl(url, params);
|
||||
// 校验(含 DNS)、重定向控制、超时夹紧、响应体截断统一在 safeFetch 内完成
|
||||
const response = await safeFetch(url, {
|
||||
method: 'GET',
|
||||
const response = await safeFetch(requestUrl, {
|
||||
headers: {
|
||||
'User-Agent': 'XAgent-Bot/1.0',
|
||||
...headers
|
||||
...applyBaiduAuthorization(requestUrl, headers)
|
||||
},
|
||||
timeout
|
||||
});
|
||||
@@ -48,9 +99,13 @@ export const httpGetTool = tool(
|
||||
},
|
||||
{
|
||||
name: 'http_get',
|
||||
description: 'Send HTTP GET request and return response content. Response body is capped at 2MB.',
|
||||
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')
|
||||
})
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
import { tool } from "@langchain/core/tools";
|
||||
import z from "zod";
|
||||
import { safeFetch } from "./http_client.js";
|
||||
|
||||
const httpPostTool = tool(
|
||||
async ({ url, body, headers = {}, contentType = 'json', timeout = 15000 }) => {
|
||||
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 {
|
||||
// 校验(含 DNS)、超时夹紧、响应体截断统一在 safeFetch 内完成;POST 不跟随重定向
|
||||
const response = await safeFetch(url, {
|
||||
method: 'POST',
|
||||
headers: requestHeaders,
|
||||
body: requestBody,
|
||||
timeout
|
||||
});
|
||||
|
||||
const responseContentType = response.headers['content-type'] || '';
|
||||
let responseBody;
|
||||
|
||||
if (responseContentType.includes('application/json')) {
|
||||
try {
|
||||
responseBody = JSON.parse(response.text);
|
||||
} catch (e) {
|
||||
responseBody = response.text;
|
||||
}
|
||||
} else {
|
||||
responseBody = response.text;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers: response.headers,
|
||||
truncated: response.truncated,
|
||||
body: responseBody
|
||||
};
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') {
|
||||
return { success: false, error: 'Request timed out' };
|
||||
}
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "http_post",
|
||||
description: "Send HTTP POST request. Supports JSON and form data. Response body is capped at 2MB.",
|
||||
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, clamped to 1s-15s")
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
export { httpPostTool };
|
||||
@@ -1,6 +1,6 @@
|
||||
import { TavilySearch } from "@langchain/tavily";
|
||||
import { tool } from "@langchain/core/tools";
|
||||
import * as z from "zod"
|
||||
import { z } from "zod";
|
||||
import config from "../../../../config.js";
|
||||
|
||||
const webSearchTool = tool(
|
||||
@@ -19,16 +19,29 @@ const webSearchTool = tool(
|
||||
return await tavilySearch._call({ query });
|
||||
},
|
||||
{
|
||||
name: "internet_search",
|
||||
description: "Run a web search",
|
||||
name: "web_search",
|
||||
description:
|
||||
"联网搜索公开网页信息,返回摘要与链接。适合查询医院公示、就医政策、停诊/号源公告等时效性信息。",
|
||||
schema: z.object({
|
||||
query: z.string().describe("The search query"),
|
||||
maxResults: z.number().optional().default(5),
|
||||
query: z.string().describe("搜索关键词或问题"),
|
||||
maxResults: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(10)
|
||||
.optional()
|
||||
.default(5)
|
||||
.describe("返回结果数量(1-10),默认 5"),
|
||||
topic: z
|
||||
.enum(["general", "news", "finance"])
|
||||
.optional()
|
||||
.default("general"),
|
||||
includeRawContent: z.boolean().optional().default(false),
|
||||
.default("general")
|
||||
.describe("搜索主题,政策/新闻类查询建议用 news"),
|
||||
includeRawContent: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.default(false)
|
||||
.describe("是否返回网页原文(内容较长,默认关闭)"),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user