@genkit-ai/anthropic

中文文档
0.7.0发布于 2026/11/04Apache-2.0TypeScriptESM + CJS近 30 天下载 4.2万

Genkit AI framework plugin for Anthropic APIs.

原始使用文档
文档目录14 节
  1. Supported models
  2. Installation
  3. Usage
  4. Initialize
  5. Basic examples
  6. Multi-modal prompt
  7. Extended thinking
  8. Document Citations
  9. Prompt Caching
  10. Beta API Limitations
  11. Within a flow
  12. Direct model usage (without Genkit instance)
  13. Acknowledgements
  14. Credits

Genkit Anthropic AI Plugin

@genkit-ai/anthropic is Anthropic plugin for Genkit. It supersedes the earlier community package genkitx-anthropic and is now maintained by Google.

Building with a coding agent? Install the Genkit JS skill first.

npx skills add genkit-ai/skills --skill developing-genkit-js

It teaches your agent the current Genkit JS APIs and common gotchas. Source, manual install and skills for other languages: genkit-ai/skills.

Supported models

The plugin supports the most recent Anthropic models like Claude Haiku 4.5, Claude Sonnet 4.5, and Claude Opus 4.5. Additionally, the plugin supports all of the non-retired older models.

Installation

Install the plugin in your project with your favorite package manager:

  • npm install @genkit-ai/anthropic
  • yarn add @genkit-ai/anthropic
  • pnpm add @genkit-ai/anthropic

Usage

Initialize

import { genkit } from "genkit";
import { anthropic } from "@genkit-ai/anthropic";

const ai = genkit({
  plugins: [anthropic({ apiKey: process.env.ANTHROPIC_API_KEY })],
  // specify a default model for generate here if you wish:
  model: anthropic.model("claude-sonnet-4-5"),
});

Basic examples

The simplest way to generate text is by using the generate method:

const response = await ai.generate({
  model: anthropic.model("claude-haiku-4-5"),
  prompt: "Tell me a joke.",
});

console.log(response.text);

Multi-modal prompt

// ...initialize Genkit instance (as shown above)...

const response = await ai.generate({
  prompt: [
    { text: "What animal is in the photo?" },
    { media: { url: imageUrl } },
  ],
});
console.log(response.text);

Extended thinking

Claude 4.5 models can expose their internal reasoning. Enable it per-request with the Anthropic thinking config and read the reasoning from the response:

const response = await ai.generate({
  prompt: "Walk me through your reasoning for Fermat’s little theorem.",
  config: {
    thinking: {
      enabled: true,
      budgetTokens: 4096, // Must be >= 1024 and less than max_tokens
    },
  },
});

console.log(response.text); // Final assistant answer
console.log(response.reasoning); // Summarized thinking steps

When thinking is enabled, request bodies sent through the plugin include the thinking payload ({ type: 'enabled', budget_tokens: … }) that Anthropic's API expects, and streamed responses deliver reasoning parts as they arrive so you can render the chain-of-thought incrementally.

Document Citations

Claude can cite specific parts of documents you provide, making it easy to trace where information in the response came from. Use the anthropicDocument() helper to create citable documents. For more details, see the Anthropic Citations documentation.

import { anthropic, anthropicDocument } from "@genkit-ai/anthropic";

const response = await ai.generate({
  model: anthropic.model("claude-sonnet-4-5"),
  messages: [
    {
      role: "user",
      content: [
        anthropicDocument({
          source: {
            type: "text",
            data: "The grass is green. The sky is blue. Water is wet.",
          },
          title: "Basic Facts",
          citations: { enabled: true },
        }),
        { text: "What color is the grass? Cite your source." },
      ],
    },
  ],
});

// Access citations from response parts
const citations = response.message?.content?.flatMap(
  (part) => part.metadata?.citations || [],
) ?? [];

console.log("Citations:", citations);

Important: Citations must be enabled on all documents in a request, or on none of them. You cannot mix documents with citations enabled and disabled in the same request.

Supported document source types:

  • text - Plain text documents (returns char_location citations)
  • base64 - Base64-encoded PDFs (returns page_location citations)
  • url - PDFs accessible via URL (returns page_location citations)
  • content - Custom content blocks with text/images (returns content_block_location citations)
  • file - File references from Anthropic's Files API, beta API only (returns page_location citations)

