@ai-sdk-tool/parser

中文文档
5.1.6发布于 2026/07/26Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 3.6万

AI SDK middleware for tool call parsing

原始使用文档
文档目录12 节
  1. Install
  2. AI SDK compatibility
  3. Upgrading to v7
  4. Tool-result media (images / files)
  5. Package map
  6. Quick start
  7. Choose middleware
  8. Build custom middleware
  9. Tool choice
  10. Streaming semantics
  11. Local development
  12. Examples in this repo
AI SDK Tool monorepo banner

npm - parser npm downloads - parser codecov

AI SDK middleware for parsing tool calls from models that do not natively support tools.

This package is ESM-only. Use import or dynamic import(); CommonJS require() is not supported.

Install

# Current stable line (v5.x) — built for AI SDK v7
pnpm add @ai-sdk-tool/parser

If you still need the AI SDK v6 line, pin the previous major:

pnpm add @ai-sdk-tool/parser@4

AI SDK compatibility

Fact-checked from this repo CHANGELOG.md and npm release metadata (as of 2026-06-25).

@ai-sdk-tool/parser majorAI SDK majorMaintenance status
v1.xv4.xLegacy (not actively maintained)
v2.xv5.xLegacy (not actively maintained)
v3.xv6.xLegacy (not actively maintained)
v4.xv6.xPrevious stable line
v5.xv7.xActive (current latest line)

Note: there is no separate formal EOL announcement in releases/changelog for v1-v3; "legacy" here means non-current release lines.

Upgrading to v7

The 5.0.0 line targets AI SDK v7 (provider specification v4). It is the current latest line; the v4.x line remains available for AI SDK v6.

pnpm add @ai-sdk-tool/parser

Breaking changes vs. the v4.x line:

  • Requires ai@^7 / @ai-sdk/provider@^4. This line is not compatible with the AI SDK v6 line. The middleware declares specificationVersion: "v4" and uses the LanguageModelV4* provider types.
  • @ai-sdk/provider and @ai-sdk/provider-utils are now peer dependencies. They are normally satisfied transitively by ai@7, so most apps need no extra install. If your package manager does not auto-install peers, add them explicitly:
    pnpm add @ai-sdk/provider@^4 @ai-sdk/provider-utils@^5
    
  • Node.js >=22 is required (Node 18 is end-of-life).
  • Tool-result file parts now use the v4 tagged file shape ({ type: "data", data }) instead of a bare data string. This only affects code that constructs tool-result file parts directly.

Tool-result media (images / files)

When a tool returns multimodal output: { type: "content", value: [...] }, the middleware projects that into the next model turn:

mediaStrategy.modeBehavior
model (default)Forward canonical { type: "file", data } content as model file parts. Protocol wrappers stay as adjacent text.
placeholderText-only fallback ([Image: image/png], [File URL: ...], …) for non-vision models.
autoKeep original tool content parts when capabilities enable that media kind; otherwise placeholder.
import {
  createHermesToolResponseFormatter,
  createToolMiddleware,
  hermesProtocol,
  hermesSystemPromptTemplate,
} from "@ai-sdk-tool/parser";

// Default preconfigured middleware already uses model media mode.
// For text-only models, opt into placeholders:
const textOnlyMiddleware = createToolMiddleware({
  protocol: hermesProtocol(),
  toolSystemPromptTemplate: hermesSystemPromptTemplate,
  toolResponsePromptTemplate: createHermesToolResponseFormatter({
    mediaStrategy: { mode: "placeholder" },
  }),
});

// YAML XML tool *responses* reuse Morph's response formatter — use the Morph
// factory when you need mediaStrategy options with yamlXmlProtocol.

Only http: / https: file URLs are forwarded as model file parts; other schemes become placeholders. String URLs from JSON-deserialized tool results are reparsed to URL objects intentionally.

User-message images are unchanged — they pass through as-is.

Status: 5.0.0 is the stable release line. Pin an exact version if you need reproducible installs.

Package map

ImportPurpose
@ai-sdk-tool/parserMain middleware factory, preconfigured middleware, protocol exports
@ai-sdk-tool/parser/communityCommunity middleware (Sijawara, UI-TARS)

Quick start

import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { morphXmlToolMiddleware } from "@ai-sdk-tool/parser";
import { stepCountIs, streamText, wrapLanguageModel } from "ai";
import { z } from "zod";

const model = createOpenAICompatible({
  name: "openrouter",
  apiKey: process.env.OPENROUTER_API_KEY,
  baseURL: "https://openrouter.ai/api/v1",
})("arcee-ai/trinity-large-preview:free");

