🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(llm): route Vertex Claude through Anthropic client (#14388)
Tobias Wochingerdea1cf8a18f5
diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 346fdc9a58..eea4adfd82 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -95,6 +95,7 @@},"dependencies": {"@anthropic-ai/tokenizer": "^0.0.4",+ "@anthropic-ai/vertex-sdk": "^0.17.1","@aws-sdk/client-cloudwatch": "^3.1013.0","@aws-sdk/client-lambda": "^3.1046.0","@aws-sdk/client-s3": "^3.1013.0",diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex 9f3f7a11dd..0dbe952eb3 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -1,5 +1,9 @@import { type ZodType, z } from "zod";+import {+ AnthropicVertex,+ type ClientOptions as AnthropicVertexClientOptions,+} from "@anthropic-ai/vertex-sdk";import { ChatAnthropic, ChatAnthropicInput } from "@langchain/anthropic";import { ChatGoogle } from "@langchain/google";import { ChatBedrockConverse } from "@langchain/aws";@@ -46,6 +50,7 @@ import {} from "./types";import type { BaseCallbackHandler } from "@langchain/core/callbacks/base";import { ProxyAgent } from "undici";+import { GoogleAuth, type GoogleAuthOptions } from "google-auth-library";import { getInternalTracingHandler } from "./getInternalTracingHandler";import { decrypt } from "../../encryption";import {@@ -93,6 +98,10 @@ const NON_RETRYABLE_LLM_ERROR_PATTERNS = [const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);const AZURE_OPENAI_API_KEY_HEADER = "api-key";const ANTHROPIC_API_KEY_HEADER = "x-api-key";+const VERTEX_AI_AUTH_HEADER = "authorization";+const VERTEX_AI_AUTH_SCOPES = [+ "https://www.googleapis.com/auth/cloud-platform",+];// Adapters whose models can return separate reasoning content. We route their// responses through `AIMessage#contentBlocks`, which normalizes provider-specific@@ -120,12 +129,101 @@ const ANTHROPIC_ALWAYS_ADAPTIVE_THINKING_MODELS = ["claude-mythos-5",] as const;+const ANTHROPIC_SAMPLING_PARAM_NORMALIZATION_MODELS = [+ "claude-fable-5",+ "claude-mythos-5",+ "claude-opus-4-8",+ "claude-opus-4-7",+ "claude-sonnet-4-6",+ "claude-sonnet-4-5",+ "claude-opus-4-1",+ "claude-opus-4-5",+ "claude-opus-4-6",+ "claude-haiku-4-5",+] as const;++const ANTHROPIC_VERTEX_MODEL_NAME_PATTERN = /^[A-Za-z0-9_.@-]+$/;++// Vertex region identifiers are lowercase alphanumerics plus hyphens+// (e.g. "us-east5", "europe-west1") with the special "global"/"us"/"eu"+// endpoints. Disallowing every URL delimiter keeps an attacker-controlled+// location from reshaping the Vertex host the SDKs build from it.+const VERTEX_LOCATION_PATTERN = /^[a-z0-9-]+$/;+function isAnthropicAlwaysAdaptiveThinkingModel(modelName: string): boolean {return ANTHROPIC_ALWAYS_ADAPTIVE_THINKING_MODELS.some((model) =>modelName.includes(model),);}+function shouldNormalizeAnthropicSamplingParams(modelName: string): boolean {+ return ANTHROPIC_SAMPLING_PARAM_NORMALIZATION_MODELS.some((model) =>+ modelName.includes(model),+ );+}++function getAnthropicInvocationKwargs(modelParams: ModelParams) {+ if (!isAnthropicAlwaysAdaptiveThinkingModel(modelParams.model)) {+ return modelParams.providerOptions;+ }++ return {+ // @langchain/anthropic currently defaults ChatAnthropic.thinking to+ // { type: "disabled" } and serializes it into every request.+ // Claude Fable 5 and Claude Mythos 5 reject that explicit disabled+ // mode because thinking defaults to adaptive when the field is+ // omitted. Newer ChatAnthropic versions might fix this default, but+ // remove this guard only after a developer has verified that the+ // pinned/newer version no longer sends thinking.disabled by default.+ thinking: undefined,+ ...modelParams.providerOptions,+ };+}++function normalizeAnthropicSamplingParams(+ chatModel: ChatAnthropic,+ modelParams: ModelParams,+) {+ if (!shouldNormalizeAnthropicSamplingParams(modelParams.model)) {+ return;+ }++ if (chatModel.topP === -1) {+ chatModel.topP = undefined;+ }++ // TopP and temperature cannot be specified both,+ // but Langchain is setting placeholder values despite that.+ if (+ modelParams.temperature !== undefined &&+ modelParams.top_p === undefined+ ) {+ chatModel.topP = undefined;+ }++ if (+ modelParams.top_p !== undefined &&+ modelParams.temperature === undefined+ ) {+ chatModel.temperature = undefined;+ }+}++function isClaudeModel(modelName: string): boolean {+ return modelName.toLowerCase().includes("claude");+}++function assertValidAnthropicVertexModelName(modelName: string) {+ if (+ !ANTHROPIC_VERTEX_MODEL_NAME_PATTERN.test(modelName) ||+ modelName.includes("..")+ ) {+ throw new Error(+ "Invalid Anthropic Vertex AI model name. Model names must be a single Vertex model ID segment.",+ );+ }+}+function shouldNormalizeContentBlocks(modelParams: ModelParams): boolean {return (adapterSupportsReasoning(modelParams.adapter) ||@@ -369,34 +467,6 @@ export async function fetchLLMCompletion(let chatModel: ChatOpenAI | ChatAnthropic | ChatBedrockConverse | ChatGoogle;let usesOpenAIResponsesApi = false;if (modelParams.adapter === LLMAdapter.Anthropic) {- const shouldNormalizeAnthropicSamplingParams =- modelParams.model?.includes("claude-fable-5") ||- modelParams.model?.includes("claude-mythos-5") ||- modelParams.model?.includes("claude-opus-4-8") ||- modelParams.model?.includes("claude-opus-4-7") ||- modelParams.model?.includes("claude-sonnet-4-6") ||- modelParams.model?.includes("claude-sonnet-4-5") ||- modelParams.model?.includes("claude-opus-4-1") ||- modelParams.model?.includes("claude-opus-4-5") ||- modelParams.model?.includes("claude-opus-4-6") ||- modelParams.model?.includes("claude-haiku-4-5");- const shouldUseAdaptiveThinking = isAnthropicAlwaysAdaptiveThinkingModel(- modelParams.model,- );- const anthropicInvocationKwargs = shouldUseAdaptiveThinking- ? {- // @langchain/anthropic currently defaults ChatAnthropic.thinking to- // { type: "disabled" } and serializes it into every request.- // Claude Fable 5 and Claude Mythos 5 reject that explicit disabled- // mode because thinking defaults to adaptive when the field is- // omitted. Newer ChatAnthropic versions might fix this default, but- // remove this guard only after a developer has verified that the- // pinned/newer version no longer sends thinking.disabled by default.- thinking: undefined,- ...modelParams.providerOptions,- }- : modelParams.providerOptions;-const chatOptions: ChatAnthropicInput = {anthropicApiKey: apiKey,anthropicApiUrl: baseURL ?? undefined,@@ -413,32 +483,11 @@ export async function fetchLLMCompletion(},temperature: modelParams.temperature,topP: modelParams.top_p,- invocationKwargs: anthropicInvocationKwargs,+ invocationKwargs: getAnthropicInvocationKwargs(modelParams),};chatModel = new ChatAnthropic(chatOptions);-- if (shouldNormalizeAnthropicSamplingParams) {- if (chatModel.topP === -1) {- chatModel.topP = undefined;- }-- // TopP and temperature cannot be specified both,- // but Langchain is setting placeholder values despite that- if (- modelParams.temperature !== undefined &&- modelParams.top_p === undefined- ) {- chatModel.topP = undefined;- }-- if (- modelParams.top_p !== undefined &&- modelParams.temperature === undefined- ) {- chatModel.temperature = undefined;- }- }+ normalizeAnthropicSamplingParams(chatModel, modelParams);} else if (modelParams.adapter === LLMAdapter.OpenAI) {const processedBaseURL = processOpenAIBaseURL({url: baseURL,@@ -520,9 +569,14 @@ export async function fetchLLMCompletion(? VertexAIConfigSchema.parse(config): { location: undefined };- const googleProviderOptions = googleProviderOptionsSchema.parse(- modelParams.providerOptions,- );+ // location flows into the Vertex host both SDKs build from it+ // (https://${location}-aiplatform.googleapis.com), so reject anything that+ // could reshape that host and exfiltrate the Google OAuth bearer token.+ if (location !== undefined && !VERTEX_LOCATION_PATTERN.test(location)) {+ throw new Error(+ "Invalid Vertex AI location. Locations must be a single Vertex region identifier.",+ );+ }// Handle both explicit credentials and default provider chain (ADC)// Only allow default provider chain in self-hosted or internal AI features@@ -533,34 +587,100 @@ export async function fetchLLMCompletion(// This supports: GKE Workload Identity, Cloud Run service accounts, GCE metadata service, gcloud auth// Security: We intentionally ignore user-provided projectId when using ADC to prevent// privilege escalation attacks where users could access other GCP projects via the server's credentials- const authOptions = shouldUseDefaultCredentials- ? undefined // Always use ADC auto-detection, never allow user-specified projectId- : {- credentials: GCPServiceAccountKeySchema.parse(JSON.parse(apiKey)),- projectId: GCPServiceAccountKeySchema.parse(JSON.parse(apiKey))- .project_id,- };+ const serviceAccountKey = shouldUseDefaultCredentials+ ? undefined+ : GCPServiceAccountKeySchema.parse(JSON.parse(apiKey));+ const authOptions: GoogleAuthOptions | undefined = serviceAccountKey+ ? {+ credentials: serviceAccountKey,+ projectId: serviceAccountKey.project_id,+ }+ : undefined; // Always use ADC auto-detection, never allow user-specified projectId// Requests time out after 60 seconds for both public and private endpoints by default// Reference: https://cloud.google.com/vertex-ai/docs/predictions/get-online-predictions#send-request- chatModel = new ChatGoogle({- model: modelParams.model,- temperature: modelParams.temperature,- maxOutputTokens: modelParams.max_tokens,- topP: modelParams.top_p,- callbacks: finalCallbacks,- maxRetries,- location,- vertexai: true,- apiClient: createSecureVertexAIApiClient({- authOptions,- dispatcher: proxyDispatcher,- }),- ...(modelParams.maxReasoningTokens !== undefined && {- maxReasoningTokens: modelParams.maxReasoningTokens,- }),- ...((googleProviderOptions as any) ?? {}), // Typecast as thinkingLevel is intentionally looser typed- });+ if (isClaudeModel(modelParams.model)) {+ assertValidAnthropicVertexModelName(modelParams.model);+ const anthropicVertexGoogleAuth = new GoogleAuth({+ ...authOptions,+ scopes: authOptions?.scopes ?? VERTEX_AI_AUTH_SCOPES,+ });+ const anthropicVertexRegion = location ?? "global";++ // LangChain keeps Claude-on-Vertex on ChatAnthropic + AnthropicVertex+ // while @langchain/google is still focused on Gemini/Gemma.+ // https://github.com/langchain-ai/langchain-google/discussions/1422+ chatModel = new ChatAnthropic({+ model: modelParams.model,+ temperature: modelParams.temperature,+ maxTokens: modelParams.max_tokens,+ topP: modelParams.top_p,+ callbacks: finalCallbacks,+ maxRetries,+ invocationKwargs: (() => {+ const { model: _ignoredModelOverride, ...sanitized } =+ (getAnthropicInvocationKwargs(modelParams) ?? {}) as Record<+ string,+ unknown+ >;+ return sanitized;+ })(),+ clientOptions: {+ timeout: timeoutMs,+ defaultHeaders: extraHeaders,+ fetch: secureLlmFetch("Anthropic Vertex AI endpoint", [+ VERTEX_AI_AUTH_HEADER,+ ]),+ },+ createClient: (options) =>+ new AnthropicVertex({+ ...options,+ // The base Anthropic SDK defaults apiKey/authToken from+ // ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN when undefined, which on+ // Vertex would ship as headers that win over Google's OAuth token+ // and leak the operator's Anthropic credentials. Force both null so+ // auth comes only from googleAuth (the vertex-sdk type omits these+ // fields though the base client still honors them).+ ...({ apiKey: null, authToken: null } as {+ apiKey: null;+ authToken: null;+ }),+ region: anthropicVertexRegion,+ projectId: serviceAccountKey?.project_id,+ // @anthropic-ai/vertex-sdk depends on its own google-auth-library+ // copy, so the structurally compatible GoogleAuth instance needs an+ // explicit cast across duplicate private class declarations.+ googleAuth: anthropicVertexGoogleAuth as unknown as NonNullable<+ AnthropicVertexClientOptions["googleAuth"]+ >,+ maxRetries: 0,+ }),+ });+ normalizeAnthropicSamplingParams(chatModel, modelParams);+ } else {+ const googleProviderOptions = googleProviderOptionsSchema.parse(+ modelParams.providerOptions,+ );++ chatModel = new ChatGoogle({+ model: modelParams.model,+ temperature: modelParams.temperature,+ maxOutputTokens: modelParams.max_tokens,+ topP: modelParams.top_p,+ callbacks: finalCallbacks,+ maxRetries,+ location,+ vertexai: true,+ apiClient: createSecureVertexAIApiClient({+ authOptions,+ dispatcher: proxyDispatcher,+ }),+ ...(modelParams.maxReasoningTokens !== undefined && {+ maxReasoningTokens: modelParams.maxReasoningTokens,+ }),+ ...((googleProviderOptions as any) ?? {}), // Typecast as thinkingLevel is intentionally looser typed+ });+ }} else if (modelParams.adapter === LLMAdapter.GoogleAIStudio) {const googleProviderOptions = googleProviderOptionsSchema.parse(modelParams.providerOptions,@@ -624,8 +744,13 @@ export async function fetchLLMCompletion(? { method: "functionCalling" as const }: undefined;const createStructuredOutputModel = () => {+ const isAnthropicChatModel =+ modelParams.adapter === LLMAdapter.Anthropic ||+ (modelParams.adapter === LLMAdapter.VertexAI &&+ isClaudeModel(modelParams.model));+if (- modelParams.adapter !== LLMAdapter.Anthropic ||+ !isAnthropicChatModel ||!isAnthropicAlwaysAdaptiveThinkingModel(modelParams.model)) {return (chatModel as ChatOpenAI).withStructuredOutput(diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b78454e1bc..fae3047633 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -21,6 +21,7 @@ overrides:'@ai-sdk/provider-utils@<=4.0.26': 4.0.27'@ai-sdk/provider-utils-v5': npm:@ai-sdk/[email protected]'@copilotkit/[email protected]>@ag-ui/langgraph': 0.0.29+ '@anthropic-ai/vertex-sdk>@anthropic-ai/sdk': 0.104.1patchedDependencies:[email protected]: 7b301d2607ee3cd8bba4f6978ba8cdd7a616b59d6e414191da3b38950ce08e66@@ -164,6 +165,9 @@ importers:'@anthropic-ai/tokenizer':specifier: ^0.0.4version: 0.0.4+ '@anthropic-ai/vertex-sdk':+ specifier: ^0.17.1+ version: 0.17.1([email protected])'@aws-sdk/client-cloudwatch':specifier: ^3.1013.0version: 3.1024.0@@ -1248,6 +1252,15 @@ packages:'@antfu/[email protected]':resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==}+ '@anthropic-ai/[email protected]':+ resolution: {integrity: sha512-gGACa/+IaiXzRRmF96aOhamoBgapKRBiFWbmmTFP8aMkpaEcuStF+Q61bjo4vPxBM7gqWJNZqsngslRdnLHv0Q==}+ hasBin: true+ peerDependencies:+ zod: 4.3.6+ peerDependenciesMeta:+ zod:+ optional: true+'@anthropic-ai/[email protected]':resolution: {integrity: sha512-srbJV7JKsc5cQ6eVuFzjZO7UR3xEPJqPamHFIe29bs38Ij2IripoAhC0S5NslNbaFUYqBKypmmpzMTpqfHEUDw==}hasBin: true@@ -1260,6 +1273,9 @@ packages:'@anthropic-ai/[email protected]':resolution: {integrity: sha512-EHRKbxlxlc8W4KCBEseByJ7YwyYCmgu9OyN59H9+IYIGPoKv8tXyQXinkeGDI+cI8Tiuz9wk2jZb/kK7AyvL7g==}+ '@anthropic-ai/[email protected]':+ resolution: {integrity: sha512-+am1LjqEpb7Qq/fKDdu0PTE2U9+XSPXSSr9Fa5dvJ8FtJ5L9XOroNBnr7iecT+6iGlbiV6BYgMIGkAwPuly/jA==}+'@appsignal/[email protected]':resolution: {integrity: sha512-ocQobEulcAHMlnDDyMg9wXlv7ipkGHpShj15eSvvrtR4AFBnvgbK+WdlpD2mfNpkXC1IF3bYIoWXLrsBXNPCig==}peerDependencies:@@ -5008,6 +5024,9 @@ packages:resolution: {integrity: sha512-2zqq5o/oizvMaFUlNiTyZ7dbgYv1a893aGut2uaxtbzTx/VYYnRxWzDHuD/ftgcw94ffenua+ZNLrbqwUYE+Bg==}engines: {node: '>=18.0.0'}+ '@stablelib/[email protected]':+ resolution: {integrity: sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==}+'@standard-community/[email protected]':resolution: {integrity: sha512-4+ZPorwDRt47i+O7RjyuaxHRK/37QY/LmgxlGrRrSTLYoFatEOzvqIc85GTlM18SFZ5E91C+v0o/M37wZPpUHA==}peerDependencies:@@ -7661,6 +7680,9 @@ packages:resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}+ resolution: {integrity: sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==}+resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}@@ -10533,6 +10555,9 @@ packages:resolution: {integrity: sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==}+ resolution: {integrity: sha512-BbHGOQK9olHPMvQNHWul6MYlrRTAOKn03rOe4A8O3CLWhNf4YHBqq2HJKKC+sfqpxiBY52pNeesD6jIiLDz8jg==}+resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==}engines: {node: '>= 0.8'}@@ -11772,6 +11797,13 @@ snapshots:package-manager-detector: 1.6.0tinyexec: 1.1.2+ '@anthropic-ai/[email protected]([email protected])':+ dependencies:+ json-schema-to-ts: 3.1.1+ standardwebhooks: 1.0.0+ optionalDependencies:+ zod: 4.3.6+'@anthropic-ai/[email protected]([email protected])':dependencies:json-schema-to-ts: 3.1.1@@ -11783,6 +11815,15 @@ snapshots:'@types/node': 18.19.123tiktoken: 1.0.20+ '@anthropic-ai/[email protected]([email protected])':+ dependencies:+ '@anthropic-ai/sdk': 0.104.1([email protected])+ google-auth-library: 9.15.1+ transitivePeerDependencies:+ - encoding+ - supports-color+ - zod+'@appsignal/[email protected]([email protected])':dependencies:'@opentelemetry/api': 1.9.1@@ -16349,6 +16390,8 @@ snapshots:'@smithy/types': 4.14.2tslib: 2.8.1+ '@stablelib/[email protected]': {}+'@standard-community/[email protected](@standard-schema/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected])':dependencies:'@standard-schema/spec': 1.1.0@@ -19391,6 +19434,8 @@ snapshots:+ [email protected]: {}+@@ -22765,6 +22810,11 @@ snapshots:+ dependencies:+ '@stablelib/base64': 1.0.1+ fast-sha256: 1.3.0+diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 60331a3626..43d40405f8 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -73,6 +73,10 @@ overrides:"@ai-sdk/provider-utils@<=4.0.26": 4.0.27"@ai-sdk/provider-utils-v5": "npm:@ai-sdk/[email protected]""@copilotkit/[email protected]>@ag-ui/langgraph": 0.0.29+ # Keep Anthropic's Vertex client on an SDK version that emits Vertex rawPredict URLs.+ # Remove once @langchain/anthropic allows the same SDK range.+ # Check: https://www.npmjs.com/package/@langchain/anthropic?activeTab=dependencies+ "@anthropic-ai/vertex-sdk>@anthropic-ai/sdk": 0.104.1patchedDependencies:[email protected]: patches/[email protected]publicHoistPattern:diff --git a/worker/src/__tests__/fetchLLMCompletionErrors.test.ts b/worker/src/__tests__/fetchLLMCompletionErrors.test.tsindex 4be994d8ba..85d3358c8d 100644--- a/worker/src/__tests__/fetchLLMCompletionErrors.test.ts+++ b/worker/src/__tests__/fetchLLMCompletionErrors.test.ts@@ -13,6 +13,20 @@ const chatAnthropicConstructorMock = vi.fn().mockImplementation(function () {};});+const mockGcpServiceAccountKey = {+ type: "service_account",+ project_id: "test-project",+ private_key_id: "test-key-id",+ private_key: "-----BEGIN PRIVATE KEY-----\ntest\n-----END PRIVATE KEY-----\n",+ client_email: "[email protected]",+ client_id: "1234567890",+ auth_uri: "https://accounts.google.com/o/oauth2/auth",+ token_uri: "https://oauth2.googleapis.com/token",+ auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",+ client_x509_cert_url:+ "https://www.googleapis.com/robot/v1/metadata/x509/test%40test-project.iam.gserviceaccount.com",+} as const;+process.env.CLICKHOUSE_URL ??= "http://localhost:8123";process.env.CLICKHOUSE_USER ??= "default";process.env.CLICKHOUSE_PASSWORD ??= "password";@@ -144,4 +158,346 @@ describe("fetchLLMCompletion provider error classification", () => {isRetryable: false,});});++ it("forwards Anthropic options and normalizes sampling params for Claude on Vertex", async () => {+ const modelInstance = {+ topP: -1,+ temperature: 0,+ invoke: anthropicInvokeMock,+ pipe: vi.fn().mockReturnValue({+ invoke: anthropicInvokeMock,+ }),+ withStructuredOutput: vi.fn().mockReturnValue({+ invoke: anthropicInvokeMock,+ }),+ };++ chatAnthropicConstructorMock.mockImplementationOnce(function () {+ return modelInstance;+ });+ anthropicInvokeMock.mockResolvedValue({ content: "ok" });++ await expect(+ fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "Score this observation.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "vertexai",+ adapter: "google-vertex-ai",+ model: "claude-sonnet-4-6",+ temperature: 0,+ max_tokens: 10,+ providerOptions: {+ thinking: {+ type: "enabled",+ budget_tokens: 16000,+ },+ },+ },+ llmConnection: {+ secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),+ config: {+ location: "us-east5",+ },+ },+ }),+ ).resolves.toEqual({ text: "ok" });++ expect(chatAnthropicConstructorMock).toHaveBeenCalledWith(+ expect.objectContaining({+ model: "claude-sonnet-4-6",+ temperature: 0,+ topP: undefined,+ invocationKwargs: {+ thinking: {+ type: "enabled",+ budget_tokens: 16000,+ },+ },+ }),+ );+ expect(modelInstance.topP).toBeUndefined();+ expect(modelInstance.temperature).toBe(0);+ });++ it("applies the adaptive thinking structured output workaround for Claude on Vertex", async () => {+ const thinkingDuringStructuredOutput: unknown[] = [];+ const modelInstance = {+ thinking: { type: "disabled" },+ invoke: anthropicInvokeMock,+ pipe: vi.fn().mockReturnValue({+ invoke: anthropicInvokeMock,+ }),+ withStructuredOutput: vi.fn().mockImplementation(function () {+ thinkingDuringStructuredOutput.push(modelInstance.thinking);+ return {+ invoke: anthropicInvokeMock,+ };+ }),+ };++ chatAnthropicConstructorMock.mockImplementationOnce(function () {+ return modelInstance;+ });+ anthropicInvokeMock.mockResolvedValue({ result: "ok" });++ await expect(+ fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "Return structured output.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "vertexai",+ adapter: "google-vertex-ai",+ model: "claude-fable-5",+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),+ config: {+ location: "us-east5",+ },+ },+ structuredOutputSchema: {+ type: "object",+ properties: {+ result: { type: "string" },+ },+ required: ["result"],+ additionalProperties: false,+ },+ }),+ ).resolves.toEqual({ result: "ok" });++ expect(thinkingDuringStructuredOutput).toEqual([{ type: "adaptive" }]);+ expect(modelInstance.thinking).toEqual({ type: "disabled" });+ });++ it("rejects Claude on Vertex model names that are not single path segments", async () => {+ await expect(+ fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "Score this observation.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "vertexai",+ adapter: "google-vertex-ai",+ model:+ "../../../../../../../projects/victim/locations/us-east5/publishers/anthropic/models/claude-3-5-sonnet",+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),+ config: {+ location: "us-east5",+ },+ },+ }),+ ).rejects.toThrow(+ "Invalid Anthropic Vertex AI model name. Model names must be a single Vertex model ID segment.",+ );++ expect(chatAnthropicConstructorMock).not.toHaveBeenCalled();+ });++ it("rejects Claude on Vertex locations that could reshape the Vertex host", async () => {+ await expect(+ fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "Score this observation.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "vertexai",+ adapter: "google-vertex-ai",+ model: "claude-sonnet-4-6",+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),+ config: {+ location: "attacker.example/",+ },+ },+ }),+ ).rejects.toThrow(+ "Invalid Vertex AI location. Locations must be a single Vertex region identifier.",+ );++ expect(chatAnthropicConstructorMock).not.toHaveBeenCalled();+ });++ it("rejects an empty Claude on Vertex location with the clean error", async () => {+ await expect(+ fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "Score this observation.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "vertexai",+ adapter: "google-vertex-ai",+ model: "claude-sonnet-4-6",+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),+ config: {+ location: "",+ },+ },+ }),+ ).rejects.toThrow(+ "Invalid Vertex AI location. Locations must be a single Vertex region identifier.",+ );++ expect(chatAnthropicConstructorMock).not.toHaveBeenCalled();+ });++ it("does not forward Anthropic env credentials to the Vertex client", async () => {+ let capturedCreateClient:+ | ((options: { apiKey?: string | null }) => {+ apiKey: string | null;+ authToken: string | null;+ })+ | undefined;++ chatAnthropicConstructorMock.mockImplementationOnce(function (args: {+ createClient: (options: { apiKey?: string | null }) => {+ apiKey: string | null;+ authToken: string | null;+ };+ }) {+ capturedCreateClient = args.createClient;+ return {+ invoke: anthropicInvokeMock,+ pipe: vi.fn().mockReturnValue({+ invoke: anthropicInvokeMock,+ }),+ withStructuredOutput: vi.fn().mockReturnValue({+ invoke: anthropicInvokeMock,+ }),+ };+ });+ anthropicInvokeMock.mockResolvedValue({ content: "ok" });++ await expect(+ fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "Score this observation.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "vertexai",+ adapter: "google-vertex-ai",+ model: "claude-sonnet-4-6",+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),+ config: {+ location: "us-east5",+ },+ },+ }),+ ).resolves.toEqual({ text: "ok" });++ expect(capturedCreateClient).toBeDefined();+ // ChatAnthropic forwards process.env.ANTHROPIC_API_KEY here, and the base+ // SDK also defaults apiKey/authToken from env. The Vertex client must force+ // both null so neither ships as a header to Google.+ const client = capturedCreateClient!({+ apiKey: "sk-should-not-leak",+ });+ expect(client.apiKey).toBeNull();+ expect(client.authToken).toBeNull();+ });++ it("drops a providerOptions.model override for Claude on Vertex", async () => {+ chatAnthropicConstructorMock.mockImplementationOnce(function () {+ return {+ invoke: anthropicInvokeMock,+ pipe: vi.fn().mockReturnValue({+ invoke: anthropicInvokeMock,+ }),+ withStructuredOutput: vi.fn().mockReturnValue({+ invoke: anthropicInvokeMock,+ }),+ };+ });+ anthropicInvokeMock.mockResolvedValue({ content: "ok" });++ await expect(+ fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "Score this observation.",+ type: "public-api-created",+ },+ ],+ modelParams: {+ provider: "vertexai",+ adapter: "google-vertex-ai",+ model: "claude-sonnet-4-6",+ temperature: 0,+ max_tokens: 10,+ providerOptions: {+ model:+ "../../../../../../../projects/victim/locations/us-east5/publishers/anthropic/models/claude-3-5-sonnet",+ },+ },+ llmConnection: {+ secretKey: encrypt(JSON.stringify(mockGcpServiceAccountKey)),+ config: {+ location: "us-east5",+ },+ },+ }),+ ).resolves.toEqual({ text: "ok" });++ expect(chatAnthropicConstructorMock).toHaveBeenCalledWith(+ expect.objectContaining({+ model: "claude-sonnet-4-6",+ invocationKwargs: {},+ }),+ );+ // The validated `model` field must win; the injected override is stripped.+ const { invocationKwargs } = chatAnthropicConstructorMock.mock.calls[0][0];+ expect(invocationKwargs).not.toHaveProperty("model");+ });});diff --git a/worker/src/__tests__/llmConnections.test.ts b/worker/src/__tests__/llmConnections.test.tsindex 18d4290d44..a9aa96b536 100644--- a/worker/src/__tests__/llmConnections.test.ts+++ b/worker/src/__tests__/llmConnections.test.ts@@ -887,6 +887,53 @@ describe("LLM Connection Tests", () => {expect((completion as CompletionWithReasoning).text).toContain("4");}, 30_000);+ test("Claude model routes through Anthropic publisher endpoint", async () => {+ checkEnvVar();++ const claudeVertexModel = "claude-3-haiku@20240307";++ try {+ const completion = await fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "What is 2+2? Answer only with the number.",+ type: ChatMessageType.PublicAPICreated,+ },+ ],+ modelParams: {+ provider: "google-vertex-ai",+ adapter: LLMAdapter.VertexAI,+ model: claudeVertexModel,+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(+ process.env.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY!,+ ),+ config: { location: "us-east5" },+ },+ });++ expect(typeof completion).toBe("object");+ expect((completion as CompletionWithReasoning).text).toContain("4");+ } catch (error) {+ const message = String(error);++ // The CI project currently does not have access to Anthropic publisher+ // models. The regression signal is that Claude-on-Vertex reaches the+ // Anthropic publisher endpoint instead of /v1/v1/messages or Google's+ // Gemini/Gemma publisher path.+ expect(message).toContain(+ `/publishers/anthropic/models/${claudeVertexModel}`,+ );+ expect(message).not.toContain("/v1/v1/messages");+ expect(message).not.toContain("/publishers/google/");+ }+ }, 30_000);+test("streaming completion", async () => {checkEnvVar();