Citations are returned in the response parts' metadata and include information about the document index, cited text, and location (character indices, page numbers, or block indices depending on the source type).

Prompt Caching

You can cache prompts by adding cache_control metadata to the prompt. Use the cacheControl() helper for type-safe cache configuration. You can cache system messages, user messages, tools, and media.

import { anthropic, cacheControl } from "@genkit-ai/anthropic";

const response = await ai.generate({
  model: anthropic.model("claude-sonnet-4-5"),
  system: {
    text: longSystemPrompt,
    metadata: { ...cacheControl() }, // default: ephemeral
  },
  messages: [
    {
      role: "user",
      content: [{ text: "What is the main idea of the text?" }],
    },
  ],
});

// Or with explicit TTL:
metadata: { ...cacheControl({ ttl: '1h' }) }

// Or using the type directly:
import { type AnthropicCacheControl } from "@genkit-ai/anthropic";
metadata: { cache_control: { type: 'ephemeral', ttl: '5m' } as AnthropicCacheControl }

Note: Caching is only used when the prompt exceeds a certain token length. This token length is documented in the Anthropic API documentation.

Beta API Limitations

The beta API surface provides access to experimental features, but some server-managed tool blocks are not yet supported by this plugin. The following beta API features will cause an error if encountered:

  • web_fetch_tool_result
  • code_execution_tool_result
  • bash_code_execution_tool_result
  • text_editor_code_execution_tool_result
  • mcp_tool_result
  • mcp_tool_use
  • container_upload

Note that server_tool_use and web_search_tool_result ARE supported and work with both stable and beta APIs.

Within a flow

import { z } from "genkit";

// ...initialize Genkit instance (as shown above)...

export const jokeFlow = ai.defineFlow(
  {
    name: "jokeFlow",
    inputSchema: z.string(),
    outputSchema: z.string(),
  },
  async (subject) => {
    const llmResponse = await ai.generate({
      prompt: `tell me a joke about ${subject}`,
    });
    return llmResponse.text;
  },
);

Direct model usage (without Genkit instance)

The plugin supports Genkit Plugin API v2, which allows you to use models directly without initializing the full Genkit framework:

import { anthropic } from "@genkit-ai/anthropic";

// Create a model reference directly
const claude = anthropic.model("claude-sonnet-4-5");

// Use the model directly
const response = await claude({
  messages: [
    {
      role: "user",
      content: [{ text: "Tell me a joke." }],
    },
  ],
});

console.log(response);

You can also create model references using the plugin's model() method:

import { anthropic } from "@genkit-ai/anthropic";

// Create model references
const claudeHaiku45 = anthropic.model("claude-haiku-4-5");
const claudeSonnet45 = anthropic.model("claude-sonnet-4-5");
const claudeOpus45 = anthropic.model("claude-opus-4-5");

// Use the model reference directly
const response = await claudeSonnet45({
  messages: [
    {
      role: "user",
      content: [{ text: "Hello!" }],
    },
  ],
});

This approach is useful for:

  • Framework developers who need raw model access
  • Testing models in isolation
  • Using Genkit models in non-Genkit applications

Acknowledgements

This plugin builds on the community work published as genkitx-anthropic by Bloom Labs Inc. Their Apache 2.0–licensed implementation provided the foundation for this maintained package.

Credits

This plugin is maintained by Google with acknowledgement to the community contributions from Bloom Labs Inc.

版本与发布记录

@genkit-ai/anthropic 共发布 15 个版本,首次发布于 2026/01/23;过去 12 个月发布了 15 个版本。

版本发布日期距今
0.7.0latest2026/11/0412 天前
0.6.02026/10/2225 天前
0.6.0-rc.3next2026/10/2225 天前
0.6.0-rc.22026/10/2126 天前
0.6.0-rc.12026/10/091 个月前
0.6.0-rc.02026/10/091 个月前

关于 @genkit-ai/anthropic 的常见问题

@genkit-ai/anthropic 是什么?

Genkit AI framework plugin for Anthropic APIs.

如何安装 @genkit-ai/anthropic?

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

@genkit-ai/anthropic 支持 TypeScript 吗?

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

@genkit-ai/anthropic 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@genkit-ai/anthropic 可以商用吗?

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

@genkit-ai/anthropic 的下载量有多少?

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

@genkit-ai/anthropic 还在维护吗?

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