ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

LangChain.js 中的 @langchain/anthropic 集成:ChatAnthropic、Strict Tool Use 与全套内置工具实战

LangChain.js 中的 @langchain/anthropic 集成:ChatAnthropic、Strict Tool Use 与全套内置工具实战 LangChain.js 中的 langchain/anthropic 集成ChatAnthropic、Strict Tool Use 与全套内置工具实战【免费下载链接】langchainjsThe agent engineering platform项目地址: https://gitcode.com/GitHub_Trending/la/langchainjs本篇技术指南基于 langchainjs 仓库中的 langchain-anthropic 包文档系统讲解langchain/anthropic集成的安装与依赖治理、ChatAnthropic模型调用、Anthropic 的 strict tool use严格工具调用三种启用方式及优先级规则以及内存、网页搜索、网页抓取、工具检索、文本编辑、计算机操作、代码执行、Bash、MCP 工具集等内置工具的完整用法并结合仓库源码剖析参数如何被解析和转发到 Anthropic API。读完后你可以直接在本仓库基础上搭建可运行、可校验的 Claude 工具调用系统。包定位与安装langchain/anthropic是 LangChain.js 生态中对接 Anthropic Claude 模型的官方集成包它构建在官方 SDKanthropic-ai/sdk之上当前仓库 package.json 声明依赖anthropic-ai/sdk ^0.122.0运行环境要求 Node.js 20zod 版本兼容^3.25.76 || ^4。安装方式npm install langchain/anthropic langchain/core保证 langchain/core 单一实例该包与主 LangChain 包都依赖langchain/core在 package.json 中以peerDependencies形式声明。当你将本包与其他 LangChain 包混合使用时必须确保所有包共享同一个langchain/core实例否则可能出现运行时类型不匹配问题。官方建议在项目的package.json中同时配置各包管理器的字段以最大化兼容性{ name: your-project, version: 0.0.0, dependencies: { langchain/anthropic: ^0.0.9, langchain/core: ^0.3.0 }, resolutions: { langchain/core: ^0.3.0 }, overrides: { langchain/core: ^0.3.0 }, pnpm: { overrides: { langchain/core: ^0.3.0 } } }其中resolutions对应 yarnoverrides对应 npmpnpm.overrides对应 pnpm。建议三个字段都加上版本约束以你实际使用的langchain/core版本为准。ChatAnthropic基础调用与流式输出ChatAnthropic是该包推荐用于访问 Claude 系列的类。先配置 API Keyexport ANTHROPIC_API_KEYyour-api-key然后初始化并发起调用import { ChatAnthropic } from langchain/anthropic; const model new ChatAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); const response await model.invoke({ role: user, content: Hello world!, });流式Streamingstream()返回增量消息块AIMessageChunkimport { ChatAnthropic } from langchain/anthropic; const model new ChatAnthropic({ apiKey: process.env.ANTHROPIC_API_KEY, model: claude-3-sonnet-20240229, }); const response await model.stream({ role: user, content: Hello world!, });源码细节max_tokens 的默认值策略从 chat_models.ts 的源码结构看ChatAnthropic内置了一张MODEL_DEFAULT_MAX_OUTPUT_TOKENS前缀匹配表当你未显式设置maxTokens时包会按模型名前缀选择默认值例如claude-opus-4-7/claude-sonnet-4-5等较新模型默认为 16384claude-3-7-sonnet/claude-3-5-*为 8192最旧的claude-3-*为 4096未匹配到任何前缀时回退到 4096。这意味着模型升级后默认输出上限会随之提高若你需要更保守的预算应显式传入maxTokens。Strict Tool Use保证工具入参符合 SchemaAnthropic 支持strict tool use严格工具调用通过语法约束采样grammar-constrained sampling保证 Claude 生成的工具入参与你定义的 Schema 完全匹配——不缺必填字段、类型不会错。你可以按“每次调用”“绑定后的模型默认值”“单个工具”三个粒度启用。方式一Per-call通过 bindTools 第二参数对绑定中的所有工具生效import { ChatAnthropic } from langchain/anthropic; import { tool } from langchain; import { z } from zod; const getWeather tool(async ({ location }) Weather in ${location}, { name: get_weather, description: Get the current weather in a given location, schema: z.object({ location: z.string() }), }); const model new ChatAnthropic({ model: claude-opus-4-7 }); const response await model .bindTools([getWeather], { strict: true }) .invoke(Whats the weather in San Francisco?);方式二绑定模型级默认值通过 withConfigconst strictModelWithTools model .bindTools([getWeather]) .withConfig({ strict: true }); const response await strictModelWithTools.invoke( Whats the weather in San Francisco? );方式三Per-tool通过 extras.strict适用于“严格工具与非严格工具混用”的场景——只对关键工具开启严格模式const lookupCustomer tool(async ({ id }) ..., { name: lookup_customer, description: Look up a customer by id, schema: z.object({ id: z.string() }), // 仅对这个关键工具开启严格模式 extras: { strict: true }, }); const searchDocs tool(async ({ query }) ..., { name: search_docs, description: Free-form documentation search, schema: z.object({ query: z.string() }), }); const response await model .bindTools([lookupCustomer, searchDocs]) .invoke(Find customer 12345 and any onboarding docs);方式四配合 withStructuredOutput 保证结构化输出const Weather z.object({ location: z.string(), temperature_celsius: z.number(), }); const structured model.withStructuredOutput(Weather, { method: functionCalling, strict: true, }); const result await structured.invoke(Whats the weather in San Francisco?);优先级规则当多个来源同时设置了strict时优先级为调用级strict例如bindTools(..., { strict })、withConfig({ strict })、withStructuredOutput(..., { strict })工具级strict例如extras.strict、OpenAI 风格工具上的function.strict、原生 Anthropic 风格工具上的strict也就是说工具级strict只相当于“该工具自己选择加入时的回退默认值”如果调用已经显式指定了strict那么该值会覆盖请求中所有工具。关于withStructuredOutput的 method 限制Anthropic 的strict是工具定义tool definition的属性因此它只在method: functionCalling默认值下生效——此时结构化输出由一次严格工具调用来产生。另一种方法jsonSchema使用 Anthropic 原生结构化输出能力不接受strict。将strict与jsonSchema或jsonMode一起传入会直接抛出异常以避免该选项被静默丢弃。如果你想要严格校验的输出请使用默认的functionCalling方法。源码印证strict 的解析与合并逻辑上述优先级在 chat_models.ts 的formatStructuredToolToAnthropic()中实现。该私有方法负责把 LangChain 各种形态的工具LangChaintool、OpenAI 风格工具、原生 Anthropic 风格工具统一格式化为 Anthropic API 的tool对象关键逻辑是// OpenAI 风格工具调用级 fields.strict 优先其次读 function.strict const strict fields?.strict ?? functionStrict; // LangChain 工具调用级 strict 优先其次读 extras.strict const { strict: extrasStrict, ...restExtras } tool.extras ? AnthropicToolExtrasSchema.parse(tool.extras) : {}; const strict fields?.strict ?? extrasStrict;??空值合并运算符正是文档所述“调用级优先、工具级兜底”的直接体现。strict同时也被暴露为ChatAnthropicCallOptions的可选字段见 chat_models.tsbindTools(tools, { strict })在 bindTools 实现 中会把它作为fields.strict传入上述格式化方法。而withStructuredOutput在method不是functionCalling时传入strict会抛错的约束对应源码 chat_models.ts 中的显式校验。集成测试 chat_models-strict.int.test.ts 则从行为侧验证了这套机制它分别用model.bindTools([getWeather], { strict: true })与带extras: { strict: true }的工具发起真实请求并断言返回的tool_calls.args能够通过 zod Schema 解析证明严格模式下模型入参确实符合 Schema。内置工具tools 命名空间除模型类外该包还提供一组 LangChain 兼容的 Anthropic 内置工具包装器统一从tools命名空间导出定义于 tools/index.ts。这些工具可以绑定到ChatAnthropicbindTools()或任意 ReactAgent 上使用。当前仓库实现的工具全集工厂函数版本标识实现文件memory_20250818跨会话内存文件tools/memory.tswebSearch_20250305网页搜索tools/webSearch.tswebFetch_20250910网页/PDF 抓取tools/webFetch.tstoolSearchRegex_20251119正则检索工具tools/toolSearch.tstoolSearchBM25_20251119BM25 自然语言检索工具tools/toolSearch.tstextEditor_20250728文本编辑器tools/textEditor.tscomputer_20251124/computer_20250124计算机操作tools/computer.tscodeExecution_20250825沙箱代码执行tools/codeExecution.tsbash_20250124持久化 Bash 会话tools/bash.tsmcpToolset_20251120MCP 服务器工具集tools/mcpToolset.tsMemory Toolmemory_20250818内存工具让 Claude 通过一个内存文件目录在多次对话之间存取信息。Claude 可以创建、读取、更新和删除文件文件在会话间持久化从而积累知识而不必把所有内容塞进上下文窗口。import { ChatAnthropic, tools } from langchain/anthropic; // 创建一个简单的内存文件存储或接入你自己的持久化层 const files new Mapstring, string(); const memory tools.memory_20250818({ execute: async (command) { switch (command.command) { case view: if (!command.path || command.path /) { return Array.from(files.keys()).join(\n) || Directory is empty.; } return ( files.get(command.path) ?? Error: File not found: ${command.path} ); case create: files.set(command.path!, command.file_text ?? ); return Successfully created file: ${command.path}; case str_replace: const content files.get(command.path!); if (content command.old_str) { files.set( command.path!, content.replace(command.old_str, command.new_str ?? ) ); } return Successfully replaced text in: ${command.path}; case delete: files.delete(command.path!); return Successfully deleted: ${command.path}; // 其他命令insert、rename 等按需处理 default: return Unknown command; } }, }); const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); const llmWithMemory llm.bindTools([memory]); const response await llmWithMemory.invoke( Remember that my favorite programming language is TypeScript );Web Search ToolwebSearch_20250305网页搜索工具让 Claude 直接访问实时网页内容回答超出其知识截止日期的问题并会在回答中自动引用搜索结果来源。import { ChatAnthropic, tools } from langchain/anthropic; const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); // 基本用法 const response await llm.invoke(What is the weather in NYC?, { tools: [tools.webSearch_20250305()], });完整配置选项const response await llm.invoke(Latest news about AI?, { tools: [ tools.webSearch_20250305({ // 该工具在单次 API 请求中可被调用的最大次数 maxUses: 5, // 只包含这些域名的结果 allowedDomains: [reuters.com, bbc.com], // 或屏蔽特定域名不能与 allowedDomains 同时使用 // blockedDomains: [example.com], // 提供用户位置以获得更相关的结果 userLocation: { type: approximate, city: San Francisco, region: California, country: US, timezone: America/Los_Angeles, }, }), ], });从 webSearch.ts 的WebSearch20250305Options接口看文档未展开但源码支持的选项还有cacheControl在此内容块创建缓存断点、deferLoading为 true 时工具不会出现在初始 system prompt 中仅在通过 tool search 的tool_reference返回时才加载、以及strict为 true 时只返回允许域名内的结果。工厂函数最终把这些驼峰字段一一映射为 Anthropic API 的下划线参数如allowed_domains、user_location你可以按此接口签名核对参数类型。Web Fetch ToolwebFetch_20250910网页抓取工具让 Claude 从指定网页和 PDF 文档中获取完整内容。限制是Claude 只能抓取用户明确提供的 URL或来自此前 web search / web fetch 结果的 URL。安全警告在 Claude 处理不可信输入同时又接触敏感数据的环境中启用 web fetch 工具会带来数据外泄风险。建议仅在可信环境或处理非敏感数据时使用。import { ChatAnthropic, tools } from langchain/anthropic; const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); // 基本用法 - 抓取 URL 内容 const response await llm.invoke( Please analyze the content at https://example.com/article, { tools: [tools.webFetch_20250910()] } );配置选项const response await llm.invoke( Summarize this research paper: https://arxiv.org/abs/2024.12345, { tools: [ tools.webFetch_20250910({ // 单次 API 请求中可被调用的最大次数 maxUses: 5, // 只从这些域名抓取 allowedDomains: [arxiv.org, example.com], // 或屏蔽特定域名不能与 allowedDomains 同时使用 // blockedDomains: [example.com], // 为抓取内容启用引用可选与 web search 不同 citations: { enabled: true }, // 内容最大长度token 数帮助控制 token 用量 maxContentTokens: 50000, }), ], } );citations与 web search 的一个关键区别webFetch.ts 的接口注释中明确说明web search 的引用始终开启而 web fetch 的引用是可选的。web 搜索与 web fetch 可以组合使用实现“先检索、再深读”的信息采集流程import { tools } from langchain/anthropic; const response await llm.invoke( Find recent articles about quantum computing and analyze the most relevant one, { tools: [ tools.webSearch_20250305({ maxUses: 3 }), tools.webFetch_20250910({ maxUses: 5, citations: { enabled: true } }), ], } );Tool Search Tools按需发现海量工具工具检索工具让 Claude 在拥有数百甚至数千个工具时动态地按需发现和加载它们——不必把所有工具都塞进上下文窗口。两个变体toolSearchRegex_20251119Claude 构造正则表达式使用 Pythonre.search()语法来搜索工具toolSearchBM25_20251119Claude 用自然语言查询基于 BM25 算法搜索工具。import { ChatAnthropic, tools } from langchain/anthropic; import { tool } from langchain; import { z } from zod; const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); // 用 defer_loading 创建可被搜索发现的工具 const getWeather tool( async (input: { location: string }) { return Weather in ${input.location}: Sunny, 72°F; }, { name: get_weather, description: Get the weather at a specific location, schema: z.object({ location: z.string(), }), extras: { defer_loading: true }, } ); const getNews tool( async (input: { topic: string }) { return Latest news about ${input.topic}...; }, { name: get_news, description: Get the latest news about a topic, schema: z.object({ topic: z.string(), }), extras: { defer_loading: true }, } ); // Claude 会在需要时搜索并发现工具 const response await llm.invoke(What is the weather in San Francisco?, { tools: [tools.toolSearchRegex_20251119(), getWeather, getNews], });使用 BM25 变体进行自然语言检索import { tools } from langchain/anthropic; const response await llm.invoke(What is the weather in San Francisco?, { tools: [tools.toolSearchBM25_20251119(), getWeather, getNews], });这里defer_loading正是把 LangChain 自定义工具标记为“延迟加载”的关键从 chat_models.ts 的formatStructuredToolToAnthropic实现看tool.extras经AnthropicToolExtrasSchema解析后会把除strict之外的字段如defer_loading原样展开到最终的工具定义上从而被 Anthropic API 识别。Text Editor TooltextEditor_20250728文本编辑工具让 Claude 查看和修改文本文件用于调试、修复和改进代码或文档。可用命令view—— 查看文件内容或列出目录内容str_replace—— 替换文件中的指定文本create—— 用指定内容创建新文件insert—— 在指定行号处插入文本import fs from node:fs; import { ChatAnthropic, tools } from langchain/anthropic; const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); const textEditor tools.textEditor_20250728({ async execute(args) { switch (args.command) { case view: const content fs.readFileSync(args.path, utf-8); // 返回带行号的内容方便 Claude 引用 return content .split(\n) .map((line, i) ${i 1}: ${line}) .join(\n); case str_replace: let fileContent fs.readFileSync(args.path, utf-8); fileContent fileContent.replace(args.old_str, args.new_str); fs.writeFileSync(args.path, fileContent); return Successfully replaced text.; case create: fs.writeFileSync(args.path, args.file_text); return Successfully created file: ${args.path}; case insert: const lines fs.readFileSync(args.path, utf-8).split(\n); lines.splice(args.insert_line, 0, args.new_str); fs.writeFileSync(args.path, lines.join(\n)); return Successfully inserted text at line ${args.insert_line}; default: return Unknown command; } }, // 可选限制查看时返回的文件内容长度 maxCharacters: 10000, }); const llmWithEditor llm.bindTools([textEditor]); const response await llmWithEditor.invoke( Theres a syntax error in my primes.py file. Can you help me fix it? );Computer Use Tool计算机操作工具让 Claude 通过截屏、鼠标控制与键盘输入与桌面环境交互实现自主桌面操作。安全警告Computer use 是 beta 功能具有独特风险。请使用专用的虚拟机或最小权限容器避免其接触敏感数据。两个变体computer_20251124—— 面向 Claude Opus 4.5支持 zoom 放大查看computer_20250124—— 面向 Claude 4 与 Claude 3.7 系列模型可用动作包括screenshot截屏、left_click/right_click/middle_click坐标点击、double_click/triple_click多次点击、left_click_drag拖拽、left_mouse_down/left_mouse_up细粒度鼠标控制、scroll滚动、type输入文本、key按键/快捷键、mouse_move移动光标、hold_key长按某键的同时执行其他动作、wait等待指定时长、zoom全分辨率查看特定屏幕区域仅 Claude Opus 4.5 可用。import { ChatAnthropic, tools, type Computer20250124Action, } from langchain/anthropic; const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); const computer tools.computer_20250124({ // 必填显示器尺寸 displayWidthPx: 1024, displayHeightPx: 768, // 可选X11 显示器编号 displayNumber: 1, execute: async (action: Computer20250124Action) { switch (action.action) { case screenshot: // 捕获屏幕并返回 base64 编码截图 // ... case left_click: // 在指定坐标点击 // ... } }, }); const llmWithComputer llm.bindTools([computer]); const response await llmWithComputer.invoke( Save a picture of a cat to my desktop. );带 zoom 能力的 Opus 4.5 变体import { tools } from langchain/anthropic; const computer tools.computer_20251124({ displayWidthPx: 1920, displayHeightPx: 1080, // 启用 zoom用于细致查看屏幕区域 enableZoom: true, execute: async (action) { // 处理包括 zoom 在内的动作 // ... }, });Code Execution ToolcodeExecution_20250825代码执行工具允许 Claude 在一个安全、沙箱化的环境中运行 Bash 命令并操作文件用于数据分析、可视化、计算和文件处理。提供该工具后Claude 自动获得Bash 命令—— 执行 shell 命令文件操作—— 直接创建、查看、编辑文件import { ChatAnthropic, tools } from langchain/anthropic; const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); // 基本用法 - 计算与数据分析 const response await llm.invoke( Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], { tools: [tools.codeExecution_20250825()] } ); // 文件操作与可视化 const response2 await llm.invoke( Create a matplotlib visualization of sales data and save it as chart.png, { tools: [tools.codeExecution_20250825()] } );容器复用——多步工作流中保持文件状态// 第一次请求 - 创建容器 const response1 await llm.invoke(Write a random number to /tmp/number.txt, { tools: [tools.codeExecution_20250825()], }); // 从响应中提取容器 ID 供复用 const containerId response1.response_metadata?.container?.id; // 第二次请求 - 复用容器以访问该文件 const response2 await llm.invoke( Read /tmp/number.txt and calculate its square, { tools: [tools.codeExecution_20250825()], container: containerId, } );对应源码中container是ChatAnthropicCallOptions的正式字段chat_models.ts容器 ID用于代码执行的多轮文件持久化最终在请求参数组装时直接透传给 Anthropic APIchat_models.ts。Bash Toolbash_20250124Bash 工具在持久化 bash 会话中执行 shell 命令。与沙箱化的 code execution 不同它要求你自行提供执行环境。安全警告bash 工具提供直接系统访问权限。请落实安全措施隔离环境Docker/VM、命令过滤、资源限制。特性持久化 bash 会话命令间保持状态、任意 shell 命令执行、环境变量与工作目录访问、命令链管道、重定向、脚本。命令形态执行命令{ command: ls -la }重启会话{ restart: true }。import { ChatAnthropic, tools } from langchain/anthropic; import { execSync } from child_process; const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); const bash tools.bash_20250124({ execute: async (args) { if (args.restart) { // 重置会话状态 return Bash session restarted; } try { const output execSync(args.command, { encoding: utf-8, timeout: 30000, }); return output; } catch (error) { return Error: ${(error as Error).message}; } }, }); const llmWithBash llm.bindTools([bash]); const response await llmWithBash.invoke( List all Python files in the current directory ); // 处理工具调用并执行命令 console.log(response.tool_calls?.[0].name); // bash console.log(response.tool_calls?.[0].args.command); // ls -la *.pyMCP ToolsetmcpToolset_20251120MCP 工具集让 Claude 通过 Messages API 直接连接远程 MCPModel Context Protocol服务器无需你自己实现 MCP 客户端。关键特性直接 API 集成—— 不必实现 MCP 客户端即可连接 MCP 服务器工具调用支持—— 通过 Messages API 访问 MCP 工具灵活的工具配置—— 启用全部工具、允许列表、或屏蔽列表逐工具配置—— 对单个工具施加自定义设置OAuth 认证—— 支持 OAuth Bearer Token多服务器—— 单次请求连接多个 MCP 服务器基本用法——启用某服务器全部工具import { ChatAnthropic, tools } from langchain/anthropic; const llm new ChatAnthropic({ model: claude-sonnet-4-5-20250929, }); const response await llm.invoke(What tools do you have available?, { mcp_servers: [ { type: url, url: https://example-server.modelcontextprotocol.io/sse, name: example-mcp, authorization_token: YOUR_TOKEN, }, ], tools: [tools.mcpToolset_20251120({ serverName: example-mcp })], });允许列表模式——默认关闭、只开指定工具const response await llm.invoke(Search for events, { mcp_servers: [ { type: url, url: https://calendar.example.com/sse, name: google-calendar-mcp, authorization_token: YOUR_TOKEN, }, ], tools: [ tools.mcpToolset_20251120({ serverName: google-calendar-mcp, // 默认禁用所有工具 defaultConfig: { enabled: false }, // 显式启用这两个工具 configs: { search_events: { enabled: true }, create_event: { enabled: true }, }, }), ], });屏蔽列表模式——默认全开、只关危险工具const response await llm.invoke(List my events, { mcp_servers: [ { type: url, url: https://calendar.example.com/sse, name: google-calendar-mcp, authorization_token: YOUR_TOKEN, }, ], tools: [ tools.mcpToolset_20251120({ serverName: google-calendar-mcp, // 默认全部启用仅关闭危险工具 configs: { delete_all_events: { enabled: false }, share_calendar_publicly: { enabled: false }, }, }), ], });多 MCP 服务器const response await llm.invoke(Use tools from both servers, { mcp_servers: [ { type: url, url: https://mcp.example1.com/sse, name: mcp-server-1, authorization_token: TOKEN1, }, { type: url, url: https://mcp.example2.com/sse, name: mcp-server-2, authorization_token: TOKEN2, }, ], tools: [ tools.mcpToolset_20251120({ serverName: mcp-server-1 }), tools.mcpToolset_20251120({ serverName: mcp-server-2, defaultConfig: { deferLoading: true }, }), ], });结合 Tool Search——用延迟加载实现按需工具发现const response await llm.invoke(Find and use the right tool, { mcp_servers: [ { type: url, url: https://example.com/sse, name: example-mcp, }, ], tools: [ tools.toolSearchRegex_20251119(), tools.mcpToolset_20251120({ serverName: example-mcp, defaultConfig: { deferLoading: true }, }), ], });源码层面mcp_servers同样是ChatAnthropicCallOptions的正式字段chat_models.ts在invocationParams()中对数组做校验与映射后透传给 APIchat_models.ts。另有一个值得注意的实现细节chat_models.ts 定义了MCP_CREDENTIALS_REDACTED **REDACTED**常量从源码结构看authorization_token等凭证在写入 LangSmith 追踪等场景时会被脱敏处理避免令牌泄漏到日志中。本包本地开发流程若要参与开发该包按 README 开发章节 的步骤操作在 monorepo 环境内执行安装依赖pnpm install构建pnpm build或在仓库根目录用 filter 指定该包pnpm build --filter langchain/anthropic对应 package.json 中build脚本实际执行的是turbo build:compile --filter langchain/anthropic编译工具为 tsdown。运行测试测试文件放在src/下的tests/目录单元测试以.test.ts结尾集成测试以.int.test.ts结尾可对照 src/tests 下的chat_models.test.ts、chat_models.int.test.ts等pnpm test pnpm test:int此外 package.json 还定义了test:standard:unit/test:standard:int脚本用于运行langchain/standard-tests提供的跨 provider 标准化测试套件对应 chat_models.standard.int.test.ts 等文件。Lint 与格式化pnpm lint pnpm format新增入口点如果导出了新文件要么在src/index.ts中 import 并 re-export要么把它加入package.json的exports字段然后运行pnpm build生成新的入口点当前主入口 src/index.ts 仅导出chat_models、convertPromptToAnthropic、ChatAnthropicContentBlock类型与tools命名空间。发布执行pnpm build后运行npm publish。小结langchain/anthropic提供ChatAnthropic模型类与tools命名空间下的 11 个内置工具工厂覆盖内存、搜索、抓取、工具检索、文件编辑、计算机操作、代码执行、Bash 与 MCP 连接strict tool use 支持调用级bindTools/withConfig/withStructuredOutput与工具级extras.strict两个粒度调用级优先strict与jsonSchema方法互斥且会显式抛错这一规则在 chat_models.ts 的格式化逻辑与 strict 集成测试 中均得到印证maxTokens、container代码执行容器复用、mcp_servers、strict等关键参数均为ChatAnthropicCallOptions的正式字段可放心在invoke()的 options 中按请求粒度传入开发侧遵循 monorepo 规范pnpm build --filter langchain/anthropic构建、.test.ts/.int.test.ts双轨测试、pnpm lint pnpm format保证代码风格。【免费下载链接】langchainjsThe agent engineering platform项目地址: https://gitcode.com/GitHub_Trending/la/langchainjs创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表