🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(model-runtime): organize Anthropic Messages code by protocol (#22785)
Arvin Xu00ec2bcd04fb
diff --git a/packages/model-runtime/src/core/anthropicCompatible/context.ts b/packages/model-runtime/src/core/anthropicCompatible/context.tsnew file mode 100644index 00000000000..7ef4c13d389--- /dev/null+++ b/packages/model-runtime/src/core/anthropicCompatible/context.ts@@ -0,0 +1,19 @@+import type Anthropic from '@anthropic-ai/sdk';++import type { ConstructorOptions } from './index';++/**+ * What the protocol modules read from an Anthropic-compatible runtime. The runtime builds it+ * per call, so its own members stay private and subclasses keep overriding `handleError`.+ */+export interface AnthropicCompatibleRuntimeContext {+ _options: ConstructorOptions;+ baseURL: string;+ client: Anthropic;+ id: string;+ logPrefix: string;+ withMappedRequestModel: <TPayload extends { model?: string }>(+ requestPayload: TPayload,+ logicalModel: string,+ ) => TPayload;+}diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatible/index.test.tssimilarity index 100%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.tsrename to packages/model-runtime/src/core/anthropicCompatible/index.test.tsdiff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatible/index.tssimilarity index 50%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/index.tsrename to packages/model-runtime/src/core/anthropicCompatible/index.tsindex 29efdeaa734..b2f1e70dcfd 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts+++ b/packages/model-runtime/src/core/anthropicCompatible/index.ts@@ -6,11 +6,6 @@ import debug from 'debug';import type { Pricing } from 'model-bank';import { ErrorClassifier } from '../../errors';-import { stripUnsupportedClaudeAssistantPrefill } from '../../providers/anthropic/claudePrefill';-import {- isAlwaysThinkingClaudeModel,- rejectsDisabledThinkingAtEffort,-} from '../../providers/anthropic/modelId';import type {ChatCompletionErrorPayload,ChatMethodOptions,@@ -21,47 +16,31 @@ import type {} from '../../types';import type { ILobeAgentRuntimeErrorType } from '../../types/error';import { AgentRuntimeErrorType } from '../../types/error';-import { respondJsonAfterStream } from '../../utils/consumeStream';import { AgentRuntimeError } from '../../utils/createError';-import { debugPayload, debugStream } from '../../utils/debugStream';import { desensitizeUrl } from '../../utils/desensitizeUrl';import { getModelPricing } from '../../utils/getModelPricing';import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';import { resolveMappedModelId } from '../../utils/modelIdMapping';import { MODEL_LIST_CONFIGS, processModelList } from '../../utils/modelParse';import { ContextExceededPreFlightError } from '../../utils/resolveSafeMaxTokens';-import { StreamingResponse } from '../../utils/response';import type { LobeRuntimeAI } from '../BaseAI';-import {- buildAnthropicMessages,- buildAnthropicTools,- buildSearchTool,-} from '../contextBuilders/anthropic';-import { resolveModelSamplingParameters } from '../parameterResolver';-import { AnthropicStream, type AnthropicStreamOptions } from '../streams';-import { readableFromAsyncIterable } from '../streams/protocol';-import { type ComputeChatCostOptions } from '../usageConverters/utils/computeChatCost';+import { chatViaMessages } from '../protocols/anthropicMessages/chat';+import { handleAnthropicError } from '../protocols/anthropicMessages/errors';import {type AnthropicGenerateObjectConfig,createAnthropicGenerateObject,-} from './generateObject';-import { handleAnthropicError } from './handleAnthropicError';+} from '../protocols/anthropicMessages/generateObject';import {- initializeAnthropicDiagnostics,- observeAnthropicStream,- recordAnthropicNonStreamingResponse,- recordAnthropicResponseMetadata,-} from './providerDiagnostics';-import { resolveCacheTTL } from './resolveCacheTTL';-import { resolveMaxTokens } from './resolveMaxTokens';-import { resolveClaudeThinkingConfig } from './resolveThinkingConfig';--type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions &+ buildDefaultAnthropicPayload,+ resolveDefaultAnthropicPricingOptions,+} from '../protocols/anthropicMessages/payload';+import { type ComputeChatCostOptions } from '../usageConverters/utils/computeChatCost';+import type { AnthropicCompatibleRuntimeContext } from './context';++export type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions &ModelIdMappingOptions &T;-type AnthropicTools = Anthropic.Tool | Anthropic.WebSearchTool20250305;-export const DEFAULT_ANTHROPIC_BASE_URL = 'https://api.anthropic.com';const ANTHROPIC_CLIENT_TIMEOUT_ENV = 'ANTHROPIC_CLIENT_TIMEOUT';/**@@ -82,6 +61,11 @@ const resolveDefaultAnthropicTimeout = () => {return Number.isInteger(timeout) && timeout > 0 ? timeout : DEFAULT_ANTHROPIC_TIMEOUT;};+export {+ buildDefaultAnthropicPayload,+ resolveDefaultAnthropicPricingOptions,+} from '../protocols/anthropicMessages/payload';+export interface CustomClientOptions<T extends Record<string, any> = any> {createClient?: (options: ConstructorOptions<T>) => Anthropic;}@@ -150,139 +134,6 @@ export interface AnthropicCompatibleParamsInput<T extends Record<string, any> =models?: AnthropicCompatibleFactoryOptions<T>['models'];}-/**- * Build the default Anthropic Messages payload with LobeChat normalization.- */-export const buildDefaultAnthropicPayload = async (- payload: ChatStreamPayload,-): Promise<Anthropic.MessageCreateParams> => {- const {- messages,- model,- max_tokens,- temperature,- top_p,- tools,- thinking,- effort,- enabledContextCaching = true,- enabledSearch,- } = payload;-- const { anthropic: anthropicModels } = await import('model-bank');-- const resolvedMaxTokens = await resolveMaxTokens({- max_tokens,- model,- providerModels: anthropicModels,- thinking,- });-- // Filter out empty/whitespace-only system prompts — Anthropic API rejects them- const systemMessage = messages.find((message) => message.role === 'system');- const userMessages = messages.filter((message) => message.role !== 'system');- const systemPromptText =- typeof systemMessage?.content === 'string' && systemMessage.content.trim()- ? systemMessage.content- : undefined;-- const systemPrompts = systemPromptText- ? ([- {- cache_control: enabledContextCaching ? { type: 'ephemeral' } : undefined,- text: systemPromptText,- type: 'text',- },- ] as Anthropic.TextBlockParam[])- : undefined;-- const postMessages = stripUnsupportedClaudeAssistantPrefill(- model,- await buildAnthropicMessages(userMessages, { enabledContextCaching }),- );-- let postTools = buildAnthropicTools(tools, { enabledContextCaching }) as- AnthropicTools[] | undefined;-- if (enabledSearch) {- const webSearchTool = buildSearchTool();- postTools = postTools?.length ? [...postTools, webSearchTool] : [webSearchTool];- }-- const resolvedThinking = resolveClaudeThinkingConfig({- maxTokens: resolvedMaxTokens,- model,- thinking,- });-- if (resolvedThinking && resolvedThinking.type !== 'disabled') {- return {- max_tokens: resolvedMaxTokens,- messages: postMessages,- model,- ...(effort ? { output_config: { effort } } : {}),- system: systemPrompts,- thinking: resolvedThinking as Anthropic.MessageCreateParams['thinking'],- tools: postTools as Anthropic.MessageCreateParams['tools'],- } as Anthropic.MessageCreateParams;- }-- // Resolve temperature/top_p: Claude 4+ doesn't allow both simultaneously.- // normalizeTemperature divides by 2 to map LobeChat's 0-2 range to Anthropic's 0-1 range.- const resolvedSamplingParams = resolveModelSamplingParameters(- model,- { temperature, top_p },- { normalizeTemperature: true, preferTemperature: true },- );-- // Claude Opus 5 and later reject disabled thinking at effort `xhigh` / `max`; every lower- // effort level stays valid, so only that pairing is dropped.- const forwardsEffort =- !!effort &&- !(resolvedThinking?.type === 'disabled' && rejectsDisabledThinkingAtEffort(model, effort));-- // Support effort parameter even without thinking (per Claude 4.6 guidance)- const basePayload: Anthropic.MessageCreateParams = {- max_tokens: resolvedMaxTokens,- messages: postMessages,- model,- system: systemPrompts,- temperature: resolvedSamplingParams.temperature,- tools: postTools as Anthropic.MessageCreateParams['tools'],- ...(resolvedThinking- ? { thinking: resolvedThinking as Anthropic.MessageCreateParams['thinking'] }- : {}),- top_p: resolvedSamplingParams.top_p,- };-- // If effort is specified without an incompatible thinking mode, add output_config- if (forwardsEffort) {- return {- ...basePayload,- output_config: { effort },- } as Anthropic.MessageCreateParams;- }-- return basePayload;-};--/**- * Resolve cache-aware pricing options for usage cost calculation.- */-export const resolveDefaultAnthropicPricingOptions = (- requestPayload: ChatStreamPayload,- anthropicPayload: Anthropic.MessageCreateParams,-): ComputeChatCostOptions | undefined => {- const cacheTTL = resolveCacheTTL(requestPayload, {- messages: anthropicPayload.messages,- system: anthropicPayload.system,- });-- if (!cacheTTL) return undefined;-- return { lookupParams: { ttl: cacheTTL } };-};-/*** Create Anthropic SDK client with optional beta headers.*/@@ -473,18 +324,20 @@ export const createAnthropicCompatibleParams = <T extends Record<string, any> =} as AnthropicCompatibleFactoryOptions<T>;};-export const createAnthropicCompatibleRuntime = <T extends Record<string, any> = any>({- provider,- baseURL: DEFAULT_BASE_URL = DEFAULT_ANTHROPIC_BASE_URL,- apiKey: DEFAULT_API_KEY,- errorType,- debug: debugParams,- constructorOptions,- chatCompletion,- customClient,- models,- generateObject,-}: AnthropicCompatibleFactoryOptions<T>) => {+export const createAnthropicCompatibleRuntime = <T extends Record<string, any> = any>(+ factory: AnthropicCompatibleFactoryOptions<T>,+) => {+ const {+ provider,+ baseURL: DEFAULT_BASE_URL = DEFAULT_ANTHROPIC_BASE_URL,+ apiKey: DEFAULT_API_KEY,+ errorType,+ constructorOptions,+ chatCompletion,+ customClient,+ models,+ generateObject,+ } = factory;const ErrorType = {bizError: errorType?.bizError || AgentRuntimeErrorType.ProviderBizError,invalidAPIKey: errorType?.invalidAPIKey || AgentRuntimeErrorType.InvalidProviderAPIKey,@@ -563,228 +416,22 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =return { ...requestPayload, model: mappedModel };}+ /** What the protocol modules read; built per call so it always reflects current state. */+ private get context(): AnthropicCompatibleRuntimeContext {+ return {+ _options: this._options,+ baseURL: this.baseURL,+ client: this.client,+ id: this.id,+ logPrefix: this.logPrefix,+ withMappedRequestModel: (payload, logicalModel) =>+ this.withMappedRequestModel(payload, logicalModel),+ };+ }+async chat(payload: ChatStreamPayload, options?: ChatMethodOptions) {try {- if (!chatCompletion?.handlePayload) {- throw new Error('Anthropic-compatible runtime requires chatCompletion.handlePayload');- }-- const log = debug(`${this.logPrefix}:chat`);- const inputStartAt = Date.now();-- log('chat called with model: %s, stream: %s', payload.model, payload.stream ?? true);-- const postPayload = await chatCompletion.handlePayload(payload, this._options);- const shouldStream = postPayload.stream ?? payload.stream ?? true;- const finalPayload = { ...postPayload, stream: shouldStream };- const requestPayload = this.withMappedRequestModel(finalPayload, payload.model);-- // Re-apply the prefill guard against the ACTUAL request model:- // handlePayload stripped by the logical id, but a custom logical id the- // parser doesn't recognize can map to a Claude 4.6+/5 request model- // here. The strip is idempotent, so this is a no-op otherwise.- if (requestPayload.model && Array.isArray(requestPayload.messages)) {- requestPayload.messages = stripUnsupportedClaudeAssistantPrefill(- requestPayload.model,- requestPayload.messages,- );- }-- // Same for disabled thinking: handlePayload resolved it by the logical id, but the- // mapped request model may be an always-thinking Claude that rejects `disabled` with a- // 400. Omitting the config is the documented fallback (see resolveClaudeThinkingConfig).- if (- requestPayload.model &&- (requestPayload as { thinking?: { type?: string } }).thinking?.type === 'disabled' &&- isAlwaysThinkingClaudeModel(requestPayload.model)- ) {- delete (requestPayload as { thinking?: unknown }).thinking;- }-- const shouldDebugChatCompletion = debugParams?.chatCompletion?.() ?? false;- if (shouldDebugChatCompletion) {- debugPayload(requestPayload);- }-- const providerRequestPayload = {- ...requestPayload,- metadata: options?.user ? { user_id: options.user } : undefined,- };- const providerRequestStartedAt = Date.now();- const providerResponseDiagnostics = initializeAnthropicDiagnostics({- diagnostics: options?.diagnostics,- endpoint: desensitizeUrl(this.baseURL),- payload: providerRequestPayload,- sentAt: providerRequestStartedAt,- });- const responsePromise = this.client.messages.create(providerRequestPayload, {- headers: options?.requestHeaders,- signal: options?.signal,- });- /**- * Custom Anthropic-compatible clients may return a plain Promise instead- * of the SDK's APIPromise. Prefer withResponse() for request IDs and safe- * headers, while preserving compatibility with those clients.- */- const responseWithMetadata =- typeof responsePromise.withResponse === 'function'- ? await responsePromise.withResponse()- : { data: await responsePromise };- const response = responseWithMetadata.data;- recordAnthropicResponseMetadata(providerResponseDiagnostics, {- requestId:- 'request_id' in responseWithMetadata ? responseWithMetadata.request_id : undefined,- response: 'response' in responseWithMetadata ? responseWithMetadata.response : undefined,- });-- const pricing = await getModelPricing(payload.model, this.id, options?.pricingContext);- const pricingOptions = await chatCompletion?.getPricingOptions?.(payload, postPayload);- const streamOptions = {- callbacks: options?.callback,- payload: {- apiMode: 'messages',- model: payload.model,- pricing,- pricingOptions,- provider: this.id,- },- } satisfies Pick<AnthropicStreamOptions, 'callbacks' | 'payload'>;-- if (shouldStream) {- const streamResponse = response as- Stream<Anthropic.MessageStreamEvent> | ReadableStream<Anthropic.MessageStreamEvent>;- let prod: Stream<Anthropic.MessageStreamEvent> | ReadableStream = streamResponse;-- if (shouldDebugChatCompletion) {- const [productionStream, useForDebug] = streamResponse.tee();- prod = productionStream;- const useForDebugStream =- useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();-- debugStream(useForDebugStream).catch(console.error);- }-- if (providerResponseDiagnostics) {- /** Observe provider-native events before the protocol adapter transforms them. */- const observedStream = observeAnthropicStream(- prod,- providerResponseDiagnostics,- options?.signal,- );- prod =- observedStream instanceof ReadableStream- ? observedStream- : readableFromAsyncIterable(observedStream, {- model: payload.model,- provider: this.id,- });- }-- return StreamingResponse(- chatCompletion?.handleStream- ? chatCompletion.handleStream(prod, {- callbacks: streamOptions.callbacks,- inputStartAt,- payload,- })- : AnthropicStream(prod, { ...streamOptions, inputStartAt }),- {- headers: options?.headers,- },- );- }-- await recordAnthropicNonStreamingResponse(- providerResponseDiagnostics,- response as Anthropic.Message,- options?.signal,- );-- const stream = new ReadableStream<Anthropic.MessageStreamEvent>({- start(controller) {- const message = response as Anthropic.Message;-- controller.enqueue({- message,- type: 'message_start',- } satisfies Anthropic.MessageStreamEvent);-- message.content?.forEach((block, index) => {- if (block.type === 'tool_use' || block.type === 'server_tool_use') {- controller.enqueue({- content_block: block,- index,- type: 'content_block_start',- } satisfies Anthropic.MessageStreamEvent);-- controller.enqueue({- delta: {- partial_json: JSON.stringify(block.input ?? {}),- type: 'input_json_delta',- },- index,- type: 'content_block_delta',- } satisfies Anthropic.MessageStreamEvent);- }-- if (block.type === 'thinking' || block.type === 'redacted_thinking') {- controller.enqueue({- content_block: block,- index,- type: 'content_block_start',- } satisfies Anthropic.MessageStreamEvent);- }-- if (block.type === 'text') {- controller.enqueue({- delta: { text: block.text, type: 'text_delta' },- index,- type: 'content_block_delta',- } satisfies Anthropic.MessageStreamEvent);- }- });-- controller.enqueue({- delta: {- stop_reason: message.stop_reason,- stop_sequence: message.stop_sequence ?? null,- },- type: 'message_delta',- usage: {- cache_creation_input_tokens: message.usage?.cache_creation_input_tokens ?? null,- cache_read_input_tokens: message.usage?.cache_read_input_tokens ?? null,- input_tokens: message.usage?.input_tokens ?? null,- // `message_delta.usage` is cumulative, so it repeats the full output count.- output_tokens: message.usage?.output_tokens ?? 0,- server_tool_use: message.usage?.server_tool_use ?? null,- },- } satisfies Anthropic.MessageStreamEvent);-- controller.enqueue({ type: 'message_stop' } satisfies Anthropic.MessageStreamEvent);- controller.close();- },- });-- const streamingResponse = StreamingResponse(- chatCompletion?.handleStream- ? chatCompletion.handleStream(stream, {- callbacks: streamOptions.callbacks,- inputStartAt,- payload,- })- : AnthropicStream(stream, {- ...streamOptions,- enableStreaming: false,- inputStartAt,- }),- {- headers: options?.headers,- },- );-- if (payload.responseMode === 'json')- return await respondJsonAfterStream(streamingResponse, response);- return streamingResponse;+ return await chatViaMessages(this.context, factory, payload, options);} catch (error) {throw this.handleError(error);}diff --git a/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.test.ts b/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.test.tsindex 10f5f0db669..30bae38d919 100644--- a/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.test.ts+++ b/packages/model-runtime/src/core/contextBuilders/inlineImageBudget.test.ts@@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { OpenAIChatMessage, UserMessageContentPart } from '../../types';import { imageUrlToBase64 } from '../../utils/imageToBase64';-import { buildAnthropicMessages } from './anthropic';+import { buildAnthropicMessages } from '../protocols/anthropicMessages/messages';import {clearInlineImageCache,type ImageSlot,diff --git a/packages/model-runtime/src/core/protocols/anthropicMessages/chat.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/chat.tsnew file mode 100644index 00000000000..a245d70bf13--- /dev/null+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/chat.ts@@ -0,0 +1,187 @@+import type Anthropic from '@anthropic-ai/sdk';+import type { Stream } from '@anthropic-ai/sdk/streaming';+import debug from 'debug';++import { stripUnsupportedClaudeAssistantPrefill } from '../../../providers/anthropic/claudePrefill';+import { isAlwaysThinkingClaudeModel } from '../../../providers/anthropic/modelId';+import type { ChatMethodOptions, ChatStreamPayload } from '../../../types';+import { respondJsonAfterStream } from '../../../utils/consumeStream';+import { debugPayload, debugStream } from '../../../utils/debugStream';+import { desensitizeUrl } from '../../../utils/desensitizeUrl';+import { getModelPricing } from '../../../utils/getModelPricing';+import { StreamingResponse } from '../../../utils/response';+import type { AnthropicCompatibleFactoryOptions } from '../../anthropicCompatible';+import type { AnthropicCompatibleRuntimeContext } from '../../anthropicCompatible/context';+import { readableFromAsyncIterable } from '../../streams/protocol';+import {+ initializeAnthropicDiagnostics,+ observeAnthropicStream,+ recordAnthropicNonStreamingResponse,+ recordAnthropicResponseMetadata,+} from './diagnostics';+import { transformMessageToStream } from './nonStreamToStream';+import { AnthropicStream, type AnthropicStreamOptions } from './stream';++export const chatViaMessages = async (+ runtime: AnthropicCompatibleRuntimeContext,+ factory: AnthropicCompatibleFactoryOptions,+ payload: ChatStreamPayload,+ options?: ChatMethodOptions,+): Promise<Response> => {+ if (!factory.chatCompletion?.handlePayload) {+ throw new Error('Anthropic-compatible runtime requires chatCompletion.handlePayload');+ }++ const log = debug(`${runtime.logPrefix}:chat`);+ const inputStartAt = Date.now();++ log('chat called with model: %s, stream: %s', payload.model, payload.stream ?? true);++ const postPayload = await factory.chatCompletion.handlePayload(payload, runtime._options);+ const shouldStream = postPayload.stream ?? payload.stream ?? true;+ const finalPayload = { ...postPayload, stream: shouldStream };+ const requestPayload = runtime.withMappedRequestModel(finalPayload, payload.model);++ // Re-apply the prefill guard against the ACTUAL request model:+ // handlePayload stripped by the logical id, but a custom logical id the+ // parser doesn't recognize can map to a Claude 4.6+/5 request model+ // here. The strip is idempotent, so this is a no-op otherwise.+ if (requestPayload.model && Array.isArray(requestPayload.messages)) {+ requestPayload.messages = stripUnsupportedClaudeAssistantPrefill(+ requestPayload.model,+ requestPayload.messages,+ );+ }++ // Same for disabled thinking: handlePayload resolved it by the logical id, but the+ // mapped request model may be an always-thinking Claude that rejects `disabled` with a+ // 400. Omitting the config is the documented fallback (see resolveClaudeThinkingConfig).+ if (+ requestPayload.model &&+ (requestPayload as { thinking?: { type?: string } }).thinking?.type === 'disabled' &&+ isAlwaysThinkingClaudeModel(requestPayload.model)+ ) {+ delete (requestPayload as { thinking?: unknown }).thinking;+ }++ const shouldDebugChatCompletion = factory.debug?.chatCompletion?.() ?? false;+ if (shouldDebugChatCompletion) {+ debugPayload(requestPayload);+ }++ const providerRequestPayload = {+ ...requestPayload,+ metadata: options?.user ? { user_id: options.user } : undefined,+ };+ const providerRequestStartedAt = Date.now();+ const providerResponseDiagnostics = initializeAnthropicDiagnostics({+ diagnostics: options?.diagnostics,+ endpoint: desensitizeUrl(runtime.baseURL),+ payload: providerRequestPayload,+ sentAt: providerRequestStartedAt,+ });+ const responsePromise = runtime.client.messages.create(providerRequestPayload, {+ headers: options?.requestHeaders,+ signal: options?.signal,+ });+ /**+ * Custom Anthropic-compatible clients may return a plain Promise instead+ * of the SDK's APIPromise. Prefer withResponse() for request IDs and safe+ * headers, while preserving compatibility with those clients.+ */+ const responseWithMetadata =+ typeof responsePromise.withResponse === 'function'+ ? await responsePromise.withResponse()+ : { data: await responsePromise };+ const response = responseWithMetadata.data;+ recordAnthropicResponseMetadata(providerResponseDiagnostics, {+ requestId: 'request_id' in responseWithMetadata ? responseWithMetadata.request_id : undefined,+ response: 'response' in responseWithMetadata ? responseWithMetadata.response : undefined,+ });++ const pricing = await getModelPricing(payload.model, runtime.id, options?.pricingContext);+ const pricingOptions = await factory.chatCompletion?.getPricingOptions?.(payload, postPayload);+ const streamOptions = {+ callbacks: options?.callback,+ payload: {+ apiMode: 'messages',+ model: payload.model,+ pricing,+ pricingOptions,+ provider: runtime.id,+ },+ } satisfies Pick<AnthropicStreamOptions, 'callbacks' | 'payload'>;++ if (shouldStream) {+ const streamResponse = response as+ Stream<Anthropic.MessageStreamEvent> | ReadableStream<Anthropic.MessageStreamEvent>;+ let prod: Stream<Anthropic.MessageStreamEvent> | ReadableStream = streamResponse;++ if (shouldDebugChatCompletion) {+ const [productionStream, useForDebug] = streamResponse.tee();+ prod = productionStream;+ const useForDebugStream =+ useForDebug instanceof ReadableStream ? useForDebug : useForDebug.toReadableStream();++ debugStream(useForDebugStream).catch(console.error);+ }++ if (providerResponseDiagnostics) {+ /** Observe provider-native events before the protocol adapter transforms them. */+ const observedStream = observeAnthropicStream(+ prod,+ providerResponseDiagnostics,+ options?.signal,+ );+ prod =+ observedStream instanceof ReadableStream+ ? observedStream+ : readableFromAsyncIterable(observedStream, {+ model: payload.model,+ provider: runtime.id,+ });+ }++ return StreamingResponse(+ factory.chatCompletion?.handleStream+ ? factory.chatCompletion.handleStream(prod, {+ callbacks: streamOptions.callbacks,+ inputStartAt,+ payload,+ })+ : AnthropicStream(prod, { ...streamOptions, inputStartAt }),+ {+ headers: options?.headers,+ },+ );+ }++ await recordAnthropicNonStreamingResponse(+ providerResponseDiagnostics,+ response as Anthropic.Message,+ options?.signal,+ );++ const stream = transformMessageToStream(response as Anthropic.Message);++ const streamingResponse = StreamingResponse(+ factory.chatCompletion?.handleStream+ ? factory.chatCompletion.handleStream(stream, {+ callbacks: streamOptions.callbacks,+ inputStartAt,+ payload,+ })+ : AnthropicStream(stream, {+ ...streamOptions,+ enableStreaming: false,+ inputStartAt,+ }),+ {+ headers: options?.headers,+ },+ );++ if (payload.responseMode === 'json')+ return await respondJsonAfterStream(streamingResponse, response);+ return streamingResponse;+};diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/diagnostics.tssimilarity index 99%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/diagnostics.tsindex 275ed0e85a8..31ea924cb68 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/providerDiagnostics.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/diagnostics.ts@@ -4,12 +4,12 @@ import type {ModelRuntimeDiagnostics,ProviderResponseDiagnostics,ProviderResponseEventDiagnostics,-} from '../../types/providerDiagnostics';+} from '../../../types/providerDiagnostics';import {appendRawProviderEvent,captureRawProviderResponse,waitForRawProviderResponse,-} from '../providerDiagnostics';+} from '../../providerDiagnostics';const MAX_RECORDED_PROVIDER_EVENTS = 128;const MAX_RECORDED_ERROR_MESSAGE_LENGTH = 500;diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/handleAnthropicError.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/errors.tssimilarity index 100%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/handleAnthropicError.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/errors.tsdiff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/generateObject.test.tssimilarity index 100%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.test.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/generateObject.test.tsdiff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/generateObject.tssimilarity index 94%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/generateObject.tsindex 52b7efd0aee..763fc8ff859 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/generateObject.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/generateObject.ts@@ -2,12 +2,12 @@ import type Anthropic from '@anthropic-ai/sdk';import debug from 'debug';import type { Pricing } from 'model-bank';-import { stripUnsupportedClaudeAssistantPrefill } from '../../providers/anthropic/claudePrefill';-import { rejectsForcedToolChoice } from '../../providers/anthropic/modelId';-import type { GenerateObjectOptions, GenerateObjectPayload } from '../../types';-import { buildAnthropicMessages, buildAnthropicTools } from '../contextBuilders/anthropic';-import { buildAnthropicInitialUsage } from '../usageConverters/anthropic';-import { withUsageCost } from '../usageConverters/utils/withUsageCost';+import { stripUnsupportedClaudeAssistantPrefill } from '../../../providers/anthropic/claudePrefill';+import { rejectsForcedToolChoice } from '../../../providers/anthropic/modelId';+import type { GenerateObjectOptions, GenerateObjectPayload } from '../../../types';+import { buildAnthropicInitialUsage } from '../../usageConverters/anthropic';+import { withUsageCost } from '../../usageConverters/utils/withUsageCost';+import { buildAnthropicMessages, buildAnthropicTools } from './messages';const log = debug('lobe-model-runtime:anthropic:generate-object');diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/messages.test.tssimilarity index 99%rename from packages/model-runtime/src/core/contextBuilders/anthropic.test.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/messages.test.tsindex 475e3bb9d0c..7a65e85b837 100644--- a/packages/model-runtime/src/core/contextBuilders/anthropic.test.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/messages.test.ts@@ -1,15 +1,15 @@import type { OpenAI } from 'openai';import { beforeEach, describe, expect, it, vi } from 'vitest';-import type { OpenAIChatMessage, UserMessageContentPart } from '../../types/chat';-import { imageUrlToBase64 } from '../../utils/imageToBase64';-import { parseDataUri } from '../../utils/uriParser';+import type { OpenAIChatMessage, UserMessageContentPart } from '../../../types/chat';+import { imageUrlToBase64 } from '../../../utils/imageToBase64';+import { parseDataUri } from '../../../utils/uriParser';import {buildAnthropicBlock,buildAnthropicMessage,buildAnthropicMessages,buildAnthropicTools,-} from './anthropic';+} from './messages';const createAssistantToolMessage = (): OpenAIChatMessage => ({content: '正在搜索...',@@ -63,8 +63,8 @@ const createSearchTools = (): OpenAI.ChatCompletionTool[] => [];// Mock the parseDataUri function since it's an implementation detail-vi.mock('../../utils/uriParser');-vi.mock('../../utils/imageToBase64', async (importOriginal) => ({+vi.mock('../../../utils/uriParser');+vi.mock('../../../utils/imageToBase64', async (importOriginal) => ({...((await importOriginal()) as object),imageUrlToBase64: vi.fn(),}));diff --git a/packages/model-runtime/src/core/contextBuilders/anthropic.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/messages.tssimilarity index 97%rename from packages/model-runtime/src/core/contextBuilders/anthropic.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/messages.tsindex 7cbb3c1263c..4aa79ec2be0 100644--- a/packages/model-runtime/src/core/contextBuilders/anthropic.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/messages.ts@@ -1,12 +1,15 @@import type Anthropic from '@anthropic-ai/sdk';import type OpenAI from 'openai';-import type { OpenAIChatMessage, UserMessageContentPart } from '../../types';-import { normalizeAnthropicToolSchema } from '../../utils/anthropicToolSchema';-import { resolveImageMimeTypeFromBase64 } from '../../utils/imageMimeType';-import { imageUrlToBase64 } from '../../utils/imageToBase64';-import { parseDataUri } from '../../utils/uriParser';-import { type InlineImageBudgetOptions, inlineImagesWithinBudget } from './inlineImageBudget';+import type { OpenAIChatMessage, UserMessageContentPart } from '../../../types';+import { normalizeAnthropicToolSchema } from '../../../utils/anthropicToolSchema';+import { resolveImageMimeTypeFromBase64 } from '../../../utils/imageMimeType';+import { imageUrlToBase64 } from '../../../utils/imageToBase64';+import { parseDataUri } from '../../../utils/uriParser';+import {+ type InlineImageBudgetOptions,+ inlineImagesWithinBudget,+} from '../../contextBuilders/inlineImageBudget';const ANTHROPIC_SUPPORTED_IMAGE_TYPES = new Set(['image/jpeg',diff --git a/packages/model-runtime/src/core/protocols/anthropicMessages/nonStreamToStream.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/nonStreamToStream.tsnew file mode 100644index 00000000000..4ae25367128--- /dev/null+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/nonStreamToStream.ts@@ -0,0 +1,68 @@+import type Anthropic from '@anthropic-ai/sdk';++/**+ * Replay a non-streaming Messages reply as the stream events the decoder reads.+ */+export const transformMessageToStream = (message: Anthropic.Message) =>+ new ReadableStream<Anthropic.MessageStreamEvent>({+ start(controller) {+ controller.enqueue({+ message,+ type: 'message_start',+ } satisfies Anthropic.MessageStreamEvent);++ message.content?.forEach((block, index) => {+ if (block.type === 'tool_use' || block.type === 'server_tool_use') {+ controller.enqueue({+ content_block: block,+ index,+ type: 'content_block_start',+ } satisfies Anthropic.MessageStreamEvent);++ controller.enqueue({+ delta: {+ partial_json: JSON.stringify(block.input ?? {}),+ type: 'input_json_delta',+ },+ index,+ type: 'content_block_delta',+ } satisfies Anthropic.MessageStreamEvent);+ }++ if (block.type === 'thinking' || block.type === 'redacted_thinking') {+ controller.enqueue({+ content_block: block,+ index,+ type: 'content_block_start',+ } satisfies Anthropic.MessageStreamEvent);+ }++ if (block.type === 'text') {+ controller.enqueue({+ delta: { text: block.text, type: 'text_delta' },+ index,+ type: 'content_block_delta',+ } satisfies Anthropic.MessageStreamEvent);+ }+ });++ controller.enqueue({+ delta: {+ stop_reason: message.stop_reason,+ stop_sequence: message.stop_sequence ?? null,+ },+ type: 'message_delta',+ usage: {+ cache_creation_input_tokens: message.usage?.cache_creation_input_tokens ?? null,+ cache_read_input_tokens: message.usage?.cache_read_input_tokens ?? null,+ input_tokens: message.usage?.input_tokens ?? null,+ // `message_delta.usage` is cumulative, so it repeats the full output count.+ output_tokens: message.usage?.output_tokens ?? 0,+ server_tool_use: message.usage?.server_tool_use ?? null,+ },+ } satisfies Anthropic.MessageStreamEvent);++ controller.enqueue({ type: 'message_stop' } satisfies Anthropic.MessageStreamEvent);+ controller.close();+ },+ });diff --git a/packages/model-runtime/src/core/protocols/anthropicMessages/payload.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/payload.tsnew file mode 100644index 00000000000..e69b5cb146f--- /dev/null+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/payload.ts@@ -0,0 +1,146 @@+import type Anthropic from '@anthropic-ai/sdk';++import { stripUnsupportedClaudeAssistantPrefill } from '../../../providers/anthropic/claudePrefill';+import { rejectsDisabledThinkingAtEffort } from '../../../providers/anthropic/modelId';+import type { ChatStreamPayload } from '../../../types';+import { resolveModelSamplingParameters } from '../../parameterResolver';+import { type ComputeChatCostOptions } from '../../usageConverters/utils/computeChatCost';+import { buildAnthropicMessages, buildAnthropicTools, buildSearchTool } from './messages';+import { resolveCacheTTL } from './resolveCacheTTL';+import { resolveMaxTokens } from './resolveMaxTokens';+import { resolveClaudeThinkingConfig } from './resolveThinkingConfig';++type AnthropicTools = Anthropic.Tool | Anthropic.WebSearchTool20250305;++/**+ * Build the default Anthropic Messages payload with LobeChat normalization.+ */+export const buildDefaultAnthropicPayload = async (+ payload: ChatStreamPayload,+): Promise<Anthropic.MessageCreateParams> => {+ const {+ messages,+ model,+ max_tokens,+ temperature,+ top_p,+ tools,+ thinking,+ effort,+ enabledContextCaching = true,+ enabledSearch,+ } = payload;++ const { anthropic: anthropicModels } = await import('model-bank');++ const resolvedMaxTokens = await resolveMaxTokens({+ max_tokens,+ model,+ providerModels: anthropicModels,+ thinking,+ });++ // Filter out empty/whitespace-only system prompts — Anthropic API rejects them+ const systemMessage = messages.find((message) => message.role === 'system');+ const userMessages = messages.filter((message) => message.role !== 'system');+ const systemPromptText =+ typeof systemMessage?.content === 'string' && systemMessage.content.trim()+ ? systemMessage.content+ : undefined;++ const systemPrompts = systemPromptText+ ? ([+ {+ cache_control: enabledContextCaching ? { type: 'ephemeral' } : undefined,+ text: systemPromptText,+ type: 'text',+ },+ ] as Anthropic.TextBlockParam[])+ : undefined;++ const postMessages = stripUnsupportedClaudeAssistantPrefill(+ model,+ await buildAnthropicMessages(userMessages, { enabledContextCaching }),+ );++ let postTools = buildAnthropicTools(tools, { enabledContextCaching }) as+ AnthropicTools[] | undefined;++ if (enabledSearch) {+ const webSearchTool = buildSearchTool();+ postTools = postTools?.length ? [...postTools, webSearchTool] : [webSearchTool];+ }++ const resolvedThinking = resolveClaudeThinkingConfig({+ maxTokens: resolvedMaxTokens,+ model,+ thinking,+ });++ if (resolvedThinking && resolvedThinking.type !== 'disabled') {+ return {+ max_tokens: resolvedMaxTokens,+ messages: postMessages,+ model,+ ...(effort ? { output_config: { effort } } : {}),+ system: systemPrompts,+ thinking: resolvedThinking as Anthropic.MessageCreateParams['thinking'],+ tools: postTools as Anthropic.MessageCreateParams['tools'],+ } as Anthropic.MessageCreateParams;+ }++ // Resolve temperature/top_p: Claude 4+ doesn't allow both simultaneously.+ // normalizeTemperature divides by 2 to map LobeChat's 0-2 range to Anthropic's 0-1 range.+ const resolvedSamplingParams = resolveModelSamplingParameters(+ model,+ { temperature, top_p },+ { normalizeTemperature: true, preferTemperature: true },+ );++ // Claude Opus 5 and later reject disabled thinking at effort `xhigh` / `max`; every lower+ // effort level stays valid, so only that pairing is dropped.+ const forwardsEffort =+ !!effort &&+ !(resolvedThinking?.type === 'disabled' && rejectsDisabledThinkingAtEffort(model, effort));++ // Support effort parameter even without thinking (per Claude 4.6 guidance)+ const basePayload: Anthropic.MessageCreateParams = {+ max_tokens: resolvedMaxTokens,+ messages: postMessages,+ model,+ system: systemPrompts,+ temperature: resolvedSamplingParams.temperature,+ tools: postTools as Anthropic.MessageCreateParams['tools'],+ ...(resolvedThinking+ ? { thinking: resolvedThinking as Anthropic.MessageCreateParams['thinking'] }+ : {}),+ top_p: resolvedSamplingParams.top_p,+ };++ // If effort is specified without an incompatible thinking mode, add output_config+ if (forwardsEffort) {+ return {+ ...basePayload,+ output_config: { effort },+ } as Anthropic.MessageCreateParams;+ }++ return basePayload;+};++/**+ * Resolve cache-aware pricing options for usage cost calculation.+ */+export const resolveDefaultAnthropicPricingOptions = (+ requestPayload: ChatStreamPayload,+ anthropicPayload: Anthropic.MessageCreateParams,+): ComputeChatCostOptions | undefined => {+ const cacheTTL = resolveCacheTTL(requestPayload, {+ messages: anthropicPayload.messages,+ system: anthropicPayload.system,+ });++ if (!cacheTTL) return undefined;++ return { lookupParams: { ttl: cacheTTL } };+};diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/resolveCacheTTL.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/resolveCacheTTL.tssimilarity index 96%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/resolveCacheTTL.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/resolveCacheTTL.tsindex e6d98039d2a..c1dd91439d6 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/resolveCacheTTL.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/resolveCacheTTL.ts@@ -1,6 +1,6 @@import type Anthropic from '@anthropic-ai/sdk';-import type { ChatStreamPayload } from '../../types';+import type { ChatStreamPayload } from '../../../types';type CacheTTL = Anthropic.Messages.CacheControlEphemeral['ttl'];diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/resolveMaxTokens.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/resolveMaxTokens.tssimilarity index 94%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/resolveMaxTokens.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/resolveMaxTokens.tsindex 660916406ad..88cae72db19 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/resolveMaxTokens.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/resolveMaxTokens.ts@@ -1,4 +1,4 @@-import type { ChatStreamPayload } from '../../types';+import type { ChatStreamPayload } from '../../../types';const smallContextWindowPatterns = [/claude-3-opus-20240229/,diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/resolveThinkingConfig.test.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/resolveThinkingConfig.test.tssimilarity index 100%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/resolveThinkingConfig.test.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/resolveThinkingConfig.test.tsdiff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/resolveThinkingConfig.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/resolveThinkingConfig.tssimilarity index 96%rename from packages/model-runtime/src/core/anthropicCompatibleFactory/resolveThinkingConfig.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/resolveThinkingConfig.tsindex 55debd8d764..3f5c753632f 100644--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/resolveThinkingConfig.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/resolveThinkingConfig.ts@@ -2,8 +2,8 @@ import {isAdaptiveThinkingDefaultOnModel,isAlwaysThinkingClaudeModel,isThinkingDisplayOmittedByDefaultModel,-} from '../../providers/anthropic/modelId';-import type { ChatStreamPayload } from '../../types';+} from '../../../providers/anthropic/modelId';+import type { ChatStreamPayload } from '../../../types';export interface ResolvedClaudeThinkingConfig {budget_tokens?: number;diff --git a/packages/model-runtime/src/core/streams/anthropic.interruption.test.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/stream.interruption.test.tssimilarity index 99%rename from packages/model-runtime/src/core/streams/anthropic.interruption.test.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/stream.interruption.test.tsindex 0d60b34f071..761eb98265f 100644--- a/packages/model-runtime/src/core/streams/anthropic.interruption.test.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/stream.interruption.test.ts@@ -1,7 +1,7 @@import type { Stream } from '@anthropic-ai/sdk/streaming';import { describe, expect, it, vi } from 'vitest';-import { AnthropicStream } from './anthropic';+import { AnthropicStream } from './stream';describe('AnthropicStream interruptions', () => {it('should report a stream closed without message_delta / message_stop as interrupted', async () => {diff --git a/packages/model-runtime/src/core/streams/anthropic.test.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/stream.test.tssimilarity index 99%rename from packages/model-runtime/src/core/streams/anthropic.test.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/stream.test.tsindex 457b021fe6e..423b31cc2e4 100644--- a/packages/model-runtime/src/core/streams/anthropic.test.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/stream.test.ts@@ -1,8 +1,8 @@import type { Stream } from '@anthropic-ai/sdk/streaming';import { describe, expect, it, vi } from 'vitest';-import { AnthropicStream } from './anthropic';-import { createReadableStream } from './utils';+import { createReadableStream } from '../../streams/utils';+import { AnthropicStream } from './stream';const createMessageStart = <T>(id: string, model: string, usage: T) => ({type: 'message_start',diff --git a/packages/model-runtime/src/core/streams/anthropic.ts b/packages/model-runtime/src/core/protocols/anthropicMessages/stream.tssimilarity index 96%rename from packages/model-runtime/src/core/streams/anthropic.tsrename to packages/model-runtime/src/core/protocols/anthropicMessages/stream.tsindex d5550ededa0..e5c86865488 100644--- a/packages/model-runtime/src/core/streams/anthropic.ts+++ b/packages/model-runtime/src/core/protocols/anthropicMessages/stream.ts@@ -2,28 +2,28 @@ import type Anthropic from '@anthropic-ai/sdk';import type { Stream } from '@anthropic-ai/sdk/streaming';import type { ChatCitationItem, ChatMessageError } from '@lobechat/types';-import type { ChatStreamCallbacks } from '../../types';-import { AgentRuntimeErrorType } from '../../types/error';-import { convertAnthropicUsage } from '../usageConverters';+import type { ChatStreamCallbacks } from '../../../types';+import { AgentRuntimeErrorType } from '../../../types/error';import {createEventCallbacksTransformer,createModelEventTransformer,createSSEEncoder,-} from './events';+} from '../../streams/events';import type {ChatPayloadForTransformStream,StreamContext,StreamProtocolChunk,StreamProtocolToolCallChunk,StreamToolCallChunkData,-} from './protocol';+} from '../../streams/protocol';import {convertIterableToStream,createFirstErrorHandleTransformer,createTokenSpeedCalculator,FIRST_CHUNK_ERROR_KEY,-} from './protocol';-import { recordProviderReportedCost } from './providerReportedCost';+} from '../../streams/protocol';+import { recordProviderReportedCost } from '../../streams/providerReportedCost';+import { convertAnthropicUsage } from '../../usageConverters';export const transformAnthropicStream = (chunk: Anthropic.MessageStreamEvent,diff --git a/packages/model-runtime/src/core/streams/bedrock/claude.ts b/packages/model-runtime/src/core/streams/bedrock/claude.tsindex e84ef3c77fb..390e9f845e9 100644--- a/packages/model-runtime/src/core/streams/bedrock/claude.ts+++ b/packages/model-runtime/src/core/streams/bedrock/claude.ts@@ -2,7 +2,7 @@ import type { InvokeModelWithResponseStreamResponse } from '@aws-sdk/client-bedrimport type { ChatStreamCallbacks } from '../../../types';import { nanoid } from '../../../utils/uuid';-import { transformAnthropicStream } from '../anthropic';+import { transformAnthropicStream } from '../../protocols/anthropicMessages/stream';import {createEventCallbacksTransformer,createModelEventTransformer,diff --git a/packages/model-runtime/src/core/streams/index.ts b/packages/model-runtime/src/core/streams/index.tsindex a49ee2680ba..00bef2a7fa9 100644--- a/packages/model-runtime/src/core/streams/index.ts+++ b/packages/model-runtime/src/core/streams/index.ts@@ -1,4 +1,3 @@-export * from './anthropic';export * from './bedrock';export * from './events';export * from './google';diff --git a/packages/model-runtime/src/core/streams/providerReportedCost.test.ts b/packages/model-runtime/src/core/streams/providerReportedCost.test.tsindex 83b199fd503..c6fcd79873f 100644--- a/packages/model-runtime/src/core/streams/providerReportedCost.test.ts+++ b/packages/model-runtime/src/core/streams/providerReportedCost.test.ts@@ -1,8 +1,8 @@import { describe, expect, it, vi } from 'vitest';+import { AnthropicStream } from '../protocols/anthropicMessages/stream';import { OpenAIStream } from '../protocols/openaiChatCompletions/stream';import { OpenAIResponsesStream } from '../protocols/openaiResponses/stream';-import { AnthropicStream } from './anthropic';import { AWSBedrockClaudeStream } from './bedrock/claude';import { readProviderReportedCost } from './providerReportedCost';diff --git a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.tsindex b8c58c29348..97db880081f 100644--- a/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts+++ b/packages/model-runtime/src/core/usageConverters/utils/computeChatCost.ts@@ -10,7 +10,7 @@ import type {} from 'model-bank';import { CREDITS_PER_DOLLAR, USD_TO_CNY } from '../../../const/currency';-import { DEFAULT_CACHE_TTL } from '../../anthropicCompatibleFactory/resolveCacheTTL';+import { DEFAULT_CACHE_TTL } from '../../protocols/anthropicMessages/resolveCacheTTL';const log = debug('lobe-cost:computeChatPricing');diff --git a/packages/model-runtime/src/providers/anthropic/index.test.ts b/packages/model-runtime/src/providers/anthropic/index.test.tsindex 1889a5c2070..04265ec57c6 100644--- a/packages/model-runtime/src/providers/anthropic/index.test.ts+++ b/packages/model-runtime/src/providers/anthropic/index.test.ts@@ -2,8 +2,8 @@import type { Mock } from 'vitest';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatibleFactory';-import * as anthropicHelpers from '../../core/contextBuilders/anthropic';+import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatible';+import * as anthropicHelpers from '../../core/protocols/anthropicMessages/messages';import type { ChatCompletionTool, ChatStreamPayload } from '../../types/chat';import * as debugStreamModule from '../../utils/debugStream';import { LobeAnthropicAI } from './index';@@ -554,7 +554,7 @@ describe('LobeAnthropicAI', () => {vi.spyOn(customInstance['client'].messages, 'create').mockRejectedValue(apiError);// Act & Assert- // anthropicCompatibleFactory normalizes the `/v1` suffix away (see #14960),+ // anthropicCompatible normalizes the `/v1` suffix away (see #14960),// then desensitizeUrl reconstructs via the WHATWG URL parser which always// emits a trailing `/` in the pathname.await expect(diff --git a/packages/model-runtime/src/providers/anthropic/index.ts b/packages/model-runtime/src/providers/anthropic/index.tsindex 46eed63b8ea..2e28aedb533 100644--- a/packages/model-runtime/src/providers/anthropic/index.ts+++ b/packages/model-runtime/src/providers/anthropic/index.ts@@ -4,7 +4,7 @@ import {buildDefaultAnthropicPayload,createAnthropicCompatibleParams,createAnthropicCompatibleRuntime,-} from '../../core/anthropicCompatibleFactory';+} from '../../core/anthropicCompatible';import type { ChatStreamPayload } from '../../types';import { normalizeClaudeThinkingHistoryMessages } from './claudeThinkingHistory';import { supportsClaudeEffortLevel } from './modelId';diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.tsindex 98a7e424548..b12a67cc466 100644--- a/packages/model-runtime/src/providers/bedrock/index.ts+++ b/packages/model-runtime/src/providers/bedrock/index.ts@@ -6,18 +6,21 @@ import {} from '@aws-sdk/client-bedrock-runtime';import { ModelProvider } from 'model-bank';-import type { AnthropicGenerateObjectResponse } from '../../core/anthropicCompatibleFactory/generateObject';+import type { LobeRuntimeAI } from '../../core/BaseAI';+import { resolveModelSamplingParameters } from '../../core/parameterResolver';+import type { AnthropicGenerateObjectResponse } from '../../core/protocols/anthropicMessages/generateObject';import {buildAnthropicGenerateObjectRequest,emitAnthropicGenerateObjectUsage,parseAnthropicGenerateObjectResponse,-} from '../../core/anthropicCompatibleFactory/generateObject';-import { resolveCacheTTL } from '../../core/anthropicCompatibleFactory/resolveCacheTTL';-import { resolveMaxTokens } from '../../core/anthropicCompatibleFactory/resolveMaxTokens';-import { resolveClaudeThinkingConfig } from '../../core/anthropicCompatibleFactory/resolveThinkingConfig';-import type { LobeRuntimeAI } from '../../core/BaseAI';-import { buildAnthropicMessages, buildAnthropicTools } from '../../core/contextBuilders/anthropic';-import { resolveModelSamplingParameters } from '../../core/parameterResolver';+} from '../../core/protocols/anthropicMessages/generateObject';+import {+ buildAnthropicMessages,+ buildAnthropicTools,+} from '../../core/protocols/anthropicMessages/messages';+import { resolveCacheTTL } from '../../core/protocols/anthropicMessages/resolveCacheTTL';+import { resolveMaxTokens } from '../../core/protocols/anthropicMessages/resolveMaxTokens';+import { resolveClaudeThinkingConfig } from '../../core/protocols/anthropicMessages/resolveThinkingConfig';import {finalizeProviderResponse,initializeProviderDiagnostics,diff --git a/packages/model-runtime/src/providers/deepseek/chatPayload.ts b/packages/model-runtime/src/providers/deepseek/chatPayload.tsindex 7101666169d..27c6fd6743f 100644--- a/packages/model-runtime/src/providers/deepseek/chatPayload.ts+++ b/packages/model-runtime/src/providers/deepseek/chatPayload.ts@@ -2,7 +2,7 @@ import type Anthropic from '@anthropic-ai/sdk';import { ModelProvider } from 'model-bank';import type OpenAI from 'openai';-import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatibleFactory';+import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatible';import type { ChatStreamPayload } from '../../types';import { getModelPropertyWithFallback } from '../../utils/getFallbackModelProperty';import { isDeepSeekV4FamilyModel } from '../../utils/modelParse';diff --git a/packages/model-runtime/src/providers/deepseek/generateObject.ts b/packages/model-runtime/src/providers/deepseek/generateObject.tsindex 17f9bd8027b..4e9dd0d9ff5 100644--- a/packages/model-runtime/src/providers/deepseek/generateObject.ts+++ b/packages/model-runtime/src/providers/deepseek/generateObject.ts@@ -1,9 +1,9 @@import type Anthropic from '@anthropic-ai/sdk';import type { Pricing } from 'model-bank';-import type { AnthropicGenerateObjectConfig } from '../../core/anthropicCompatibleFactory/generateObject';-import { createAnthropicGenerateObject } from '../../core/anthropicCompatibleFactory/generateObject';import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatible';+import type { AnthropicGenerateObjectConfig } from '../../core/protocols/anthropicMessages/generateObject';+import { createAnthropicGenerateObject } from '../../core/protocols/anthropicMessages/generateObject';import type { ChatStreamPayload, GenerateObjectOptions, GenerateObjectPayload } from '../../types';import { isDeepSeekV4Model } from './chatPayload';import { sanitizeDeepSeekJsonPayload } from './sanitizePayload';diff --git a/packages/model-runtime/src/providers/deepseek/index.ts b/packages/model-runtime/src/providers/deepseek/index.tsindex 76e8ea0d256..7d0bb0838cc 100644--- a/packages/model-runtime/src/providers/deepseek/index.ts+++ b/packages/model-runtime/src/providers/deepseek/index.ts@@ -3,7 +3,7 @@ import { ModelProvider } from 'model-bank';import {createAnthropicCompatibleParams,createAnthropicCompatibleRuntime,-} from '../../core/anthropicCompatibleFactory';+} from '../../core/anthropicCompatible';import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatible';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatible';import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime';diff --git a/packages/model-runtime/src/providers/githubCopilot/index.ts b/packages/model-runtime/src/providers/githubCopilot/index.tsindex cd0e3c60d6a..a491d5854e0 100644--- a/packages/model-runtime/src/providers/githubCopilot/index.ts+++ b/packages/model-runtime/src/providers/githubCopilot/index.ts@@ -3,15 +3,15 @@ import { type ChatModelCard } from '@lobechat/types';import { ModelProvider } from 'model-bank';import OpenAI from 'openai';-import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatibleFactory';+import { buildDefaultAnthropicPayload } from '../../core/anthropicCompatible';import { type LobeRuntimeAI } from '../../core/BaseAI';import { pruneReasoningPayload } from '../../core/contextBuilders/openai';import { transformResponseAPIToStream } from '../../core/openaiCompatible';+import { AnthropicStream } from '../../core/protocols/anthropicMessages/stream';import { convertOpenAIMessages } from '../../core/protocols/openaiChatCompletions/messages';import { OpenAIStream } from '../../core/protocols/openaiChatCompletions/stream';import { convertOpenAIResponseInputs } from '../../core/protocols/openaiResponses/inputs';import { OpenAIResponsesStream } from '../../core/protocols/openaiResponses/stream';-import { AnthropicStream } from '../../core/streams';import { type ChatMethodOptions, type ChatStreamPayload } from '../../types';import { AgentRuntimeErrorType } from '../../types/error';import { AgentRuntimeError } from '../../utils/createError';diff --git a/packages/model-runtime/src/providers/kimiCodingPlan/index.ts b/packages/model-runtime/src/providers/kimiCodingPlan/index.tsindex 4d8c515cb91..6acdd53d03d 100644--- a/packages/model-runtime/src/providers/kimiCodingPlan/index.ts+++ b/packages/model-runtime/src/providers/kimiCodingPlan/index.ts@@ -5,7 +5,7 @@ import {buildDefaultAnthropicPayload,createAnthropicCompatibleParams,createAnthropicCompatibleRuntime,-} from '../../core/anthropicCompatibleFactory';+} from '../../core/anthropicCompatible';import type { ChatStreamPayload } from '../../types';import { processMultiProviderModelList } from '../../utils/modelParse';import { sanitizeAnthropicThinkingParts } from '../../utils/sanitizeAnthropicThinkingParts';diff --git a/packages/model-runtime/src/providers/minimax/index.ts b/packages/model-runtime/src/providers/minimax/index.tsindex 885ce03481f..eb09712efcf 100644--- a/packages/model-runtime/src/providers/minimax/index.ts+++ b/packages/model-runtime/src/providers/minimax/index.ts@@ -5,7 +5,7 @@ import {buildDefaultAnthropicPayload,createAnthropicCompatibleParams,createAnthropicCompatibleRuntime,-} from '../../core/anthropicCompatibleFactory';+} from '../../core/anthropicCompatible';import type { OpenAICompatibleFactoryOptions } from '../../core/openaiCompatible';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatible';import { resolveParameters } from '../../core/parameterResolver';diff --git a/packages/model-runtime/src/providers/moonshot/index.ts b/packages/model-runtime/src/providers/moonshot/index.tsindex 2cdff344cf8..532b7e69942 100644--- a/packages/model-runtime/src/providers/moonshot/index.ts+++ b/packages/model-runtime/src/providers/moonshot/index.ts@@ -8,10 +8,10 @@ import {buildDefaultAnthropicPayload,createAnthropicCompatibleParams,createAnthropicCompatibleRuntime,-} from '../../core/anthropicCompatibleFactory';-import type { AnthropicGenerateObjectConfig } from '../../core/anthropicCompatibleFactory/generateObject';-import { createAnthropicGenerateObject } from '../../core/anthropicCompatibleFactory/generateObject';+} from '../../core/anthropicCompatible';import { createOpenAICompatibleRuntime } from '../../core/openaiCompatible';+import type { AnthropicGenerateObjectConfig } from '../../core/protocols/anthropicMessages/generateObject';+import { createAnthropicGenerateObject } from '../../core/protocols/anthropicMessages/generateObject';import type { CreateRouterRuntimeOptions } from '../../core/RouterRuntime';import { createRouterRuntime } from '../../core/RouterRuntime';import type { ChatStreamPayload, GenerateObjectOptions, GenerateObjectPayload } from '../../types';diff --git a/packages/model-runtime/src/utils/anthropicToolSchema.test.ts b/packages/model-runtime/src/utils/anthropicToolSchema.test.tsindex e74ea155ff4..f5f49a08895 100644--- a/packages/model-runtime/src/utils/anthropicToolSchema.test.ts+++ b/packages/model-runtime/src/utils/anthropicToolSchema.test.ts@@ -3,7 +3,7 @@ import Ajv from 'ajv';import Ajv2020 from 'ajv/dist/2020';import { describe, expect, it } from 'vitest';-import { buildAnthropicTools } from '../core/contextBuilders/anthropic';+import { buildAnthropicTools } from '../core/protocols/anthropicMessages/messages';import { normalizeAnthropicToolSchema } from './anthropicToolSchema';const ajv = new Ajv({ strict: false });