You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中组合LangChain Tools为Toolkit后加载Agent报错求助

TypeScript中LangChain Toolkit组合后Agent加载报错的解决方法

问题描述

编写自定义Toolkit组合多个LangChain Tools后,将其加载到Agent时出现类型错误:

Type 'CustomToolkit' is missing the following properties from type 'Tool': schema, call, lc_namespace, _call, and 11 more.ts(2740)

自定义Toolkit代码:

import { Toolkit } from 'langchain/agents';
import { DynamicTool, Tool } from 'langchain/tools';

export class CustomToolkit extends Toolkit {
  tools: Tool[];

  constructor() {
    super();
    this.tools = [
      new DynamicTool({
        name: 'FOO',
        description:
          'call this to get the value of foo. input should be an empty string.',
        func: async () => 'baz'
      }),
      new DynamicTool({
        name: 'BAR',
        description:
          'call this to get the value of bar. input should be an empty string.',
        func: async () => 'baz1'
      })
    ];
  }
}

报错原因

LangChain的Agent构造函数(如createOpenAIToolsAgent)要求传入Tool[]类型的工具数组,而非直接传入Toolkit实例。报错是因为误将Toolkit对象当作单个Tool传入,导致类型不匹配。

解决方法

从CustomToolkit实例中提取tools数组,传入Agent的配置参数即可:

import { AgentExecutor, createOpenAIToolsAgent } from "langchain/agents";
import { ChatOpenAI } from "@langchain/openai";
import { CustomToolkit } from "./path-to-your-toolkit";

// 初始化大模型
const llm = new ChatOpenAI({ model: "gpt-3.5-turbo" });
// 创建Toolkit实例
const customToolkit = new CustomToolkit();

// 使用Toolkit中的tools数组创建Agent
const agent = await createOpenAIToolsAgent({
  llm,
  tools: customToolkit.tools, // 关键:传入tools数组而非Toolkit实例
});

// 创建Agent执行器
const agentExecutor = new AgentExecutor({
  agent,
  tools: customToolkit.tools,
});

// 测试运行示例
const result = await agentExecutor.invoke({
  input: "获取foo的值"
});
console.log(result.output);

额外说明

这种提取tools数组的方式是LangChain官方推荐的通用做法,可有效复用Toolkit的工具组合逻辑。少数特定Agent类型可能支持直接传入Toolkit,但绝大多数场景下,传入tools数组即可解决类型错误问题。

内容的提问来源于stack exchange,提问作者Joost Dübken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:16:17