Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(web): cap non-streaming LLM requests (#15613)

Tobias Wochinger341940486091
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 1ff0010998..bad134ea5d 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -27,6 +27,8 @@ export const redisSocketTimeoutMsSchema = z.coerce
})
.default(30_000);
+const DEFAULT_LLM_COMPLETION_TIMEOUT_MS = 120_000;
+
const EnvSchema = z.object({
NEXT_PUBLIC_LANGFUSE_CLOUD_REGION: z.string().optional(),
// Dev-only override: set to an ISO datetime string to shift the legacy blob
@@ -484,7 +486,7 @@ const EnvSchema = z.object({
.number()
.int()
.positive()
- .default(120_000), // 2 minutes
+ .default(DEFAULT_LLM_COMPLETION_TIMEOUT_MS), // 2 minutes
LANGFUSE_AWS_BEDROCK_REGION: z.string().optional(),
LANGFUSE_AWS_BEDROCK_MODEL: z.string().optional(),
diff --git a/packages/shared/src/server/llm/langfuseAiCompletion.ts b/packages/shared/src/server/llm/langfuseAiCompletion.ts
index 8b754659e1..3fa0a96ca0 100644
--- a/packages/shared/src/server/llm/langfuseAiCompletion.ts
+++ b/packages/shared/src/server/llm/langfuseAiCompletion.ts
@@ -43,6 +43,7 @@ export async function generateLangfuseAIText(params: {
model?: string;
maxTokens?: number;
traceSinkParams?: TraceSinkParams;
+ timeout?: number;
}): Promise<string> {
const model = params.model ?? env.LANGFUSE_AWS_BEDROCK_MODEL;
@@ -69,6 +70,7 @@ export async function generateLangfuseAIText(params: {
credentialSource: "langfuse",
}),
trace: params.traceSinkParams,
+ timeout: params.timeout,
});
return result.text;
diff --git a/packages/shared/src/server/llm/llmText.test.ts b/packages/shared/src/server/llm/llmText.test.ts
index 9ad6485a6c..56ce8b0c61 100644
--- a/packages/shared/src/server/llm/llmText.test.ts
+++ b/packages/shared/src/server/llm/llmText.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import { createOpenAI } from "@ai-sdk/openai";
@@ -6,11 +6,13 @@ import { APICallError, tool } from "ai";
import { MockLanguageModelV4 } from "ai/test";
import { encrypt } from "../../encryption";
+import { env } from "../../env";
import { LLMValidationError } from "./errors";
import {
createLLMOutput,
createLLMToolSet,
generateLLMText,
+ getClientInitiatedNonStreamingLlmTimeoutMs,
mapLegacyLLMCompletionParams,
streamLLMText,
} from "./llmText";
@@ -57,6 +59,26 @@ beforeEach(() => {
vi.clearAllMocks();
});
+describe("getClientInitiatedNonStreamingLlmTimeoutMs", () => {
+ const configuredTimeout = env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS;
+
+ afterEach(() => {
+ env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS = configuredTimeout;
+ });
+
+ it.each([
+ { configured: 120_000, expected: 95_000 },
+ { configured: 60_000, expected: 60_000 },
+ ])(
+ "returns $expected for a configured $configured ms timeout",
+ ({ configured, expected }) => {
+ env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS = configured;
+
+ expect(getClientInitiatedNonStreamingLlmTimeoutMs()).toBe(expected);
+ },
+ );
+});
+
describe("generateLLMText", () => {
it("returns the native text and reasoning result", async () => {
useModel(
diff --git a/packages/shared/src/server/llm/llmText.ts b/packages/shared/src/server/llm/llmText.ts
index 1ac665ba36..e813775aac 100644
--- a/packages/shared/src/server/llm/llmText.ts
+++ b/packages/shared/src/server/llm/llmText.ts
@@ -60,6 +60,15 @@ import { decryptAndParseExtraHeaders } from "./utils";
type RuntimeContext = Record<string, unknown>;
type ProviderOptions = Record<string, Record<string, JSONValue>>;
+const CLIENT_INITIATED_NON_STREAMING_LLM_TIMEOUT_CAP_MS = 95_000;
+
+// Finish client-initiated non-streaming calls before the 102-second load balancer timeout.
+export const getClientInitiatedNonStreamingLlmTimeoutMs = () =>
+ Math.min(
+ env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS,
+ CLIENT_INITIATED_NON_STREAMING_LLM_TIMEOUT_CAP_MS,
+ );
+
export type LLMModelRef = {
adapter: LLMAdapter;
id: string;
diff --git a/packages/shared/src/server/llm/testModelCall.ts b/packages/shared/src/server/llm/testModelCall.ts
index 437f2270fd..f908c8ce81 100644
--- a/packages/shared/src/server/llm/testModelCall.ts
+++ b/packages/shared/src/server/llm/testModelCall.ts
@@ -20,12 +20,14 @@ export const testModelCall = async ({
apiKey,
modelConfig,
structuredOutputSchema,
+ timeout,
}: {
provider: string;
model: string;
apiKey: z.infer<typeof LLMApiKeySchema>;
modelConfig?: ModelConfig | null;
structuredOutputSchema?: StructuredOutputSchema;
+ timeout?: number;
}) => {
const schema =
structuredOutputSchema ??
@@ -53,5 +55,6 @@ export const testModelCall = async ({
},
}),
output: createLLMOutput(schema),
+ timeout,
});
};
diff --git a/packages/shared/src/server/services/DefaultEvaluationModelService/DefaultEvalModelService.ts b/packages/shared/src/server/services/DefaultEvaluationModelService/DefaultEvalModelService.ts
index 3cd1d5f8b7..df3e0876d4 100644
--- a/packages/shared/src/server/services/DefaultEvaluationModelService/DefaultEvalModelService.ts
+++ b/packages/shared/src/server/services/DefaultEvaluationModelService/DefaultEvalModelService.ts
@@ -1,6 +1,7 @@
import z from "zod";
import { prisma } from "../../../db";
import { ForbiddenError, LangfuseNotFoundError } from "../../../errors";
+import { getClientInitiatedNonStreamingLlmTimeoutMs } from "../../llm/llmText";
import { LLMAdapter, LLMApiKeySchema, ZodModelConfig } from "../../llm/types";
import { testModelCall } from "../../llm/testModelCall";
@@ -57,6 +58,7 @@ export class DefaultEvalModelService {
model,
apiKey: llmApiKey as z.infer<typeof LLMApiKeySchema>,
modelConfig: modelParams,
+ timeout: getClientInitiatedNonStreamingLlmTimeoutMs(),
});
}
} catch (err) {
diff --git a/web/src/__tests__/server/llm-api-key.servertest.ts b/web/src/__tests__/server/llm-api-key.servertest.ts
index 7512962e52..d0361c7b2a 100644
--- a/web/src/__tests__/server/llm-api-key.servertest.ts
+++ b/web/src/__tests__/server/llm-api-key.servertest.ts
@@ -511,6 +511,9 @@ describe("llmApiKey.all RPC", () => {
expect(result).toEqual({ success: true });
expect(mockGenerateLLMText).toHaveBeenCalledTimes(1);
+ expect(mockGenerateLLMText).toHaveBeenCalledWith(
+ expect.objectContaining({ timeout: 95_000 }),
+ );
});
it("should allow testUpdate without a new secret key when the base URL is unchanged", async () => {
diff --git a/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts b/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts
index 7ee3128ed1..9e80244505 100644
--- a/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts
+++ b/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts
@@ -100,6 +100,7 @@ describe("chatCompletionHandler", () => {
model: { adapter: "openai", id: "gpt-4.1" },
connection: { secretKey: "encrypted-key" },
messages: [{ role: "user", content: "Hello" }],
+ timeout: 95_000,
});
});
@@ -213,6 +214,11 @@ describe("chatCompletionHandler", () => {
"text/plain; charset=utf-8",
);
expect(mocks.generate).not.toHaveBeenCalled();
+ expect(mocks.stream).toHaveBeenCalledWith({
+ model: { adapter: "openai", id: "gpt-4.1" },
+ connection: { secretKey: "encrypted-key" },
+ messages: [{ role: "user", content: "Hello" }],
+ });
});
it("preserves terminal LLM configuration status codes", async () => {
diff --git a/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts b/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts
index 82c710c4ce..a6aaf23ce5 100644
--- a/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts
+++ b/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts
@@ -130,7 +130,7 @@ describe("evaluator preflight", () => {
expect(mockGetLLMErrorInfo).not.toHaveBeenCalled();
});
- describe("live provider call failures", () => {
+ describe("live provider calls", () => {
// The preflight skips the provider call in test-like environments;
// stub these so the mocked testModelCall is actually reached.
beforeEach(() => {
@@ -142,6 +142,21 @@ describe("evaluator preflight", () => {
vi.unstubAllEnvs();
});
+ it("limits the non-streaming model call to 95 seconds", async () => {
+ const result = await getEvaluatorDefinitionPreflightError({
+ projectId: "project_test",
+ template: {
+ name: "Answer correctness",
+ outputDefinition: numericOutputDefinition,
+ },
+ });
+
+ expect(result).toBeNull();
+ expect(mockTestModelCall).toHaveBeenCalledWith(
+ expect.objectContaining({ timeout: 95_000 }),
+ );
+ });
+
it("returns a clean model-not-found message when the provider responds with 404", async () => {
mockTestModelCall.mockRejectedValue(
new Error(
diff --git a/web/src/features/evals/server/evalTemplateCreation.ts b/web/src/features/evals/server/evalTemplateCreation.ts
index 4864e65d1c..dee73097ff 100644
--- a/web/src/features/evals/server/evalTemplateCreation.ts
+++ b/web/src/features/evals/server/evalTemplateCreation.ts
@@ -9,6 +9,7 @@ import {
import {
CODE_EVAL_SOURCE_MAX_BYTES,
DefaultEvalModelService,
+ getClientInitiatedNonStreamingLlmTimeoutMs,
testModelCall,
} from "@langfuse/shared/src/server";
import { TRPCError } from "@trpc/server";
@@ -126,6 +127,7 @@ async function validateLlmAsJudgeTemplateModel(
structuredOutputSchema: compilePersistedEvalOutputDefinition(
input.outputDefinition,
).outputResultSchema,
+ timeout: getClientInitiatedNonStreamingLlmTimeoutMs(),
});
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
diff --git a/web/src/features/evals/server/evaluator-preflight.ts b/web/src/features/evals/server/evaluator-preflight.ts
index caa0f60e64..5d78946231 100644
--- a/web/src/features/evals/server/evaluator-preflight.ts
+++ b/web/src/features/evals/server/evaluator-preflight.ts
@@ -5,6 +5,7 @@ import {
} from "@langfuse/shared";
import {
DefaultEvalModelService,
+ getClientInitiatedNonStreamingLlmTimeoutMs,
getLLMErrorInfo,
testModelCall,
} from "@langfuse/shared/src/server";
@@ -73,6 +74,7 @@ export async function getEvaluatorDefinitionPreflightError(params: {
apiKey: modelConfig.config.apiKey,
modelConfig: modelConfig.config.modelParams,
structuredOutputSchema: compiledOutputDefinition.outputResultSchema,
+ timeout: getClientInitiatedNonStreamingLlmTimeoutMs(),
});
} catch (err) {
const llmError = getLLMErrorInfo(err);
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
index 478340177a..8a367b808e 100644
--- a/web/src/features/llm-api-key/server/router.ts
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -33,6 +33,7 @@ import { encrypt, decrypt } from "@langfuse/shared/encryption";
import {
ChatMessageType,
generateLLMText,
+ getClientInitiatedNonStreamingLlmTimeoutMs,
LLMAdapter,
logger,
mapLegacyLLMCompletionParams,
@@ -162,6 +163,7 @@ async function testLLMConnection(
messages: testMessages,
}),
maxRetries: 1,
+ timeout: getClientInitiatedNonStreamingLlmTimeoutMs(),
});
return { success: true };
diff --git a/web/src/features/natural-language-filters/server/router.ts b/web/src/features/natural-language-filters/server/router.ts
index 0abc2166b9..ed5ea0925f 100644
--- a/web/src/features/natural-language-filters/server/router.ts
+++ b/web/src/features/natural-language-filters/server/router.ts
@@ -9,6 +9,7 @@ import {
LangfuseInternalTraceEnvironment,
logger,
generateLangfuseAIText,
+ getClientInitiatedNonStreamingLlmTimeoutMs,
getLangfuseAITraceSinkParams,
isLangfuseAITracingConfigured,
} from "@langfuse/shared/src/server";
@@ -122,6 +123,7 @@ export const naturalLanguageFilterRouter = createTRPCRouter({
type: ChatMessageType.PublicAPICreated,
})),
maxTokens: 1000,
+ timeout: getClientInitiatedNonStreamingLlmTimeoutMs(),
traceSinkParams: aiTelemetryEnabled
? getLangfuseAITraceSinkParams({
environment:
diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.ts
index d0974df578..e5258faf9c 100644
--- a/web/src/features/playground/server/chatCompletionHandler.ts
+++ b/web/src/features/playground/server/chatCompletionHandler.ts
@@ -17,6 +17,7 @@ import {
createLLMOutput,
createLLMToolSet,
generateLLMText,
+ getClientInitiatedNonStreamingLlmTimeoutMs,
getLLMErrorInfo,
logger,
contextWithLangfuseProps,
@@ -110,10 +111,14 @@ export default async function chatCompletionHandler(req: NextRequest) {
messages: fixedMessages,
modelParams,
});
+ const nonStreamingCompletionParams = {
+ ...completionParams,
+ timeout: getClientInitiatedNonStreamingLlmTimeoutMs(),
+ };
if (structuredOutputSchema) {
const result = await generateLLMText({
- ...completionParams,
+ ...nonStreamingCompletionParams,
output: createLLMOutput(structuredOutputSchema),
});
return NextResponse.json(result.output);
@@ -121,7 +126,7 @@ export default async function chatCompletionHandler(req: NextRequest) {
if ((tools && tools.length > 0) || hasToolResults) {
const result = await generateLLMText({
- ...completionParams,
+ ...nonStreamingCompletionParams,
tools: createLLMToolSet(tools ?? []),
});
return NextResponse.json({
@@ -154,7 +159,7 @@ export default async function chatCompletionHandler(req: NextRequest) {
},
);
}
- const completion = await generateLLMText(completionParams);
+ const completion = await generateLLMText(nonStreamingCompletionParams);
return NextResponse.json({
content: completion.text,
...(completion.finalStep.reasoningText
diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.ts
index d4e4fd4c21..2ae7c02e31 100644
--- a/web/src/features/search-bar/server/router.ts
+++ b/web/src/features/search-bar/server/router.ts
@@ -25,6 +25,7 @@ import {
LangfuseInternalTraceEnvironment,
logger,
generateLangfuseAIText,
+ getClientInitiatedNonStreamingLlmTimeoutMs,
getLangfuseAITraceSinkParams,
isLangfuseAITracingConfigured,
} from "@langfuse/shared/src/server";
@@ -201,6 +202,7 @@ export const searchBarRouter = createTRPCRouter({
messages,
model,
maxTokens: 2048,
+ timeout: getClientInitiatedNonStreamingLlmTimeoutMs(),
traceSinkParams: aiTelemetryEnabled
? getLangfuseAITraceSinkParams({
traceId,