Skip to content

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

fix(experiments): pass prompt tools to dataset runs (#15157)

Tobias Wochinger757d1e845d39
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 1b9bc5ee64..6b057b6040 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -30,6 +30,7 @@ export * from "./domain/home-dashboard";
// llm api
export * from "./server/llm/types";
+export * from "./server/llm/promptToolConfig";
// evals
export * from "./features/evals/types";
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 116fcbfa80..16af87be04 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -47,6 +47,7 @@ export * from "./llm/llmText";
export * from "./llm/errors";
export * from "./llm/utils";
export * from "./llm/types";
+export * from "./llm/promptToolConfig";
export * from "./llm/internalTraceEvents";
export * from "./llm/compileChatMessages";
export * from "./llm/testModelCall";
diff --git a/packages/shared/src/server/llm/promptToolConfig.test.ts b/packages/shared/src/server/llm/promptToolConfig.test.ts
new file mode 100644
index 0000000000..8b2d27e81c
--- /dev/null
+++ b/packages/shared/src/server/llm/promptToolConfig.test.ts
@@ -0,0 +1,167 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ hasPromptToolStructuredOutputConflict,
+ parsePromptToolConfig,
+} from "./promptToolConfig";
+
+const weatherTool = {
+ name: "get_weather",
+ description: "Get the weather for a location",
+ parameters: {
+ type: "object",
+ properties: { location: { type: "string" } },
+ required: ["location"],
+ },
+};
+
+describe("parsePromptToolConfig", () => {
+ describe("configs without tools", () => {
+ it.each([
+ ["null config", null],
+ ["undefined config", undefined],
+ ["string config", "some config"],
+ ["array config", [weatherTool]],
+ ["empty object", {}],
+ ["object without tools key", { model: "gpt-4.1" }],
+ ["null tools", { tools: null }],
+ ["empty tools array", { tools: [] }],
+ ])("returns none for %s", (_label, config) => {
+ expect(parsePromptToolConfig(config)).toEqual({ status: "none" });
+ });
+ });
+
+ describe("valid tool configs", () => {
+ it("parses the flat Langfuse shape", () => {
+ expect(parsePromptToolConfig({ tools: [weatherTool] })).toEqual({
+ status: "valid",
+ tools: [weatherTool],
+ });
+ });
+
+ it("unwraps the OpenAI function shape", () => {
+ expect(
+ parsePromptToolConfig({
+ tools: [{ type: "function", function: weatherTool }],
+ }),
+ ).toEqual({ status: "valid", tools: [weatherTool] });
+ });
+
+ it("parses mixed flat and OpenAI-wrapped tools", () => {
+ const timeTool = {
+ name: "get_time",
+ description: "Get the current time",
+ parameters: { type: "object", properties: {} },
+ };
+
+ expect(
+ parsePromptToolConfig({
+ tools: [weatherTool, { type: "function", function: timeTool }],
+ }),
+ ).toEqual({ status: "valid", tools: [weatherTool, timeTool] });
+ });
+
+ it("normalizes omitted optional fields in the flat shape", () => {
+ expect(parsePromptToolConfig({ tools: [{ name: "get_time" }] })).toEqual({
+ status: "valid",
+ tools: [
+ {
+ name: "get_time",
+ description: "",
+ parameters: { type: "object", properties: {} },
+ },
+ ],
+ });
+ });
+
+ it("normalizes omitted optional fields in the OpenAI wrapper", () => {
+ expect(
+ parsePromptToolConfig({
+ tools: [{ type: "function", function: { name: "get_time" } }],
+ }),
+ ).toEqual({
+ status: "valid",
+ tools: [
+ {
+ name: "get_time",
+ description: "",
+ parameters: { type: "object", properties: {} },
+ },
+ ],
+ });
+ });
+
+ it("normalizes explicit null fields in flat and OpenAI-wrapped tools", () => {
+ expect(
+ parsePromptToolConfig({
+ tools: [
+ { name: "get_time", description: null, parameters: null },
+ {
+ type: "function",
+ function: {
+ name: "get_date",
+ description: null,
+ parameters: null,
+ },
+ },
+ ],
+ }),
+ ).toEqual({
+ status: "valid",
+ tools: [
+ {
+ name: "get_time",
+ description: "",
+ parameters: { type: "object", properties: {} },
+ },
+ {
+ name: "get_date",
+ description: "",
+ parameters: { type: "object", properties: {} },
+ },
+ ],
+ });
+ });
+ });
+
+ describe("invalid tool configs", () => {
+ it.each([
+ ["tools is not an array", { tools: "get_weather" }],
+ ["tools is an object", { tools: { get_weather: weatherTool } }],
+ ["entry missing name", { tools: [{ parameters: { type: "object" } }] }],
+ ["entry is a string", { tools: ["get_weather"] }],
+ ["entry has an empty name", { tools: [{ ...weatherTool, name: "" }] }],
+ [
+ "entry has a provider-incompatible name",
+ { tools: [{ ...weatherTool, name: "get weather" }] },
+ ],
+ [
+ "one invalid entry invalidates all tools",
+ { tools: [weatherTool, { name: "broken", parameters: "invalid" }] },
+ ],
+ [
+ "duplicate tool names",
+ { tools: [weatherTool, { ...weatherTool, description: "duplicate" }] },
+ ],
+ ])("returns invalid for %s", (_label, config) => {
+ expect(parsePromptToolConfig(config)).toEqual({ status: "invalid" });
+ });
+ });
+});
+
+describe("hasPromptToolStructuredOutputConflict", () => {
+ const validConfig = parsePromptToolConfig({ tools: [weatherTool] });
+
+ it("detects valid tools combined with structured output", () => {
+ expect(hasPromptToolStructuredOutputConflict(validConfig, true)).toBe(true);
+ });
+
+ it("allows tools or structured output independently", () => {
+ expect(hasPromptToolStructuredOutputConflict(validConfig, false)).toBe(
+ false,
+ );
+ expect(
+ hasPromptToolStructuredOutputConflict({ status: "invalid" }, true),
+ ).toBe(false);
+ });
+});
diff --git a/packages/shared/src/server/llm/promptToolConfig.ts b/packages/shared/src/server/llm/promptToolConfig.ts
new file mode 100644
index 0000000000..8642f639c8
--- /dev/null
+++ b/packages/shared/src/server/llm/promptToolConfig.ts
@@ -0,0 +1,89 @@
+import z from "zod";
+
+import {
+ LLMJSONSchema,
+ LLMToolDefinitionSchema,
+ LLMToolNameSchema,
+ OpenAIToolSchema,
+ type LLMToolDefinition,
+} from "./types";
+
+const EMPTY_TOOL_PARAMETERS = { type: "object", properties: {} };
+
+const PromptToolDefinitionSchema = LLMToolDefinitionSchema.extend({
+ name: LLMToolNameSchema,
+ // OpenAI-compatible prompt configs may omit or explicitly null these fields.
+ // Keep the runtime representation complete for createLLMToolSet.
+ description: z
+ .string()
+ .nullish()
+ .transform((value) => value ?? ""),
+ parameters: LLMJSONSchema.nullish().transform(
+ (value) => value ?? EMPTY_TOOL_PARAMETERS,
+ ),
+});
+
+const PromptConfigToolSchema = z.union([
+ PromptToolDefinitionSchema,
+ OpenAIToolSchema.extend({
+ function: PromptToolDefinitionSchema,
+ }).transform((tool) => tool.function),
+]);
+
+export type PromptToolConfig =
+ | { status: "none" }
+ | { status: "valid"; tools: LLMToolDefinition[] }
+ | { status: "invalid" };
+
+export const PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE =
+ "Your prompt contains tool definitions - tool calls are not compatible with structured output";
+
+export const hasPromptToolStructuredOutputConflict = (
+ toolConfig: PromptToolConfig,
+ structuredOutputEnabled: boolean,
+) => toolConfig.status === "valid" && structuredOutputEnabled;
+
+/**
+ * Extracts LLM tool definitions from a prompt's free-form `config` JSON.
+ *
+ * Accepts both the flat Langfuse shape (`{name, description, parameters}`)
+ * and the OpenAI wrapper (`{type: "function", function: {...}}`).
+ *
+ * - `none`: config carries no tools — nothing to pass, nothing to warn about.
+ * - `valid`: every entry parsed; pass `tools` to the LLM call.
+ * - `invalid`: a `tools` key exists but cannot be used as a whole (not an
+ * array, an entry is malformed, or duplicate tool names). Callers must
+ * ignore ALL tools and surface a warning — running with a silently
+ * altered tool set would be worse than running without tools.
+ */
+export function parsePromptToolConfig(config: unknown): PromptToolConfig {
+ if (typeof config !== "object" || config === null || Array.isArray(config)) {
+ return { status: "none" };
+ }
+ if (!("tools" in config)) {
+ return { status: "none" };
+ }
+
+ const rawTools = (config as Record<string, unknown>).tools;
+ if (rawTools === null || rawTools === undefined) {
+ return { status: "none" };
+ }
+ if (!Array.isArray(rawTools)) {
+ return { status: "invalid" };
+ }
+ if (rawTools.length === 0) {
+ return { status: "none" };
+ }
+
+ const parsed = z.array(PromptConfigToolSchema).safeParse(rawTools);
+ if (!parsed.success) {
+ return { status: "invalid" };
+ }
+
+ const uniqueNames = new Set(parsed.data.map((tool) => tool.name));
+ if (uniqueNames.size !== parsed.data.length) {
+ return { status: "invalid" };
+ }
+
+ return { status: "valid", tools: parsed.data };
+}
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index cb82ec79b2..5a004e32e8 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -42,6 +42,14 @@ export const JSONSchemaFormSchema = z
.transform((data) => JSON.stringify(data, null, 2)),
);
+export const LLMToolNameSchema = z
+ .string()
+ .regex(
+ /^[a-zA-Z0-9._-]+$/,
+ "Name must contain only alphanumeric letters, hyphens, periods and underscores",
+ )
+ .min(1, "Name is required");
+
export const LLMToolDefinitionSchema = z.object({
name: z.string(),
description: z.string(),
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 8bd8b44413..7ee3128ed1 100644
--- a/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts
+++ b/web/src/__tests__/server/unit/chat-completion-handler.servertest.ts
@@ -167,6 +167,34 @@ describe("chatCompletionHandler", () => {
);
});
+ it("preserves extracted tool names for provider validation", async () => {
+ const toolSet = { "ns:get_time": { description: "Get the time" } };
+ mocks.createToolSet.mockReturnValue(toolSet);
+ mocks.generate.mockResolvedValue({
+ text: "",
+ finalStep: {},
+ toolCalls: [],
+ });
+
+ const toolDefinition = {
+ name: "ns:get_time",
+ description: "Get the time",
+ parameters: { type: "object", properties: {} },
+ };
+ const response = await chatCompletionHandler(
+ createRequest({
+ ...baseBody,
+ tools: [toolDefinition],
+ }),
+ );
+
+ expect(response.status).toBe(200);
+ expect(mocks.createToolSet).toHaveBeenCalledWith([toolDefinition]);
+ expect(mocks.generate).toHaveBeenCalledWith(
+ expect.objectContaining({ tools: toolSet }),
+ );
+ });
+
it("preserves the text/plain streaming response", async () => {
const textStream = new ReadableStream<string>({
start(controller) {
diff --git a/web/src/components/ModelParameters/index.tsx b/web/src/components/ModelParameters/index.tsx
index 24096d8a85..842ac56808 100644
--- a/web/src/components/ModelParameters/index.tsx
+++ b/web/src/components/ModelParameters/index.tsx
@@ -302,6 +302,11 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
{customHeader ? customHeader : <p className="font-semibold">Model</p>}
{SettingsButton}
</div>
+ ) : customHeader ? (
+ <div className="mb-2 flex items-center justify-between">
+ {customHeader}
+ {SettingsButton}
+ </div>
) : (
<div className="mb-2 flex justify-end">{SettingsButton}</div>
)}
diff --git a/web/src/features/experiments/components/MultiStepExperimentForm.tsx b/web/src/features/experiments/components/MultiStepExperimentForm.tsx
index 0e3aa90d21..9bcce97bce 100644
--- a/web/src/features/experiments/components/MultiStepExperimentForm.tsx
+++ b/web/src/features/experiments/components/MultiStepExperimentForm.tsx
@@ -50,7 +50,11 @@ import { ExperimentDetailsStep } from "./steps/ExperimentDetailsStep";
import { ReviewStep } from "./steps/ReviewStep";
// Import step prop types
-import { PromptType } from "@langfuse/shared";
+import {
+ hasPromptToolStructuredOutputConflict,
+ PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE,
+ PromptType,
+} from "@langfuse/shared";
export const MultiStepExperimentForm = ({
projectId,
@@ -178,6 +182,7 @@ export const MultiStepExperimentForm = ({
promptsByName,
expectedColumns,
selectedPromptModelConfig,
+ selectedPromptToolConfig,
} = useExperimentPromptData({
projectId,
form,
@@ -269,6 +274,19 @@ export const MultiStepExperimentForm = ({
};
const onSubmit = async (data: CreateExperiment) => {
+ if (
+ hasPromptToolStructuredOutputConflict(
+ selectedPromptToolConfig,
+ Boolean(data.structuredOutputSchema),
+ )
+ ) {
+ showErrorToast(
+ PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE,
+ "Disable structured output or choose a prompt without tools.",
+ );
+ return;
+ }
+
capture("dataset_run:new_form_submit");
const experiment = {
...data,
@@ -329,6 +347,10 @@ export const MultiStepExperimentForm = ({
// Get dataset info for review step
const selectedDataset = datasets.data?.find((d) => d.id === datasetId);
+ const hasToolStructuredOutputConflict = hasPromptToolStructuredOutputConflict(
+ selectedPromptToolConfig,
+ structuredOutputEnabled,
+ );
// Step validation function
const isStepValid = (stepId: string): boolean => {
@@ -338,6 +360,7 @@ export const MultiStepExperimentForm = ({
form.getValues("promptId") &&
modelParams.provider.value &&
modelParams.model.value &&
+ !hasToolStructuredOutputConflict &&
!form.formState.errors.promptId &&
!form.formState.errors.modelConfig
);
@@ -379,6 +402,7 @@ export const MultiStepExperimentForm = ({
selectedPromptVersion,
setSelectedPromptVersion,
promptsByName,
+ selectedPromptToolConfig,
};
const modelState = {
modelParams,
@@ -566,6 +590,7 @@ export const MultiStepExperimentForm = ({
disabled={
(Boolean(promptIdFromHook && datasetId) &&
!validationResult.data?.isValid) ||
+ hasToolStructuredOutputConflict ||
!!form.formState.errors.name
}
loading={form.formState.isSubmitting}
diff --git a/web/src/features/experiments/components/steps/PromptModelStep.tsx b/web/src/features/experiments/components/steps/PromptModelStep.tsx
index 921a01107d..6c77721c89 100644
--- a/web/src/features/experiments/components/steps/PromptModelStep.tsx
+++ b/web/src/features/experiments/components/steps/PromptModelStep.tsx
@@ -20,9 +20,19 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/src/components/ui/popover";
-import { ChevronDown, CheckIcon, PlusIcon, EyeIcon } from "lucide-react";
+import {
+ ChevronDown,
+ CheckIcon,
+ PlusIcon,
+ EyeIcon,
+ TriangleAlert,
+} from "lucide-react";
import { CreateOrEditLLMSchemaDialog } from "@/src/features/playground/page/components/CreateOrEditLLMSchemaDialog";
-import { type LlmSchema } from "@langfuse/shared";
+import {
+ hasPromptToolStructuredOutputConflict,
+ PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE,
+ type LlmSchema,
+} from "@langfuse/shared";
import { Switch } from "@/src/components/design-system/Switch/Switch";
import { api } from "@/src/utils/api";
import { CardDescription } from "@/src/components/ui/card";
@@ -45,6 +55,7 @@ export const PromptModelStep: React.FC<PromptModelStepProps> = ({
setSelectedPromptName,
selectedPromptVersion,
setSelectedPromptVersion,
+ selectedPromptToolConfig,
} = promptModelState;
const {
modelParams,
@@ -62,6 +73,10 @@ export const PromptModelStep: React.FC<PromptModelStepProps> = ({
const [open, setOpen] = useState(false);
const [selectedSchema, setSelectedSchema] = useState<LlmSchema | null>(null);
const [schemaPopoverOpen, setSchemaPopoverOpen] = useState(false);
+ const hasToolStructuredOutputConflict = hasPromptToolStructuredOutputConflict(
+ selectedPromptToolConfig,
+ structuredOutputEnabled,
+ );
const savedSchemas = api.llmSchemas.getAll.useQuery(
{ projectId },
@@ -239,6 +254,13 @@ export const PromptModelStep: React.FC<PromptModelStepProps> = ({
</PopoverContent>
</Popover>
</div>
+ {selectedPromptToolConfig.status === "invalid" && (
+ <p className="text-dark-yellow flex items-center gap-1.5 text-sm">
+ <TriangleAlert className="h-4 w-4 shrink-0" />
+ Invalid tool config detected on this prompt version. Its tools
+ will be ignored when running the experiment.
+ </p>
+ )}
<FormMessage />
</FormItem>
)}
@@ -249,8 +271,8 @@ export const PromptModelStep: React.FC<PromptModelStepProps> = ({
name="modelConfig"
render={() => (
<FormItem>
- <FormLabel>Model</FormLabel>
<ModelParameters
+ customHeader={<FormLabel>Model</FormLabel>}
{...{
modelParams,
availableModels,
@@ -397,10 +419,16 @@ export const PromptModelStep: React.FC<PromptModelStepProps> = ({
</>
)}
- <CardDescription>
- {structuredOutputEnabled
- ? "Configure the schema for structured LLM outputs"
- : "Enable to enforce a specific output format"}
+ <CardDescription
+ className={cn(
+ hasToolStructuredOutputConflict && "text-destructive",
+ )}
+ >
+ {hasToolStructuredOutputConflict
+ ? PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE
+ : structuredOutputEnabled
+ ? "Configure the schema for structured LLM outputs"
+ : "Enable to enforce a specific output format"}
</CardDescription>
<FormMessage />
</FormItem>
diff --git a/web/src/features/experiments/hooks/useExperimentPromptData.ts b/web/src/features/experiments/hooks/useExperimentPromptData.ts
index 5c63cdcc50..8a7f470f01 100644
--- a/web/src/features/experiments/hooks/useExperimentPromptData.ts
+++ b/web/src/features/experiments/hooks/useExperimentPromptData.ts
@@ -3,9 +3,11 @@ import { api } from "@/src/utils/api";
import { type UseFormReturn } from "react-hook-form";
import {
extractVariables,
+ parsePromptToolConfig,
PromptType,
extractPlaceholderNames,
type PromptMessage,
+ type PromptToolConfig,
ZodModelConfig,
} from "@langfuse/shared";
import { z } from "zod/v4";
@@ -74,11 +76,17 @@ export function useExperimentPromptData({
return getPromptModelConfig(prompt?.config);
}, [promptId, promptMeta.data]);
+ const selectedPromptToolConfig: PromptToolConfig = useMemo(() => {
+ const prompt = promptMeta.data?.find((p) => p.id === promptId);
+ return parsePromptToolConfig(prompt?.config);
+ }, [promptId, promptMeta.data]);
+
return {
expectedColumns,
promptsByName,
promptId,
selectedPromptModelConfig,
+ selectedPromptToolConfig,
};
}
diff --git a/web/src/features/experiments/server/router.ts b/web/src/features/experiments/server/router.ts
index 8d729d98a7..9f81b58982 100644
--- a/web/src/features/experiments/server/router.ts
+++ b/web/src/features/experiments/server/router.ts
@@ -48,6 +48,10 @@ import {
timeFilter,
AGGREGATABLE_SCORE_TYPES,
filterAndValidateDbScoreList,
+ hasPromptToolStructuredOutputConflict,
+ InvalidRequestError,
+ parsePromptToolConfig,
+ PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE,
} from "@langfuse/shared";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
@@ -231,6 +235,19 @@ export const experimentsRouter = createTRPCRouter({
scope: "promptExperiments:CUD",
});
+ if (input.structuredOutputSchema) {
+ const prompt = await ctx.prisma.prompt.findUnique({
+ where: { id: input.promptId, projectId: input.projectId },
+ select: { config: true },
+ });
+ const toolConfig = parsePromptToolConfig(prompt?.config);
+ if (hasPromptToolStructuredOutputConflict(toolConfig, true)) {
+ throw new InvalidRequestError(
+ PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE,
+ );
+ }
+ }
+
if (!redis) {
throw new UnauthorizedError("Experiment creation failed");
}
diff --git a/web/src/features/experiments/types/stepProps.ts b/web/src/features/experiments/types/stepProps.ts
index f9fe7c31d8..9108c3c205 100644
--- a/web/src/features/experiments/types/stepProps.ts
+++ b/web/src/features/experiments/types/stepProps.ts
@@ -2,7 +2,11 @@ import { type UseFormReturn } from "react-hook-form";
import { type CreateExperiment } from "@/src/features/experiments/types";
import { type UIModelParams } from "@langfuse/shared/src/server";
import { type ModelParamsContext } from "@/src/components/ModelParameters";
-import { type EvalTemplate, type PromptType } from "@langfuse/shared";
+import {
+ type EvalTemplate,
+ type PromptToolConfig,
+ type PromptType,
+} from "@langfuse/shared";
import { type PartialConfig } from "@/src/features/evals/types";
type ValidationResult =
@@ -45,6 +49,7 @@ export type PromptModelState = {
promptsByName:
| Record<string, Array<{ id: string; version: number; labels: string[] }>>
| undefined;
+ selectedPromptToolConfig: PromptToolConfig;
};
export type ModelState = {
diff --git a/web/src/features/llm-tools/validation.ts b/web/src/features/llm-tools/validation.ts
index 6f7461a913..c9605e6193 100644
--- a/web/src/features/llm-tools/validation.ts
+++ b/web/src/features/llm-tools/validation.ts
@@ -1,13 +1,7 @@
import { z } from "zod";
-import { LLMJSONSchema } from "@langfuse/shared";
+import { LLMJSONSchema, LLMToolNameSchema } from "@langfuse/shared";
-export const LLMToolNameSchema = z
- .string()
- .regex(
- /^[a-zA-Z0-9\._-]+$/,
- "Name must contain only alphanumeric letters, hyphens, periods and underscores",
- )
- .min(1, "Name is required");
+export { LLMToolNameSchema } from "@langfuse/shared";
export const LLMToolInput = z.object({
name: LLMToolNameSchema,
diff --git a/worker/src/__tests__/experimentsService.test.ts b/worker/src/__tests__/experimentsService.test.ts
index 24f48d432f..aa113291bc 100644
--- a/worker/src/__tests__/experimentsService.test.ts
+++ b/worker/src/__tests__/experimentsService.test.ts
@@ -7,6 +7,7 @@ import { createExperimentJobClickhouse } from "../features/experiments/experimen
import {
createDatasetItem,
createOrgProjectAndApiKey,
+ generateLLMText,
logger,
} from "@langfuse/shared/src/server";
@@ -575,3 +576,159 @@ describe("experiment processing integration", () => {
// );
});
});
+
+describe("experiment prompt tool config", () => {
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ vi.mocked(generateLLMText).mockResolvedValue({
+ text: "test output",
+ } as any);
+ });
+
+ const setupExperimentWithPromptConfig = async (
+ promptConfig: unknown,
+ runMetadata: Record<string, unknown> = {},
+ ) => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const datasetId = randomUUID();
+ const runId = randomUUID();
+ const promptId = randomUUID();
+
+ await prisma.prompt.create({
+ data: {
+ id: promptId,
+ projectId,
+ name: "Test Prompt",
+ prompt: "Hello {{name}}",
+ config: promptConfig as any,
+ type: "text",
+ version: 1,
+ createdBy: "test-user",
+ },
+ });
+ await prisma.dataset.create({
+ data: { id: datasetId, projectId, name: "Test Dataset" },
+ });
+ await prisma.datasetRuns.create({
+ data: {
+ id: runId,
+ name: "Test Run",
+ projectId,
+ datasetId,
+ metadata: {
+ prompt_id: promptId,
+ provider: "openai",
+ model: "gpt-3.5-turbo",
+ model_params: { temperature: 0 },
+ ...runMetadata,
+ },
+ },
+ });
+ await createDatasetItem({
+ projectId,
+ datasetId,
+ input: { name: "World" },
+ });
+ await prisma.llmApiKeys.create({
+ data: {
+ id: randomUUID(),
+ projectId,
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ displaySecretKey: "test-key",
+ secretKey: encrypt("test-key"),
+ },
+ });
+
+ return { projectId, datasetId, runId };
+ };
+
+ test("passes valid prompt config tools to the LLM call", async () => {
+ const { projectId, datasetId, runId } =
+ await setupExperimentWithPromptConfig({
+ tools: [
+ {
+ name: "get_weather",
+ parameters: {
+ type: "object",
+ properties: { location: { type: "string" } },
+ required: ["location"],
+ },
+ },
+ // OpenAI-wrapped shape must be accepted as well
+ {
+ type: "function",
+ function: {
+ name: "get_time",
+ description: "Get the current time",
+ },
+ },
+ ],
+ });
+
+ const result = await createExperimentJobClickhouse({
+ event: { projectId, datasetId, runId },
+ });
+
+ expect(result).toEqual({ success: true });
+ expect(vi.mocked(generateLLMText)).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tools: expect.objectContaining({
+ get_weather: expect.anything(),
+ get_time: expect.anything(),
+ }),
+ }),
+ );
+ });
+
+ test("ignores invalid prompt config tools and runs without tools", async () => {
+ const { projectId, datasetId, runId } =
+ await setupExperimentWithPromptConfig({
+ tools: [{ name: "broken_tool", parameters: "invalid" }],
+ });
+
+ const result = await createExperimentJobClickhouse({
+ event: { projectId, datasetId, runId },
+ });
+
+ expect(result).toEqual({ success: true });
+ expect(vi.mocked(generateLLMText)).toHaveBeenCalledTimes(1);
+ const callArgs = vi.mocked(generateLLMText).mock.calls[0][0];
+ expect(callArgs.tools).toBeUndefined();
+ });
+
+ test("rejects combining prompt config tools with structured output", async () => {
+ const { projectId, datasetId, runId } =
+ await setupExperimentWithPromptConfig(
+ {
+ tools: [
+ {
+ name: "get_weather",
+ description: "Get the weather for a location",
+ parameters: { type: "object", properties: {} },
+ },
+ ],
+ },
+ {
+ structured_output_schema: {
+ type: "object",
+ properties: { answer: { type: "string" } },
+ },
+ },
+ );
+
+ const result = await createExperimentJobClickhouse({
+ event: { projectId, datasetId, runId },
+ });
+
+ expect(result).toEqual({ success: true });
+ expect(vi.mocked(generateLLMText)).not.toHaveBeenCalled();
+ expect(vi.mocked(logger).error).toHaveBeenCalledWith(
+ "Failed to validate and setup experiment",
+ expect.objectContaining({
+ message:
+ "Your prompt contains tool definitions - tool calls are not compatible with structured output",
+ }),
+ );
+ });
+});
diff --git a/worker/src/features/experiments/experimentServiceClickhouse.ts b/worker/src/features/experiments/experimentServiceClickhouse.ts
index 84488d536f..b431a86fd1 100644
--- a/worker/src/features/experiments/experimentServiceClickhouse.ts
+++ b/worker/src/features/experiments/experimentServiceClickhouse.ts
@@ -8,6 +8,7 @@ import {
ChatMessage,
convertDateToClickhouseDateTime,
createLLMOutput,
+ createLLMToolSet,
createUnknownSdkIngestionAttribution,
createDatasetItemFilterState,
DatasetRunItemUpsertQueue,
@@ -222,9 +223,12 @@ async function processLLMCall(
await generateLLMText({
...llmParams,
maxRetries: 1,
+ // Setup rejects the unsupported tools + structured-output combination.
...(config.structuredOutputSchema
? { output: createLLMOutput(config.structuredOutputSchema) }
- : {}),
+ : config.tools.length > 0
+ ? { tools: createLLMToolSet(config.tools) }
+ : {}),
trace: traceSinkParams,
}).catch(() => undefined); // catch errors and do not retry
diff --git a/worker/src/features/experiments/utils.ts b/worker/src/features/experiments/utils.ts
index 686e148527..088325a474 100644
--- a/worker/src/features/experiments/utils.ts
+++ b/worker/src/features/experiments/utils.ts
@@ -5,7 +5,9 @@ import {
compileChatMessages,
extractPlaceholderNames,
extractVariables,
+ hasPromptToolStructuredOutputConflict,
MessagePlaceholderValues,
+ PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE,
Prisma,
PromptContent,
PromptType,
@@ -14,6 +16,7 @@ import {
import { compileTemplateString } from "../utils/utilities";
import {
logger,
+ parsePromptToolConfig,
PromptService,
type PromptMessage,
redis,
@@ -196,6 +199,27 @@ export async function validateAndSetupExperiment(
throw new UnrecoverableError(`Prompt ${prompt_id} has invalid format`);
}
+ // Tools are lenient by design: the experiment form warns about invalid tool
+ // configs at creation time, so at execution time we run without tools
+ // instead of failing the whole run.
+ const toolConfig = parsePromptToolConfig(prompt.config);
+ if (toolConfig.status === "invalid") {
+ logger.info(
+ `Prompt ${prompt_id} has an invalid tool config, ignoring tools for experiment run ${runId}`,
+ );
+ }
+
+ if (
+ hasPromptToolStructuredOutputConflict(
+ toolConfig,
+ Boolean(validatedRunMetadata.data.structured_output_schema),
+ )
+ ) {
+ throw new UnrecoverableError(
+ PROMPT_TOOL_STRUCTURED_OUTPUT_CONFLICT_MESSAGE,
+ );
+ }
+
// Fetch and validate API key
const apiKey = await prisma.llmApiKeys.findFirst({
where: { projectId, provider },
@@ -231,6 +255,7 @@ export async function validateAndSetupExperiment(
provider,
model,
model_params,
+ tools: toolConfig.status === "valid" ? toolConfig.tools : [],
structuredOutputSchema: validatedRunMetadata.data.structured_output_schema,
experimentName: validatedRunMetadata.data.experiment_name,
experimentRunName: validatedRunMetadata.data.experiment_run_name,