Skip to content

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

feat(llm-invocations): allow additional provider options (#8510)

Hassieb Pakzad1cf7c81386bb
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 94d0f4db9e..07ef45649f 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -242,6 +242,7 @@ export async function fetchLLMCompletion(
timeout: 1000 * 60 * 2, // 2 minutes timeout
...(proxyAgent && { httpAgent: proxyAgent }),
},
+ invocationKwargs: modelParams.providerOptions,
});
} else if (modelParams.adapter === LLMAdapter.OpenAI) {
chatModel = new ChatOpenAI({
@@ -258,6 +259,7 @@ export async function fetchLLMCompletion(
defaultHeaders: extraHeaders,
...(proxyAgent && { httpAgent: proxyAgent }),
},
+ modelKwargs: modelParams.providerOptions,
timeout: 1000 * 60 * 2, // 2 minutes timeout
});
} else if (modelParams.adapter === LLMAdapter.Azure) {
@@ -276,6 +278,7 @@ export async function fetchLLMCompletion(
defaultHeaders: extraHeaders,
...(proxyAgent && { httpAgent: proxyAgent }),
},
+ modelKwargs: modelParams.providerOptions,
});
} else if (modelParams.adapter === LLMAdapter.Bedrock) {
const { region } = BedrockConfigSchema.parse(config);
@@ -295,6 +298,7 @@ export async function fetchLLMCompletion(
callbacks: finalCallbacks,
maxRetries,
timeout: 1000 * 60 * 2, // 2 minutes timeout
+ additionalModelRequestFields: modelParams.providerOptions as any,
});
} else if (modelParams.adapter === LLMAdapter.VertexAI) {
const credentials = GCPServiceAccountKeySchema.parse(JSON.parse(apiKey));
@@ -351,52 +355,6 @@ export async function fetchLLMCompletion(
};
}
- /*
- Workaround OpenAI reasoning models:
-
- This is a temporary workaround to avoid sending unsupported parameters to OpenAI's O1 models.
- O1 models do not support:
- - system messages
- - top_p
- - max_tokens at all, one has to use max_completion_tokens instead
- - temperature different than 1
-
- Reference: https://platform.openai.com/docs/guides/reasoning/beta-limitations
- */
- if (
- modelParams.model.startsWith("o1-") ||
- modelParams.model.startsWith("o3-")
- ) {
- const filteredMessages = finalMessages.filter((message) => {
- return (
- modelParams.model.startsWith("o3-") || message._getType() !== "system"
- );
- });
-
- return {
- completion: await new ChatOpenAI({
- openAIApiKey: apiKey,
- modelName: modelParams.model,
- temperature: 1,
- maxTokens: undefined,
- topP: undefined,
- callbacks,
- maxRetries,
- modelKwargs: {
- max_completion_tokens: modelParams.max_tokens,
- },
- configuration: {
- baseURL,
- ...(proxyAgent && { httpAgent: proxyAgent }),
- },
- timeout: 1000 * 60 * 2, // 2 minutes timeout
- })
- .pipe(new StringOutputParser())
- .invoke(filteredMessages, runConfig),
- processTracedEvents,
- };
- }
-
if (tools && tools.length > 0) {
const langchainTools = tools.map((tool) => ({
type: "function",
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 3be41e60de..be8659cc59 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -6,6 +6,7 @@ import {
} from "../../interfaces/customLLMProviderConfigSchemas";
import { TokenCountDelegate } from "../ingestion/processEventBatch";
import { AuthHeaderValidVerificationResult } from "../auth/types";
+import { JSONObjectSchema } from "../../utils/zod";
/* eslint-disable no-unused-vars */
// disable lint as this is exported and used in web/worker
@@ -271,6 +272,7 @@ export const ZodModelConfig = z.object({
max_tokens: z.coerce.number().optional(),
temperature: z.coerce.number().optional(),
top_p: z.coerce.number().optional(),
+ providerOptions: JSONObjectSchema.optional(),
});
// Experiment config
diff --git a/packages/shared/src/utils/zod.ts b/packages/shared/src/utils/zod.ts
index 3f3831df44..69b3f12dca 100644
--- a/packages/shared/src/utils/zod.ts
+++ b/packages/shared/src/utils/zod.ts
@@ -1,3 +1,4 @@
+import { InputJsonValue } from "@prisma/client/runtime/library";
import { z } from "zod/v4";
// to be used for Prisma JSON type
@@ -111,3 +112,26 @@ export const validateZodSchema = <T extends z.ZodTypeAny>(
): z.infer<T> => {
return schema.parse(object);
};
+
+// JSON Schema validation
+export const JSONPrimitiveValueSchema = z.union([
+ z.string(),
+ z.number().finite(),
+ z.boolean(),
+]);
+
+export const JSONValueSchema: z.ZodType<InputJsonValue> = z.lazy(() =>
+ z.union([
+ JSONPrimitiveValueSchema,
+ z.array(JSONValueSchema),
+ z.record(z.string(), JSONValueSchema),
+ ]),
+);
+
+export const JSONObjectSchema = z.record(z.string(), JSONValueSchema);
+export const JSONArraySchema = z.array(JSONValueSchema);
+
+export type JSONPrimitiveValue = z.infer<typeof JSONPrimitiveValueSchema>;
+export type JSONValue = z.infer<typeof JSONValueSchema>;
+export type JSONObject = z.infer<typeof JSONObjectSchema>;
+export type JSONArray = z.infer<typeof JSONArraySchema>;
diff --git a/web/src/components/ModelParameters/index.tsx b/web/src/components/ModelParameters/index.tsx
index ff0401fec5..b7b4ca55b3 100644
--- a/web/src/components/ModelParameters/index.tsx
+++ b/web/src/components/ModelParameters/index.tsx
@@ -15,19 +15,27 @@ import { CreateLLMApiKeyDialog } from "@/src/features/public-api/components/Crea
import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import { cn } from "@/src/utils/tailwind";
import {
- type LLMAdapter,
+ type JSONObject,
+ JSONObjectSchema,
+ LLMAdapter,
type supportedModels,
type UIModelParams,
} from "@langfuse/shared";
-import { Settings2 } from "lucide-react";
+import { InfoIcon, Settings2 } from "lucide-react";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/src/components/ui/popover";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
import { LLMApiKeyComponent } from "./LLMApiKeyComponent";
import { FormDescription } from "@/src/components/ui/form";
+import { CodeMirrorEditor } from "../editor";
export type ModelParamsContext = {
modelParams: UIModelParams;
@@ -99,6 +107,11 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
);
}
+ const isProviderOptionsSupported = ![
+ LLMAdapter.GoogleAIStudio,
+ LLMAdapter.VertexAI,
+ ].includes(modelParams.adapter.value);
+
// Settings button component for reuse
const SettingsButton = (
<Popover open={modelSettingsOpen} onOpenChange={setModelSettingsOpen}>
@@ -166,6 +179,15 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."
updateModelParam={updateModelParamValue}
/>
+ {isProviderOptionsSupported ? (
+ <ProviderOptionsInput
+ value={modelParams.providerOptions.value}
+ formDisabled={formDisabled}
+ enabled={modelParams.providerOptions.enabled}
+ setModelParamEnabled={setModelParamEnabled}
+ updateModelParam={updateModelParamValue}
+ />
+ ) : null}
<LLMApiKeyComponent {...{ projectId, modelParams }} />
</div>
</PopoverContent>
@@ -273,21 +295,6 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
layout="vertical"
/>
</div>
-
- {modelParams.model.value?.startsWith("o1-") ? (
- <p className="mt-1 text-xs text-dark-yellow">
- For {modelParams.model.value}, the system message and the
- temperature, max_tokens and top_p setting are not supported while it
- is in beta.{" "}
- <a
- href="https://platform.openai.com/docs/guides/reasoning/beta-limitations"
- target="_blank"
- rel="noreferrer noopener"
- >
- More info ↗
- </a>
- </p>
- ) : null}
</div>
</div>
);
@@ -484,3 +491,92 @@ const ModelParamsSlider = ({
</div>
);
};
+
+type ProviderOptionsInputProps = {
+ value: JSONObject | undefined;
+ updateModelParam: ModelParamsContext["updateModelParamValue"];
+ setModelParamEnabled: ModelParamsContext["setModelParamEnabled"];
+ enabled: boolean;
+ formDisabled: boolean;
+};
+const ProviderOptionsInput = ({
+ value,
+ updateModelParam,
+ setModelParamEnabled,
+ enabled,
+ formDisabled,
+}: ProviderOptionsInputProps) => {
+ const [inputValue, setInputValue] = useState<string>(
+ value ? JSON.stringify(value, null, 2) : "{}",
+ );
+ const [error, setError] = useState<string | null>(null);
+
+ return (
+ <div
+ className="space-y-3"
+ title="Additional options to pass to the invocation. Please check your provider's API reference for supported values."
+ >
+ <div className="flex flex-row">
+ <div className="flex-1 flex-row space-x-1">
+ <span
+ className={cn(
+ "text-xs font-semibold",
+ (!enabled || formDisabled) && "text-muted-foreground",
+ )}
+ >
+ Additional options
+ </span>
+ <Tooltip>
+ <TooltipTrigger>
+ <InfoIcon className="size-3 text-muted-foreground" />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-[200px] p-2">
+ Additional options to pass to the invocation. Please check your
+ provider&apos;s API reference for supported values.
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ <div className="flex flex-row space-x-3">
+ {setModelParamEnabled ? (
+ <Switch
+ title={`Control sending the additional options parameter`}
+ disabled={formDisabled}
+ checked={enabled}
+ onCheckedChange={(checked) => {
+ setModelParamEnabled("providerOptions", checked);
+ }}
+ />
+ ) : null}
+ </div>
+ </div>
+
+ {enabled && (
+ <div>
+ <CodeMirrorEditor
+ value={inputValue}
+ onChange={(value) => {
+ setInputValue(value);
+
+ try {
+ const parsed = JSONObjectSchema.parse(JSON.parse(value));
+ updateModelParam("providerOptions", parsed);
+ setError(null);
+ } catch {
+ setError("Invalid JSON Object");
+ }
+ }}
+ editable={enabled && !formDisabled}
+ mode="json"
+ minHeight="none"
+ lineNumbers={false}
+ />
+ {error && (
+ <span className="pt-6">
+ <p className="text-[12px] text-red-500">{error}</p>
+ </span>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/web/src/features/evals/pages/default-evaluation-model.tsx b/web/src/features/evals/pages/default-evaluation-model.tsx
index b170f49ebb..3450221c24 100644
--- a/web/src/features/evals/pages/default-evaluation-model.tsx
+++ b/web/src/features/evals/pages/default-evaluation-model.tsx
@@ -15,6 +15,7 @@ import { DeleteEvaluationModelButton } from "@/src/components/deleteButton";
import { ManageDefaultEvalModel } from "@/src/features/evals/components/manage-default-eval-model";
import { useState } from "react";
import { DialogContent, DialogTrigger } from "@/src/components/ui/dialog";
+import { getFinalModelParams } from "@/src/utils/getFinalModelParams";
import { Dialog } from "@/src/components/ui/dialog";
import { Pencil } from "lucide-react";
import {
@@ -80,11 +81,7 @@ export default function DefaultEvaluationModelPage() {
provider: modelParams.provider.value,
adapter: modelParams.adapter.value,
model: modelParams.model.value,
- modelParams: {
- max_tokens: modelParams.max_tokens.value,
- temperature: modelParams.temperature.value,
- top_p: modelParams.top_p.value,
- },
+ modelParams: getFinalModelParams(modelParams),
});
};
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
index bc0b8ff88a..a66d3d59cf 100644
--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -611,7 +611,7 @@ function parseModelParams(
if (!modelParams) return;
modelParams[key as keyof typeof parsedParams.data] = {
- value,
+ value: value as any,
enabled: true,
};
});
diff --git a/web/src/features/playground/page/hooks/useModelParams.ts b/web/src/features/playground/page/hooks/useModelParams.ts
index fac07a038e..94a44c1be1 100644
--- a/web/src/features/playground/page/hooks/useModelParams.ts
+++ b/web/src/features/playground/page/hooks/useModelParams.ts
@@ -213,6 +213,7 @@ function getDefaultAdapterParams(
maxTemperature: { value: 2, enabled: false },
max_tokens: { value: 4096, enabled: false },
top_p: { value: 1, enabled: false },
+ providerOptions: { value: {}, enabled: false },
};
case LLMAdapter.Azure:
@@ -225,6 +226,7 @@ function getDefaultAdapterParams(
maxTemperature: { value: 2, enabled: false },
max_tokens: { value: 4096, enabled: false },
top_p: { value: 1, enabled: false },
+ providerOptions: { value: {}, enabled: false },
};
// Docs: https://docs.anthropic.com/claude/reference/messages_post
@@ -238,6 +240,7 @@ function getDefaultAdapterParams(
maxTemperature: { value: 1, enabled: false },
max_tokens: { value: 4096, enabled: false },
top_p: { value: 1, enabled: false },
+ providerOptions: { value: {}, enabled: false },
};
case LLMAdapter.Bedrock:
@@ -250,6 +253,7 @@ function getDefaultAdapterParams(
maxTemperature: { value: 1, enabled: false },
max_tokens: { value: 4096, enabled: false },
top_p: { value: 1, enabled: false },
+ providerOptions: { value: {}, enabled: false },
};
case LLMAdapter.VertexAI:
@@ -262,6 +266,7 @@ function getDefaultAdapterParams(
maxTemperature: { value: 2, enabled: false },
max_tokens: { value: 4096, enabled: false },
top_p: { value: 1, enabled: false },
+ providerOptions: { value: {}, enabled: false },
};
case LLMAdapter.GoogleAIStudio:
@@ -274,6 +279,7 @@ function getDefaultAdapterParams(
maxTemperature: { value: 2, enabled: false },
max_tokens: { value: 4096, enabled: false },
top_p: { value: 1, enabled: false },
+ providerOptions: { value: {}, enabled: false },
};
}
}
diff --git a/web/src/features/playground/server/validateChatCompletionBody.ts b/web/src/features/playground/server/validateChatCompletionBody.ts
index 505d2fbe14..64df205c37 100644
--- a/web/src/features/playground/server/validateChatCompletionBody.ts
+++ b/web/src/features/playground/server/validateChatCompletionBody.ts
@@ -4,6 +4,7 @@ import {
LLMJSONSchema,
LLMToolDefinitionSchema,
ChatMessageSchema,
+ JSONObjectSchema,
} from "@langfuse/shared";
const ModelParamsSchema = z.object({
@@ -13,6 +14,7 @@ const ModelParamsSchema = z.object({
temperature: z.number().optional(),
max_tokens: z.number().optional(),
top_p: z.number().optional(),
+ providerOptions: JSONObjectSchema.optional(),
});
export const ChatCompletionBodySchema = z.object({