Skip to content

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

feat(api): expose code evaluators in public endpoints (#14058)

Tobias Wochingerc82119e26602
diff --git a/fern/apis/server/definition/unstable/commons.yml b/fern/apis/server/definition/unstable/commons.yml
index cd2afb0f4f..9f3437929b 100644
--- a/fern/apis/server/definition/unstable/commons.yml
+++ b/fern/apis/server/definition/unstable/commons.yml
@@ -4,9 +4,16 @@ types:
docs: |
The evaluator engine type.
- The unstable public API currently supports only LLM-as-a-judge evaluators.
+ The unstable public API supports LLM-as-a-judge and code evaluators.
enum:
- llm_as_judge
+ - code
+
+ CodeEvaluatorSourceCodeLanguage:
+ docs: Code evaluator runtime language.
+ enum:
+ - PYTHON
+ - TYPESCRIPT
EvaluatorScope:
docs: |
@@ -409,7 +416,9 @@ types:
EvaluationRuleMapping:
docs: |
- Maps one evaluator prompt variable to one source field from the target object.
+ Maps one evaluator variable to one source field from the target object.
+
+ Manual mappings are used for `llm_as_judge` evaluators. `code` evaluators use a fixed runtime mapping managed by Langfuse.
How to build a valid mapping list:
1. Create the evaluator or fetch it with `GET /evaluators/{id}`.
@@ -422,7 +431,7 @@ types:
Recovery guidance:
- `invalid_variable_mapping`: the variable name is unknown for this evaluator, or the selected `source` is not valid for the chosen `target`
- - `missing_variable_mapping`: one or more evaluator variables are not mapped yet
+ - `missing_variable_mapping`: one or more LLM-as-judge evaluator variables are not mapped yet
- `duplicate_variable_mapping`: the same evaluator variable appears more than once
- `invalid_json_path`: the JSONPath expression is malformed. Remove it or correct it.
properties:
diff --git a/fern/apis/server/definition/unstable/evaluation-rules.yml b/fern/apis/server/definition/unstable/evaluation-rules.yml
index fbb8399a6d..cf7e1b8d51 100644
--- a/fern/apis/server/definition/unstable/evaluation-rules.yml
+++ b/fern/apis/server/definition/unstable/evaluation-rules.yml
@@ -22,8 +22,9 @@ service:
- `evaluator.name` + `evaluator.scope` must identify an existing evaluator family returned by the evaluator endpoints
- Langfuse resolves that family to its latest version before saving the evaluation rule
- for `target=experiment`, use dataset `id` values from `GET /api/public/v2/datasets` when filtering by `datasetId`
- - every evaluator prompt variable must be mapped exactly once
- - `expected_output` and `experiment_item_metadata` mappings are only valid for `target=experiment`
+ - for `llm_as_judge` evaluators, every evaluator prompt variable must be mapped exactly once
+ - for `code` evaluators, Langfuse uses the fixed code runtime mapping; omit `mapping` in create and update requests
+ - for user-provided `llm_as_judge` mappings, `expected_output` and `experiment_item_metadata` are only valid for `target=experiment`
- if `enabled=true`, Langfuse validates that the referenced evaluator can currently run
- at most 50 evaluation rules can be effectively active in one project at the same time
@@ -40,9 +41,9 @@ service:
Recovery guidance:
- `400 invalid_filter_value`: fix the filter `column` or `value` using `details.column`, `details.invalidValues`, and `details.allowedValues`
- `400 invalid_filter_value` with `details.column=datasetId`: call `GET /api/public/v2/datasets`, then retry with dataset `id` values from that response
- - `400 missing_variable_mapping`: fetch the evaluator again and make sure every variable in `variables` appears exactly once in `mapping`
+ - `400 missing_variable_mapping`: for `llm_as_judge` evaluators, fetch the evaluator again and make sure every variable in `variables` appears exactly once in `mapping`
- `400 duplicate_variable_mapping`: remove repeated mappings for the same variable
- - `400 invalid_variable_mapping`: switch to a valid `source` for the selected `target`, or fix the variable name
+ - `400 invalid_variable_mapping`: for `llm_as_judge`, switch to a valid `source` for the selected `target`, or fix the variable name
- `400 invalid_json_path`: remove or correct the `jsonPath`
- `422 evaluator_preflight_failed`: the selected evaluator cannot run with the resolved model configuration. Fix the evaluator/default model setup, then retry the create request.
method: POST
@@ -67,6 +68,7 @@ service:
evaluator:
name: answer-correctness
scope: project
+ type: llm_as_judge
target: observation
enabled: true
sampling: 1
@@ -89,6 +91,7 @@ service:
id: evaltmpl_123
name: answer-correctness
scope: project
+ type: llm_as_judge
target: observation
enabled: true
status: active
@@ -108,6 +111,57 @@ service:
source: output
createdAt: "2026-03-30T09:20:00.000Z"
updatedAt: "2026-03-30T09:20:00.000Z"
+ - name: CreateCodeObservationEvaluationRule
+ docs: Deploy a code evaluator to score live generation outputs.
+ request:
+ name: toxicity-code-live
+ evaluator:
+ name: toxicity-detector
+ scope: project
+ type: code
+ target: observation
+ enabled: true
+ sampling: 1
+ filter:
+ - type: stringOptions
+ column: type
+ operator: any of
+ value:
+ - GENERATION
+ response:
+ body:
+ id: erule_234
+ name: toxicity-code-live
+ evaluator:
+ id: evaltmpl_234
+ name: toxicity-detector
+ scope: project
+ type: code
+ target: observation
+ enabled: true
+ status: active
+ pausedReason: null
+ pausedMessage: null
+ sampling: 1
+ filter:
+ - type: stringOptions
+ column: type
+ operator: any of
+ value:
+ - GENERATION
+ mapping:
+ - variable: input
+ source: input
+ - variable: output
+ source: output
+ - variable: metadata
+ source: metadata
+ - variable: experimentItemExpectedOutput
+ source: expected_output
+ - variable: experimentItemMetadata
+ source: experiment_item_metadata
+ createdAt: "2026-03-30T09:25:00.000Z"
+ updatedAt: "2026-03-30T09:25:00.000Z"
- name: CreateExperimentEvaluationRule
docs: Deploy an evaluator to compare experiment outputs against expected outputs. Discover valid dataset IDs with `GET /api/public/v2/datasets` first.
request:
@@ -115,6 +169,7 @@ service:
evaluator:
name: expected-output-match
scope: project
+ type: llm_as_judge
target: experiment
enabled: true
sampling: 0.5
@@ -137,6 +192,7 @@ service:
id: evaltmpl_456
name: expected-output-match
scope: project
+ type: llm_as_judge
target: experiment
enabled: true
status: active
@@ -212,18 +268,19 @@ service:
- switch to another evaluator
- adjust sampling
- change filters
- - update variable mappings
+ - update LLM-as-judge variable mappings
Important behavior:
- provide only the fields you want to change
- if you provide `evaluator`, Langfuse resolves that evaluator family to its latest version before saving
- - changing `target`, `filter`, or `mapping` must still produce a valid target-specific configuration
- - if you change `target`, also send a compatible `filter` and `mapping` in the same request unless the existing ones are still valid for the new target
+ - changing `target`, `filter`, or an LLM-as-judge `mapping` must still produce a valid target-specific configuration
+ - if you change `target` for an LLM-as-judge rule, also send a compatible `filter` and `mapping` in the same request unless the existing ones are still valid for the new target
+ - for `code` evaluator rules, omit `mapping`; Langfuse stores the fixed code runtime mapping automatically
- if the resulting config is enabled, Langfuse re-validates that the selected evaluator can run
- if the update would move a non-active evaluation rule into the active state and the project already has 50 active evaluation rules, the API returns `409`
Recovery guidance:
- - if the update fails with `missing_variable_mapping` or `invalid_variable_mapping` after changing `evaluator` or `target`, resend the request with a complete new `mapping`
+ - if an LLM-as-judge update fails with `missing_variable_mapping` or `invalid_variable_mapping` after changing `evaluator` or `target`, resend the request with a complete new `mapping`
- if the update fails with `invalid_filter_value` after changing `target`, resend the request with a target-compatible `filter`
method: PATCH
path: /evaluation-rules/{evaluationRuleId}
@@ -323,7 +380,7 @@ types:
docs: List of filter conditions used to decide whether a target should be evaluated.
mapping:
type: list<commons.EvaluationRuleMapping>
- docs: Variable mappings used to populate the evaluator prompt from the live target object.
+ docs: Variable mappings used to populate evaluator runtime variables from the live target object.
createdAt:
type: datetime
docs: Timestamp when the evaluation rule was created.
@@ -338,6 +395,7 @@ types:
id: evaltmpl_123
name: answer-correctness
scope: project
+ type: llm_as_judge
target: observation
enabled: true
status: active
@@ -376,19 +434,26 @@ types:
- reference an existing evaluator family by `evaluator.name` and `evaluator.scope`
- choose `target=observation` or `target=experiment`
- if `target=experiment` and you want a dataset filter, call `GET /api/public/v2/datasets` first and use dataset `id` values in `filter[].value`
- - fetch or inspect the evaluator first, then provide a complete variable mapping for every evaluator variable listed in `variables`
+ - for `llm_as_judge`, fetch or inspect the evaluator first and provide a complete variable mapping for every evaluator variable
+ - for `code`, do not send variables or mappings; Langfuse stores the fixed code runtime mapping automatically
- optionally narrow execution with `filter`
- set `enabled=true` only when you want live execution immediately
+ discriminated: false
+ union:
+ - CreateLlmAsJudgeEvaluationRuleRequest
+ - CreateCodeEvaluationRuleRequest
+
+ CreateLlmAsJudgeEvaluationRuleRequest:
properties:
name:
type: string
docs: Human-readable deployment name.
evaluator:
- type: EvaluationRuleEvaluatorReference
+ type: LlmAsJudgeEvaluationRuleEvaluatorReference
docs: |
- Evaluator family to use.
+ LLM-as-judge evaluator family to use.
- Use `name` and `scope` from the evaluator endpoints.
+ Use `name`, `scope`, and `type` from the evaluator endpoints. If `type` is omitted, Langfuse defaults it to `llm_as_judge` for backwards compatibility.
Langfuse resolves that family to its latest version before saving the rule.
target:
type: commons.EvaluationRuleTarget
@@ -410,11 +475,41 @@ types:
mapping:
type: list<commons.EvaluationRuleMapping>
docs: |
- Required variable mappings.
+ LLM-as-judge variable mappings.
Every evaluator variable must appear exactly once.
Build this list from the evaluator `variables` array returned by the evaluator endpoints.
+ CreateCodeEvaluationRuleRequest:
+ properties:
+ name:
+ type: string
+ docs: Human-readable deployment name.
+ evaluator:
+ type: CodeEvaluationRuleEvaluatorReference
+ docs: |
+ Code evaluator family to use.
+
+ Use `name`, `scope`, and `type` from the evaluator endpoints.
+ Langfuse resolves that family to its latest version before saving the rule.
+ target:
+ type: commons.EvaluationRuleTarget
+ docs: Target object type to evaluate.
+ enabled:
+ type: boolean
+ docs: Whether the deployment should be active immediately after creation.
+ sampling:
+ type: optional<double>
+ docs: Optional sampling fraction. Defaults to `1`.
+ filter:
+ type: optional<list<commons.EvaluationRuleFilter>>
+ docs: |
+ Optional filter list.
+
+ Omit or pass an empty list to evaluate all matching targets for the selected `target`.
+ Each filter object must use a column that is valid for that `target`.
+ For `target=experiment`, `column=datasetId` expects dataset `id` values from `GET /api/public/v2/datasets`, not dataset names.
+
UpdateEvaluationRuleRequest:
docs: |
Partial update body for an evaluation rule.
@@ -424,8 +519,9 @@ types:
Practical guidance:
- If you only want to rename the rule or change sampling, send just those fields.
- - If you change `evaluator`, send a fresh `mapping` unless you are certain the existing mapping still matches the evaluator variables.
- - If you change `target`, usually send both `filter` and `mapping` in the same request.
+ - If you change to an LLM-as-judge `evaluator`, send a fresh `mapping` unless you are certain the existing mapping still matches the evaluator variables.
+ - If you change `target` for an LLM-as-judge rule, usually send both `filter` and `mapping` in the same request.
+ - For code evaluator rules, omit `mapping`; Langfuse stores the fixed code runtime mapping automatically.
- If you change an experiment `datasetId` filter, call `GET /api/public/v2/datasets` and use dataset `id` values from that response.
properties:
name:
@@ -437,6 +533,7 @@ types:
Updated evaluator family.
Langfuse resolves the provided evaluator family to its latest version before saving the rule.
+ A rule's evaluator type cannot be changed: provide `name` and `scope` for an evaluator family of the rule's current type. To use a different evaluator type, create a new rule.
target:
type: optional<commons.EvaluationRuleTarget>
docs: Updated target object type.
@@ -454,7 +551,10 @@ types:
For `target=experiment`, `column=datasetId` expects dataset `id` values from `GET /api/public/v2/datasets`, not dataset names.
mapping:
type: optional<list<commons.EvaluationRuleMapping>>
- docs: Updated variable mappings.
+ docs: |
+ Updated LLM-as-judge variable mappings.
+
+ Do not send this field for code evaluator rules. Langfuse stores the fixed code runtime mapping automatically and returns it in the response.
DeleteEvaluationRuleResponse:
docs: Confirmation response returned after successful deletion.
@@ -465,9 +565,33 @@ types:
EvaluationRuleEvaluatorReference:
docs: |
- Evaluator family reference used when creating or updating an evaluation rule.
+ Evaluator family reference used when updating an evaluation rule.
+
+ `name` and `scope` identify the evaluator family in the authenticated project context.
+ A rule's evaluator type cannot be changed, so this reference does not accept a `type`; the family must match the rule's current evaluator type.
+ properties:
+ name:
+ type: string
+ docs: Evaluator family name.
+ scope:
+ type: commons.EvaluatorScope
+ docs: Whether the evaluator family is project-owned or Langfuse-managed.
+
+ LlmAsJudgeEvaluationRuleEvaluatorReference:
+ docs: LLM-as-judge evaluator family reference used when creating an evaluation rule.
+ properties:
+ name:
+ type: string
+ docs: Evaluator family name.
+ scope:
+ type: commons.EvaluatorScope
+ docs: Whether the evaluator family is project-owned or Langfuse-managed.
+ type:
+ type: optional<LlmAsJudgeEvaluatorType>
+ docs: Evaluator engine type. Defaults to `llm_as_judge` when omitted.
- `name` and `scope` are enough to identify the evaluator family in the authenticated project context.
+ CodeEvaluationRuleEvaluatorReference:
+ docs: Code evaluator family reference used when creating an evaluation rule.
properties:
name:
type: string
@@ -475,13 +599,20 @@ types:
scope:
type: commons.EvaluatorScope
docs: Whether the evaluator family is project-owned or Langfuse-managed.
+ type:
+ type: literal<"code">
+ docs: Must be `code`.
+
+ LlmAsJudgeEvaluatorType:
+ enum:
+ - llm_as_judge
EvaluationRuleEvaluator:
docs: |
Resolved evaluator currently used by the evaluation rule.
`id` is the exact active evaluator version.
- `name` and `scope` identify the evaluator family conceptually.
+ `name`, `scope`, and `type` identify the evaluator family conceptually.
properties:
id:
type: string
@@ -492,3 +623,6 @@ types:
scope:
type: commons.EvaluatorScope
docs: Whether the evaluator family is project-owned or Langfuse-managed.
+ type:
+ type: commons.EvaluatorType
+ docs: Evaluator engine type.
diff --git a/fern/apis/server/definition/unstable/evaluators.yml b/fern/apis/server/definition/unstable/evaluators.yml
index 5fa89d7972..0085a4dbca 100644
--- a/fern/apis/server/definition/unstable/evaluators.yml
+++ b/fern/apis/server/definition/unstable/evaluators.yml
@@ -12,7 +12,9 @@ service:
docs: |
Create an evaluator in the authenticated project.
- Use evaluators to define **how** Langfuse should score data: the prompt, the expected structured output, and the optional model configuration.
+ Use evaluators to define **how** Langfuse should score data.
+ LLM-as-a-judge evaluators define a prompt, expected structured output, and optional model configuration.
+ Code evaluators define source code and a runtime language.
Naming behavior:
- If this is a new evaluator name in your project, Langfuse creates version `1`.
@@ -25,10 +27,15 @@ service:
3. Read the returned `outputDefinition.dataType` so the client knows whether future scores will be numeric, boolean, or categorical.
4. Create one or more evaluation rules that reference the returned evaluator family using `name` and `scope`.
+ Code evaluator validation:
+ - At creation, Langfuse only validates the request shape
+ - The `sourceCode` itself is not executed here. It is first run (preflight-tested against a sample observation) when you link the evaluator to an evaluation rule, so runtime errors in the code surface at evaluation-rule creation, not at evaluator creation.
+
Recovery guidance:
- `422` with `code=evaluator_preflight_failed`: the evaluator cannot run with the resolved model configuration. Add a valid explicit `modelConfig`, or configure the project's default evaluation model, then retry the same request.
- `400` with `code=invalid_body`: the request shape is malformed. Use the structured `details.issues` array to fix the specific fields and retry.
- - `400` with `code=invalid_body` on `outputDefinition`: send `dataType`, `reasoning.description`, and `score.description`. Do not send `version`; it is not part of the public request shape.
+ - `400` with `code=invalid_body` on `outputDefinition`: for `type=llm_as_judge`, send `dataType`, `reasoning.description`, and `score.description`. Do not send `version`; it is not part of the public request shape.
+ - If `type` is omitted, Langfuse treats the request as `type=llm_as_judge` for backwards compatibility. New clients should send `type` explicitly.
Unstable API note:
- This surface may evolve while the underlying evaluation data model is being redesigned.
@@ -50,6 +57,7 @@ service:
docs: Create a new version of an evaluator named `answer-correctness`.
request:
name: answer-correctness
+ type: llm_as_judge
prompt: |
You are grading an answer.
@@ -101,6 +109,140 @@ service:
evaluationRuleCount: 0
createdAt: "2026-03-30T09:00:00.000Z"
updatedAt: "2026-03-30T09:00:00.000Z"
+ - name: CreateTypeScriptCodeEvaluator
+ docs: |
+ Create a TypeScript code evaluator named `exact-match`.
+
+ Send only the `evaluate` function; Langfuse injects the `EvaluationContext`,
+ `EvaluationResult`, and `Score` type definitions at runtime.
+ Code evaluators always expose the fixed runtime payload variables and do not take a `mapping`.
+ request:
+ name: exact-match
+ type: code
+ sourceCode: |
+ function evaluate(ctx: EvaluationContext): EvaluationResult {
+ const input = ctx.observation.input;
+ const matchesOutput =
+ input !== undefined && ctx.observation.output === input;
+
+ return {
+ scores: [
+ {
+ name: "Exact match",
+ value: matchesOutput,
+ dataType: "BOOLEAN",
+ comment: matchesOutput
+ ? "Output exactly matches the input."
+ : "Output does not match the input.",
+ },
+ ],
+ };
+ }
+ sourceCodeLanguage: TYPESCRIPT
+ response:
+ body:
+ id: evaltmpl_ts_123
+ name: exact-match
+ version: 1
+ scope: project
+ type: code
+ variables:
+ - input
+ - output
+ - metadata
+ - experimentItemExpectedOutput
+ - experimentItemMetadata
+ sourceCode: |
+ function evaluate(ctx: EvaluationContext): EvaluationResult {
+ const input = ctx.observation.input;
+ const matchesOutput =
+ input !== undefined && ctx.observation.output === input;
+
+ return {
+ scores: [
+ {
+ name: "Exact match",
+ value: matchesOutput,
+ dataType: "BOOLEAN",
+ comment: matchesOutput
+ ? "Output exactly matches the input."
+ : "Output does not match the input.",
+ },
+ ],
+ };
+ }
+ sourceCodeLanguage: TYPESCRIPT
+ evaluationRuleCount: 0
+ createdAt: "2026-03-30T09:10:00.000Z"
+ updatedAt: "2026-03-30T09:10:00.000Z"
+ - name: CreatePythonCodeEvaluator
+ docs: |
+ Create a Python code evaluator named `exact-match`.
+
+ Send only the `evaluate` function; Langfuse injects the `EvaluationContext`,
+ `EvaluationResult`, and `Score` definitions at runtime.
+ Code evaluators always expose the fixed runtime payload variables and do not take a `mapping`.
+ request:
+ name: exact-match
+ type: code
+ sourceCode: |
+ def evaluate(ctx: EvaluationContext) -> EvaluationResult:
+ """Evaluates one observation and returns one or more Langfuse scores."""
+ input = ctx.observation.input
+ matches_output = input is not None and ctx.observation.output == input
+
+ return EvaluationResult(
+ scores=[
+ Score(
+ name="Exact match",
+ value=matches_output,
+ data_type="BOOLEAN",
+ comment=(
+ "Output exactly matches the input."
+ if matches_output
+ else "Output does not match the input."
+ ),
+ )
+ ]
+ )
+ sourceCodeLanguage: PYTHON
+ response:
+ body:
+ id: evaltmpl_py_123
+ name: exact-match
+ version: 1
+ scope: project
+ type: code
+ variables:
+ - input
+ - output
+ - metadata
+ - experimentItemExpectedOutput
+ - experimentItemMetadata
+ sourceCode: |
+ def evaluate(ctx: EvaluationContext) -> EvaluationResult:
+ """Evaluates one observation and returns one or more Langfuse scores."""
+ input = ctx.observation.input
+ matches_output = input is not None and ctx.observation.output == input
+
+ return EvaluationResult(
+ scores=[
+ Score(
+ name="Exact match",
+ value=matches_output,
+ data_type="BOOLEAN",
+ comment=(
+ "Output exactly matches the input."
+ if matches_output
+ else "Output does not match the input."
+ ),
+ )
+ ]
+ )
+ sourceCodeLanguage: PYTHON
+ evaluationRuleCount: 0
+ createdAt: "2026-03-30T09:15:00.000Z"
+ updatedAt: "2026-03-30T09:15:00.000Z"
list:
docs: |
@@ -156,23 +298,26 @@ types:
docs: |
One evaluator that can be used for scoring.
- An evaluator describes **how** to score data:
- - prompt
- - extracted prompt variables
- - output schema
- - optional explicit model configuration
+ An evaluator describes **how** to score data.
It does not define **which** live objects are evaluated. That is the job of `evaluation-rules`.
For agent clients, the most important fields are:
- - `variables`: use these exact names when building the evaluation-rule `mapping` array
- - `outputDefinition`: tells you the expected score type and the evaluator's response instructions
- - `modelConfig`: tells you whether the evaluator uses the project default model (`null`) or an explicit provider/model
+ - `type`: determines which evaluator fields are present
+ - `variables`: for LLM evaluators, use these exact names when building the evaluation-rule `mapping` array. LLM evaluators require every variable to be mapped. Code evaluators always expose the fixed runtime payload fields and Langfuse maps them automatically.
Versioning behavior:
- `GET /evaluators` returns the latest version of each available evaluator.
- `GET /evaluators/{id}` can return an older version.
- Evaluation rules always run against the latest version for the selected evaluator name within the same source (`project` or `managed`).
+ discriminant: type
+ union:
+ llm_as_judge:
+ type: LlmAsJudgeEvaluator
+ code:
+ type: CodeEvaluator
+
+ EvaluatorBase:
properties:
id:
type: string
@@ -186,18 +331,28 @@ types:
scope:
type: commons.EvaluatorScope
docs: "Where this evaluator comes from: your project or Langfuse-managed defaults."
- type:
- type: commons.EvaluatorType
- docs: Evaluator engine type. Currently always `llm_as_judge`.
- prompt:
- type: string
- docs: Prompt template used during evaluation.
variables:
type: list<string>
docs: |
- Variables extracted from the evaluator prompt.
+ Variables that can be mapped when creating an evaluation rule.
+
+ LLM evaluators require every variable to be mapped exactly once. Code evaluators always expose the fixed runtime payload fields and Langfuse maps them automatically.
+ evaluationRuleCount:
+ type: integer
+ docs: Number of evaluation rules in the project that currently use this evaluator version.
+ createdAt:
+ type: datetime
+ docs: Timestamp when this evaluator was created.
+ updatedAt:
+ type: datetime
+ docs: Timestamp when this evaluator was last updated.
- Every variable in this list must be mapped exactly once when creating an evaluation rule.
+ LlmAsJudgeEvaluator:
+ extends: EvaluatorBase
+ properties:
+ prompt:
+ type: string
+ docs: Prompt template used during evaluation.
outputDefinition:
type: commons.PublicEvaluatorOutputDefinition
docs: |
@@ -208,15 +363,16 @@ types:
modelConfig:
type: nullable<commons.EvaluatorModelConfig>
docs: Explicit model configuration, or `null` when the project default evaluation model is used.
- evaluationRuleCount:
- type: integer
- docs: Number of evaluation rules in the project that currently use this evaluator version.
- createdAt:
- type: datetime
- docs: Timestamp when this evaluator was created.
- updatedAt:
- type: datetime
- docs: Timestamp when this evaluator was last updated.
+
+ CodeEvaluator:
+ extends: EvaluatorBase
+ properties:
+ sourceCode:
+ type: string
+ docs: Source code executed for each matched observation.
+ sourceCodeLanguage:
+ type: commons.CodeEvaluatorSourceCodeLanguage
+ docs: Runtime language for `sourceCode`.
Evaluators:
properties:
@@ -231,6 +387,15 @@ types:
If the same `name` already exists in your project, Langfuse creates the next version and returns it.
Existing evaluation rules in the same project are then moved to that new latest version automatically.
+ If `type` is omitted, Langfuse defaults it to `llm_as_judge` for backwards compatibility.
+ discriminant: type
+ union:
+ llm_as_judge:
+ type: CreateLlmAsJudgeEvaluatorRequest
+ code:
+ type: CreateCodeEvaluatorRequest
+
+ CreateLlmAsJudgeEvaluatorRequest:
properties:
name:
type: string
@@ -248,3 +413,15 @@ types:
modelConfig:
type: optional<nullable<commons.EvaluatorModelConfig>>
docs: Optional explicit model configuration. Omit or set to `null` to use the project default evaluation model.
+
+ CreateCodeEvaluatorRequest:
+ properties:
+ name:
+ type: string
+ docs: Evaluator name within the authenticated project.
+ sourceCode:
+ type: string
+ docs: Code executed for each matched observation.
+ sourceCodeLanguage:
+ type: commons.CodeEvaluatorSourceCodeLanguage
+ docs: Runtime language for `sourceCode`.
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 4f62edea21..2ccd451fae 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -6449,10 +6449,14 @@ paths:
- for `target=experiment`, use dataset `id` values from `GET
/api/public/v2/datasets` when filtering by `datasetId`
- - every evaluator prompt variable must be mapped exactly once
+ - for `llm_as_judge` evaluators, every evaluator prompt variable must be
+ mapped exactly once
- - `expected_output` and `experiment_item_metadata` mappings are only
- valid for `target=experiment`
+ - for `code` evaluators, Langfuse uses the fixed code runtime mapping;
+ omit `mapping` in create and update requests
+
+ - for user-provided `llm_as_judge` mappings, `expected_output` and
+ `experiment_item_metadata` are only valid for `target=experiment`
- if `enabled=true`, Langfuse validates that the referenced evaluator
can currently run
@@ -6492,14 +6496,15 @@ paths:
/api/public/v2/datasets`, then retry with dataset `id` values from that
response
- - `400 missing_variable_mapping`: fetch the evaluator again and make
- sure every variable in `variables` appears exactly once in `mapping`
+ - `400 missing_variable_mapping`: for `llm_as_judge` evaluators, fetch
+ the evaluator again and make sure every variable in `variables` appears
+ exactly once in `mapping`
- `400 duplicate_variable_mapping`: remove repeated mappings for the
same variable
- - `400 invalid_variable_mapping`: switch to a valid `source` for the
- selected `target`, or fix the variable name
+ - `400 invalid_variable_mapping`: for `llm_as_judge`, switch to a valid
+ `source` for the selected `target`, or fix the variable name
- `400 invalid_json_path`: remove or correct the `jsonPath`
@@ -6526,6 +6531,7 @@ paths:
id: evaltmpl_123
name: answer-correctness
scope: project
+ type: llm_as_judge
target: observation
enabled: true
status: active
@@ -6543,6 +6549,38 @@ paths:
source: output
createdAt: '2026-03-30T09:20:00.000Z'
updatedAt: '2026-03-30T09:20:00.000Z'
+ CreateCodeObservationEvaluationRule:
+ value:
+ id: erule_234
+ name: toxicity-code-live
+ evaluator:
+ id: evaltmpl_234
+ name: toxicity-detector
+ scope: project
+ type: code
+ target: observation
+ enabled: true
+ status: active
+ sampling: 1
+ filter:
+ - type: stringOptions
+ column: type
+ operator: any of
+ value:
+ - GENERATION
+ mapping:
+ - variable: input
+ source: input
+ - variable: output
+ source: output
+ - variable: metadata
+ source: metadata
+ - variable: experimentItemExpectedOutput
+ source: expected_output
+ - variable: experimentItemMetadata
+ source: experiment_item_metadata
+ createdAt: '2026-03-30T09:25:00.000Z'
+ updatedAt: '2026-03-30T09:25:00.000Z'
CreateExperimentEvaluationRule:
value:
id: erule_456
@@ -6551,6 +6589,7 @@ paths:
id: evaltmpl_456
name: expected-output-match
scope: project
+ type: llm_as_judge
target: experiment
enabled: true
status: active
@@ -6632,6 +6671,7 @@ paths:
evaluator:
name: answer-correctness
scope: project
+ type: llm_as_judge
target: observation
enabled: true
sampling: 1
@@ -6646,12 +6686,29 @@ paths:
source: input
- variable: output
source: output
+ CreateCodeObservationEvaluationRule:
+ value:
+ name: toxicity-code-live
+ evaluator:
+ name: toxicity-detector
+ scope: project
+ type: code
+ target: observation
+ enabled: true
+ sampling: 1
+ filter:
+ - type: stringOptions
+ column: type
+ operator: any of
+ value:
+ - GENERATION
CreateExperimentEvaluationRule:
value:
name: experiment-expected-output-match
evaluator:
name: expected-output-match
scope: project
+ type: llm_as_judge
target: experiment
enabled: true
sampling: 0.5
@@ -6818,7 +6875,7 @@ paths:
- change filters
- - update variable mappings
+ - update LLM-as-judge variable mappings
Important behavior:
@@ -6828,12 +6885,15 @@ paths:
- if you provide `evaluator`, Langfuse resolves that evaluator family to
its latest version before saving
- - changing `target`, `filter`, or `mapping` must still produce a valid
- target-specific configuration
+ - changing `target`, `filter`, or an LLM-as-judge `mapping` must still
+ produce a valid target-specific configuration
+
+ - if you change `target` for an LLM-as-judge rule, also send a
+ compatible `filter` and `mapping` in the same request unless the
+ existing ones are still valid for the new target
- - if you change `target`, also send a compatible `filter` and `mapping`
- in the same request unless the existing ones are still valid for the new
- target
+ - for `code` evaluator rules, omit `mapping`; Langfuse stores the fixed
+ code runtime mapping automatically
- if the resulting config is enabled, Langfuse re-validates that the
selected evaluator can run
@@ -6845,7 +6905,7 @@ paths:
Recovery guidance:
- - if the update fails with `missing_variable_mapping` or
+ - if an LLM-as-judge update fails with `missing_variable_mapping` or
`invalid_variable_mapping` after changing `evaluator` or `target`,
resend the request with a complete new `mapping`
@@ -6988,8 +7048,12 @@ paths:
Create an evaluator in the authenticated project.
- Use evaluators to define **how** Langfuse should score data: the prompt,
- the expected structured output, and the optional model configuration.
+ Use evaluators to define **how** Langfuse should score data.
+
+ LLM-as-a-judge evaluators define a prompt, expected structured output,
+ and optional model configuration.
+
+ Code evaluators define source code and a runtime language.
Naming behavior:
@@ -7018,6 +7082,16 @@ paths:
evaluator family using `name` and `scope`.
+ Code evaluator validation:
+
+ - At creation, Langfuse only validates the request shape
+
+ - The `sourceCode` itself is not executed here. It is first run
+ (preflight-tested against a sample observation) when you link the
+ evaluator to an evaluation rule, so runtime errors in the code surface
+ at evaluation-rule creation, not at evaluator creation.
+
+
Recovery guidance:
- `422` with `code=evaluator_preflight_failed`: the evaluator cannot run
@@ -7029,9 +7103,14 @@ paths:
the structured `details.issues` array to fix the specific fields and
retry.
- - `400` with `code=invalid_body` on `outputDefinition`: send `dataType`,
- `reasoning.description`, and `score.description`. Do not send `version`;
- it is not part of the public request shape.
+ - `400` with `code=invalid_body` on `outputDefinition`: for
+ `type=llm_as_judge`, send `dataType`, `reasoning.description`, and
+ `score.description`. Do not send `version`; it is not part of the public
+ request shape.
+
+ - If `type` is omitted, Langfuse treats the request as
+ `type=llm_as_judge` for backwards compatibility. New clients should send
+ `type` explicitly.
Unstable API note:
@@ -7082,6 +7161,80 @@ paths:
evaluationRuleCount: 0
createdAt: '2026-03-30T09:00:00.000Z'
updatedAt: '2026-03-30T09:00:00.000Z'
+ CreateTypeScriptCodeEvaluator:
+ value:
+ id: evaltmpl_ts_123
+ name: exact-match
+ version: 1
+ scope: project
+ type: code
+ variables:
+ - input
+ - output
+ - metadata
+ - experimentItemExpectedOutput
+ - experimentItemMetadata
+ sourceCode: >
+ function evaluate(ctx: EvaluationContext):
+ EvaluationResult {
+ const input = ctx.observation.input;
+ const matchesOutput =
+ input !== undefined && ctx.observation.output === input;
+
+ return {
+ scores: [
+ {
+ name: "Exact match",
+ value: matchesOutput,
+ dataType: "BOOLEAN",
+ comment: matchesOutput
+ ? "Output exactly matches the input."
+ : "Output does not match the input.",
+ },
+ ],
+ };
+ }
+ sourceCodeLanguage: TYPESCRIPT
+ evaluationRuleCount: 0
+ createdAt: '2026-03-30T09:10:00.000Z'
+ updatedAt: '2026-03-30T09:10:00.000Z'
+ CreatePythonCodeEvaluator:
+ value:
+ id: evaltmpl_py_123
+ name: exact-match
+ version: 1
+ scope: project
+ type: code
+ variables:
+ - input
+ - output
+ - metadata
+ - experimentItemExpectedOutput
+ - experimentItemMetadata
+ sourceCode: |
+ def evaluate(ctx: EvaluationContext) -> EvaluationResult:
+ """Evaluates one observation and returns one or more Langfuse scores."""
+ input = ctx.observation.input
+ matches_output = input is not None and ctx.observation.output == input
+
+ return EvaluationResult(
+ scores=[
+ Score(
+ name="Exact match",
+ value=matches_output,
+ data_type="BOOLEAN",
+ comment=(
+ "Output exactly matches the input."
+ if matches_output
+ else "Output does not match the input."
+ ),
+ )
+ ]
+ )
+ sourceCodeLanguage: PYTHON
+ evaluationRuleCount: 0
+ createdAt: '2026-03-30T09:15:00.000Z'
+ updatedAt: '2026-03-30T09:15:00.000Z'
'400':
description: ''
content:
@@ -7143,6 +7296,7 @@ paths:
CreateEvaluatorVersion:
value:
name: answer-correctness
+ type: llm_as_judge
prompt: |
You are grading an answer.
@@ -7162,6 +7316,56 @@ paths:
modelConfig:
provider: openai
model: gpt-4.1-mini
+ CreateTypeScriptCodeEvaluator:
+ value:
+ name: exact-match
+ type: code
+ sourceCode: >
+ function evaluate(ctx: EvaluationContext): EvaluationResult
+ {
+ const input = ctx.observation.input;
+ const matchesOutput =
+ input !== undefined && ctx.observation.output === input;
+
+ return {
+ scores: [
+ {
+ name: "Exact match",
+ value: matchesOutput,
+ dataType: "BOOLEAN",
+ comment: matchesOutput
+ ? "Output exactly matches the input."
+ : "Output does not match the input.",
+ },
+ ],
+ };
+ }
+ sourceCodeLanguage: TYPESCRIPT
+ CreatePythonCodeEvaluator:
+ value:
+ name: exact-match
+ type: code
+ sourceCode: |
+ def evaluate(ctx: EvaluationContext) -> EvaluationResult:
+ """Evaluates one observation and returns one or more Langfuse scores."""
+ input = ctx.observation.input
+ matches_output = input is not None and ctx.observation.output == input
+
+ return EvaluationResult(
+ scores=[
+ Score(
+ name="Exact match",
+ value=matches_output,
+ data_type="BOOLEAN",
+ comment=(
+ "Output exactly matches the input."
+ if matches_output
+ else "Output does not match the input."
+ ),
+ )
+ ]
+ )
+ sourceCodeLanguage: PYTHON
get:
description: >-
List the evaluators available to the authenticated project.
@@ -12703,12 +12907,18 @@ components:
type: string
enum:
- llm_as_judge
- description: >-
+ - code
+ description: |-
The evaluator engine type.
-
- The unstable public API currently supports only LLM-as-a-judge
- evaluators.
+ The unstable public API supports LLM-as-a-judge and code evaluators.
+ unstableCodeEvaluatorSourceCodeLanguage:
+ title: unstableCodeEvaluatorSourceCodeLanguage
+ type: string
+ enum:
+ - PYTHON
+ - TYPESCRIPT
+ description: Code evaluator runtime language.
unstableEvaluatorScope:
title: unstableEvaluatorScope
type: string
@@ -13278,8 +13488,11 @@ components:
title: unstableEvaluationRuleMapping
type: object
description: >-
- Maps one evaluator prompt variable to one source field from the target
- object.
+ Maps one evaluator variable to one source field from the target object.
+
+
+ Manual mappings are used for `llm_as_judge` evaluators. `code`
+ evaluators use a fixed runtime mapping managed by Langfuse.
How to build a valid mapping list:
@@ -13306,8 +13519,8 @@ components:
- `invalid_variable_mapping`: the variable name is unknown for this
evaluator, or the selected `source` is not valid for the chosen `target`
- - `missing_variable_mapping`: one or more evaluator variables are not
- mapped yet
+ - `missing_variable_mapping`: one or more LLM-as-judge evaluator
+ variables are not mapped yet
- `duplicate_variable_mapping`: the same evaluator variable appears more
than once
@@ -13825,8 +14038,8 @@ components:
items:
$ref: '#/components/schemas/unstableEvaluationRuleMapping'
description: >-
- Variable mappings used to populate the evaluator prompt from the
- live target object.
+ Variable mappings used to populate evaluator runtime variables from
+ the live target object.
createdAt:
type: string
format: date-time
@@ -13867,7 +14080,9 @@ components:
- meta
unstableCreateEvaluationRuleRequest:
title: unstableCreateEvaluationRuleRequest
- type: object
+ oneOf:
+ - $ref: '#/components/schemas/unstableCreateLlmAsJudgeEvaluationRuleRequest'
+ - $ref: '#/components/schemas/unstableCreateCodeEvaluationRuleRequest'
description: >-
Request body for creating an evaluation rule.
@@ -13883,24 +14098,32 @@ components:
/api/public/v2/datasets` first and use dataset `id` values in
`filter[].value`
- - fetch or inspect the evaluator first, then provide a complete variable
- mapping for every evaluator variable listed in `variables`
+ - for `llm_as_judge`, fetch or inspect the evaluator first and provide a
+ complete variable mapping for every evaluator variable
+
+ - for `code`, do not send variables or mappings; Langfuse stores the
+ fixed code runtime mapping automatically
- optionally narrow execution with `filter`
- set `enabled=true` only when you want live execution immediately
+ unstableCreateLlmAsJudgeEvaluationRuleRequest:
+ title: unstableCreateLlmAsJudgeEvaluationRuleRequest
+ type: object
properties:
name:
type: string
description: Human-readable deployment name.
- example: answer-correctness-live
evaluator:
- $ref: '#/components/schemas/unstableEvaluationRuleEvaluatorReference'
+ $ref: >-
+ #/components/schemas/unstableLlmAsJudgeEvaluationRuleEvaluatorReference
description: >-
- Evaluator family to use.
+ LLM-as-judge evaluator family to use.
- Use `name` and `scope` from the evaluator endpoints.
+ Use `name`, `scope`, and `type` from the evaluator endpoints. If
+ `type` is omitted, Langfuse defaults it to `llm_as_judge` for
+ backwards compatibility.
Langfuse resolves that family to its latest version before saving
the rule.
@@ -13910,7 +14133,6 @@ components:
enabled:
type: boolean
description: Whether the deployment should be active immediately after creation.
- example: true
sampling:
type: number
format: double
@@ -13938,7 +14160,7 @@ components:
items:
$ref: '#/components/schemas/unstableEvaluationRuleMapping'
description: >-
- Required variable mappings.
+ LLM-as-judge variable mappings.
Every evaluator variable must appear exactly once.
@@ -13951,6 +14173,56 @@ components:
- target
- enabled
- mapping
+ unstableCreateCodeEvaluationRuleRequest:
+ title: unstableCreateCodeEvaluationRuleRequest
+ type: object
+ properties:
+ name:
+ type: string
+ description: Human-readable deployment name.
+ evaluator:
+ $ref: '#/components/schemas/unstableCodeEvaluationRuleEvaluatorReference'
+ description: >-
+ Code evaluator family to use.
+
+
+ Use `name`, `scope`, and `type` from the evaluator endpoints.
+
+ Langfuse resolves that family to its latest version before saving
+ the rule.
+ target:
+ $ref: '#/components/schemas/unstableEvaluationRuleTarget'
+ description: Target object type to evaluate.
+ enabled:
+ type: boolean
+ description: Whether the deployment should be active immediately after creation.
+ sampling:
+ type: number
+ format: double
+ nullable: true
+ description: Optional sampling fraction. Defaults to `1`.
+ filter:
+ type: array
+ items:
+ $ref: '#/components/schemas/unstableEvaluationRuleFilter'
+ nullable: true
+ description: >-
+ Optional filter list.
+
+
+ Omit or pass an empty list to evaluate all matching targets for the
+ selected `target`.
+
+ Each filter object must use a column that is valid for that
+ `target`.
+
+ For `target=experiment`, `column=datasetId` expects dataset `id`
+ values from `GET /api/public/v2/datasets`, not dataset names.
+ required:
+ - name
+ - evaluator
+ - target
+ - enabled
unstableUpdateEvaluationRuleRequest:
title: unstableUpdateEvaluationRuleRequest
type: object
@@ -13968,11 +14240,15 @@ components:
- If you only want to rename the rule or change sampling, send just
those fields.
- - If you change `evaluator`, send a fresh `mapping` unless you are
- certain the existing mapping still matches the evaluator variables.
+ - If you change to an LLM-as-judge `evaluator`, send a fresh `mapping`
+ unless you are certain the existing mapping still matches the evaluator
+ variables.
- - If you change `target`, usually send both `filter` and `mapping` in
- the same request.
+ - If you change `target` for an LLM-as-judge rule, usually send both
+ `filter` and `mapping` in the same request.
+
+ - For code evaluator rules, omit `mapping`; Langfuse stores the fixed
+ code runtime mapping automatically.
- If you change an experiment `datasetId` filter, call `GET
/api/public/v2/datasets` and use dataset `id` values from that response.
@@ -13990,6 +14266,10 @@ components:
Langfuse resolves the provided evaluator family to its latest
version before saving the rule.
+
+ A rule's evaluator type cannot be changed: provide `name` and
+ `scope` for an evaluator family of the rule's current type. To use a
+ different evaluator type, create a new rule.
target:
$ref: '#/components/schemas/unstableEvaluationRuleTarget'
nullable: true
@@ -14019,7 +14299,13 @@ components:
items:
$ref: '#/components/schemas/unstableEvaluationRuleMapping'
nullable: true
- description: Updated variable mappings.
+ description: >-
+ Updated LLM-as-judge variable mappings.
+
+
+ Do not send this field for code evaluator rules. Langfuse stores the
+ fixed code runtime mapping automatically and returns it in the
+ response.
unstableDeleteEvaluationRuleResponse:
title: unstableDeleteEvaluationRuleResponse
type: object
@@ -14034,12 +14320,15 @@ components:
title: unstableEvaluationRuleEvaluatorReference
type: object
description: >-
- Evaluator family reference used when creating or updating an evaluation
- rule.
+ Evaluator family reference used when updating an evaluation rule.
+
+ `name` and `scope` identify the evaluator family in the authenticated
+ project context.
- `name` and `scope` are enough to identify the evaluator family in the
- authenticated project context.
+ A rule's evaluator type cannot be changed, so this reference does not
+ accept a `type`; the family must match the rule's current evaluator
+ type.
properties:
name:
type: string
@@ -14050,6 +14339,50 @@ components:
required:
- name
- scope
+ unstableLlmAsJudgeEvaluationRuleEvaluatorReference:
+ title: unstableLlmAsJudgeEvaluationRuleEvaluatorReference
+ type: object
+ description: >-
+ LLM-as-judge evaluator family reference used when creating an evaluation
+ rule.
+ properties:
+ name:
+ type: string
+ description: Evaluator family name.
+ scope:
+ $ref: '#/components/schemas/unstableEvaluatorScope'
+ description: Whether the evaluator family is project-owned or Langfuse-managed.
+ type:
+ $ref: '#/components/schemas/unstableLlmAsJudgeEvaluatorType'
+ nullable: true
+ description: Evaluator engine type. Defaults to `llm_as_judge` when omitted.
+ required:
+ - name
+ - scope
+ unstableCodeEvaluationRuleEvaluatorReference:
+ title: unstableCodeEvaluationRuleEvaluatorReference
+ type: object
+ description: Code evaluator family reference used when creating an evaluation rule.
+ properties:
+ name:
+ type: string
+ description: Evaluator family name.
+ scope:
+ $ref: '#/components/schemas/unstableEvaluatorScope'
+ description: Whether the evaluator family is project-owned or Langfuse-managed.
+ type:
+ type: string
+ const: code
+ description: Must be `code`.
+ required:
+ - name
+ - scope
+ - type
+ unstableLlmAsJudgeEvaluatorType:
+ title: unstableLlmAsJudgeEvaluatorType
+ type: string
+ enum:
+ - llm_as_judge
unstableEvaluationRuleEvaluator:
title: unstableEvaluationRuleEvaluator
type: object
@@ -14057,7 +14390,7 @@ components:
Resolved evaluator currently used by the evaluation rule.
`id` is the exact active evaluator version.
- `name` and `scope` identify the evaluator family conceptually.
+ `name`, `scope`, and `type` identify the evaluator family conceptually.
properties:
id:
type: string
@@ -14070,26 +14403,44 @@ components:
scope:
$ref: '#/components/schemas/unstableEvaluatorScope'
description: Whether the evaluator family is project-owned or Langfuse-managed.
+ type:
+ $ref: '#/components/schemas/unstableEvaluatorType'
+ description: Evaluator engine type.
required:
- id
- name
- scope
+ - type
unstableEvaluator:
title: unstableEvaluator
- type: object
+ oneOf:
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - llm_as_judge
+ - $ref: '#/components/schemas/unstableLlmAsJudgeEvaluator'
+ required:
+ - type
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - code
+ - $ref: '#/components/schemas/unstableCodeEvaluator'
+ required:
+ - type
description: >-
One evaluator that can be used for scoring.
- An evaluator describes **how** to score data:
-
- - prompt
-
- - extracted prompt variables
-
- - output schema
-
- - optional explicit model configuration
+ An evaluator describes **how** to score data.
It does not define **which** live objects are evaluated. That is the job
@@ -14098,14 +14449,12 @@ components:
For agent clients, the most important fields are:
- - `variables`: use these exact names when building the evaluation-rule
- `mapping` array
+ - `type`: determines which evaluator fields are present
- - `outputDefinition`: tells you the expected score type and the
- evaluator's response instructions
-
- - `modelConfig`: tells you whether the evaluator uses the project
- default model (`null`) or an explicit provider/model
+ - `variables`: for LLM evaluators, use these exact names when building
+ the evaluation-rule `mapping` array. LLM evaluators require every
+ variable to be mapped. Code evaluators always expose the fixed runtime
+ payload fields and Langfuse maps them automatically.
Versioning behavior:
@@ -14117,97 +14466,100 @@ components:
- Evaluation rules always run against the latest version for the
selected evaluator name within the same source (`project` or `managed`).
+ unstableEvaluatorBase:
+ title: unstableEvaluatorBase
+ type: object
properties:
id:
type: string
description: Identifier of this evaluator.
- example: evaltmpl_123
name:
type: string
description: Evaluator name.
- example: answer-correctness
version:
type: integer
description: Version number of this evaluator.
- example: 2
scope:
$ref: '#/components/schemas/unstableEvaluatorScope'
description: >-
Where this evaluator comes from: your project or Langfuse-managed
defaults.
- type:
- $ref: '#/components/schemas/unstableEvaluatorType'
- description: Evaluator engine type. Currently always `llm_as_judge`.
- prompt:
- type: string
- description: Prompt template used during evaluation.
- example: |
- You are grading an answer.
-
- Input:
- {{input}}
-
- Output:
- {{output}}
-
- Return a score between 0 and 1.
variables:
type: array
items:
type: string
description: >-
- Variables extracted from the evaluator prompt.
-
+ Variables that can be mapped when creating an evaluation rule.
- Every variable in this list must be mapped exactly once when
- creating an evaluation rule.
- example:
- - input
- - output
- outputDefinition:
- $ref: '#/components/schemas/unstablePublicEvaluatorOutputDefinition'
- description: >-
- Structured output schema returned by this evaluator.
-
- Responses always include `dataType` and omit the internal
- output-definition `version`.
-
- Use `dataType` to decide how future scores should be interpreted.
- modelConfig:
- $ref: '#/components/schemas/unstableEvaluatorModelConfig'
- nullable: true
- description: >-
- Explicit model configuration, or `null` when the project default
- evaluation model is used.
+ LLM evaluators require every variable to be mapped exactly once.
+ Code evaluators always expose the fixed runtime payload fields and
+ Langfuse maps them automatically.
evaluationRuleCount:
type: integer
description: >-
Number of evaluation rules in the project that currently use this
evaluator version.
- example: 0
createdAt:
type: string
format: date-time
description: Timestamp when this evaluator was created.
- example: '2026-03-30T09:00:00.000Z'
updatedAt:
type: string
format: date-time
description: Timestamp when this evaluator was last updated.
- example: '2026-03-30T09:00:00.000Z'
required:
- id
- name
- version
- scope
- - type
- - prompt
- variables
- - outputDefinition
- evaluationRuleCount
- createdAt
- updatedAt
+ unstableLlmAsJudgeEvaluator:
+ title: unstableLlmAsJudgeEvaluator
+ type: object
+ properties:
+ prompt:
+ type: string
+ description: Prompt template used during evaluation.
+ outputDefinition:
+ $ref: '#/components/schemas/unstablePublicEvaluatorOutputDefinition'
+ description: >-
+ Structured output schema returned by this evaluator.
+
+
+ Responses always include `dataType` and omit the internal
+ output-definition `version`.
+
+ Use `dataType` to decide how future scores should be interpreted.
+ modelConfig:
+ $ref: '#/components/schemas/unstableEvaluatorModelConfig'
+ nullable: true
+ description: >-
+ Explicit model configuration, or `null` when the project default
+ evaluation model is used.
+ required:
+ - prompt
+ - outputDefinition
+ allOf:
+ - $ref: '#/components/schemas/unstableEvaluatorBase'
+ unstableCodeEvaluator:
+ title: unstableCodeEvaluator
+ type: object
+ properties:
+ sourceCode:
+ type: string
+ description: Source code executed for each matched observation.
+ sourceCodeLanguage:
+ $ref: '#/components/schemas/unstableCodeEvaluatorSourceCodeLanguage'
+ description: Runtime language for `sourceCode`.
+ required:
+ - sourceCode
+ - sourceCodeLanguage
+ allOf:
+ - $ref: '#/components/schemas/unstableEvaluatorBase'
unstableEvaluators:
title: unstableEvaluators
type: object
@@ -14223,7 +14575,29 @@ components:
- meta
unstableCreateEvaluatorRequest:
title: unstableCreateEvaluatorRequest
- type: object
+ oneOf:
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - llm_as_judge
+ - $ref: '#/components/schemas/unstableCreateLlmAsJudgeEvaluatorRequest'
+ required:
+ - type
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - code
+ - $ref: '#/components/schemas/unstableCreateCodeEvaluatorRequest'
+ required:
+ - type
description: >-
Request body for creating an evaluator.
@@ -14233,24 +14607,19 @@ components:
Existing evaluation rules in the same project are then moved to that new
latest version automatically.
+
+ If `type` is omitted, Langfuse defaults it to `llm_as_judge` for
+ backwards compatibility.
+ unstableCreateLlmAsJudgeEvaluatorRequest:
+ title: unstableCreateLlmAsJudgeEvaluatorRequest
+ type: object
properties:
name:
type: string
description: Evaluator name within the authenticated project.
- example: answer-correctness
prompt:
type: string
description: Prompt template used by the evaluator.
- example: |
- You are grading an answer.
-
- Input:
- {{input}}
-
- Output:
- {{output}}
-
- Return a score between 0 and 1.
outputDefinition:
$ref: '#/components/schemas/unstableEvaluatorOutputDefinition'
description: >-
@@ -14271,6 +14640,23 @@ components:
- name
- prompt
- outputDefinition
+ unstableCreateCodeEvaluatorRequest:
+ title: unstableCreateCodeEvaluatorRequest
+ type: object
+ properties:
+ name:
+ type: string
+ description: Evaluator name within the authenticated project.
+ sourceCode:
+ type: string
+ description: Code executed for each matched observation.
+ sourceCodeLanguage:
+ $ref: '#/components/schemas/unstableCodeEvaluatorSourceCodeLanguage'
+ description: Runtime language for `sourceCode`.
+ required:
+ - name
+ - sourceCode
+ - sourceCodeLanguage
utilsMetaResponse:
title: utilsMetaResponse
type: object
diff --git a/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts
index 7ff4965a74..590833c6a5 100644
--- a/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts
+++ b/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts
@@ -3,6 +3,8 @@ import {
EvalTargetObject,
JobConfigState,
} from "@langfuse/shared";
+import { CODE_EVAL_SOURCE_MAX_BYTES } from "@langfuse/shared/src/server";
+import { EvalTemplateType } from "@langfuse/shared/src/db";
import {
toApiEvaluationRule,
toApiEvaluator,
@@ -22,6 +24,14 @@ import {
GetUnstableEvaluatorsQuery,
PostUnstableEvaluatorBody,
} from "@/src/features/public-api/types/unstable-evaluators";
+import {
+ PUBLIC_EVALUATOR_TYPE_CODE,
+ PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
+} from "@/src/features/public-api/types/unstable-public-evals-contract";
+import {
+ CODE_EVAL_TEMPLATE_VARIABLES,
+ getCodeEvalVariableMapping,
+} from "@/src/features/evals/utils/code-eval-template-utils";
const numericOutputDefinition = createNumericEvalOutputDefinition({
reasoningDescription: "Why the score was assigned",
@@ -71,6 +81,7 @@ describe("unstable public eval contracts", () => {
expect(parsed).toEqual({
name: "Answer correctness",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
prompt: "Judge {{input}} against {{output}}",
outputDefinition: {
dataType: "NUMERIC",
@@ -108,6 +119,63 @@ describe("unstable public eval contracts", () => {
);
});
+ it("accepts explicitly typed code evaluator creation bodies", () => {
+ const parsed = PostUnstableEvaluatorBody.parse({
+ name: "Exact match",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ sourceCode:
+ 'function evaluate() { return { scores: [{ name: "match", value: true, dataType: "BOOLEAN" }] }; }',
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+
+ expect(parsed).toEqual({
+ name: "Exact match",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ sourceCode:
+ 'function evaluate() { return { scores: [{ name: "match", value: true, dataType: "BOOLEAN" }] }; }',
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+ });
+
+ it("rejects LLM-only fields on code evaluator creation bodies", () => {
+ const parsed = PostUnstableEvaluatorBody.safeParse({
+ name: "Exact match",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ prompt: "Judge {{input}}",
+ sourceCode:
+ 'function evaluate() { return { scores: [{ name: "match", value: true, dataType: "BOOLEAN" }] }; }',
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+
+ expect(parsed.success).toBe(false);
+ expect(parsed.error?.issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ path: ["prompt"],
+ }),
+ ]),
+ );
+ });
+
+ it("rejects code evaluator creation bodies when source code is too large", () => {
+ const parsed = PostUnstableEvaluatorBody.safeParse({
+ name: "Oversized code",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ sourceCode: "a".repeat(CODE_EVAL_SOURCE_MAX_BYTES + 1),
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+
+ expect(parsed.success).toBe(false);
+ expect(parsed.error?.issues).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ path: ["sourceCode"],
+ message: `Source code must be ${CODE_EVAL_SOURCE_MAX_BYTES} bytes or less`,
+ }),
+ ]),
+ );
+ });
+
it("rejects observation evaluation rules that use expected_output mappings", () => {
const parsed = PostUnstableEvaluationRuleBody.safeParse({
name: "answer_quality",
@@ -126,13 +194,58 @@ describe("unstable public eval contracts", () => {
});
expect(parsed.success).toBe(false);
- expect(parsed.error?.issues).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- path: ["mapping", 1, "source"],
- }),
- ]),
- );
+ });
+
+ it("accepts code evaluation rule create bodies without mappings", () => {
+ const parsed = PostUnstableEvaluationRuleBody.parse({
+ name: "toxicity-code-live",
+ evaluator: {
+ name: "Toxicity detector",
+ scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ },
+ target: "observation",
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ });
+
+ expect("mapping" in parsed).toBe(false);
+ expect("variableMapping" in parsed).toBe(false);
+ });
+
+ it("rejects code evaluation rule create bodies with mappings", () => {
+ const parsed = PostUnstableEvaluationRuleBody.safeParse({
+ name: "toxicity-code-live",
+ evaluator: {
+ name: "Toxicity detector",
+ scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ },
+ target: "observation",
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ mapping: [{ variable: "output", source: "output" }],
+ });
+
+ expect(parsed.success).toBe(false);
+ });
+
+ it("rejects LLM evaluation rule create bodies without mappings", () => {
+ const parsed = PostUnstableEvaluationRuleBody.safeParse({
+ name: "answer-correctness-live",
+ evaluator: {
+ name: "Answer correctness",
+ scope: "project",
+ },
+ target: "observation",
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ });
+
+ expect(parsed.success).toBe(false);
});
it("rejects experiment filter updates unless target is provided", () => {
@@ -245,6 +358,25 @@ describe("unstable public eval contracts", () => {
expect(parsed.success).toBe(false);
expect(parsed.error?.issues.length).toBeGreaterThan(0);
});
+
+ it("strips evaluator type from patch bodies so a rule's evaluator type cannot be changed", () => {
+ const parsed = PatchUnstableEvaluationRuleBody.parse({
+ evaluator: {
+ name: "toxicity-detector",
+ scope: "project",
+ type: "llm_as_judge",
+ },
+ });
+
+ // `type` is dropped: the service inherits the rule's current evaluator type,
+ // so a code rule cannot be retargeted to an LLM evaluator family.
+ expect(parsed).toEqual({
+ evaluator: { name: "toxicity-detector", scope: "project" },
+ });
+ expect(
+ (parsed as { evaluator: { type?: string } }).evaluator.type,
+ ).toBeUndefined();
+ });
});
describe("unstable public eval adapters", () => {
@@ -269,6 +401,7 @@ describe("unstable public eval adapters", () => {
],
},
evaluatorVariables: ["output", "expected_output"],
+ evaluatorType: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
});
expect(writeModel).toMatchObject({
@@ -358,6 +491,7 @@ describe("unstable public eval adapters", () => {
mapping: [{ variable: "input", source: "input" }],
},
evaluatorVariables: ["input"],
+ evaluatorType: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
}),
{
code: "invalid_filter_value",
@@ -389,6 +523,7 @@ describe("unstable public eval adapters", () => {
],
},
evaluatorVariables: ["input"],
+ evaluatorType: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
}),
{
code: "invalid_json_path",
@@ -416,6 +551,7 @@ describe("unstable public eval adapters", () => {
],
},
evaluatorVariables: ["expected_output"],
+ evaluatorType: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
}),
{
code: "invalid_variable_mapping",
@@ -440,6 +576,7 @@ describe("unstable public eval adapters", () => {
mapping: [{ variable: "input", source: "input" }],
},
evaluatorVariables: ["input", "output"],
+ evaluatorType: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
}),
{
code: "missing_variable_mapping",
@@ -451,12 +588,29 @@ describe("unstable public eval adapters", () => {
);
});
+ it("stores canonical mappings for code evaluation rule writes", () => {
+ const writeModel = toJobConfigurationInput({
+ input: {
+ name: "toxicity-code-live",
+ target: "observation",
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ },
+ evaluatorVariables: [],
+ evaluatorType: PUBLIC_EVALUATOR_TYPE_CODE,
+ });
+
+ expect(writeModel.variableMapping).toEqual(getCodeEvalVariableMapping());
+ });
+
it("maps evaluator records to exact template versions", () => {
const template: StoredPublicEvaluatorTemplate = {
id: "tmpl_latest",
projectId: null,
name: "answer-correctness",
version: 7,
+ type: EvalTemplateType.LLM_AS_JUDGE,
prompt: "Judge {{input}} against {{output}}",
partner: "ragas",
provider: "openai",
@@ -464,6 +618,8 @@ describe("unstable public eval adapters", () => {
modelParams: { temperature: 0 },
vars: ["input", "output"],
outputDefinition: numericOutputDefinition,
+ sourceCode: null,
+ sourceCodeLanguage: null,
createdAt: new Date("2026-03-30T08:00:00.000Z"),
updatedAt: new Date("2026-03-30T09:00:00.000Z"),
};
@@ -478,7 +634,7 @@ describe("unstable public eval adapters", () => {
name: "answer-correctness",
version: 7,
scope: "managed",
- type: "llm_as_judge",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
outputDefinition: {
dataType: "NUMERIC",
reasoning: {
@@ -497,12 +653,47 @@ describe("unstable public eval adapters", () => {
});
});
+ it("maps code evaluator records with canonical runtime variables", () => {
+ const template: StoredPublicEvaluatorTemplate = {
+ id: "tmpl_code",
+ projectId: "project_123",
+ name: "toxicity-detector",
+ version: 1,
+ type: EvalTemplateType.CODE,
+ prompt: null,
+ partner: null,
+ provider: null,
+ model: null,
+ modelParams: null,
+ vars: ["stale"],
+ outputDefinition: null,
+ sourceCode:
+ 'function evaluate() { return { scores: [{ name: "toxicity", value: false, dataType: "BOOLEAN" }] }; }',
+ sourceCodeLanguage: "TYPESCRIPT",
+ createdAt: new Date("2026-03-30T08:00:00.000Z"),
+ updatedAt: new Date("2026-03-30T09:00:00.000Z"),
+ };
+
+ expect(
+ toApiEvaluator({
+ template,
+ evaluationRuleCount: 0,
+ }),
+ ).toMatchObject({
+ id: "tmpl_code",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ variables: [...CODE_EVAL_TEMPLATE_VARIABLES],
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+ });
+
it("normalizes legacy evaluator output definitions into the public response shape", () => {
const template: StoredPublicEvaluatorTemplate = {
id: "tmpl_legacy",
projectId: "project_123",
name: "answer-correctness",
version: 1,
+ type: EvalTemplateType.LLM_AS_JUDGE,
prompt: "Judge {{input}} against {{output}}",
partner: null,
provider: null,
@@ -513,6 +704,8 @@ describe("unstable public eval adapters", () => {
reasoning: "Explain why the answer is correct or incorrect.",
score: "Return a score between 0 and 1.",
},
+ sourceCode: null,
+ sourceCodeLanguage: null,
createdAt: new Date("2026-03-30T08:00:00.000Z"),
updatedAt: new Date("2026-03-30T09:00:00.000Z"),
};
@@ -521,14 +714,16 @@ describe("unstable public eval adapters", () => {
toApiEvaluator({
template,
evaluationRuleCount: 0,
- }).outputDefinition,
- ).toEqual({
- dataType: "NUMERIC",
- reasoning: {
- description: "Explain why the answer is correct or incorrect.",
- },
- score: {
- description: "Return a score between 0 and 1.",
+ }),
+ ).toMatchObject({
+ outputDefinition: {
+ dataType: "NUMERIC",
+ reasoning: {
+ description: "Explain why the answer is correct or incorrect.",
+ },
+ score: {
+ description: "Return a score between 0 and 1.",
+ },
},
});
});
@@ -559,8 +754,7 @@ describe("unstable public eval adapters", () => {
id: "tmpl_exact",
projectId: "project_123",
name: "Answer correctness",
- vars: ["input"],
- prompt: "Judge {{input}}",
+ type: EvalTemplateType.LLM_AS_JUDGE,
},
};
diff --git a/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts
index 6b3f0a103b..150f3b68c6 100644
--- a/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts
+++ b/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts
@@ -155,7 +155,6 @@ describe("unstable public eval queries", () => {
blockedAt: null,
evalTemplate: {
is: {
- type: EvalTemplateType.LLM_AS_JUDGE,
OR: [{ projectId: "project_123" }, { projectId: null }],
},
},
@@ -177,6 +176,7 @@ describe("unstable public eval queries", () => {
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: "llm_as_judge",
},
});
expect(mockEvalTemplateFindFirst).toHaveBeenCalledWith({
@@ -205,6 +205,7 @@ describe("unstable public eval queries", () => {
evaluator: {
name: "Answer correctness",
scope: "managed",
+ type: "llm_as_judge",
},
});
diff --git a/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts
index b6f86e4379..d5297368d2 100644
--- a/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts
+++ b/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts
@@ -1,7 +1,12 @@
import type * as PrismaClientModule from "@prisma/client";
import type { Mock } from "vitest";
+const { mockAssertCodeEvalJobConfigCanRun } = vi.hoisted(() => ({
+ mockAssertCodeEvalJobConfigCanRun: vi.fn(),
+}));
+
const mockEvalTemplateCreate = vi.fn();
+const mockEvalTemplateFindFirst = vi.fn();
const mockEvalTemplateFindMany = vi.fn();
const mockJobConfigurationFindMany = vi.fn();
const mockJobConfigurationUpdate = vi.fn();
@@ -20,6 +25,25 @@ vi.mock(
},
);
+vi.mock("../../../features/evals/server/isCodeEvalEnabled", () => ({
+ isCodeEvalEnabled: vi.fn(() => true),
+ isCodeEvalSourceCodeLanguageSupported: vi.fn(() => true),
+}));
+
+vi.mock(
+ "../../../features/evals/server/codeEvalJobConfigValidation",
+ async () => {
+ const actual = await vi.importActual(
+ "../../../features/evals/server/codeEvalJobConfigValidation",
+ );
+
+ return {
+ ...actual,
+ assertCodeEvalJobConfigCanRun: mockAssertCodeEvalJobConfigCanRun,
+ };
+ },
+);
+
vi.mock("../../../features/evals/server/unstable-public-api/queries", () => ({
countActiveEvaluationRules: vi.fn(),
findPublicEvaluatorTemplateOrThrow: vi.fn(),
@@ -95,9 +119,19 @@ import {
createPublicEvaluationRule,
updatePublicEvaluationRule,
} from "@/src/features/evals/server/unstable-public-api/evaluation-rule-service";
+import { CodeEvalJobConfigError } from "@/src/features/evals/server/codeEvalJobConfigValidation";
import { createPublicEvaluator } from "@/src/features/evals/server/unstable-public-api/evaluator-service";
import * as queryModule from "@/src/features/evals/server/unstable-public-api/queries";
import * as validationModule from "@/src/features/evals/server/unstable-public-api/validation";
+import {
+ PUBLIC_EVALUATOR_TYPE_CODE,
+ PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
+} from "@/src/features/public-api/types/unstable-public-evals-contract";
+import {
+ CODE_EVAL_TEMPLATE_VARIABLES,
+ getCodeEvalVariableMapping,
+} from "@/src/features/evals/utils/code-eval-template-utils";
+import { PostUnstableEvaluationRuleBody } from "@/src/features/public-api/types/unstable-evaluation-rules";
const numericOutputDefinition = createNumericEvalOutputDefinition({
reasoningDescription: "Why the score was assigned",
@@ -109,6 +143,7 @@ const projectTemplate = {
projectId: "project_123",
name: "Answer correctness",
version: 2,
+ type: EvalTemplateType.LLM_AS_JUDGE,
prompt: "Judge {{input}}",
partner: null,
provider: null,
@@ -116,15 +151,36 @@ const projectTemplate = {
modelParams: null,
vars: ["input"],
outputDefinition: numericOutputDefinition,
+ sourceCode: null,
+ sourceCodeLanguage: null,
createdAt: new Date("2026-03-30T08:00:00.000Z"),
updatedAt: new Date("2026-03-30T08:00:00.000Z"),
};
+const codeEvaluatorSourceCode =
+ 'function evaluate() { return { scores: [{ name: "match", value: true, dataType: "BOOLEAN" }] }; }';
+
+const codeTemplate = {
+ ...projectTemplate,
+ id: "tmpl_code_v1",
+ name: "Exact match",
+ type: EvalTemplateType.CODE,
+ prompt: null,
+ provider: null,
+ model: null,
+ modelParams: null,
+ vars: [...CODE_EVAL_TEMPLATE_VARIABLES],
+ outputDefinition: null,
+ sourceCode: codeEvaluatorSourceCode,
+ sourceCodeLanguage: "TYPESCRIPT" as const,
+};
+
const managedTemplate = {
id: "tmpl_managed",
projectId: null,
name: "Answer correctness",
version: 7,
+ type: EvalTemplateType.LLM_AS_JUDGE,
prompt: "Judge {{input}}",
partner: "ragas",
provider: null,
@@ -132,6 +188,8 @@ const managedTemplate = {
modelParams: null,
vars: ["input"],
outputDefinition: numericOutputDefinition,
+ sourceCode: null,
+ sourceCodeLanguage: null,
createdAt: new Date("2026-03-30T08:00:00.000Z"),
updatedAt: new Date("2026-03-30T08:00:00.000Z"),
};
@@ -189,6 +247,7 @@ const createEvaluationRuleRecord = (overrides?: Record<string, unknown>) =>
id: "tmpl_project_v2",
projectId: "project_123",
name: "Answer correctness",
+ type: EvalTemplateType.LLM_AS_JUDGE,
vars: ["input"],
prompt: "Judge {{input}}",
},
@@ -200,12 +259,15 @@ describe("unstable public eval services", () => {
vi.clearAllMocks();
mockCountActiveEvaluationRules.mockResolvedValue(0);
mockCountEvaluationRulesForEvaluator.mockResolvedValue(0);
+ mockEvalTemplateFindFirst.mockResolvedValue(null);
+ mockAssertCodeEvalJobConfigCanRun.mockResolvedValue(undefined);
mockedPrisma.dataset.findMany.mockResolvedValue([]);
mockedPrisma.$transaction.mockImplementation(async (callback) =>
callback({
evalTemplate: {
create: mockEvalTemplateCreate,
+ findFirst: mockEvalTemplateFindFirst,
findMany: mockEvalTemplateFindMany,
},
jobConfiguration: {
@@ -230,6 +292,7 @@ describe("unstable public eval services", () => {
projectId: "project_123",
input: {
name: "Answer correctness",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
prompt: "Judge {{input}}",
outputDefinition: numericOutputDefinition,
},
@@ -254,6 +317,7 @@ describe("unstable public eval services", () => {
projectId: "project_123",
input: {
name: "Answer correctness",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
prompt: "Judge {{input}}",
outputDefinition: numericOutputDefinition,
},
@@ -297,6 +361,50 @@ describe("unstable public eval services", () => {
});
});
+ it("creates a new project-owned code evaluator family at version 1", async () => {
+ mockEvalTemplateFindMany.mockResolvedValueOnce([]);
+ mockEvalTemplateCreate.mockResolvedValueOnce({
+ ...codeTemplate,
+ version: 1,
+ createdAt: new Date("2026-03-31T08:00:00.000Z"),
+ updatedAt: new Date("2026-03-31T08:00:00.000Z"),
+ });
+
+ const result = await createPublicEvaluator({
+ projectId: "project_123",
+ input: {
+ name: "Exact match",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ sourceCode: codeEvaluatorSourceCode,
+ sourceCodeLanguage: "TYPESCRIPT",
+ },
+ });
+
+ expect(
+ mockAssertEvaluatorDefinitionCanRunForPublicApi,
+ ).not.toHaveBeenCalled();
+ expect(mockEvalTemplateCreate).toHaveBeenCalledWith({
+ data: expect.objectContaining({
+ projectId: "project_123",
+ name: "Exact match",
+ version: 1,
+ type: EvalTemplateType.CODE,
+ prompt: null,
+ vars: [...CODE_EVAL_TEMPLATE_VARIABLES],
+ outputDefinition: undefined,
+ sourceCode: codeEvaluatorSourceCode,
+ sourceCodeLanguage: "TYPESCRIPT",
+ }),
+ });
+ expect(result).toMatchObject({
+ id: "tmpl_code_v1",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ version: 1,
+ scope: "project",
+ sourceCodeLanguage: "TYPESCRIPT",
+ });
+ });
+
it("creates a new evaluator version when the project name already exists", async () => {
mockCountEvaluationRulesForEvaluator.mockResolvedValueOnce(2);
mockEvalTemplateFindMany.mockResolvedValueOnce([
@@ -333,6 +441,7 @@ describe("unstable public eval services", () => {
projectId: "project_123",
input: {
name: "Answer correctness",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
prompt: "Judge {{input}}",
outputDefinition: numericOutputDefinition,
},
@@ -421,6 +530,7 @@ describe("unstable public eval services", () => {
projectId: "project_123",
input: {
name: "Answer correctness",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
prompt: "Judge {{input}}",
outputDefinition: numericOutputDefinition,
},
@@ -484,6 +594,7 @@ describe("unstable public eval services", () => {
projectId: "project_123",
input: {
name: "Answer correctness",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
prompt: "Judge {{input}}",
outputDefinition: numericOutputDefinition,
},
@@ -534,6 +645,7 @@ describe("unstable public eval services", () => {
projectId: "project_123",
input: {
name: "Answer correctness",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
prompt: "Judge {{input}} against {{output}}",
outputDefinition: numericOutputDefinition,
},
@@ -568,12 +680,14 @@ describe("unstable public eval services", () => {
);
const result = await createPublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
input: {
name: "answer_quality_latest",
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
target: "observation",
enabled: true,
@@ -588,6 +702,7 @@ describe("unstable public eval services", () => {
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
});
expect(mockedPrisma.jobConfiguration.create).toHaveBeenCalledWith({
@@ -619,12 +734,14 @@ describe("unstable public eval services", () => {
await expect(
createPublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
input: {
name: "answer_quality",
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
target: "observation",
enabled: true,
@@ -638,6 +755,121 @@ describe("unstable public eval services", () => {
expect(mockedPrisma.jobConfiguration.create).not.toHaveBeenCalled();
});
+ it("rejects enabled code evaluation rules when the config test fails", async () => {
+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({
+ template: codeTemplate,
+ });
+ mockAssertCodeEvalJobConfigCanRun.mockRejectedValueOnce(
+ new CodeEvalJobConfigError("Evaluator failed during test run"),
+ );
+
+ await expect(
+ createPublicEvaluationRule({
+ orgId: "org_123",
+ projectId: "project_123",
+ input: PostUnstableEvaluationRuleBody.parse({
+ name: "exact_match_live",
+ evaluator: {
+ name: "Exact match",
+ scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ },
+ target: "observation",
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ }),
+ }),
+ ).rejects.toThrow("Evaluator failed during test run");
+
+ expect(mockAssertCodeEvalJobConfigCanRun).toHaveBeenCalledWith({
+ prisma: mockedPrisma,
+ orgId: "org_123",
+ projectId: "project_123",
+ evalTemplateId: "tmpl_code_v1",
+ target: EvalTargetObject.EVENT,
+ mapping: getCodeEvalVariableMapping(),
+ scoreName: "exact_match_live",
+ filter: [],
+ });
+ expect(mockedPrisma.jobConfiguration.create).not.toHaveBeenCalled();
+ });
+
+ it("translates code-eval preflight request failures into structured public API errors", async () => {
+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({
+ template: codeTemplate,
+ });
+ mockAssertCodeEvalJobConfigCanRun.mockRejectedValueOnce(
+ new CodeEvalJobConfigError(
+ "This code evaluator language is not supported by the configured dispatcher.",
+ "invalid_request",
+ ),
+ );
+
+ await expect(
+ createPublicEvaluationRule({
+ orgId: "org_123",
+ projectId: "project_123",
+ input: PostUnstableEvaluationRuleBody.parse({
+ name: "exact_match_live",
+ evaluator: {
+ name: "Exact match",
+ scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ },
+ target: "observation",
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ }),
+ }),
+ ).rejects.toMatchObject({
+ httpCode: 400,
+ code: "invalid_request",
+ message:
+ "This code evaluator language is not supported by the configured dispatcher.",
+ });
+
+ expect(mockedPrisma.jobConfiguration.create).not.toHaveBeenCalled();
+ });
+
+ it("translates code-eval invalid-target failures into structured public API errors", async () => {
+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({
+ template: codeTemplate,
+ });
+ mockAssertCodeEvalJobConfigCanRun.mockRejectedValueOnce(
+ new CodeEvalJobConfigError(
+ "Code evaluators can only run on observations or experiments.",
+ "invalid_target",
+ ),
+ );
+
+ await expect(
+ createPublicEvaluationRule({
+ orgId: "org_123",
+ projectId: "project_123",
+ input: PostUnstableEvaluationRuleBody.parse({
+ name: "exact_match_live",
+ evaluator: {
+ name: "Exact match",
+ scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ },
+ target: "observation",
+ enabled: true,
+ sampling: 1,
+ filter: [],
+ }),
+ }),
+ ).rejects.toMatchObject({
+ httpCode: 400,
+ code: "invalid_request",
+ message: "Code evaluators can only run on observations or experiments.",
+ });
+
+ expect(mockedPrisma.jobConfiguration.create).not.toHaveBeenCalled();
+ });
+
it("returns a conflict when an evaluation rule name already exists in the project", async () => {
mockedPrisma.jobConfiguration.findFirst.mockResolvedValueOnce({
id: "ceval_existing",
@@ -645,12 +877,14 @@ describe("unstable public eval services", () => {
await expect(
createPublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
input: {
name: "answer_quality",
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
target: "observation",
enabled: true,
@@ -673,7 +907,6 @@ describe("unstable public eval services", () => {
scoreName: "answer_quality",
evalTemplate: {
is: {
- type: EvalTemplateType.LLM_AS_JUDGE,
OR: [{ projectId: "project_123" }, { projectId: null }],
},
},
@@ -691,12 +924,14 @@ describe("unstable public eval services", () => {
await expect(
createPublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
input: {
name: "answer_quality",
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
target: "observation",
enabled: true,
@@ -720,12 +955,14 @@ describe("unstable public eval services", () => {
await expect(
createPublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
input: {
name: "experiment_answer_quality",
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
target: "experiment",
enabled: true,
@@ -774,12 +1011,14 @@ describe("unstable public eval services", () => {
);
await createPublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
input: {
name: "answer_quality",
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
target: "observation",
enabled: true,
@@ -813,12 +1052,14 @@ describe("unstable public eval services", () => {
);
const result = await createPublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
input: {
name: "answer_quality",
evaluator: {
name: "Answer correctness",
scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
target: "observation",
enabled: false,
@@ -860,12 +1101,14 @@ describe("unstable public eval services", () => {
);
const result = await createPublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
input: {
name: "managed_answer_quality",
evaluator: {
name: "Answer correctness",
scope: "managed",
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
},
target: "observation",
enabled: true,
@@ -917,6 +1160,7 @@ describe("unstable public eval services", () => {
);
const result = await updatePublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
evaluationRuleId: "ceval_123",
input: {
@@ -956,6 +1200,7 @@ describe("unstable public eval services", () => {
);
await updatePublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
evaluationRuleId: "ceval_123",
input: {
@@ -976,6 +1221,108 @@ describe("unstable public eval services", () => {
});
});
+ it("rejects code evaluation rule updates when the config test fails", async () => {
+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(
+ createEvaluationRuleRecord({
+ evalTemplate: {
+ id: "tmpl_code_v1",
+ projectId: "project_123",
+ name: "Exact match",
+ type: EvalTemplateType.CODE,
+ },
+ }),
+ );
+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({
+ template: codeTemplate,
+ });
+ mockAssertCodeEvalJobConfigCanRun.mockRejectedValueOnce(
+ new CodeEvalJobConfigError("Evaluator failed during update test run"),
+ );
+
+ await expect(
+ updatePublicEvaluationRule({
+ orgId: "org_123",
+ projectId: "project_123",
+ evaluationRuleId: "ceval_123",
+ input: {
+ name: "renamed_exact_match",
+ },
+ }),
+ ).rejects.toThrow("Evaluator failed during update test run");
+
+ expect(mockAssertCodeEvalJobConfigCanRun).toHaveBeenCalled();
+ expect(mockedPrisma.jobConfiguration.update).not.toHaveBeenCalled();
+ });
+
+ it("rejects user-provided mappings for code evaluation rule updates", async () => {
+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(
+ createEvaluationRuleRecord({
+ evalTemplate: {
+ id: "tmpl_code_v1",
+ projectId: "project_123",
+ name: "Exact match",
+ type: EvalTemplateType.CODE,
+ },
+ }),
+ );
+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({
+ template: codeTemplate,
+ });
+
+ await expect(
+ updatePublicEvaluationRule({
+ orgId: "org_123",
+ projectId: "project_123",
+ evaluationRuleId: "ceval_123",
+ input: {
+ target: "observation",
+ mapping: [{ variable: "input", source: "input" }],
+ },
+ }),
+ ).rejects.toThrow(
+ "Code evaluator mappings are managed by Langfuse and cannot be provided in the request body.",
+ );
+
+ expect(mockAssertCodeEvalJobConfigCanRun).not.toHaveBeenCalled();
+ expect(mockedPrisma.jobConfiguration.update).not.toHaveBeenCalled();
+ });
+
+ it("keeps the existing code evaluator type when a patch omits evaluator type", async () => {
+ const codeRuleRecord = createEvaluationRuleRecord({
+ evalTemplate: {
+ id: "tmpl_code_v1",
+ projectId: "project_123",
+ name: "Exact match",
+ type: EvalTemplateType.CODE,
+ },
+ });
+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(codeRuleRecord);
+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({
+ template: codeTemplate,
+ });
+ mockedPrisma.jobConfiguration.update.mockResolvedValueOnce(codeRuleRecord);
+
+ await updatePublicEvaluationRule({
+ orgId: "org_123",
+ projectId: "project_123",
+ evaluationRuleId: "ceval_123",
+ // No `type` on the evaluator reference: it must inherit the rule's current
+ // `code` type, not silently fall back to `llm_as_judge`.
+ input: {
+ evaluator: { name: "Exact match", scope: "project" },
+ },
+ });
+
+ expect(mockLoadEvaluatorForEvaluationRule).toHaveBeenCalledWith({
+ projectId: "project_123",
+ evaluator: {
+ name: "Exact match",
+ scope: "project",
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ },
+ });
+ });
+
it("rejects enabling a non-active evaluation rule when the active limit is reached", async () => {
mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(
createEvaluationRuleRecord({
@@ -986,6 +1333,7 @@ describe("unstable public eval services", () => {
await expect(
updatePublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
evaluationRuleId: "ceval_123",
input: {
@@ -1010,6 +1358,7 @@ describe("unstable public eval services", () => {
await expect(
updatePublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
evaluationRuleId: "ceval_123",
input: {
@@ -1077,6 +1426,7 @@ describe("unstable public eval services", () => {
);
const result = await updatePublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
evaluationRuleId: "ceval_123",
input: {
@@ -1114,6 +1464,7 @@ describe("unstable public eval services", () => {
);
await updatePublicEvaluationRule({
+ orgId: "org_123",
projectId: "project_123",
evaluationRuleId: "ceval_123",
input: {
diff --git a/web/src/__tests__/server/unstable-evals-api.servertest.ts b/web/src/__tests__/server/unstable-evals-api.servertest.ts
index 909ebc5366..0388441b63 100644
--- a/web/src/__tests__/server/unstable-evals-api.servertest.ts
+++ b/web/src/__tests__/server/unstable-evals-api.servertest.ts
@@ -274,6 +274,7 @@ describe("/api/public/unstable evaluators API", () => {
id: v2.body.id,
name: "Faithfulness",
scope: "project",
+ type: "llm_as_judge",
});
});
@@ -328,6 +329,7 @@ describe("/api/public/unstable evaluators API", () => {
id: v2.body.id,
name: "Answer groundedness",
scope: "project",
+ type: "llm_as_judge",
});
});
@@ -428,6 +430,7 @@ describe("/api/public/unstable evaluators API", () => {
id: managed.id,
name: "Answer relevance",
scope: "managed",
+ type: "llm_as_judge",
});
const deleted = await makeZodVerifiedAPICall(
diff --git a/web/src/features/evals/server/codeEvalJobConfigValidation.ts b/web/src/features/evals/server/codeEvalJobConfigValidation.ts
new file mode 100644
index 0000000000..9d1d2c7ae6
--- /dev/null
+++ b/web/src/features/evals/server/codeEvalJobConfigValidation.ts
@@ -0,0 +1,101 @@
+import { z } from "zod";
+import {
+ EvalTargetObject,
+ observationVariableMapping,
+ type EvalTargetObject as EvalTargetObjectType,
+ type FilterCondition,
+} from "@langfuse/shared";
+import type { PrismaClient } from "@prisma/client";
+import { env } from "@/src/env.mjs";
+import {
+ CodeEvalTestRunSetupError,
+ runCodeEvalTestForJobConfig,
+} from "@/src/features/evals/server/codeEvalTestRun";
+import { assertUnreachable } from "@/src/utils/types";
+
+export type CodeEvalJobConfigErrorCode =
+ | "invalid_target"
+ | "invalid_request"
+ | "resource_not_found"
+ | "preflight_failed";
+
+export class CodeEvalJobConfigError extends Error {
+ constructor(
+ message: string,
+ readonly code: CodeEvalJobConfigErrorCode = "preflight_failed",
+ ) {
+ super(message);
+ this.name = "CodeEvalJobConfigError";
+ Object.setPrototypeOf(this, CodeEvalJobConfigError.prototype);
+ }
+}
+
+export async function assertCodeEvalJobConfigCanRun(params: {
+ prisma: PrismaClient;
+ orgId: string;
+ projectId: string;
+ evalTemplateId: string;
+ target: EvalTargetObjectType;
+ mapping: unknown;
+ scoreName: string;
+ filter: FilterCondition[] | null;
+}): Promise<void> {
+ if (
+ params.target !== EvalTargetObject.EVENT &&
+ params.target !== EvalTargetObject.EXPERIMENT
+ ) {
+ throw new CodeEvalJobConfigError(
+ "Code evaluators can only run on observations or experiments.",
+ "invalid_target",
+ );
+ }
+
+ const parsedMapping = z
+ .array(observationVariableMapping)
+ .parse(params.mapping);
+
+ if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {
+ const result = await runCodeEvalTestForJobConfig({
+ prisma: params.prisma,
+ orgId: params.orgId,
+ projectId: params.projectId,
+ evalTemplateId: params.evalTemplateId,
+ target: params.target,
+ mapping: parsedMapping,
+ scoreName: params.scoreName,
+ filter: params.filter,
+ }).catch((error) => {
+ if (!(error instanceof CodeEvalTestRunSetupError)) {
+ throw error;
+ }
+
+ switch (error.code) {
+ case "INVALID_TARGET":
+ throw new CodeEvalJobConfigError(error.message, "invalid_target");
+ case "TEMPLATE_NOT_FOUND":
+ throw new CodeEvalJobConfigError(error.message, "resource_not_found");
+ case "UNSUPPORTED_LANGUAGE":
+ throw new CodeEvalJobConfigError(error.message, "invalid_request");
+ case "DISPATCHER_NOT_CONFIGURED":
+ case "OBSERVATION_NOT_FOUND":
+ throw new CodeEvalJobConfigError(error.message);
+ default:
+ return assertUnreachable(error.code);
+ }
+ });
+
+ if (!result) {
+ if (params.target !== EvalTargetObject.EXPERIMENT) {
+ throw new CodeEvalJobConfigError(
+ "No matching observation found to test this code evaluator. Adjust the filters and try again.",
+ );
+ }
+
+ return;
+ }
+
+ if (!result.success) {
+ throw new CodeEvalJobConfigError(result.error.message);
+ }
+ }
+}
diff --git a/web/src/features/evals/server/codeEvalTestRun.ts b/web/src/features/evals/server/codeEvalTestRun.ts
index 9586f9e2a8..6015e0bdb9 100644
--- a/web/src/features/evals/server/codeEvalTestRun.ts
+++ b/web/src/features/evals/server/codeEvalTestRun.ts
@@ -13,7 +13,6 @@ import {
type DispatchResult,
type InternalTraceWriteInput,
} from "@langfuse/shared/src/server";
-import { TRPCError } from "@trpc/server";
import {
LangfuseNotFoundError,
@@ -34,7 +33,25 @@ import {
} from "@/src/features/evals/utils/typeHelpers";
import { isCodeEvalSourceCodeLanguageSupported } from "@/src/features/evals/server/isCodeEvalEnabled";
-type CodeEvalTestRunError = Omit<CodeEvalUserVisibleError, "retryable">;
+type CodeEvalTestRunDispatchError = Omit<CodeEvalUserVisibleError, "retryable">;
+
+type CodeEvalTestRunSetupErrorCode =
+ | "DISPATCHER_NOT_CONFIGURED"
+ | "TEMPLATE_NOT_FOUND"
+ | "UNSUPPORTED_LANGUAGE"
+ | "INVALID_TARGET"
+ | "OBSERVATION_NOT_FOUND";
+
+export class CodeEvalTestRunSetupError extends Error {
+ constructor(
+ readonly code: CodeEvalTestRunSetupErrorCode,
+ message: string,
+ ) {
+ super(message);
+ this.name = "CodeEvalTestRunSetupError";
+ Object.setPrototypeOf(this, CodeEvalTestRunSetupError.prototype);
+ }
+}
export type CodeEvalTestRunResult =
| {
@@ -45,7 +62,7 @@ export type CodeEvalTestRunResult =
}
| {
success: false;
- error: CodeEvalTestRunError;
+ error: CodeEvalTestRunDispatchError;
executionTraceId: string;
executionTraceFromTimestamp: Date;
};
@@ -116,10 +133,10 @@ async function runCodeEvalTestForObservation(params: {
const dispatcher = resolveConfiguredCodeEvalDispatcher();
if (!dispatcher) {
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message: "Code eval dispatcher is not configured",
- });
+ throw new CodeEvalTestRunSetupError(
+ "DISPATCHER_NOT_CONFIGURED",
+ "Code eval dispatcher is not configured",
+ );
}
const codeTemplate = (await params.prisma.evalTemplate.findFirst({
@@ -133,18 +150,17 @@ async function runCodeEvalTestForObservation(params: {
})) as EvalTemplateCodeBased | null;
if (!codeTemplate) {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Evaluator template not found",
- });
+ throw new CodeEvalTestRunSetupError(
+ "TEMPLATE_NOT_FOUND",
+ "Evaluator template not found",
+ );
}
if (!isCodeEvalSourceCodeLanguageSupported(codeTemplate.sourceCodeLanguage)) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message:
- "This code evaluator language is not supported by the configured dispatcher.",
- });
+ throw new CodeEvalTestRunSetupError(
+ "UNSUPPORTED_LANGUAGE",
+ "This code evaluator language is not supported by the configured dispatcher.",
+ );
}
const extractedVariables = extractObservationVariables({
@@ -198,7 +214,7 @@ async function runCodeEvalTestForObservation(params: {
function toCodeEvalTestRunError({
retryable: _retryable,
...error
-}: CodeEvalUserVisibleError): CodeEvalTestRunError {
+}: CodeEvalUserVisibleError): CodeEvalTestRunDispatchError {
return error;
}
@@ -208,10 +224,10 @@ async function getObservationForEvalByFilter(params: {
filter: FilterCondition[] | null;
}): Promise<ObservationForEval | null> {
if (!isEventTarget(params.target) && !isExperimentTarget(params.target)) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Code evaluators can only run on observations or experiments.",
- });
+ throw new CodeEvalTestRunSetupError(
+ "INVALID_TARGET",
+ "Code evaluators can only run on observations or experiments.",
+ );
}
const filter = isExperimentTarget(params.target)
@@ -354,10 +370,10 @@ async function getObservationForEvalByIdFromLegacyObservations(params: {
}
function throwObservationNotFound(): never {
- throw new TRPCError({
- code: "NOT_FOUND",
- message: "Observation not found",
- });
+ throw new CodeEvalTestRunSetupError(
+ "OBSERVATION_NOT_FOUND",
+ "Observation not found",
+ );
}
async function writeTraceViaIngestion(trace: InternalTraceWriteInput) {
diff --git a/web/src/features/evals/server/evalTemplateCreation.ts b/web/src/features/evals/server/evalTemplateCreation.ts
index 48e429ad77..50d1bb6df8 100644
--- a/web/src/features/evals/server/evalTemplateCreation.ts
+++ b/web/src/features/evals/server/evalTemplateCreation.ts
@@ -19,14 +19,6 @@ import {
isCodeEvalSourceCodeLanguageSupported,
} from "@/src/features/evals/server/isCodeEvalEnabled";
-export const CODE_EVAL_TEMPLATE_VARIABLES = [
- "input",
- "output",
- "metadata",
- "experimentItemExpectedOutput",
- "experimentItemMetadata",
-] as const;
-
const CreateEvalTemplateBaseInputSchema = z.object({
name: z.string().min(1),
projectId: z.string(),
diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.ts
index 7f5d184659..d03b18ebc8 100644
--- a/web/src/features/evals/server/router.ts
+++ b/web/src/features/evals/server/router.ts
@@ -67,14 +67,18 @@ import {
} from "@/src/features/evals/server/audit-log-resource-types";
import { getEvaluatorDefinitionPreflightError } from "@/src/features/evals/server/evaluator-preflight";
import {
+ CodeEvalTestRunSetupError,
runCodeEvalTest,
- runCodeEvalTestForJobConfig,
} from "@/src/features/evals/server/codeEvalTestRun";
import {
- CODE_EVAL_TEMPLATE_VARIABLES,
+ assertCodeEvalJobConfigCanRun,
+ CodeEvalJobConfigError,
+} from "@/src/features/evals/server/codeEvalJobConfigValidation";
+import {
CreateEvalTemplateInputSchema,
validateEvalTemplateCreation,
} from "@/src/features/evals/server/evalTemplateCreation";
+import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
import {
getCodeEvalCapabilities,
isCodeEvalEnabled,
@@ -338,7 +342,7 @@ const validateEvalTemplateCanRun = async ({
}
};
-const assertCodeEvalJobConfigTestSucceeds = async ({
+const assertCodeEvalJobConfigCanRunForTRPC = async ({
prisma,
orgId,
projectId,
@@ -357,55 +361,72 @@ const assertCodeEvalJobConfigTestSucceeds = async ({
scoreName: string;
filter: z.infer<typeof singleFilter>[] | null;
}) => {
- if (
- target !== EvalTargetObject.EVENT &&
- target !== EvalTargetObject.EXPERIMENT
- ) {
- throw new TRPCError({
- code: "BAD_REQUEST",
- message: "Code evaluators can only run on observations or experiments.",
- });
- }
-
- const parsedMapping = z.array(observationVariableMapping).parse(mapping);
-
- if (env.LANGFUSE_MIGRATION_V4_ALLOW_PREVIEW_OPT_IN === "true") {
- const result = await runCodeEvalTestForJobConfig({
+ try {
+ await assertCodeEvalJobConfigCanRun({
prisma,
orgId,
projectId,
evalTemplateId,
target,
- mapping: parsedMapping,
+ mapping,
scoreName,
filter,
});
-
- if (!result) {
- if (target !== EvalTargetObject.EXPERIMENT) {
- throw new TRPCError({
- code: "PRECONDITION_FAILED",
- message:
- "No matching observation found to test this code evaluator. Adjust the filters and try again.",
- });
- }
-
- return;
+ } catch (error) {
+ if (error instanceof CodeEvalJobConfigError) {
+ throw toCodeEvalJobConfigTRPCError(error);
}
- if (!result.success) {
- throw new TRPCError({
+ throw error;
+ }
+};
+
+function toCodeEvalJobConfigTRPCError(error: CodeEvalJobConfigError) {
+ switch (error.code) {
+ case "invalid_target":
+ case "invalid_request":
+ return new TRPCError({
+ code: "BAD_REQUEST",
+ message: error.message,
+ });
+ case "resource_not_found":
+ return new TRPCError({
+ code: "NOT_FOUND",
+ message: error.message,
+ });
+ case "preflight_failed":
+ return new TRPCError({
code: "PRECONDITION_FAILED",
- message: result.error.message,
+ message: error.message,
});
- }
- } else if (target === EvalTargetObject.EXPERIMENT) {
- return;
- } else {
- // TODO: add self-hosting path for target events
- return;
+ default:
+ return assertUnreachable(error.code);
}
-};
+}
+
+function toCodeEvalTRPCError(error: CodeEvalTestRunSetupError) {
+ switch (error.code) {
+ case "TEMPLATE_NOT_FOUND":
+ case "OBSERVATION_NOT_FOUND":
+ return new TRPCError({
+ code: "NOT_FOUND",
+ message: error.message,
+ });
+ case "UNSUPPORTED_LANGUAGE":
+ case "INVALID_TARGET":
+ return new TRPCError({
+ code: "BAD_REQUEST",
+ message: error.message,
+ });
+ case "DISPATCHER_NOT_CONFIGURED":
+ return new TRPCError({
+ code: "PRECONDITION_FAILED",
+ message: error.message,
+ });
+ default:
+ return assertUnreachable(error.code);
+ }
+}
export const evalRouter = createTRPCRouter({
codeEvalCapabilities: authenticatedProcedure.query(() =>
@@ -958,7 +979,7 @@ export const evalRouter = createTRPCRouter({
const validatedFilter = filterValidation.validatedFilters;
if (evalTemplate.type === EvalTemplateType.CODE) {
- await assertCodeEvalJobConfigTestSucceeds({
+ await assertCodeEvalJobConfigCanRunForTRPC({
prisma: ctx.prisma,
orgId: ctx.session.orgId,
projectId: input.projectId,
@@ -1058,19 +1079,28 @@ export const evalRouter = createTRPCRouter({
mapping: input.mapping,
});
- return runCodeEvalTest({
- prisma: ctx.prisma,
- orgId: ctx.session.orgId,
- projectId: input.projectId,
- evalTemplateId: input.evalTemplateId,
- target: input.target,
- mapping: input.mapping,
- scoreName: input.scoreName,
- observationId: input.observationId,
- traceId: input.traceId,
- startTime: input.startTime,
- shouldReadFromObservationsTable: input.shouldReadFromObservationsTable,
- });
+ try {
+ return await runCodeEvalTest({
+ prisma: ctx.prisma,
+ orgId: ctx.session.orgId,
+ projectId: input.projectId,
+ evalTemplateId: input.evalTemplateId,
+ target: input.target,
+ mapping: input.mapping,
+ scoreName: input.scoreName,
+ observationId: input.observationId,
+ traceId: input.traceId,
+ startTime: input.startTime,
+ shouldReadFromObservationsTable:
+ input.shouldReadFromObservationsTable,
+ });
+ } catch (error) {
+ if (error instanceof CodeEvalTestRunSetupError) {
+ throw toCodeEvalTRPCError(error);
+ }
+
+ throw error;
+ }
}),
createTemplate: protectedProjectProcedure
.input(CreateEvalTemplateInputSchema)
@@ -1444,7 +1474,7 @@ export const evalRouter = createTRPCRouter({
sourceCodeLanguage: existingJob.evalTemplate.sourceCodeLanguage,
});
- await assertCodeEvalJobConfigTestSucceeds({
+ await assertCodeEvalJobConfigCanRunForTRPC({
prisma: ctx.prisma,
orgId: ctx.session.orgId,
projectId,
diff --git a/web/src/features/evals/server/unstable-public-api/adapters.ts b/web/src/features/evals/server/unstable-public-api/adapters.ts
index 26d5ee65ef..01bd703133 100644
--- a/web/src/features/evals/server/unstable-public-api/adapters.ts
+++ b/web/src/features/evals/server/unstable-public-api/adapters.ts
@@ -13,17 +13,25 @@ import {
type PersistedEvalOutputDefinition,
} from "@langfuse/shared";
import { InternalServerError } from "@langfuse/shared";
+import { EvalTemplateType } from "@langfuse/shared/src/db";
import { logger } from "@langfuse/shared/src/server";
import { z } from "zod";
import {
ExperimentEvaluationRuleFilter,
ObservationEvaluationRuleFilter,
+ PUBLIC_EVALUATOR_TYPE_CODE,
+ PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
type PublicEvaluationRuleFilterType,
type PublicEvaluationRuleMappingType,
type PublicEvaluationRuleTargetType,
type PublicEvaluatorModelConfigType,
type PublicEvaluatorOutputDefinitionType,
+ type PublicEvaluatorTypeType,
} from "@/src/features/public-api/types/unstable-public-evals-contract";
+import {
+ CODE_EVAL_TEMPLATE_VARIABLES,
+ getCodeEvalVariableMapping,
+} from "@/src/features/evals/utils/code-eval-template-utils";
import type {
ApiEvaluationRuleRecord,
ApiEvaluatorRecord,
@@ -35,6 +43,20 @@ import {
validateEvaluatorVariableMappings,
} from "./validation";
+export function toPublicEvaluatorType(type: EvalTemplateType) {
+ return type === EvalTemplateType.CODE
+ ? PUBLIC_EVALUATOR_TYPE_CODE
+ : PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE;
+}
+
+export function toStoredEvaluatorType(
+ type: PublicEvaluatorTypeType,
+): EvalTemplateType {
+ return type === PUBLIC_EVALUATOR_TYPE_CODE
+ ? EvalTemplateType.CODE
+ : EvalTemplateType.LLM_AS_JUDGE;
+}
+
const PUBLIC_TARGET_TO_INTERNAL_TARGET_OBJECT: Record<
PublicEvaluationRuleTargetType,
string
@@ -85,30 +107,33 @@ function getPublicFilterArraySchema(target: PublicEvaluationRuleTargetType) {
);
}
-export function toStoredModelConfig(
- modelConfig?: PublicEvaluatorModelConfigType | null,
-) {
- if (!modelConfig) {
- return {
- provider: null,
- model: null,
- modelParams: undefined,
- };
- }
-
- return {
- provider: modelConfig.provider,
- model: modelConfig.model,
- modelParams: undefined,
- };
-}
-
export function deriveEvaluatorVariables(
template: Pick<StoredPublicEvaluatorTemplate, "vars" | "prompt">,
) {
return template.vars.length > 0
? template.vars
- : extractVariables(template.prompt);
+ : extractVariables(template.prompt ?? "");
+}
+
+function toStoredVariableMappings(params: {
+ mappings: PublicEvaluationRuleMappingType[];
+ variables: string[];
+ target: PublicEvaluationRuleTargetType;
+}) {
+ validateEvaluatorVariableMappings({
+ mappings: params.mappings,
+ variables: params.variables,
+ target: params.target,
+ });
+
+ return observationVariableMappingList.parse(
+ params.mappings.map((mapping) => ({
+ templateVariable: mapping.variable,
+ selectedColumnId:
+ PUBLIC_MAPPING_SOURCE_TO_INTERNAL_COLUMN[mapping.source],
+ jsonSelector: mapping.jsonPath ?? null,
+ })),
+ );
}
export function parseStoredOutputDefinition(
@@ -314,20 +339,41 @@ export function toApiEvaluator(params: {
evaluationRuleCount: number;
}): ApiEvaluatorRecord {
const template = params.template;
-
- return {
+ const base = {
id: template.id,
name: template.name,
version: template.version,
scope: template.projectId === null ? "managed" : "project",
- type: "llm_as_judge",
- prompt: template.prompt,
variables: deriveEvaluatorVariables(template),
- outputDefinition: parseStoredOutputDefinition(template),
- modelConfig: toApiModelConfig(template),
evaluationRuleCount: params.evaluationRuleCount,
createdAt: template.createdAt,
updatedAt: template.updatedAt,
+ } as const;
+
+ if (template.type === EvalTemplateType.CODE) {
+ if (!template.sourceCode || !template.sourceCodeLanguage) {
+ throw new InternalServerError("Code evaluator definition is corrupted");
+ }
+
+ return {
+ ...base,
+ type: PUBLIC_EVALUATOR_TYPE_CODE,
+ variables: [...CODE_EVAL_TEMPLATE_VARIABLES],
+ sourceCode: template.sourceCode,
+ sourceCodeLanguage: template.sourceCodeLanguage,
+ };
+ }
+
+ if (!template.prompt) {
+ throw new InternalServerError("Evaluator prompt is corrupted");
+ }
+
+ return {
+ ...base,
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
+ prompt: template.prompt,
+ outputDefinition: parseStoredOutputDefinition(template),
+ modelConfig: toApiModelConfig(template),
};
}
@@ -347,6 +393,7 @@ export function toApiEvaluationRule(
id: config.evalTemplate.id,
name: config.evalTemplate.name,
scope: config.evalTemplate.projectId === null ? "managed" : "project",
+ type: toPublicEvaluatorType(config.evalTemplate.type),
},
target,
enabled: config.status === JobConfigState.ACTIVE,
@@ -355,7 +402,11 @@ export function toApiEvaluationRule(
pausedMessage: config.blockMessage ?? null,
sampling: Number(config.sampling),
filter: toApiFilters(config.filter, target),
- mapping: toApiMappings(config.variableMapping),
+ mapping: toApiMappings(
+ config.evalTemplate.type === EvalTemplateType.CODE
+ ? getCodeEvalVariableMapping()
+ : config.variableMapping,
+ ),
createdAt: config.createdAt,
updatedAt: config.updatedAt,
};
@@ -368,19 +419,23 @@ export function toJobConfigurationInput(params: {
enabled: boolean;
sampling: number;
filter: PublicEvaluationRuleFilterType[];
- mapping: PublicEvaluationRuleMappingType[];
+ mapping?: PublicEvaluationRuleMappingType[];
};
evaluatorVariables: string[];
+ evaluatorType: PublicEvaluatorTypeType;
}) {
validateEvaluationRuleFilters({
target: params.input.target,
filters: params.input.filter,
});
- validateEvaluatorVariableMappings({
- mappings: params.input.mapping,
- variables: params.evaluatorVariables,
- target: params.input.target,
- });
+ const variableMapping =
+ params.evaluatorType === PUBLIC_EVALUATOR_TYPE_CODE
+ ? getCodeEvalVariableMapping()
+ : toStoredVariableMappings({
+ mappings: params.input.mapping ?? [],
+ variables: params.evaluatorVariables,
+ target: params.input.target,
+ });
return {
scoreName: params.input.name,
@@ -388,14 +443,7 @@ export function toJobConfigurationInput(params: {
filter: params.input.filter.map((filter) =>
toStoredFilter(filter, params.input.target),
),
- variableMapping: observationVariableMappingList.parse(
- params.input.mapping.map((mapping) => ({
- templateVariable: mapping.variable,
- selectedColumnId:
- PUBLIC_MAPPING_SOURCE_TO_INTERNAL_COLUMN[mapping.source],
- jsonSelector: mapping.jsonPath ?? null,
- })),
- ),
+ variableMapping,
sampling: params.input.sampling,
status: params.input.enabled
? JobConfigState.ACTIVE
diff --git a/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts b/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts
index a40d5e4139..ade63d813e 100644
--- a/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts
+++ b/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts
@@ -1,6 +1,18 @@
import { invalidateProjectEvalConfigCaches } from "@langfuse/shared/src/server";
import { EvalTemplateType, prisma } from "@langfuse/shared/src/db";
-import { EvalTargetObject, JobConfigState } from "@langfuse/shared";
+import {
+ EvalTargetObject,
+ JobConfigState,
+ type FilterCondition,
+} from "@langfuse/shared";
+import {
+ assertCodeEvalJobConfigCanRun,
+ CodeEvalJobConfigError,
+} from "@/src/features/evals/server/codeEvalJobConfigValidation";
+import {
+ isCodeEvalEnabled,
+ isCodeEvalSourceCodeLanguageSupported,
+} from "@/src/features/evals/server/isCodeEvalEnabled";
import type {
PatchUnstableEvaluationRuleBodyType,
PostUnstableEvaluationRuleBodyType,
@@ -9,6 +21,7 @@ import {
deriveEvaluatorVariables,
toApiEvaluationRule,
toJobConfigurationInput,
+ toPublicEvaluatorType,
} from "./adapters";
import {
countActiveEvaluationRules,
@@ -16,14 +29,113 @@ import {
listPublicEvaluationRuleConfigs,
loadEvaluatorForEvaluationRule,
} from "./queries";
+import type { StoredPublicEvaluatorTemplate } from "./types";
import {
assertEvaluationRuleFilterValuesExistForProject,
assertEvaluatorDefinitionCanRunForPublicApi,
} from "./validation";
import { createUnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";
+import { assertUnreachable } from "@/src/utils/types";
const MAX_ACTIVE_EVALUATION_RULES = 50;
+async function assertEvaluationRuleCanRunForPublicApi(params: {
+ orgId: string;
+ projectId: string;
+ template: StoredPublicEvaluatorTemplate;
+ target: EvalTargetObject;
+ mapping: unknown;
+ scoreName: string;
+ filter: FilterCondition[] | null;
+}) {
+ if (params.template.type !== EvalTemplateType.CODE) {
+ await assertEvaluatorDefinitionCanRunForPublicApi({
+ projectId: params.projectId,
+ template: {
+ name: params.template.name,
+ provider: params.template.provider,
+ model: params.template.model,
+ modelParams: params.template.modelParams,
+ outputDefinition: params.template.outputDefinition,
+ },
+ });
+ return;
+ }
+
+ // Code evaluators only run when the project has a configured dispatcher that
+ // supports the template language. Reject here so we never persist an active
+ // rule that would silently fail at execution time, matching the create path.
+ if (!isCodeEvalEnabled()) {
+ throw createUnstablePublicApiError({
+ httpCode: 403,
+ code: "access_denied",
+ message: "Code evals are not enabled",
+ details: {
+ evaluatorName: params.template.name,
+ },
+ });
+ }
+
+ if (
+ !isCodeEvalSourceCodeLanguageSupported(params.template.sourceCodeLanguage)
+ ) {
+ throw createUnstablePublicApiError({
+ httpCode: 400,
+ code: "invalid_request",
+ message:
+ "This code evaluator language is not supported by the configured dispatcher.",
+ details: {
+ evaluatorName: params.template.name,
+ },
+ });
+ }
+
+ try {
+ await assertCodeEvalJobConfigCanRun({
+ prisma,
+ orgId: params.orgId,
+ projectId: params.projectId,
+ evalTemplateId: params.template.id,
+ target: params.target,
+ mapping: params.mapping,
+ scoreName: params.scoreName,
+ filter: params.filter,
+ });
+ } catch (error) {
+ if (error instanceof CodeEvalJobConfigError) {
+ const details = { evaluatorName: params.template.name };
+ switch (error.code) {
+ case "invalid_target":
+ case "invalid_request":
+ throw createUnstablePublicApiError({
+ httpCode: 400,
+ code: "invalid_request",
+ message: error.message,
+ details,
+ });
+ case "resource_not_found":
+ throw createUnstablePublicApiError({
+ httpCode: 404,
+ code: "resource_not_found",
+ message: error.message,
+ details,
+ });
+ case "preflight_failed":
+ throw createUnstablePublicApiError({
+ httpCode: 422,
+ code: "evaluator_preflight_failed",
+ message: error.message,
+ details,
+ });
+ default:
+ return assertUnreachable(error.code);
+ }
+ }
+
+ throw error;
+ }
+}
+
async function assertActivePublicApiEvaluationRuleLimitNotExceeded(
projectId: string,
) {
@@ -68,6 +180,7 @@ export async function getPublicEvaluationRule(params: {
}
export async function createPublicEvaluationRule(params: {
+ orgId: string;
projectId: string;
input: PostUnstableEvaluationRuleBodyType;
}) {
@@ -81,7 +194,6 @@ export async function createPublicEvaluationRule(params: {
scoreName: params.input.name,
evalTemplate: {
is: {
- type: EvalTemplateType.LLM_AS_JUDGE,
OR: [{ projectId: params.projectId }, { projectId: null }],
},
},
@@ -127,18 +239,18 @@ export async function createPublicEvaluationRule(params: {
mapping: params.input.mapping,
},
evaluatorVariables: deriveEvaluatorVariables(template),
+ evaluatorType: toPublicEvaluatorType(template.type),
});
if (data.status === JobConfigState.ACTIVE) {
- await assertEvaluatorDefinitionCanRunForPublicApi({
+ await assertEvaluationRuleCanRunForPublicApi({
+ orgId: params.orgId,
projectId: params.projectId,
- template: {
- name: template.name,
- provider: template.provider,
- model: template.model,
- modelParams: template.modelParams,
- outputDefinition: template.outputDefinition,
- },
+ template,
+ target: data.targetObject as EvalTargetObject,
+ mapping: data.variableMapping,
+ scoreName: data.scoreName,
+ filter: data.filter,
});
}
@@ -162,6 +274,7 @@ export async function createPublicEvaluationRule(params: {
id: true,
projectId: true,
name: true,
+ type: true,
},
},
},
@@ -175,6 +288,7 @@ export async function createPublicEvaluationRule(params: {
}
export async function updatePublicEvaluationRule(params: {
+ orgId: string;
projectId: string;
evaluationRuleId: string;
input: PatchUnstableEvaluationRuleBodyType;
@@ -204,14 +318,42 @@ export async function updatePublicEvaluationRule(params: {
});
}
- const nextEvaluator = params.input.evaluator ?? {
- name: existingPublic.evaluator.name,
- scope: existingPublic.evaluator.scope,
- };
+ // A rule's evaluator type cannot be changed via PATCH; always inherit the
+ // current type. This keeps the family lookup scoped to the same type, so a
+ // code rule cannot be retargeted to an LLM evaluator (which would inherit the
+ // synthesized code mapping and fail validation against the LLM variables).
+ const nextEvaluator = params.input.evaluator
+ ? {
+ name: params.input.evaluator.name,
+ scope: params.input.evaluator.scope,
+ type: existingPublic.evaluator.type,
+ }
+ : {
+ name: existingPublic.evaluator.name,
+ scope: existingPublic.evaluator.scope,
+ type: existingPublic.evaluator.type,
+ };
const { template } = await loadEvaluatorForEvaluationRule({
projectId: params.projectId,
evaluator: nextEvaluator,
});
+
+ if (
+ template.type === EvalTemplateType.CODE &&
+ "mapping" in params.input &&
+ params.input.mapping !== undefined
+ ) {
+ throw createUnstablePublicApiError({
+ httpCode: 400,
+ code: "invalid_body",
+ message:
+ "Code evaluator mappings are managed by Langfuse and cannot be provided in the request body.",
+ details: {
+ field: "mapping",
+ },
+ });
+ }
+
const nextFilter =
"filter" in params.input && params.input.filter !== undefined
? params.input.filter
@@ -231,19 +373,19 @@ export async function updatePublicEvaluationRule(params: {
mapping: nextMapping,
},
evaluatorVariables: deriveEvaluatorVariables(template),
+ evaluatorType: toPublicEvaluatorType(template.type),
});
const shouldResetBlockState = data.status === JobConfigState.ACTIVE;
if (shouldResetBlockState) {
- await assertEvaluatorDefinitionCanRunForPublicApi({
+ await assertEvaluationRuleCanRunForPublicApi({
+ orgId: params.orgId,
projectId: params.projectId,
- template: {
- name: template.name,
- provider: template.provider,
- model: template.model,
- modelParams: template.modelParams,
- outputDefinition: template.outputDefinition,
- },
+ template,
+ target: data.targetObject as EvalTargetObject,
+ mapping: data.variableMapping,
+ scoreName: data.scoreName,
+ filter: data.filter,
});
}
@@ -274,6 +416,7 @@ export async function updatePublicEvaluationRule(params: {
id: true,
projectId: true,
name: true,
+ type: true,
},
},
},
diff --git a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
index b1fdbc585e..4c6242e6b3 100644
--- a/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
+++ b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts
@@ -6,11 +6,20 @@ import {
variableMappingList,
} from "@langfuse/shared";
import { invalidateProjectEvalConfigCaches } from "@langfuse/shared/src/server";
-import { EvalTemplateType, Prisma, prisma } from "@langfuse/shared/src/db";
-import type { PostUnstableEvaluatorBodyType } from "@/src/features/public-api/types/unstable-evaluators";
+import { Prisma, prisma } from "@langfuse/shared/src/db";
+import { type PostUnstableEvaluatorBodyParsedType } from "@/src/features/public-api/types/unstable-evaluators";
+import {
+ type PUBLIC_EVALUATOR_TYPE_CODE,
+ PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
+} from "@/src/features/public-api/types/unstable-public-evals-contract";
+import {
+ isCodeEvalEnabled,
+ isCodeEvalSourceCodeLanguageSupported,
+} from "@/src/features/evals/server/isCodeEvalEnabled";
+import { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
import {
toApiEvaluator,
- toStoredModelConfig,
+ toStoredEvaluatorType,
toStoredOutputDefinition,
} from "./adapters";
import {
@@ -65,6 +74,34 @@ function prepareVariableMappingForEvaluatorUpgrade(params: {
return migratedVariableMapping;
}
+function assertCodeEvaluatorDefinitionCanRunForPublicApi(
+ input: Extract<
+ PostUnstableEvaluatorBodyParsedType,
+ { type: typeof PUBLIC_EVALUATOR_TYPE_CODE }
+ >,
+) {
+ if (!isCodeEvalEnabled()) {
+ throw createUnstablePublicApiError({
+ httpCode: 403,
+ code: "access_denied",
+ message: "Code evals are not enabled",
+ });
+ }
+
+ if (!isCodeEvalSourceCodeLanguageSupported(input.sourceCodeLanguage)) {
+ throw createUnstablePublicApiError({
+ httpCode: 400,
+ code: "invalid_request",
+ message:
+ "This code evaluator language is not supported by the configured dispatcher.",
+ details: {
+ field: "sourceCodeLanguage",
+ value: input.sourceCodeLanguage,
+ },
+ });
+ }
+}
+
export async function listPublicEvaluators(params: {
projectId: string;
page: number;
@@ -107,30 +144,65 @@ export async function getPublicEvaluator(params: {
export async function createPublicEvaluator(params: {
projectId: string;
- input: PostUnstableEvaluatorBodyType;
+ input: PostUnstableEvaluatorBodyParsedType;
}) {
- const storedOutputDefinition = toStoredOutputDefinition(
- params.input.outputDefinition,
- );
+ const { input } = params;
+ const storedEvalTemplateType = toStoredEvaluatorType(input.type);
+ const storedOutputDefinition =
+ input.type === PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE
+ ? toStoredOutputDefinition(input.outputDefinition)
+ : undefined;
+ const nextVariables =
+ input.type === PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE
+ ? extractVariables(input.prompt)
+ : [...CODE_EVAL_TEMPLATE_VARIABLES];
- await assertEvaluatorDefinitionCanRunForPublicApi({
- projectId: params.projectId,
- template: {
- name: params.input.name,
- provider: params.input.modelConfig?.provider ?? null,
- model: params.input.modelConfig?.model ?? null,
- outputDefinition: storedOutputDefinition,
- },
- });
+ if (input.type === PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE) {
+ await assertEvaluatorDefinitionCanRunForPublicApi({
+ projectId: params.projectId,
+ template: {
+ name: input.name,
+ provider: input.modelConfig?.provider ?? null,
+ model: input.modelConfig?.model ?? null,
+ outputDefinition: storedOutputDefinition,
+ },
+ });
+ } else {
+ assertCodeEvaluatorDefinitionCanRunForPublicApi(input);
+ }
try {
const { template, upgradedConfigCount } = await prisma.$transaction(
async (tx) => {
+ const conflictingTemplate = await tx.evalTemplate.findFirst({
+ where: {
+ projectId: params.projectId,
+ name: input.name,
+ type: {
+ not: storedEvalTemplateType,
+ },
+ },
+ select: {
+ type: true,
+ },
+ });
+
+ if (conflictingTemplate) {
+ throw createUnstablePublicApiError({
+ httpCode: 409,
+ code: "name_conflict",
+ message: `An evaluator named "${input.name}" already exists with a different type in this project. Use a different name for the ${input.type} evaluator.`,
+ details: {
+ field: "name",
+ },
+ });
+ }
+
const existingProjectTemplates = await tx.evalTemplate.findMany({
where: {
projectId: params.projectId,
- name: params.input.name,
- type: EvalTemplateType.LLM_AS_JUDGE,
+ name: input.name,
+ type: storedEvalTemplateType,
},
orderBy: [
{
@@ -148,7 +220,6 @@ export async function createPublicEvaluator(params: {
version: true,
},
});
- const nextVariables = extractVariables(params.input.prompt);
const configsToUpgrade =
existingProjectTemplates.length > 0
? await tx.jobConfiguration.findMany({
@@ -161,7 +232,7 @@ export async function createPublicEvaluator(params: {
},
evalTemplate: {
is: {
- type: EvalTemplateType.LLM_AS_JUDGE,
+ type: storedEvalTemplateType,
},
},
},
@@ -182,20 +253,22 @@ export async function createPublicEvaluator(params: {
nextVariables,
}),
}));
- const modelConfig = toStoredModelConfig(params.input.modelConfig);
const latestProjectTemplate = existingProjectTemplates[0];
const template = await tx.evalTemplate.create({
data: {
projectId: params.projectId,
- name: params.input.name,
+ name: input.name,
version: (latestProjectTemplate?.version ?? 0) + 1,
- prompt: params.input.prompt,
- provider: modelConfig.provider,
- model: modelConfig.model,
- modelParams: modelConfig.modelParams,
+ type: storedEvalTemplateType,
+ prompt: input.prompt ?? null,
+ provider: input.modelConfig?.provider ?? null,
+ model: input.modelConfig?.model ?? null,
+ modelParams: undefined,
vars: nextVariables,
outputDefinition: storedOutputDefinition,
+ sourceCode: input.sourceCode ?? null,
+ sourceCodeLanguage: input.sourceCodeLanguage ?? null,
},
});
diff --git a/web/src/features/evals/server/unstable-public-api/queries.ts b/web/src/features/evals/server/unstable-public-api/queries.ts
index 46c353ec85..2819a3c20a 100644
--- a/web/src/features/evals/server/unstable-public-api/queries.ts
+++ b/web/src/features/evals/server/unstable-public-api/queries.ts
@@ -3,13 +3,14 @@ import {
JobConfigState,
LangfuseNotFoundError,
} from "@langfuse/shared";
-import { EvalTemplateType, Prisma, prisma } from "@langfuse/shared/src/db";
+import { Prisma, prisma } from "@langfuse/shared/src/db";
import type {
EvaluationRuleEvaluatorFamilyReference,
PrismaClientLike,
StoredPublicEvaluationRuleConfig,
StoredPublicEvaluatorTemplate,
} from "./types";
+import { toStoredEvaluatorType } from "./adapters";
export function getPrismaClient(client?: PrismaClientLike) {
return client ?? prisma;
@@ -22,10 +23,9 @@ export async function findPublicEvaluatorTemplateOrThrow(params: {
}) {
const client = getPrismaClient(params.client);
- const template = await client.evalTemplate.findUnique({
+ const template = await client.evalTemplate.findFirst({
where: {
id: params.evaluatorId,
- type: EvalTemplateType.LLM_AS_JUDGE,
},
});
@@ -51,7 +51,7 @@ export async function findLatestPublicEvaluatorTemplateInFamilyOrThrow(params: {
where: {
name: params.evaluator.name,
projectId: params.evaluator.scope === "project" ? params.projectId : null,
- type: EvalTemplateType.LLM_AS_JUDGE,
+ type: toStoredEvaluatorType(params.evaluator.type),
},
orderBy: {
version: "desc",
@@ -131,15 +131,15 @@ export async function listPublicEvaluatorTemplates(params: {
prisma.$queryRaw<Array<{ id: string }>>(
Prisma.sql`
WITH latest_templates AS (
- SELECT DISTINCT ON (project_id, name)
+ SELECT DISTINCT ON (project_id, name, type)
id,
project_id,
name,
+ type,
updated_at
FROM eval_templates
WHERE (project_id = ${params.projectId} OR project_id IS NULL)
- AND type = ${EvalTemplateType.LLM_AS_JUDGE}::"EvalTemplateType"
- ORDER BY project_id, name, version DESC
+ ORDER BY project_id, name, type, version DESC
)
SELECT id
FROM latest_templates
@@ -156,10 +156,9 @@ export async function listPublicEvaluatorTemplates(params: {
Prisma.sql`
SELECT COUNT(*) as count
FROM (
- SELECT DISTINCT project_id, name
+ SELECT DISTINCT project_id, name, type
FROM eval_templates
WHERE (project_id = ${params.projectId} OR project_id IS NULL)
- AND type = ${EvalTemplateType.LLM_AS_JUDGE}::"EvalTemplateType"
) latest_template_families
`,
),
@@ -218,7 +217,6 @@ export async function findPublicEvaluationRuleOrThrow(params: {
},
evalTemplate: {
is: {
- type: EvalTemplateType.LLM_AS_JUDGE,
OR: [{ projectId: params.projectId }, { projectId: null }],
},
},
@@ -229,6 +227,7 @@ export async function findPublicEvaluationRuleOrThrow(params: {
id: true,
projectId: true,
name: true,
+ type: true,
},
},
},
@@ -272,7 +271,6 @@ export async function countActiveEvaluationRules(params: {
blockedAt: null,
evalTemplate: {
is: {
- type: EvalTemplateType.LLM_AS_JUDGE,
OR: [{ projectId: params.projectId }, { projectId: null }],
},
},
@@ -294,7 +292,6 @@ export async function listPublicEvaluationRuleConfigs(params: {
},
evalTemplate: {
is: {
- type: EvalTemplateType.LLM_AS_JUDGE,
OR: [{ projectId: params.projectId }, { projectId: null }],
},
},
@@ -305,6 +302,7 @@ export async function listPublicEvaluationRuleConfigs(params: {
id: true,
projectId: true,
name: true,
+ type: true,
},
},
},
@@ -322,7 +320,6 @@ export async function listPublicEvaluationRuleConfigs(params: {
},
evalTemplate: {
is: {
- type: EvalTemplateType.LLM_AS_JUDGE,
OR: [{ projectId: params.projectId }, { projectId: null }],
},
},
diff --git a/web/src/features/evals/server/unstable-public-api/types.ts b/web/src/features/evals/server/unstable-public-api/types.ts
index 20cc1f7971..7866d75cb1 100644
--- a/web/src/features/evals/server/unstable-public-api/types.ts
+++ b/web/src/features/evals/server/unstable-public-api/types.ts
@@ -1,4 +1,4 @@
-import type { EvalTemplateLlmAsAJudge } from "@langfuse/shared";
+import type { EvalTemplate } from "@langfuse/shared/src/db";
import type {
JobConfiguration,
Prisma as PrismaNamespace,
@@ -14,27 +14,45 @@ import type {
PublicEvaluatorModelConfigType,
PublicEvaluatorOutputDefinitionType,
PublicEvaluatorScopeType,
+ PublicCodeEvaluatorSourceCodeLanguageType,
+ PUBLIC_EVALUATOR_TYPE_CODE,
+ PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
} from "@/src/features/public-api/types/unstable-public-evals-contract";
+import type { CODE_EVAL_TEMPLATE_VARIABLES } from "@/src/features/evals/utils/code-eval-template-utils";
export type PrismaClientLike =
| typeof prisma
| PrismaNamespace.TransactionClient;
-export type ApiEvaluatorRecord = {
+type ApiEvaluatorRecordBase = {
id: string;
name: string;
version: number;
scope: PublicEvaluatorScopeType;
- type: "llm_as_judge";
- prompt: string;
variables: string[];
- outputDefinition: PublicEvaluatorOutputDefinitionType;
- modelConfig: PublicEvaluatorModelConfigType | null;
evaluationRuleCount: number;
createdAt: Date;
updatedAt: Date;
};
+export type ApiLlmAsJudgeEvaluatorRecord = ApiEvaluatorRecordBase & {
+ type: typeof PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE;
+ prompt: string;
+ outputDefinition: PublicEvaluatorOutputDefinitionType;
+ modelConfig: PublicEvaluatorModelConfigType | null;
+};
+
+export type ApiCodeEvaluatorRecord = ApiEvaluatorRecordBase & {
+ type: typeof PUBLIC_EVALUATOR_TYPE_CODE;
+ variables: Array<(typeof CODE_EVAL_TEMPLATE_VARIABLES)[number]>;
+ sourceCode: string;
+ sourceCodeLanguage: PublicCodeEvaluatorSourceCodeLanguageType;
+};
+
+export type ApiEvaluatorRecord =
+ | ApiLlmAsJudgeEvaluatorRecord
+ | ApiCodeEvaluatorRecord;
+
export type ApiEvaluationRuleRecord = {
id: string;
name: string;
@@ -55,18 +73,21 @@ export type EvaluationRuleEvaluatorFamilyReference =
PublicEvaluationRuleEvaluatorReferenceType;
export type StoredPublicEvaluatorTemplate = Pick<
- EvalTemplateLlmAsAJudge,
+ EvalTemplate,
| "id"
| "projectId"
| "name"
| "version"
| "prompt"
+ | "type"
| "partner"
| "provider"
| "model"
| "modelParams"
| "vars"
| "outputDefinition"
+ | "sourceCode"
+ | "sourceCodeLanguage"
| "createdAt"
| "updatedAt"
>;
@@ -88,8 +109,5 @@ export type StoredPublicEvaluationRuleConfig = Pick<
| "createdAt"
| "updatedAt"
> & {
- evalTemplate: Pick<
- EvalTemplateLlmAsAJudge,
- "id" | "projectId" | "name"
- > | null;
+ evalTemplate: Pick<EvalTemplate, "id" | "projectId" | "name" | "type"> | null;
};
diff --git a/web/src/features/evals/utils/code-eval-template-utils.ts b/web/src/features/evals/utils/code-eval-template-utils.ts
index 8daf765607..b1224e9091 100644
--- a/web/src/features/evals/utils/code-eval-template-utils.ts
+++ b/web/src/features/evals/utils/code-eval-template-utils.ts
@@ -15,6 +15,14 @@ type CodeEvalCapabilities = {
supportedSourceCodeLanguages: EvalTemplateSourceCodeLanguage[];
};
+export const CODE_EVAL_TEMPLATE_VARIABLES = [
+ "input",
+ "output",
+ "metadata",
+ "experimentItemExpectedOutput",
+ "experimentItemMetadata",
+] as const;
+
export const shouldShowEvalTemplate = (
template: Partial<Pick<EvalTemplate, "type" | "sourceCodeLanguage">>,
codeEvalCapabilities: CodeEvalCapabilities,
@@ -36,33 +44,11 @@ export const CODE_EVAL_ESCAPE_CONFIRM_MESSAGE =
"Close code editor? Unsaved changes will be lost.";
export function getCodeEvalVariableMapping(): ObservationVariableMapping[] {
- return [
- {
- templateVariable: "input",
- selectedColumnId: "input",
- jsonSelector: null,
- },
- {
- templateVariable: "output",
- selectedColumnId: "output",
- jsonSelector: null,
- },
- {
- templateVariable: "metadata",
- selectedColumnId: "metadata",
- jsonSelector: null,
- },
- {
- templateVariable: "experimentItemExpectedOutput",
- selectedColumnId: "experimentItemExpectedOutput",
- jsonSelector: null,
- },
- {
- templateVariable: "experimentItemMetadata",
- selectedColumnId: "experimentItemMetadata",
- jsonSelector: null,
- },
- ];
+ return CODE_EVAL_TEMPLATE_VARIABLES.map((variable) => ({
+ templateVariable: variable,
+ selectedColumnId: variable,
+ jsonSelector: null,
+ }));
}
export function resolveCodeEvalTarget(target: EvalTargetObject) {
diff --git a/web/src/features/public-api/types/unstable-evaluation-rules.ts b/web/src/features/public-api/types/unstable-evaluation-rules.ts
index fa72aa363e..dd3169e638 100644
--- a/web/src/features/public-api/types/unstable-evaluation-rules.ts
+++ b/web/src/features/public-api/types/unstable-evaluation-rules.ts
@@ -4,9 +4,11 @@ import {
ExperimentEvaluationRuleMapping,
ObservationEvaluationRuleFilter,
ObservationEvaluationRuleMapping,
+ PUBLIC_EVALUATOR_TYPE_CODE,
PublicEvaluationRuleFilter,
PublicEvaluationRuleEvaluator,
PublicEvaluationRuleEvaluatorReference,
+ PublicEvaluationRuleEvaluatorReferencePatch,
PublicEvaluationRuleMapping,
PublicEvaluationRuleStatus,
PublicEvaluationRuleTarget,
@@ -54,20 +56,46 @@ const EvaluationRuleCreateBase = {
sampling: z.number().gt(0).lte(1).default(1),
};
-export const PostUnstableEvaluationRuleBody = z.discriminatedUnion("target", [
- z.object({
- ...EvaluationRuleCreateBase,
- target: z.literal("observation"),
- filter: z.array(ObservationEvaluationRuleFilter).default([]),
- mapping: z.array(ObservationEvaluationRuleMapping),
- }),
- z.object({
- ...EvaluationRuleCreateBase,
- target: z.literal("experiment"),
- filter: z.array(ExperimentEvaluationRuleFilter).default([]),
- mapping: z.array(ExperimentEvaluationRuleMapping),
- }),
-]);
+const PostUnstableObservationEvaluationRuleBody = z.object({
+ ...EvaluationRuleCreateBase,
+ target: z.literal("observation"),
+ filter: z.array(ObservationEvaluationRuleFilter).default([]),
+ mapping: z.array(ObservationEvaluationRuleMapping).optional(),
+});
+
+const PostUnstableExperimentEvaluationRuleBody = z.object({
+ ...EvaluationRuleCreateBase,
+ target: z.literal("experiment"),
+ filter: z.array(ExperimentEvaluationRuleFilter).default([]),
+ mapping: z.array(ExperimentEvaluationRuleMapping).optional(),
+});
+
+// `code` evaluators use a fixed runtime mapping managed by Langfuse and must
+// omit `mapping`; `llm_as_judge` evaluators require it.
+export const PostUnstableEvaluationRuleBody = z
+ .discriminatedUnion("target", [
+ PostUnstableObservationEvaluationRuleBody,
+ PostUnstableExperimentEvaluationRuleBody,
+ ])
+ .refine(
+ (data) =>
+ data.evaluator.type !== PUBLIC_EVALUATOR_TYPE_CODE ||
+ data.mapping === undefined,
+ {
+ path: ["mapping"],
+ message:
+ "Code evaluator mappings are managed by Langfuse and cannot be provided in the request body.",
+ },
+ )
+ .refine(
+ (data) =>
+ data.evaluator.type === PUBLIC_EVALUATOR_TYPE_CODE ||
+ data.mapping !== undefined,
+ {
+ path: ["mapping"],
+ message: "LLM-as-judge evaluation rules require a variable mapping.",
+ },
+ );
export type PostUnstableEvaluationRuleBodyType = z.infer<
typeof PostUnstableEvaluationRuleBody
>;
@@ -78,7 +106,7 @@ export const PatchUnstableEvaluationRuleQuery = GetUnstableEvaluationRuleQuery;
const EvaluationRulePatchBase = {
name: z.string().min(1).optional(),
- evaluator: PublicEvaluationRuleEvaluatorReference.optional(),
+ evaluator: PublicEvaluationRuleEvaluatorReferencePatch.optional(),
enabled: z.boolean().optional(),
sampling: z.number().gt(0).lte(1).optional(),
};
diff --git a/web/src/features/public-api/types/unstable-evaluators.ts b/web/src/features/public-api/types/unstable-evaluators.ts
index 3df00dff98..d087dc23f2 100644
--- a/web/src/features/public-api/types/unstable-evaluators.ts
+++ b/web/src/features/public-api/types/unstable-evaluators.ts
@@ -1,31 +1,48 @@
import { z } from "zod";
import {
- PublicEvaluatorDefinitionInput,
+ PUBLIC_EVALUATOR_TYPE_CODE,
+ PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
+ PublicCodeEvaluatorDefinitionInput,
PublicEvaluatorModelConfig,
PublicEvaluatorOutputDefinition,
PublicEvaluatorScope,
- PublicEvaluatorType,
+ PublicLlmAsJudgeEvaluatorDefinitionInput,
UnstablePublicApiPaginationQuery,
UnstablePublicApiPaginationResponse,
} from "@/src/features/public-api/types/unstable-public-evals-contract";
-export const APIEvaluator = z
+const APIEvaluatorBase = z
.object({
id: z.string(),
name: z.string(),
version: z.number().int().positive(),
scope: PublicEvaluatorScope,
- type: PublicEvaluatorType,
- prompt: z.string(),
variables: z.array(z.string()),
- outputDefinition: PublicEvaluatorOutputDefinition,
- modelConfig: PublicEvaluatorModelConfig.nullable(),
evaluationRuleCount: z.number().int().nonnegative(),
createdAt: z.coerce.date(),
updatedAt: z.coerce.date(),
})
.strict();
+export const APILlmAsJudgeEvaluator = APIEvaluatorBase.extend({
+ type: z.literal(PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE),
+ prompt: z.string(),
+ outputDefinition: PublicEvaluatorOutputDefinition,
+ modelConfig: PublicEvaluatorModelConfig.nullable(),
+}).strict();
+
+export const APICodeEvaluator = APIEvaluatorBase.extend({
+ type: z.literal(PUBLIC_EVALUATOR_TYPE_CODE),
+ sourceCode: z.string().min(1),
+ sourceCodeLanguage:
+ PublicCodeEvaluatorDefinitionInput.shape.sourceCodeLanguage,
+}).strict();
+
+export const APIEvaluator = z.discriminatedUnion("type", [
+ APILlmAsJudgeEvaluator,
+ APICodeEvaluator,
+]);
+
export const GetUnstableEvaluatorsQuery = UnstablePublicApiPaginationQuery;
export const GetUnstableEvaluatorsResponse = z
@@ -41,12 +58,43 @@ export const GetUnstableEvaluatorQuery = z.object({
export const GetUnstableEvaluatorResponse = APIEvaluator;
-export const PostUnstableEvaluatorBody = z.object({
+const PostUnstableLlmAsJudgeEvaluatorBody = z.object({
+ name: z.string().min(1),
+ type: z.literal(PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE),
+ ...PublicLlmAsJudgeEvaluatorDefinitionInput.shape,
+ sourceCode: z.never().optional(),
+ sourceCodeLanguage: z.never().optional(),
+});
+
+const PostUnstableCodeEvaluatorBody = z.object({
name: z.string().min(1),
- ...PublicEvaluatorDefinitionInput.shape,
+ type: z.literal(PUBLIC_EVALUATOR_TYPE_CODE),
+ ...PublicCodeEvaluatorDefinitionInput.shape,
+ prompt: z.never().optional(),
+ outputDefinition: z.never().optional(),
+ modelConfig: z.never().optional(),
});
-export type PostUnstableEvaluatorBodyType = z.infer<
- typeof PostUnstableEvaluatorBody
+
+const PostUnstableTypedEvaluatorBody = z.discriminatedUnion("type", [
+ PostUnstableLlmAsJudgeEvaluatorBody,
+ PostUnstableCodeEvaluatorBody,
+]);
+
+// `type` may be omitted; it defaults to `llm_as_judge` for backwards
+// compatibility. New clients should send `type` explicitly.
+export const PostUnstableEvaluatorBody = z.preprocess((value) => {
+ if (typeof value !== "object" || value === null || "type" in value) {
+ return value;
+ }
+
+ return {
+ ...value,
+ type: PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE,
+ };
+}, PostUnstableTypedEvaluatorBody);
+
+export type PostUnstableEvaluatorBodyParsedType = z.infer<
+ typeof PostUnstableTypedEvaluatorBody
>;
export const PostUnstableEvaluatorResponse = APIEvaluator;
diff --git a/web/src/features/public-api/types/unstable-public-evals-contract.ts b/web/src/features/public-api/types/unstable-public-evals-contract.ts
index e703d529a1..d28260ac70 100644
--- a/web/src/features/public-api/types/unstable-public-evals-contract.ts
+++ b/web/src/features/public-api/types/unstable-public-evals-contract.ts
@@ -13,6 +13,7 @@ import {
experimentEvalFilterColumns,
booleanFilter,
} from "@langfuse/shared";
+import { CODE_EVAL_SOURCE_MAX_BYTES } from "@langfuse/shared/src/server";
import { z } from "zod";
export {
UnstablePublicApiErrorCode,
@@ -24,8 +25,16 @@ import type {
UnstablePublicApiErrorDetailsType,
} from "@/src/features/public-api/shared/unstable-public-api-error-schema";
-export const PublicEvaluatorType = z.literal("llm_as_judge");
+export const PUBLIC_EVALUATOR_TYPES = ["llm_as_judge", "code"] as const;
+export const [PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE, PUBLIC_EVALUATOR_TYPE_CODE] =
+ PUBLIC_EVALUATOR_TYPES;
+
+export const PublicEvaluatorType = z.enum(PUBLIC_EVALUATOR_TYPES);
export const PublicEvaluatorScope = z.enum(["project", "managed"]);
+export const PublicCodeEvaluatorSourceCodeLanguage = z.enum([
+ "PYTHON",
+ "TYPESCRIPT",
+]);
export const PublicEvaluatorModelConfig = z.object({
provider: z.string().min(1),
@@ -80,6 +89,17 @@ export const PublicEvaluationRuleStatus = z.enum([
export const PublicEvaluationRuleEvaluatorReference = z.object({
name: z.string().min(1),
scope: PublicEvaluatorScope,
+ type: PublicEvaluatorType.default(PUBLIC_EVALUATOR_TYPE_LLM_AS_JUDGE),
+});
+
+// PATCH intentionally omits `type`: an evaluation rule's evaluator type cannot
+// be changed. The service always inherits the rule's current type, so a code
+// rule is never retargeted to an LLM evaluator family (which would otherwise
+// inherit the synthesized code mapping and fail validation against the LLM
+// evaluator's variables). To use a different evaluator type, create a new rule.
+export const PublicEvaluationRuleEvaluatorReferencePatch = z.object({
+ name: z.string().min(1),
+ scope: PublicEvaluatorScope,
});
export const PublicEvaluationRuleEvaluator =
@@ -207,6 +227,7 @@ export type PublicEvaluatorModelConfigType = z.infer<
export type PublicEvaluatorOutputDefinitionType = z.infer<
typeof PublicEvaluatorOutputDefinition
>;
+export type PublicEvaluatorTypeType = z.infer<typeof PublicEvaluatorType>;
export type PublicEvaluatorScopeType = z.infer<typeof PublicEvaluatorScope>;
export type PublicEvaluationRuleTargetType = z.infer<
typeof PublicEvaluationRuleTarget
@@ -244,8 +265,26 @@ export const UnstablePublicApiPaginationQuery = z.object({
export const UnstablePublicApiPaginationResponse = paginationMetaResponseZod;
-export const PublicEvaluatorDefinitionInput = z.object({
+export const PublicLlmAsJudgeEvaluatorDefinitionInput = z.object({
prompt: z.string().min(1),
outputDefinition: PublicEvaluatorOutputDefinition,
modelConfig: PublicEvaluatorModelConfig.nullable().optional(),
});
+
+export const PublicCodeEvaluatorDefinitionInput = z.object({
+ sourceCode: z
+ .string()
+ .min(1)
+ .refine(
+ (sourceCode) =>
+ Buffer.byteLength(sourceCode, "utf8") <= CODE_EVAL_SOURCE_MAX_BYTES,
+ {
+ message: `Source code must be ${CODE_EVAL_SOURCE_MAX_BYTES} bytes or less`,
+ },
+ ),
+ sourceCodeLanguage: PublicCodeEvaluatorSourceCodeLanguage,
+});
+
+export type PublicCodeEvaluatorSourceCodeLanguageType = z.infer<
+ typeof PublicCodeEvaluatorSourceCodeLanguage
+>;
diff --git a/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts b/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts
index 7cd7b31e00..805b8eeb7b 100644
--- a/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts
+++ b/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts
@@ -42,6 +42,7 @@ export default withUnstablePublicEvalsMiddlewares({
});
const evaluationRule = await updatePublicEvaluationRule({
+ orgId: auth.scope.orgId,
projectId: auth.scope.projectId,
evaluationRuleId: query.evaluationRuleId,
input: body,
diff --git a/web/src/pages/api/public/unstable/evaluation-rules/index.ts b/web/src/pages/api/public/unstable/evaluation-rules/index.ts
index 96955cbe7b..b222c6f1be 100644
--- a/web/src/pages/api/public/unstable/evaluation-rules/index.ts
+++ b/web/src/pages/api/public/unstable/evaluation-rules/index.ts
@@ -33,6 +33,7 @@ export default withUnstablePublicEvalsMiddlewares({
responseSchema: PostUnstableEvaluationRuleResponse,
fn: async ({ body, auth }) => {
const evaluationRule = await createPublicEvaluationRule({
+ orgId: auth.scope.orgId,
projectId: auth.scope.projectId,
input: body,
});