langchain-tools
БесплатноБез исполняемых скриптовНе проверенLangChain 工具集成使用指南,包括预构建工具包、Tavily、Wikipedia 和自定义工具
от majiayu000★ 31 звезда на GitHubОб этом скилле
langchain-tools (JavaScript/TypeScript)
概述
工具使 LLM 能够与外部系统交互、执行计算、搜索网络、查询数据库等。它们将模型能力扩展到文本生成之外,使 Agent 真正具备可执行性。
核心概念
- 工具(Tools):Agent 可以调用的函数,用于执行特定任务
- 工具调用(Tool Calling):模型根据用户查询决定何时以及如何使用工具
- 工具包(Toolkits):相关工具的集合
- 工具模式(Tool Schema):使用 Zod 或 JSON Schema 描述工具参数
工具选择决策表
| 工具/工具包 | 最适用于 | 包 | 主要特性 |
|---|---|---|---|
| Tavily 搜索 | 网络搜索 | @langchain/community |
AI 优化的搜索 API |
| Wikipedia | 百科全书查询 | @langchain/community |
Wikipedia API 访问 |
| 计算器(Calculator) | 数学运算 | @langchain/community |
表达式求值 |
| DuckDuckGo 搜索 | 注重隐私的搜索 | @langchain/community |
无需 API 密钥 |
| 浏览器工具 | 网页自动化 | @langchain/community |
无头浏览器 |
| 向量存储工具 | 语义搜索 | 基于向量存储 | 查询您自己的数据 |
| 自定义工具 | 您的特定需求 | @langchain/core/tools |
定义任何函数 |
何时选择各工具
选择 Tavily 如果:
- 您需要高质量的网络搜索
- 您希望获得 AI 优化的结果
- 您正在构建研究/RAG 应用程序
选择 Wikipedia 如果:
- 您需要百科全书式知识
- 需要事实性信息
- 免费,无需 API 密钥
选择自定义工具如果:
- 您有特定的业务逻辑
- 您需要集成专有系统
- 内置工具无法满足您的需求
代码示例
Tavily 搜索工具
import { TavilySearchResults } from "@langchain/community/tools/tavily_search";
// 初始化 Tavily(需要 API 密钥)
const searchTool = new TavilySearchResults({
maxResults: 3,
apiKey: process.env.TAVILY_API_KEY,
});
// 直接使用
const results = await searchTool.invoke("Latest AI news");
console.log(results);
// 与 Agent 一起使用
import { ChatOpenAI } from "@langchain/openai";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
const model = new ChatOpenAI({ modelName: "gpt-4" });
const agent = createReactAgent({
llm: model,
tools: [searchTool],
});
const response = await agent.invoke({
messages: [{ role: "user", content: "What's new in AI today?" }]
});
Wikipedia 工具
import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";
const wikipediaTool = new WikipediaQueryRun({
topKResults: 3,
maxDocContentLength: 4000,
});
// 查询 Wikipedia
const result = await wikipediaTool.invoke("Artificial Intelligence");
console.log(result);
计算器工具
import { Calculator } from "@langchain/community/tools/calculator";
const calculator = new Calculator();
// 执行计算
const result = await calculator.invoke("sqrt(144) + 5 * 3");
console.log(result); // "27"
// 在 Agent 中用于数学问题
const mathAgent = createReactAgent({
llm: model,
tools: [calculator],
});
DuckDuckGo 搜索(无需 API 密钥)
import { DuckDuckGoSearch } from "@langchain/community/tools/duckduckgo_search";
const searchTool = new DuckDuckGoSearch({
maxResults: 5,
});
const results = await searchTool.invoke("LangChain framework");
使用 Zod 模式的自定义工具
import { tool } from "@langchain/core/tools";
import { z } from "zod";
// 定义自定义工具
const weatherTool = tool(
async ({ location, unit = "celsius" }) => {
// 您的实现
const data = await fetchWeather(location, unit);
return `The weather in ${location} is ${data.temp}°${unit === "celsius" ? "C" : "F"}`;
},
{
name: "get_weather",
description: "Get the current weather for a location. Use this when users ask about weather.",
schema: z.object({
location: z.string().describe("The city name, e.g., 'San Francisco'"),
unit: z.enum(["celsius", "fahrenheit"]).optional().describe("Temperature unit"),
}),
}
);
// 与 Agent 一起使用
const agent = createReactAgent({
llm: model,
tools: [weatherTool],
});
const response = await agent.invoke({
messages: [{ role: "user", content: "What's the weather in London?" }]
});
自定义工具 - 基于类
import { StructuredTool } from "@langchain/core/tools";
import { z } from "zod";
class DatabaseQueryTool extends StructuredTool {
name = "database_query";
description = "Query the customer database for information";
schema = z.object({
customerId: z.string().describe("Customer ID to look up"),
});
async _call({ customerId }: { customerId: string }): Promise<string> {
// 您的数据库逻辑
const customer = await db.getCustomer(customerId);
return JSON.stringify(customer);
}
}
const dbTool = new DatabaseQueryTool();
将向量存储作为工具
import { createRetrieverTool } from "langchain/tools/retriever";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { OpenAIEmbeddings } from "@langchain/openai";
// 创建向量存储
const vectorStore = await MemoryVectorStore.fromTexts(
["LangChain is a framework...", "Agents use tools..."],
[{}, {}],
new OpenAIEmbeddings()
);
// 转换为工具
const retrieverTool = createRetrieverTool(
vectorStore.asRetriever(),
{
name: "knowledge_base",
description: "Search the knowledge base for information about LangChain",
}
);
// 在 Agent 中使用
const agent = createReactAgent({
llm: model,
tools: [retrieverTool],
});
多工具示例
import { ChatOpenAI } from "@langchain/openai";
import { TavilySearchResults } from "@langchain/community/tools/tavily_search";
import { Calculator } from "@langchain/community/tool
Установить langchain-tools в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл langchain-tools?
LangChain 工具集成使用指南,包括预构建工具包、Tavily、Wikipedia 和自定义工具
Как установить скилл langchain-tools?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл langchain-tools запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic