Skip to content

🤯 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.

🐛 fix: configure anthropic client timeout (#15042)

YuTengjingfc088773bd4d
diff --git a/.env.example b/.env.example
index 87a37e00573..e8cf9b878a3 100644
--- a/.env.example
+++ b/.env.example
@@ -77,6 +77,9 @@ OPENAI_API_KEY=sk-xxxxxxxxx
# use a proxy to connect to the Anthropic API
# ANTHROPIC_PROXY_URL=https://api.anthropic.com
+# Anthropic SDK client timeout in milliseconds
+# ANTHROPIC_CLIENT_TIMEOUT=295000
+
# ## Google AI ####
# GOOGLE_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
diff --git a/Dockerfile b/Dockerfile
index f4ad70ac84f..46cb454d634 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -219,7 +219,7 @@ ENV \
# AiHubMix
AIHUBMIX_API_KEY="" AIHUBMIX_MODEL_LIST="" \
# Anthropic
- ANTHROPIC_API_KEY="" ANTHROPIC_MODEL_LIST="" ANTHROPIC_PROXY_URL="" \
+ ANTHROPIC_API_KEY="" ANTHROPIC_CLIENT_TIMEOUT="" ANTHROPIC_MODEL_LIST="" ANTHROPIC_PROXY_URL="" \
# Amazon Bedrock
ENABLED_AWS_BEDROCK="" AWS_ACCESS_KEY_ID="" AWS_SECRET_ACCESS_KEY="" AWS_REGION="" AWS_BEDROCK_MODEL_LIST="" \
# Azure OpenAI
diff --git a/docs/self-hosting/environment-variables/model-provider.mdx b/docs/self-hosting/environment-variables/model-provider.mdx
index 6e2a4e95968..04d05e797d6 100644
--- a/docs/self-hosting/environment-variables/model-provider.mdx
+++ b/docs/self-hosting/environment-variables/model-provider.mdx
@@ -167,6 +167,13 @@ If you need to use Azure OpenAI to provide model services, you can refer to the
- Default: `https://api.anthropic.com`
- Example: `https://my-anthropic-proxy.com`
+### `ANTHROPIC_CLIENT_TIMEOUT`
+
+- Type: Optional
+- Description: Anthropic SDK client request timeout in milliseconds. This timeout is also used by Anthropic-compatible providers that rely on the Anthropic SDK.
+- Default: `295000`
+- Example: `780000`
+
## AWS Bedrock
### `ENABLED_AWS_BEDROCK`
diff --git a/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx b/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx
index 99679ac1c6d..b136fd76a74 100644
--- a/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/model-provider.zh-CN.mdx
@@ -165,6 +165,13 @@ LobeHub 在部署时提供了丰富的模型服务商相关的环境变量,你
- 默认值:`https://api.anthropic.com`
- 示例:`https://my-anthropic-proxy.com`
+### `ANTHROPIC_CLIENT_TIMEOUT`
+
+- 类型:可选
+- 描述:Anthropic SDK 客户端请求超时时间,单位为毫秒。依赖 Anthropic SDK 的 Anthropic 兼容服务商也会使用此超时时间。
+- 默认值:`295000`
+- 示例:`780000`
+
## AWS Bedrock
### `ENABLED_AWS_BEDROCK`
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
index 950051697bd..91e153a3522 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.test.ts
@@ -1,8 +1,12 @@
// @vitest-environment node
import Anthropic from '@anthropic-ai/sdk';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
-import { createAnthropicCompatibleRuntime, createDefaultAnthropicClient } from './index';
+import {
+ createAnthropicCompatibleRuntime,
+ createDefaultAnthropicClient,
+ DEFAULT_ANTHROPIC_TIMEOUT,
+} from './index';
vi.mock('@anthropic-ai/sdk', () => {
const MockAnthropic = vi.fn();
@@ -14,6 +18,15 @@ vi.mock('@lobechat/const', () => ({
}));
const MockedAnthropic = vi.mocked(Anthropic);
+const originalAnthropicClientTimeout = process.env.ANTHROPIC_CLIENT_TIMEOUT;
+
+afterEach(() => {
+ if (originalAnthropicClientTimeout === undefined) {
+ delete process.env.ANTHROPIC_CLIENT_TIMEOUT;
+ } else {
+ process.env.ANTHROPIC_CLIENT_TIMEOUT = originalAnthropicClientTimeout;
+ }
+});
describe('createDefaultAnthropicClient', () => {
it('should include User-Agent header with current version', () => {
@@ -46,6 +59,67 @@ describe('createDefaultAnthropicClient', () => {
});
});
+ it('should set the default Anthropic timeout explicitly', () => {
+ MockedAnthropic.mockClear();
+ delete process.env.ANTHROPIC_CLIENT_TIMEOUT;
+
+ createDefaultAnthropicClient({ apiKey: 'test-key' });
+
+ expect(MockedAnthropic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ timeout: DEFAULT_ANTHROPIC_TIMEOUT,
+ }),
+ );
+ });
+
+ it('should use ANTHROPIC_CLIENT_TIMEOUT as the default timeout when configured', () => {
+ MockedAnthropic.mockClear();
+ process.env.ANTHROPIC_CLIENT_TIMEOUT = '780000';
+
+ createDefaultAnthropicClient({ apiKey: 'test-key' });
+
+ expect(MockedAnthropic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ timeout: 780_000,
+ }),
+ );
+
+ delete process.env.ANTHROPIC_CLIENT_TIMEOUT;
+ });
+
+ it('should ignore invalid ANTHROPIC_CLIENT_TIMEOUT values', () => {
+ MockedAnthropic.mockClear();
+ process.env.ANTHROPIC_CLIENT_TIMEOUT = 'invalid';
+
+ createDefaultAnthropicClient({ apiKey: 'test-key' });
+
+ expect(MockedAnthropic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ timeout: DEFAULT_ANTHROPIC_TIMEOUT,
+ }),
+ );
+
+ delete process.env.ANTHROPIC_CLIENT_TIMEOUT;
+ });
+
+ it('should preserve caller-provided timeout', () => {
+ MockedAnthropic.mockClear();
+ process.env.ANTHROPIC_CLIENT_TIMEOUT = '780000';
+
+ createDefaultAnthropicClient({
+ apiKey: 'test-key',
+ timeout: 3_600_000,
+ });
+
+ expect(MockedAnthropic).toHaveBeenCalledWith(
+ expect.objectContaining({
+ timeout: 3_600_000,
+ }),
+ );
+
+ delete process.env.ANTHROPIC_CLIENT_TIMEOUT;
+ });
+
it.each([
['https://aihubmix.com/v1', 'https://aihubmix.com'],
['https://aihubmix.com/v1/messages', 'https://aihubmix.com'],
@@ -78,6 +152,7 @@ describe('createAnthropicCompatibleRuntime', () => {
expect(createClient).toHaveBeenCalledWith(
expect.objectContaining({
baseURL: 'https://aihubmix.com',
+ timeout: DEFAULT_ANTHROPIC_TIMEOUT,
}),
);
expect(runtime.baseURL).toBe('https://aihubmix.com');
diff --git a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
index 2b9b4fd4602..5d33a57919c 100644
--- a/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/anthropicCompatibleFactory/index.ts
@@ -44,11 +44,25 @@ type ConstructorOptions<T extends Record<string, any> = any> = ClientOptions & 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';
+/**
+ * Keep Anthropic SDK's timeout explicit so non-streaming structured output
+ * calls with large max_tokens do not hit the SDK's long-request guard before
+ * the request is sent. The default stays below Vercel Hobby's 300s function
+ * duration limit while provider/router options can still override it.
+ */
+export const DEFAULT_ANTHROPIC_TIMEOUT = 295_000;
const ANTHROPIC_SDK_MESSAGES_PATH_PATTERN = /\/v1(?:\/messages)?\/?$/;
const normalizeAnthropicCompatibleBaseURL = (baseURL?: string | null) =>
baseURL?.replace(ANTHROPIC_SDK_MESSAGES_PATH_PATTERN, '');
+const resolveDefaultAnthropicTimeout = () => {
+ const timeout = Number(process.env[ANTHROPIC_CLIENT_TIMEOUT_ENV]);
+
+ return Number.isInteger(timeout) && timeout > 0 ? timeout : DEFAULT_ANTHROPIC_TIMEOUT;
+};
+
export interface CustomClientOptions<T extends Record<string, any> = any> {
createClient?: (options: ConstructorOptions<T>) => Anthropic;
}
@@ -261,7 +275,12 @@ export const createDefaultAnthropicClient = <T extends Record<string, any> = any
...(betaHeaders ? { 'anthropic-beta': betaHeaders } : {}),
};
- return new Anthropic({ ...options, ...(baseURL ? { baseURL } : {}), defaultHeaders });
+ return new Anthropic({
+ ...options,
+ ...(baseURL ? { baseURL } : {}),
+ defaultHeaders,
+ timeout: options.timeout ?? resolveDefaultAnthropicTimeout(),
+ });
};
/**
@@ -466,6 +485,8 @@ export const createAnthropicCompatibleRuntime = <T extends Record<string, any> =
baseURL: finalBaseURL,
...constructorOptions,
...rest,
+ timeout:
+ rest.timeout ?? constructorOptions?.timeout ?? resolveDefaultAnthropicTimeout(),
};
if (customClient?.createClient) {