Skip to content

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

feat(llm): support OpenAI Responses API connections (#14002)

Tobias Wochinger9ce4aa475299
diff --git a/fern/apis/server/definition/llm-connections.yml b/fern/apis/server/definition/llm-connections.yml
index 3a3a731f0e..431d5f9485 100644
--- a/fern/apis/server/definition/llm-connections.yml
+++ b/fern/apis/server/definition/llm-connections.yml
@@ -62,7 +62,7 @@ types:
docs: Keys of extra headers sent with requests (values excluded for security)
config:
type: optional<map<string, unknown>>
- docs: Adapter-specific configuration. Required for Bedrock (`{"region":"us-east-1"}`), optional for VertexAI (`{"location":"us-central1"}`), not used by other adapters.
+ docs: Adapter-specific configuration. Required for Bedrock (`{"region":"us-east-1"}`), optional for OpenAI (`{"useResponsesApi":true}`), optional for VertexAI (`{"location":"us-central1"}`), not used by other adapters.
createdAt: datetime
updatedAt: datetime
@@ -100,6 +100,7 @@ types:
docs: >
Adapter-specific configuration. Validation rules:
- **Bedrock**: Required. Must be `{"region": "<aws-region>"}` (e.g., `{"region":"us-east-1"}`)
+ - **OpenAI**: Optional. If provided, must be `{"useResponsesApi": <boolean>}` to control whether Langfuse routes calls through OpenAI's Responses API.
- **VertexAI**: Optional. If provided, must be `{"location": "<gcp-location>"}` (e.g., `{"location":"us-central1"}`)
- **Other adapters**: Not supported. Omit this field or set to null.
diff --git a/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts b/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts
index db5f399247..5cf4089e98 100644
--- a/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts
+++ b/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts
@@ -11,6 +11,23 @@ export const VERTEXAI_USE_DEFAULT_CREDENTIALS =
export const BedrockConfigSchema = z.object({ region: z.string() });
export type BedrockConfig = z.infer<typeof BedrockConfigSchema>;
+export const LLMConnectionConfigValueSchema = z.union([
+ z.string(),
+ z.boolean(),
+]);
+export const LLMConnectionConfigSchema = z.record(
+ z.string(),
+ LLMConnectionConfigValueSchema,
+);
+export type LLMConnectionConfig = z.infer<typeof LLMConnectionConfigSchema>;
+
+export const OpenAIConfigSchema = z
+ .object({
+ useResponsesApi: z.boolean().default(false),
+ })
+ .strict();
+export type OpenAIConfig = z.infer<typeof OpenAIConfigSchema>;
+
export const BedrockAccessKeysSchema = z
.object({
accessKeyId: z.string().min(1),
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 24a0e5d0fd..4b0311f598 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -24,6 +24,8 @@ import GCPServiceAccountKeySchema, {
BedrockAccessKeysSchema,
BedrockConfigSchema,
BedrockCredentialSchema,
+ LLMConnectionConfig,
+ OpenAIConfigSchema,
VertexAIConfigSchema,
BEDROCK_USE_DEFAULT_CREDENTIALS,
VERTEXAI_USE_DEFAULT_CREDENTIALS,
@@ -185,7 +187,7 @@ type LLMCompletionParams = {
secretKey: string;
extraHeaders?: string | null;
baseURL?: string | null;
- config?: Record<string, string> | null;
+ config?: LLMConnectionConfig | null;
};
structuredOutputSchema?: ZodType | LLMJSONSchema;
callbacks?: BaseCallbackHandler[];
@@ -346,6 +348,7 @@ export async function fetchLLMCompletion(
});
let chatModel: ChatOpenAI | ChatAnthropic | ChatBedrockConverse | ChatGoogle;
+ let usesOpenAIResponsesApi = false;
if (modelParams.adapter === LLMAdapter.Anthropic) {
const shouldNormalizeAnthropicSamplingParams =
modelParams.model?.includes("claude-opus-4-8") ||
@@ -404,6 +407,8 @@ export async function fetchLLMCompletion(
url: baseURL,
modelName: modelParams.model,
});
+ const openAIConfig = OpenAIConfigSchema.parse(config ?? {});
+ usesOpenAIResponsesApi = openAIConfig.useResponsesApi;
chatModel = new ChatOpenAI({
apiKey,
@@ -422,6 +427,7 @@ export async function fetchLLMCompletion(
defaultHeaders: extraHeaders,
fetch: secureLlmFetch("OpenAI LLM base URL"),
},
+ useResponsesApi: openAIConfig.useResponsesApi,
modelKwargs: modelParams.providerOptions,
timeout: timeoutMs,
});
@@ -566,6 +572,8 @@ export async function fetchLLMCompletion(
: runConfig;
const supportsReasoning = adapterSupportsReasoning(modelParams.adapter);
+ const shouldNormalizeStreamingContentBlocks =
+ supportsReasoning || usesOpenAIResponsesApi;
try {
// Important: await all generations in the try block as otherwise `processTracedEvents` will run too early in finally block
@@ -632,7 +640,9 @@ export async function fetchLLMCompletion(
abortController: runtimeTimeoutController,
operation: () =>
chatModel
- .pipe(createBytesOutputParser(supportsReasoning))
+ .pipe(
+ createBytesOutputParser(shouldNormalizeStreamingContentBlocks),
+ )
.stream(finalMessages, runConfigWithTimeout),
});
@@ -735,18 +745,19 @@ function extractCompletionWithReasoning(
}
function createBytesOutputParser(
- filterReasoningBlocks: boolean,
+ normalizeContentBlocks: boolean,
): BytesOutputParser {
- return filterReasoningBlocks
- ? new ReasoningStrippingBytesOutputParser()
+ return normalizeContentBlocks
+ ? new ContentBlockBytesOutputParser()
: new BytesOutputParser();
}
-class ReasoningStrippingBytesOutputParser extends BytesOutputParser {
+class ContentBlockBytesOutputParser extends BytesOutputParser {
// Override `_baseMessageToString` (not `_baseMessageContentToString`) so we
// have the whole AIMessage(Chunk) and can read `contentBlocks`, which the
- // langchain provider translator normalizes into standard blocks. Streaming
- // yields AIMessageChunk instances, so we check both predicates explicitly.
+ // langchain provider translator normalizes into standard blocks. This strips
+ // reasoning blocks and also avoids serializing OpenAI Responses API lifecycle
+ // chunks such as empty `final_answer` phase markers.
protected _baseMessageToString(message: BaseMessage): string {
if (AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {
return splitAIMessage(message).text;
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 9899dc0697..a664ce0953 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -2,6 +2,7 @@ import { LlmApiKeys } from "@prisma/client";
import z from "zod";
import {
BedrockConfigSchema,
+ OpenAIConfigSchema,
VertexAIConfigSchema,
} from "../../interfaces/customLLMProviderConfigSchemas";
import { JSONObjectSchema } from "../../utils/zod";
@@ -513,7 +514,9 @@ export const LLMApiKeySchema = z
baseURL: z.string().nullable(),
customModels: z.array(z.string()),
withDefaultModels: z.boolean(),
- config: z.union([BedrockConfigSchema, VertexAIConfigSchema]).nullish(), // Bedrock and VertexAI have additional config
+ config: z
+ .union([BedrockConfigSchema, VertexAIConfigSchema, OpenAIConfigSchema])
+ .nullish(),
})
// strict mode to prevent extra keys. Thorws error otherwise
// https://github.com/colinhacks/zod?tab=readme-ov-file#strict
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 6e278e0528..feeb1eb576 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -10480,7 +10480,8 @@ components:
nullable: true
description: >-
Adapter-specific configuration. Required for Bedrock
- (`{"region":"us-east-1"}`), optional for VertexAI
+ (`{"region":"us-east-1"}`), optional for OpenAI
+ (`{"useResponsesApi":true}`), optional for VertexAI
(`{"location":"us-central1"}`), not used by other adapters.
createdAt:
type: string
@@ -10554,10 +10555,12 @@ components:
description: >-
Adapter-specific configuration. Validation rules: - **Bedrock**:
Required. Must be `{"region": "<aws-region>"}` (e.g.,
- `{"region":"us-east-1"}`) - **VertexAI**: Optional. If provided,
- must be `{"location": "<gcp-location>"}` (e.g.,
- `{"location":"us-central1"}`) - **Other adapters**: Not supported.
- Omit this field or set to null.
+ `{"region":"us-east-1"}`) - **OpenAI**: Optional. If provided, must
+ be `{"useResponsesApi": <boolean>}` to control whether Langfuse
+ routes calls through OpenAI's Responses API. - **VertexAI**:
+ Optional. If provided, must be `{"location": "<gcp-location>"}`
+ (e.g., `{"location":"us-central1"}`) - **Other adapters**: Not
+ supported. Omit this field or set to null.
required:
- provider
- adapter
diff --git a/web/src/__tests__/server/llm-api-key.servertest.ts b/web/src/__tests__/server/llm-api-key.servertest.ts
index dc6c10614d..60142f3b87 100644
--- a/web/src/__tests__/server/llm-api-key.servertest.ts
+++ b/web/src/__tests__/server/llm-api-key.servertest.ts
@@ -242,6 +242,89 @@ describe("llmApiKey.all RPC", () => {
expect(secretKey).toBeUndefined();
});
+ it("should create and get an OpenAI llm api key with Responses API config", async () => {
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: "test-secret",
+ provider: "openai-responses",
+ adapter: LLMAdapter.OpenAI,
+ baseURL: "https://example.com/v1",
+ customModels: ["openai.gpt-5.4"],
+ withDefaultModels: false,
+ config: { useResponsesApi: true },
+ });
+
+ const { data: llmApiKeys } = await caller.llmApiKey.all({
+ projectId,
+ });
+
+ expect(llmApiKeys).toHaveLength(1);
+ expect(llmApiKeys[0].config).toEqual({ useResponsesApi: true });
+ expect(llmApiKeys[0].customModels).toEqual(["openai.gpt-5.4"]);
+ expect(llmApiKeys[0].secretKey).toBeUndefined();
+ });
+
+ it("should update an OpenAI llm api key to disable Responses API config", async () => {
+ await caller.llmApiKey.create({
+ projectId,
+ secretKey: "test-secret",
+ provider: "openai-responses",
+ adapter: LLMAdapter.OpenAI,
+ baseURL: "https://example.com/v1",
+ customModels: ["openai.gpt-5.4"],
+ withDefaultModels: false,
+ config: { useResponsesApi: true },
+ });
+
+ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({
+ where: {
+ projectId,
+ provider: "openai-responses",
+ },
+ });
+
+ await caller.llmApiKey.update({
+ id: existingKey.id,
+ projectId,
+ provider: "openai-responses",
+ adapter: LLMAdapter.OpenAI,
+ baseURL: "https://example.com/v1",
+ customModels: ["openai.gpt-5.4"],
+ withDefaultModels: false,
+ config: { useResponsesApi: false },
+ });
+
+ const { data: llmApiKeys } = await caller.llmApiKey.all({
+ projectId,
+ });
+
+ expect(llmApiKeys).toHaveLength(1);
+ expect(llmApiKeys[0].config).toEqual({ useResponsesApi: false });
+ });
+
+ it("should preserve empty VertexAI config without applying OpenAI defaults", async () => {
+ await prisma.llmApiKeys.create({
+ data: {
+ projectId,
+ provider: "vertex-empty-config",
+ adapter: LLMAdapter.VertexAI,
+ secretKey: encrypt("test-secret"),
+ displaySecretKey: "...cret",
+ customModels: ["gemini-2.5-flash"],
+ withDefaultModels: false,
+ extraHeaderKeys: [],
+ config: {},
+ },
+ });
+
+ const { data: llmApiKeys } = await caller.llmApiKey.all({
+ projectId,
+ });
+
+ expect(llmApiKeys).toHaveLength(1);
+ expect(llmApiKeys[0].config).toEqual({});
+ });
+
it("should derive the Bedrock auth method in llmApiKey.all without returning secrets", async () => {
await prisma.llmApiKeys.createMany({
data: [
diff --git a/web/src/__tests__/server/llm-connections-api.servertest.ts b/web/src/__tests__/server/llm-connections-api.servertest.ts
index f6e2f5ceff..2f0a37bce0 100644
--- a/web/src/__tests__/server/llm-connections-api.servertest.ts
+++ b/web/src/__tests__/server/llm-connections-api.servertest.ts
@@ -1095,13 +1095,36 @@ describe("/api/public/llm-connections API Endpoints", () => {
expect(response.body.config).toBeNull();
});
- it("should reject OpenAI connection with config", async () => {
+ it("should create OpenAI connection with Responses API config", async () => {
+ const createData = {
+ provider: generateUniqueProvider("openai-responses-api"),
+ adapter: LLMAdapter.OpenAI,
+ secretKey: "sk-test123",
+ config: {
+ useResponsesApi: true,
+ },
+ };
+
+ const response = await makeZodVerifiedAPICall(
+ PutLlmConnectionV1Response,
+ "PUT",
+ "/api/public/llm-connections",
+ createData,
+ auth,
+ 201,
+ );
+
+ expect(response.status).toBe(201);
+ expect(response.body.config).toEqual({ useResponsesApi: true });
+ });
+
+ it("should reject OpenAI connection with unsupported config", async () => {
const createData = {
provider: generateUniqueProvider("openai-with-config"),
adapter: LLMAdapter.OpenAI,
secretKey: "sk-test123",
config: {
- region: "us-east-1", // OpenAI doesn't support config
+ region: "us-east-1",
},
};
@@ -1114,7 +1137,7 @@ describe("/api/public/llm-connections API Endpoints", () => {
expect(response.status).toBe(400);
expect(JSON.stringify(response.body)).toContain(
- "Config is not supported for openai adapter",
+ "Invalid OpenAI config",
);
});
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
index f0ffdb89b0..6336af6ec6 100644
--- a/web/src/features/llm-api-key/server/router.ts
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -20,11 +20,13 @@ import {
GCPServiceAccountKeySchema,
BedrockConfigSchema,
BedrockCredentialSchema,
+ OpenAIConfigSchema,
VertexAIConfigSchema,
BEDROCK_USE_DEFAULT_CREDENTIALS,
VERTEXAI_USE_DEFAULT_CREDENTIALS,
EvaluatorBlockReason,
getEvaluatorBlockMetadata,
+ type LLMConnectionConfig,
} from "@langfuse/shared";
import { findDefaultModelEvalTemplateIds } from "@/src/features/evals/server/defaultModelEvalTemplateRepository";
import { encrypt, decrypt } from "@langfuse/shared/encryption";
@@ -128,11 +130,13 @@ async function testLLMConnection(
];
// Parse config properly for type safety
- let parsedConfig: Record<string, string> | null = null;
+ let parsedConfig: LLMConnectionConfig | null = null;
if (params.config && params.adapter === LLMAdapter.Bedrock) {
const bedrockConfig = BedrockConfigSchema.parse(params.config);
parsedConfig = { region: bedrockConfig.region };
+ } else if (params.config && params.adapter === LLMAdapter.OpenAI) {
+ parsedConfig = OpenAIConfigSchema.parse(params.config);
} else if (params.config && params.adapter === LLMAdapter.VertexAI) {
const vertexAIConfig = VertexAIConfigSchema.parse(params.config);
parsedConfig = vertexAIConfig.location
diff --git a/web/src/features/llm-api-key/types.ts b/web/src/features/llm-api-key/types.ts
index 46b7eedb93..973f155fe2 100644
--- a/web/src/features/llm-api-key/types.ts
+++ b/web/src/features/llm-api-key/types.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
import {
LLMAdapter,
BedrockConfigSchema,
+ OpenAIConfigSchema,
VertexAIConfigSchema,
LLMApiKeySchema,
} from "@langfuse/shared";
@@ -16,7 +17,9 @@ export const LlmApiKeySchema = z.object({
baseURL: z.url().optional(),
withDefaultModels: z.boolean().optional(),
customModels: z.array(z.string().min(1)).optional(),
- config: z.union([VertexAIConfigSchema, BedrockConfigSchema]).optional(),
+ config: z
+ .union([VertexAIConfigSchema, BedrockConfigSchema, OpenAIConfigSchema])
+ .optional(),
extraHeaders: z.record(z.string(), z.string()).optional(),
});
diff --git a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
index fb17af6aad..795ee7f586 100644
--- a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
+++ b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
@@ -5,6 +5,7 @@ import {
type BedrockApiKey,
type BedrockAccessKeys,
type BedrockConfig,
+ type OpenAIConfig,
type VertexAIConfig,
LLMAdapter,
BEDROCK_USE_DEFAULT_CREDENTIALS,
@@ -106,6 +107,7 @@ const createFormSchema = (params: {
authMethod: BedrockAuthMethodSchema,
awsRegion: z.string().optional(),
vertexAILocation: z.string().optional(),
+ openAIUseResponsesApi: z.boolean(),
extraHeaders: z.array(
z.object({
key: z.string().min(1),
@@ -325,6 +327,11 @@ export function CreateLLMApiKeyForm({
existingKey.adapter === LLMAdapter.VertexAI && existingKey.config
? ((existingKey.config as VertexAIConfig).location ?? "")
: "",
+ openAIUseResponsesApi:
+ existingKey.adapter === LLMAdapter.OpenAI &&
+ existingKey.config != null
+ ? Boolean((existingKey.config as OpenAIConfig).useResponsesApi)
+ : false,
awsRegion:
existingKey.adapter === LLMAdapter.Bedrock && existingKey.config
? ((existingKey.config as BedrockConfig).region ?? "")
@@ -346,6 +353,7 @@ export function CreateLLMApiKeyForm({
customModels: [],
extraHeaders: [],
vertexAILocation: "global",
+ openAIUseResponsesApi: false,
awsRegion: "",
awsAccessKeyId: "",
awsSecretAccessKey: "",
@@ -525,7 +533,7 @@ export function CreateLLMApiKeyForm({
}
let secretKey = values.secretKey;
- let config: BedrockConfig | VertexAIConfig | undefined;
+ let config: BedrockConfig | OpenAIConfig | VertexAIConfig | undefined;
if (currentAdapter === LLMAdapter.Bedrock) {
const shouldPreserveExistingBedrockCredentials =
@@ -573,14 +581,18 @@ export function CreateLLMApiKeyForm({
// In create mode, secretKey is already set from values.secretKey
// Build config with location only (projectId removed for security - ADC auto-detects)
- config = {};
+ const vertexAIConfig: VertexAIConfig = {};
if (values.vertexAILocation?.trim()) {
- config.location = values.vertexAILocation.trim();
+ vertexAIConfig.location = values.vertexAILocation.trim();
}
// If config is empty, set to undefined
- if (Object.keys(config).length === 0) {
- config = undefined;
- }
+ config =
+ Object.keys(vertexAIConfig).length > 0 ? vertexAIConfig : undefined;
+ } else if (currentAdapter === LLMAdapter.OpenAI) {
+ config =
+ values.openAIUseResponsesApi || mode === "update"
+ ? { useResponsesApi: values.openAIUseResponsesApi }
+ : undefined;
}
const extraHeaders =
@@ -1225,6 +1237,36 @@ export function CreateLLMApiKeyForm({
/>
)}
+ {/* OpenAI Responses API */}
+ {currentAdapter === LLMAdapter.OpenAI && (
+ <FormField
+ control={form.control}
+ name="openAIUseResponsesApi"
+ render={({ field }) => (
+ <FormItem>
+ <span className="row flex">
+ <span className="flex-1">
+ <FormLabel>Use Responses API</FormLabel>
+ <FormDescription>
+ Route OpenAI requests through the Responses API
+ instead of Chat Completions.
+ </FormDescription>
+ </span>
+
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </span>
+
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ )}
+
{/* Extra Headers */}
{[LLMAdapter.OpenAI, LLMAdapter.Anthropic].includes(
currentAdapter,
diff --git a/web/src/features/public-api/types/llm-connections.ts b/web/src/features/public-api/types/llm-connections.ts
index 56a8b35766..5d4125521a 100644
--- a/web/src/features/public-api/types/llm-connections.ts
+++ b/web/src/features/public-api/types/llm-connections.ts
@@ -6,6 +6,8 @@ import {
BedrockConfigSchema,
BedrockCredentialSchema,
BEDROCK_USE_DEFAULT_CREDENTIALS,
+ LLMConnectionConfigSchema,
+ OpenAIConfigSchema,
VertexAIConfigSchema,
} from "@langfuse/shared";
@@ -20,7 +22,7 @@ export const LlmConnectionResponse = z
customModels: z.array(z.string()),
withDefaultModels: z.boolean(),
extraHeaderKeys: z.array(z.string()),
- config: z.record(z.string(), z.unknown()).nullable(),
+ config: LLMConnectionConfigSchema.nullable(),
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
})
@@ -55,7 +57,7 @@ const PutLlmConnectionV1BodyBase = z.object({
customModels: z.array(z.string().min(1)).optional(),
withDefaultModels: z.boolean().optional().default(true),
extraHeaders: z.record(z.string(), z.string()).optional(),
- config: z.record(z.string(), z.string()).optional(),
+ config: LLMConnectionConfigSchema.optional(),
});
// PUT /api/public/llm-connections request body (upsert) with adapter-specific validation
@@ -103,6 +105,18 @@ export const PutLlmConnectionV1Body = PutLlmConnectionV1BodyBase.superRefine(
});
}
}
+ } else if (adapter === LLMAdapter.OpenAI) {
+ // OpenAI config is optional, but if provided only supports explicit Responses API routing
+ if (config) {
+ const result = OpenAIConfigSchema.safeParse(config);
+ if (!result.success) {
+ ctx.addIssue({
+ code: "custom",
+ message: `Invalid OpenAI config: ${result.error.issues.map((e) => e.message).join(", ")}. Expected: { useResponsesApi: boolean }`,
+ path: ["config"],
+ });
+ }
+ }
} else if (adapter === LLMAdapter.VertexAI) {
// VertexAI config is optional, but if provided must be valid
if (config) {
diff --git a/worker/src/__tests__/secureLlmFetch.test.ts b/worker/src/__tests__/secureLlmFetch.test.ts
index d92ce1fd8d..eca1ea3c1a 100644
--- a/worker/src/__tests__/secureLlmFetch.test.ts
+++ b/worker/src/__tests__/secureLlmFetch.test.ts
@@ -37,6 +37,51 @@ const OPENAI_RESPONSE_BODY = JSON.stringify({
],
});
+const OPENAI_RESPONSES_BODY = JSON.stringify({
+ id: "resp_test",
+ object: "response",
+ created_at: 1,
+ status: "completed",
+ error: null,
+ incomplete_details: null,
+ instructions: null,
+ max_output_tokens: null,
+ model: "gpt-4o-mini",
+ output: [
+ {
+ id: "msg_test",
+ type: "message",
+ status: "completed",
+ role: "assistant",
+ content: [
+ {
+ type: "output_text",
+ text: "4",
+ annotations: [],
+ },
+ ],
+ },
+ ],
+ parallel_tool_calls: true,
+ previous_response_id: null,
+ reasoning: null,
+ store: true,
+ temperature: 0,
+ text: { format: { type: "text" } },
+ tool_choice: "auto",
+ tools: [],
+ top_p: 1,
+ truncation: "disabled",
+ usage: {
+ input_tokens: 10,
+ output_tokens: 1,
+ total_tokens: 11,
+ },
+ user: null,
+ metadata: {},
+});
+const OPENAI_RESPONSES_RESPONSE = JSON.parse(OPENAI_RESPONSES_BODY);
+
describe("secure LLM fetch", () => {
const originalWhitelistedHosts = env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST;
// env is the zod-validated object: read from process.env at module load and
@@ -109,6 +154,138 @@ describe("secure LLM fetch", () => {
});
},
);
+
+ test(
+ "OpenAI Responses API config routes through the responses endpoint",
+ { timeout: 30_000 },
+ async () => {
+ const server = await spinUp((_req, _body, res) => {
+ res.setHeader("content-type", "application/json");
+ res.end(OPENAI_RESPONSES_BODY);
+ });
+
+ const completion = await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ modelParams: {
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ model: "gpt-4o-mini",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt("openai-api-key"),
+ baseURL: `${server.url}/v1`,
+ config: {
+ useResponsesApi: true,
+ },
+ },
+ });
+
+ expect(completion).toBe("4");
+ expect(server.requests).toHaveLength(1);
+ const [request] = server.requests;
+ expect(request.method).toBe("POST");
+ expect(request.url).toBe("/v1/responses");
+ expect(request.headers.authorization).toBe("Bearer openai-api-key");
+ expect(JSON.parse(request.body)).toMatchObject({
+ model: "gpt-4o-mini",
+ });
+ },
+ );
+
+ test(
+ "OpenAI Responses API streaming returns text instead of content block arrays",
+ { timeout: 30_000 },
+ async () => {
+ const server = await spinUp((_req, _body, res) => {
+ res.writeHead(200, {
+ "content-type": "text/event-stream",
+ "cache-control": "no-cache",
+ connection: "keep-alive",
+ });
+
+ const writeEvent = (event: Record<string, unknown>) => {
+ res.write(`data: ${JSON.stringify(event)}\n\n`);
+ };
+
+ writeEvent({
+ type: "response.created",
+ response: {
+ id: "resp_test",
+ model: "gpt-4o-mini",
+ },
+ });
+ writeEvent({
+ type: "response.output_item.added",
+ output_index: 0,
+ item: {
+ id: "msg_test",
+ type: "message",
+ status: "in_progress",
+ role: "assistant",
+ content: [],
+ phase: "final_answer",
+ },
+ });
+ writeEvent({
+ type: "response.output_text.delta",
+ item_id: "msg_test",
+ output_index: 0,
+ content_index: 0,
+ delta: "pong",
+ });
+ writeEvent({
+ type: "response.completed",
+ response: OPENAI_RESPONSES_RESPONSE,
+ });
+ res.write("data: [DONE]\n\n");
+ res.end();
+ });
+
+ const stream = await fetchLLMCompletion({
+ streaming: true,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ modelParams: {
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ model: "gpt-4o-mini",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt("openai-api-key"),
+ baseURL: `${server.url}/v1`,
+ config: {
+ useResponsesApi: true,
+ },
+ },
+ });
+
+ const decoder = new TextDecoder();
+ let text = "";
+ for await (const chunk of stream) {
+ text += decoder.decode(chunk);
+ }
+
+ expect(text).toBe("pong");
+ expect(server.requests).toHaveLength(1);
+ expect(server.requests[0].url).toBe("/v1/responses");
+ },
+ );
});
describe("SSRF protection", () => {