UNPKG

@genkit-ai/anthropic

Version:

Genkit AI framework plugin for Anthropic APIs.

1 lines 11.2 kB
{"version":3,"sources":["../src/types.ts"],"sourcesContent":["/**\n * Copyright 2024 Bloom Labs Inc\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type Anthropic from '@anthropic-ai/sdk';\nimport type { CacheControlEphemeral } from '@anthropic-ai/sdk/resources/messages';\nimport { z } from 'genkit';\nimport { GenerationCommonConfigSchema } from 'genkit/model';\n\nexport type { CacheControlEphemeral as AnthropicCacheControl };\n\n/**\n * Internal symbol for dependency injection in tests.\n * Not part of the public API.\n * @internal\n */\nexport const __testClient = Symbol('testClient');\n\n/**\n * Plugin configuration options for the Anthropic plugin.\n */\nexport interface PluginOptions {\n apiKey?: string;\n /** Default API surface for all requests unless overridden per-request. */\n apiVersion?: 'stable' | 'beta';\n}\n\n/**\n * Internal plugin options that include test client injection.\n * @internal\n */\nexport interface InternalPluginOptions extends PluginOptions {\n [__testClient]?: Anthropic;\n}\n\n/**\n * Shared parameters required to construct Claude helpers.\n */\ninterface ClaudeHelperParamsBase {\n name: string;\n client: Anthropic;\n defaultApiVersion?: 'stable' | 'beta';\n}\n\n/**\n * Parameters for creating a Claude model action.\n */\nexport interface ClaudeModelParams extends ClaudeHelperParamsBase {}\n\n/**\n * Parameters for creating a Claude runner.\n */\nexport interface ClaudeRunnerParams extends ClaudeHelperParamsBase {}\n\nexport const ThinkingConfigSchema = z\n .object({\n enabled: z.boolean().optional(),\n budgetTokens: z.number().min(1_024).optional(),\n adaptive: z.boolean().optional(),\n display: z.enum(['summarized', 'omitted']).optional(),\n })\n .passthrough()\n .superRefine((value, ctx) => {\n if (value.enabled && value.adaptive) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['adaptive'],\n message:\n 'Cannot use both enabled and adaptive thinking modes simultaneously',\n });\n }\n\n if (value.enabled) {\n if (value.budgetTokens === undefined) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['budgetTokens'],\n message: 'budgetTokens is required when thinking is enabled',\n });\n } else if (!Number.isInteger(value.budgetTokens)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n path: ['budgetTokens'],\n message: 'budgetTokens must be an integer',\n });\n }\n }\n });\n\nexport const AnthropicConfigSchema = GenerationCommonConfigSchema.extend({\n tool_choice: z\n .union([\n z\n .object({\n type: z.literal('auto'),\n })\n .passthrough(),\n z\n .object({\n type: z.literal('any'),\n })\n .passthrough(),\n z\n .object({\n type: z.literal('tool'),\n name: z.string(),\n })\n .passthrough(),\n ])\n .describe(\n 'The tool choice to use for the request. This can be used to specify the tool to use for the request. If not specified, the model will choose the tool to use.'\n )\n .optional(),\n metadata: z\n .object({\n user_id: z.string().optional(),\n })\n .describe('The metadata to include in the request.')\n .passthrough()\n .optional(),\n /** Optional shorthand to pick API surface for this request. */\n apiVersion: z\n .enum(['stable', 'beta'])\n .optional()\n .describe(\n 'The API version to use for the request. Both stable and beta features are available on the beta API surface.'\n ),\n thinking: ThinkingConfigSchema.optional().describe(\n 'The thinking configuration to use for the request. Thinking is a feature that allows the model to think about the request and provide a better response.'\n ),\n output_config: z\n .object({\n effort: z.enum(['low', 'medium', 'high', 'xhigh']).optional(),\n task_budget: z\n .object({\n type: z.literal('tokens').default('tokens'),\n total: z.number().min(20000),\n })\n .optional(),\n })\n .passthrough()\n .describe(\n 'Configuration for output generation, such as setting the effort parameter and task budgets.'\n )\n .optional(),\n}).passthrough();\n\nexport type ThinkingConfig = z.infer<typeof ThinkingConfigSchema>;\nexport type ClaudeConfig = z.infer<typeof AnthropicConfigSchema>;\nexport type AnthropicConfigSchemaType = typeof AnthropicConfigSchema;\n\n// Backwards compatibility aliases for previous schema naming convention\nexport const AnthropicBaseConfigSchema = AnthropicConfigSchema;\nexport const AnthropicThinkingConfigSchema = AnthropicConfigSchema;\nexport type AnthropicBaseConfigSchemaType = typeof AnthropicConfigSchema;\nexport type AnthropicThinkingConfigSchemaType = typeof AnthropicConfigSchema;\nexport type AnthropicBaseConfig = ClaudeConfig;\nexport type AnthropicThinkingConfig = ClaudeConfig;\n\n/**\n * Media object representation with URL and optional content type.\n */\nexport interface Media {\n url: string;\n contentType?: string;\n}\n\nexport const MediaSchema = z.object({\n url: z.string(),\n contentType: z.string().optional(),\n});\n\nexport const MediaTypeSchema = z.enum([\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'image/webp',\n]);\n\nexport type MediaType = z.infer<typeof MediaTypeSchema>;\n\nexport const MEDIA_TYPES = {\n JPEG: 'image/jpeg',\n PNG: 'image/png',\n GIF: 'image/gif',\n WEBP: 'image/webp',\n} as const satisfies Record<string, MediaType>;\n\n/**\n * Resolve whether beta API should be used for this call.\n * Priority:\n * 1. request.config.apiVersion (per-request override - explicit stable or beta)\n * 2. pluginDefaultApiVersion (plugin-wide default)\n * 3. otherwise stable\n */\nexport function resolveBetaEnabled(\n cfg: ClaudeConfig | undefined,\n pluginDefaultApiVersion?: 'stable' | 'beta'\n): boolean {\n if (cfg?.apiVersion !== undefined) {\n return cfg.apiVersion === 'beta';\n }\n if (pluginDefaultApiVersion === 'beta') return true;\n return false;\n}\n\n/** Plain text document source. */\nexport interface AnthropicTextSource {\n type: 'text';\n data: string;\n mediaType?: string;\n}\n\n/** Base64-encoded document source (e.g., PDF). */\nexport interface AnthropicBase64Source {\n type: 'base64';\n data: string;\n mediaType: string;\n}\n\n/** File reference source (from Files API). */\nexport interface AnthropicFileSource {\n type: 'file';\n fileId: string;\n}\n\n/** Custom content blocks for granular citation control. */\nexport interface AnthropicContentSource {\n type: 'content';\n content: Array<\n | { type: 'text'; text: string }\n | {\n type: 'image';\n source: { type: 'base64'; mediaType: string; data: string };\n }\n >;\n}\n\n/** URL source for PDFs. */\nexport interface AnthropicURLSource {\n type: 'url';\n url: string;\n}\n\n/** Union of all document source types. */\nexport type AnthropicDocumentSource =\n | AnthropicTextSource\n | AnthropicBase64Source\n | AnthropicFileSource\n | AnthropicContentSource\n | AnthropicURLSource;\n\n/** Options for creating an Anthropic document with optional citations. */\nexport interface AnthropicDocumentOptions {\n source: AnthropicDocumentSource;\n title?: string;\n context?: string;\n citations?: { enabled: boolean };\n}\n\n/** Citation from a plain text document (character indices). */\nexport interface CharLocationCitation {\n type: 'char_location';\n citedText: string;\n documentIndex: number;\n documentTitle?: string;\n fileId?: string;\n startCharIndex: number;\n endCharIndex: number;\n}\n\n/** Citation from a PDF document (page numbers). */\nexport interface PageLocationCitation {\n type: 'page_location';\n citedText: string;\n documentIndex: number;\n documentTitle?: string;\n fileId?: string;\n startPageNumber: number;\n endPageNumber: number;\n}\n\n/** Citation from a custom content document (block indices). */\nexport interface ContentBlockLocationCitation {\n type: 'content_block_location';\n citedText: string;\n documentIndex: number;\n documentTitle?: string;\n fileId?: string;\n startBlockIndex: number;\n endBlockIndex: number;\n}\n\n/** Union of all citation types for documents. */\nexport type AnthropicCitation =\n | CharLocationCitation\n | PageLocationCitation\n | ContentBlockLocationCitation;\n"],"mappings":"AAmBA,SAAS,SAAS;AAClB,SAAS,oCAAoC;AAStC,MAAM,eAAe,uBAAO,YAAY;AAsCxC,MAAM,uBAAuB,EACjC,OAAO;AAAA,EACN,SAAS,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC9B,cAAc,EAAE,OAAO,EAAE,IAAI,IAAK,EAAE,SAAS;AAAA,EAC7C,UAAU,EAAE,QAAQ,EAAE,SAAS;AAAA,EAC/B,SAAS,EAAE,KAAK,CAAC,cAAc,SAAS,CAAC,EAAE,SAAS;AACtD,CAAC,EACA,YAAY,EACZ,YAAY,CAAC,OAAO,QAAQ;AAC3B,MAAI,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