const result = streamText({
  model: wrapLanguageModel({
    model,
    middleware: morphXmlToolMiddleware,
  }),
  stopWhen: stepCountIs(4),
  prompt: "What is the weather in Seoul?",
  tools: {
    get_weather: {
      description: "Get weather by city name",
      inputSchema: z.object({ city: z.string() }),
      execute: async ({ city }) => ({ city, condition: "sunny", celsius: 23 }),
    },
  },
});

for await (const part of result.fullStream) {
  // text-delta / tool-input-start / tool-input-delta / tool-input-end / tool-call / tool-result
}

Choose middleware

Use the preconfigured middleware exports from src/preconfigured-middleware.ts:

MiddlewareBest for
hermesToolMiddlewareJSON-style tool payloads
morphXmlToolMiddlewareXML-style payloads with schema-aware coercion
yamlXmlToolMiddlewareXML tool tags + YAML bodies
qwen3CoderToolMiddlewareQwen/UI-TARS style <tool_call> markup

Build custom middleware

import { createToolMiddleware, qwen3CoderProtocol } from "@ai-sdk-tool/parser";

export const myToolMiddleware = createToolMiddleware({
  protocol: qwen3CoderProtocol,
  toolSystemPromptTemplate: (tools) =>
    `Use these tools and emit <tool_call> blocks only: ${JSON.stringify(tools)}`,
});

Tool choice

  • toolChoice: "auto" (default) parses tool calls out of the model text.
  • toolChoice: "required" and toolChoice: { type: "tool", toolName } are emulated through JSON responseFormat constraints.
  • toolChoice: "none" skips tool prompt injection and tool-call parsing entirely; tool-call history in the conversation is still serialized to text.

Streaming semantics

  • Stream parsers emit tool-input-start, tool-input-delta, and tool-input-end when a tool input can be incrementally reconstructed.
  • tool-input-start.id, tool-input-end.id, and final tool-call.toolCallId are reconciled to the same ID.
  • emitRawToolCallTextOnError defaults to false; malformed tool-call markup is suppressed from text-delta unless explicitly enabled.
  • Text blocks that consist of a bare {"name": ..., "arguments": ...} payload (or a fenced ```json block) for a known tool are recovered into tool calls in both generate and stream paths, and finishReason is normalized to tool-calls whenever tool calls were parsed.

Configure parser error behavior through providerOptions.toolCallMiddleware:

const result = streamText({
  // ...
  providerOptions: {
    toolCallMiddleware: {
      onError: (message, metadata) => {
        console.warn(message, metadata);
      },
      emitRawToolCallTextOnError: false,
    },
  },
});

Local development

pnpm build
pnpm test
pnpm check:biome
pnpm check:types
pnpm check

Examples in this repo

  • Parser middleware examples: examples/parser-core/README.md
  • RXML examples: examples/rxml-core/README.md

Run one example from repo root:

pnpm dlx tsx examples/parser-core/src/01-stream-tool-call.ts

版本与发布记录

@ai-sdk-tool/parser 共发布 82 个版本,首次发布于 2025/04/20;过去 12 个月发布了 54 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
5.1.6latest2026/07/263 个月前
5.1.52026/07/263 个月前
5.1.42026/07/133 个月前
5.1.32026/07/133 个月前
5.1.22026/07/093 个月前
5.1.12026/07/064 个月前

其他发布通道:canary → 3.0.0-canary.3,beta → 5.0.0-beta.1。

关于 @ai-sdk-tool/parser 的常见问题

@ai-sdk-tool/parser 是什么?

AI SDK middleware for tool call parsing

如何安装 @ai-sdk-tool/parser?

在项目目录运行 npm install @ai-sdk-tool/parser,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@ai-sdk/provider(^4.0.0)、@ai-sdk/provider-utils(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ai-sdk-tool/parser 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ai-sdk-tool/parser 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@ai-sdk-tool/parser 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@ai-sdk-tool/parser 可以商用吗?

@ai-sdk-tool/parser 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@ai-sdk-tool/parser 的下载量有多少?

根据 npm 官方下载统计,@ai-sdk-tool/parser 在 2026/10/05 – 2026/11/03 这 30 天内被下载 35,797 次,日均约 1,193 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ai-sdk-tool/parser 还在维护吗?

最新版本 5.1.6 发布于 2026/07/26(3 个月前);至今共发布 82 个版本,其中过去 12 个月发布了 54 个;首次发布于 2025/04/20。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。