🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(api): add unstable evals public endpoints (#12829)
Hassieb Pakzadecb0d443ad35
diff --git a/.agents/AGENTS.md b/.agents/AGENTS.mdindex cfadb160a0..5802a6d468 100644--- a/.agents/AGENTS.md+++ b/.agents/AGENTS.md@@ -124,7 +124,7 @@ Minimum verification matrix:- `*/dist/*`- `packages/shared/prisma/generated/*`- Public API contract changes must update Fern sources in `fern/apis/**` and- regenerated outputs; never hand-edit `generated/**`.+ regenerated outputs. Never hand-edit `generated/**`.- Keep tests independent and parallel-safe.- For bug fixes, write the failing test first, confirm it fails, then fix thebug.diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 3451dfcd4e..5970e7742f 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -261,6 +261,7 @@ jobs:echo "LANGFUSE_TRACE_DELETE_CONCURRENCY=100" >> .envecho "ADMIN_API_KEY=admin-api-key" >> .envecho "LANGFUSE_EE_LICENSE_KEY=langfuse_ee_test" >> .env+ echo "LANGFUSE_SKIP_EVALUATOR_MODEL_CALL_VALIDATION=true" >> .env- name: Setup Turbo cacheuses: actions/cache@668228422ae6a00e4ad889ee87cd7109ec5666a7 # v5.0.4 # zizmor: ignore[cache-poisoning] test job cache only; publish jobs rebuild artifacts and do not restore this cachewith:diff --git a/fern/apis/server/definition/unstable/commons.yml b/fern/apis/server/definition/unstable/commons.ymlnew file mode 100644index 0000000000..c17431cbd5--- /dev/null+++ b/fern/apis/server/definition/unstable/commons.yml@@ -0,0 +1,564 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+types:+ EvaluatorType:+ docs: |+ The evaluator engine type.++ The unstable public API currently supports only LLM-as-a-judge evaluators.+ enum:+ - llm_as_judge++ EvaluatorScope:+ docs: |+ Where an evaluator comes from.++ - `project`: created in your project+ - `managed`: provided by Langfuse+ enum:+ - project+ - managed++ EvaluationRuleTarget:+ docs: |+ The ingestion object type that should trigger evaluation runs.++ Choose the target first, because it changes both the valid filter columns and the valid variable-mapping sources:+ - `observation` evaluates live-ingested observations such as generations, spans, and events.+ It supports mapping from `input`, `output`, and `metadata`.+ - `experiment` evaluates live experiment executions and can additionally map `expected_output`.+ It currently supports filtering by `datasetId`.+ Discover valid dataset IDs with `GET /api/public/v2/datasets`, then use the returned dataset `id` values in your filter.+ enum:+ - observation+ - experiment++ EvaluationRuleStatus:+ docs: |+ Effective runtime status of the evaluation rule.++ - `active`: enabled and currently runnable.+ - `inactive`: disabled by configuration.+ - `paused`: enabled, but Langfuse has blocked execution until the underlying issue is resolved.+ enum:+ - active+ - inactive+ - paused++ EvaluationRuleMappingSource:+ docs: |+ Source field used to populate a prompt variable.++ Use these values when mapping evaluator prompt variables to live data.++ Target-specific rules:+ - `target=observation` supports `input`, `output`, and `metadata`+ - `target=experiment` supports `input`, `output`, `metadata`, and `expected_output`++ Source semantics:+ - `input`: the observation or experiment input payload+ - `output`: the observation or experiment output payload+ - `metadata`: the metadata object for the target. Combine with `jsonPath` when you need one nested field instead of the whole object.+ - `expected_output`: the experiment item's expected output. Only valid for `target=experiment`.+ enum:+ - input+ - output+ - metadata+ - expected_output++ EvaluatorModelConfig:+ docs: |+ Optional explicit model configuration for an evaluator.++ If omitted, Langfuse uses the project's default evaluation model.+ If provided, the model must be available to the project when the evaluator or evaluation rule is enabled.++ To discover valid configured `provider` values for a project, call `GET /api/public/llm-connections` and read the `provider` field from the returned connections.+ Use a `provider` value that matches one of the connections already configured in the same project.++ Recovery guidance:+ - If evaluator creation returns `422` with `code=evaluator_preflight_failed`, either provide a valid explicit `modelConfig` here or configure the project's default evaluation model, then retry the same request.+ properties:+ provider:+ type: string+ docs: |+ Provider identifier to use for this evaluator, for example `openai` or `anthropic`.++ To discover valid values for the current project, call `GET /api/public/llm-connections` and use one of the returned `provider` values.+ model:+ type: string+ docs: Model identifier exposed by the provider, for example `gpt-4.1-mini`.+ examples:+ - value:+ provider: openai+ model: gpt-4.1-mini++ EvaluatorOutputDataType:+ docs: |+ Structured score type returned by an evaluator.++ This controls the type of score value Langfuse stores for evaluation results:+ - `NUMERIC`: a numeric score such as `0.82`+ - `BOOLEAN`: a boolean score such as `true`+ - `CATEGORICAL`: one or more category labels from a fixed list+ enum:+ - NUMERIC+ - BOOLEAN+ - CATEGORICAL++ EvaluatorOutputFieldDefinition:+ properties:+ description:+ type: string+ docs: Human-readable instructions for what the evaluator should return in this field.++ EvaluatorOutputDefinition:+ docs: |+ Structured output definition to send when creating an evaluator.++ Agent guidance:+ - `dataType` is required.+ - Do not send `version`; that is an internal storage detail and is not part of the public request contract.+ - For `NUMERIC` and `BOOLEAN`, provide `reasoning.description` and `score.description`.+ - For `CATEGORICAL`, also provide `score.categories` and `score.shouldAllowMultipleMatches`.+ discriminant: dataType+ union:+ NUMERIC:+ type: PublicNumericEvaluatorOutputDefinition+ BOOLEAN:+ type: PublicBooleanEvaluatorOutputDefinition+ CATEGORICAL:+ type: PublicCategoricalEvaluatorOutputDefinition+ examples:+ - name: Numeric+ value:+ dataType: NUMERIC+ reasoning:+ description: Explain why the answer is correct or incorrect.+ score:+ description: Return a score between 0 and 1.+ - name: Boolean+ value:+ dataType: BOOLEAN+ reasoning:+ description: Explain why the output satisfies the requirement.+ score:+ description: Return true if the output satisfies the requirement, otherwise false.+ - name: Categorical+ value:+ dataType: CATEGORICAL+ reasoning:+ description: Explain which category best fits the output.+ score:+ description: Choose the best category.+ categories:+ - correct+ - partially_correct+ - incorrect+ shouldAllowMultipleMatches: false++ PublicNumericEvaluatorOutputDefinition:+ properties:+ dataType:+ type: EvaluatorOutputDataType+ docs: Always `NUMERIC`.+ reasoning:+ type: EvaluatorOutputFieldDefinition+ score:+ type: EvaluatorOutputFieldDefinition++ PublicBooleanEvaluatorOutputDefinition:+ properties:+ dataType:+ type: EvaluatorOutputDataType+ docs: Always `BOOLEAN`.+ reasoning:+ type: EvaluatorOutputFieldDefinition+ score:+ type: EvaluatorOutputFieldDefinition++ PublicCategoricalEvaluatorOutputScoreDefinition:+ properties:+ description:+ type: string+ categories:+ type: list<string>+ shouldAllowMultipleMatches:+ type: boolean++ PublicCategoricalEvaluatorOutputDefinition:+ properties:+ dataType:+ type: EvaluatorOutputDataType+ docs: Always `CATEGORICAL`.+ reasoning:+ type: EvaluatorOutputFieldDefinition+ score:+ type: PublicCategoricalEvaluatorOutputScoreDefinition++ PublicEvaluatorOutputDefinition:+ docs: |+ Evaluator output definition returned by the public API.++ This response always includes `dataType` and never includes an internal output-definition `version`.+ Legacy stored evaluator definitions are normalized into this shape before they are returned.++ Use this response shape when deciding how to interpret future evaluation scores:+ - `NUMERIC`: expect numeric score values+ - `BOOLEAN`: expect `true` / `false`+ - `CATEGORICAL`: expect one or more values from `score.categories`+ discriminant: dataType+ union:+ NUMERIC:+ type: PublicNumericEvaluatorOutputDefinition+ BOOLEAN:+ type: PublicBooleanEvaluatorOutputDefinition+ CATEGORICAL:+ type: PublicCategoricalEvaluatorOutputDefinition+ examples:+ - name: PublicNumeric+ value:+ dataType: NUMERIC+ reasoning:+ description: Explain why the answer is correct or incorrect.+ score:+ description: Return a score between 0 and 1.+ - name: PublicCategorical+ value:+ dataType: CATEGORICAL+ reasoning:+ description: Explain which label best fits the output.+ score:+ description: Choose the best label.+ categories:+ - correct+ - partially_correct+ - incorrect+ shouldAllowMultipleMatches: false++ EvaluationRuleStringFilterOperator:+ enum:+ - name: Equals+ value: "="+ - name: Contains+ value: contains+ - name: DoesNotContain+ value: does not contain+ - name: StartsWith+ value: starts with+ - name: EndsWith+ value: ends with++ EvaluationRuleNumberFilterOperator:+ enum:+ - name: Equals+ value: "="+ - name: GreaterThan+ value: ">"+ - name: LessThan+ value: "<"+ - name: GreaterThanOrEqual+ value: ">="+ - name: LessThanOrEqual+ value: "<="++ EvaluationRuleOptionsFilterOperator:+ enum:+ - name: AnyOf+ value: any of+ - name: NoneOf+ value: none of++ EvaluationRuleArrayOptionsFilterOperator:+ enum:+ - name: AnyOf+ value: any of+ - name: NoneOf+ value: none of+ - name: AllOf+ value: all of++ EvaluationRuleBooleanFilterOperator:+ enum:+ - name: Equals+ value: "="+ - name: NotEquals+ value: "<>"++ EvaluationRuleNullFilterOperator:+ enum:+ - name: IsNull+ value: is null+ - name: IsNotNull+ value: is not null++ DateTimeEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Column to filter on.+ operator:+ type: EvaluationRuleNumberFilterOperator+ docs: Comparison operator for datetime values.+ value:+ type: datetime+ docs: Datetime value to compare against.++ StringEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Column to filter on.+ operator:+ type: EvaluationRuleStringFilterOperator+ value:+ type: string++ NumberEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Column to filter on.+ operator:+ type: EvaluationRuleNumberFilterOperator+ value:+ type: double++ StringOptionsEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Column to filter on.+ operator:+ type: EvaluationRuleOptionsFilterOperator+ value:+ type: list<string>+ docs: One or more allowed string values.++ ArrayOptionsEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Column to filter on.+ operator:+ type: EvaluationRuleArrayOptionsFilterOperator+ value:+ type: list<string>+ docs: One or more array elements to match.++ StringObjectEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Object-valued column to filter on. In the unstable public API this is currently `metadata`.+ key:+ type: string+ docs: Top-level key inside the object-valued column to filter on.+ operator:+ type: EvaluationRuleStringFilterOperator+ value:+ type: string++ NumberObjectEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Object-valued column to filter on.+ key:+ type: string+ docs: Key inside the object-valued column to filter on.+ operator:+ type: EvaluationRuleNumberFilterOperator+ value:+ type: double++ CategoryOptionsEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Object-valued column to filter on.+ key:+ type: string+ docs: Key inside the object-valued column to filter on.+ operator:+ type: EvaluationRuleOptionsFilterOperator+ value:+ type: list<string>++ BooleanEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Column to filter on.+ operator:+ type: EvaluationRuleBooleanFilterOperator+ value:+ type: boolean++ NullEvaluationRuleFilter:+ properties:+ column:+ type: string+ docs: Column to filter on. In the unstable public API this is currently `parentObservationId`.+ operator:+ type: EvaluationRuleNullFilterOperator+ value:+ type: optional<string>+ docs: Ignored placeholder value. Clients may omit it or send an empty string.++ EvaluationRuleMapping:+ docs: |+ Maps one evaluator prompt variable to one source field from the target object.++ How to build a valid mapping list:+ 1. Create the evaluator or fetch it with `GET /evaluators/{id}`.+ 2. Read the evaluator `variables` array.+ 3. Add exactly one mapping object for each variable in that array.+ 4. Use the variable name exactly as returned, without braces such as `{{` or `}}`.+ 5. Choose a `source` that is valid for the selected `target`.++ `jsonPath` is optional. Use it only when the selected source is a JSON object and you want to extract one nested field before inserting it into the evaluator prompt.++ 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+ - `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:+ variable:+ type: string+ docs: |+ Prompt variable name without braces.++ Example: for the prompt `Judge {{input}} against {{output}}`, use `input` and `output`.+ source:+ type: EvaluationRuleMappingSource+ docs: |+ Source field that should populate the prompt variable.++ Quick reference:+ - `target=observation`: `input`, `output`, `metadata`+ - `target=experiment`: `input`, `output`, `metadata`, `expected_output`+ jsonPath:+ type: optional<string>+ docs: |+ Optional JSONPath selector applied to the selected source before it is passed to the evaluator prompt.++ Requirements:+ - Must start with `$`+ - Must be a syntactically valid JSONPath expression+ - Most useful with `source=metadata`+ examples:+ - name: BasicObservationMapping+ value:+ variable: input+ source: input+ - name: MetadataProjectionMapping+ value:+ variable: customer_tier+ source: metadata+ jsonPath: "$.customer.tier"+ - name: ExperimentExpectedOutputMapping+ value:+ variable: expected_output+ source: expected_output++ EvaluationRuleFilter:+ docs: |+ One filter condition used to decide whether a live-ingested target should be evaluated.++ An evaluation rule can include zero or more filter objects. All filters must be satisfied for the target to run.++ How to build a valid filter object:+ - Pick the `target` first, because it changes the supported columns.+ - Pick the filter `type`. That determines which fields are required.+ - Use `key` only for object filters such as `metadata`.+ - Use the correct `value` shape for the chosen filter `type`.++ Operator quick reference by filter `type`:+ - `string`: `"="`, `contains`, `does not contain`, `starts with`, `ends with`+ - `number`: `"="`, `">"`, `"<"`, `">="`, `"<="`+ - `datetime`: `"="`, `">"`, `"<"`, `">="`, `"<="`+ - `stringOptions`: `any of`, `none of`+ - `arrayOptions`: `any of`, `none of`, `all of`+ - `stringObject`: same operators as `string`+ - `null`: `is null`, `is not null`++ Supported columns by target:+ - `target=observation`+ - `type`: `stringOptions`, operators `any of` / `none of`, values `GENERATION`, `SPAN`, `EVENT`+ - `name`: `stringOptions`, operators `any of` / `none of`+ - `environment`: `stringOptions`, operators `any of` / `none of`+ - `level`: `stringOptions`, operators `any of` / `none of`, values `DEBUG`, `DEFAULT`, `WARNING`, `ERROR`+ - `version`: `string`+ - `traceName`: `stringOptions`, operators `any of` / `none of`+ - `userId`: `string`+ - `sessionId`: `string`+ - `tags`: `arrayOptions`, operators `any of` / `none of` / `all of`+ - `metadata`: `stringObject` with `key`+ - `parentObservationId`: `null`, operators `is null` / `is not null`+ - `calledToolNames`: `arrayOptions`, operators `any of` / `none of` / `all of`+ - `toolCalls`: `number`+ - `target=experiment`+ - `datasetId`: `stringOptions`, operators `any of` / `none of`+ Use dataset `id` values from `GET /api/public/v2/datasets`, not dataset names.++ Recovery guidance:+ - `invalid_filter_value` with `details.column` but no `invalidValues`: the selected `column` is not supported for the chosen `target`+ - `invalid_filter_value` with `details.invalidValues`: the selected values are not allowed for that column. Replace them with one of `details.allowedValues` when provided.+ - `invalid_filter_value` for `column=datasetId`: call `GET /api/public/v2/datasets`, then retry with dataset `id` values from that response.+ discriminant: type+ union:+ "datetime":+ type: DateTimeEvaluationRuleFilter+ "string":+ type: StringEvaluationRuleFilter+ "number":+ type: NumberEvaluationRuleFilter+ "stringOptions":+ type: StringOptionsEvaluationRuleFilter+ "categoryOptions":+ type: CategoryOptionsEvaluationRuleFilter+ "arrayOptions":+ type: ArrayOptionsEvaluationRuleFilter+ "stringObject":+ type: StringObjectEvaluationRuleFilter+ "numberObject":+ type: NumberObjectEvaluationRuleFilter+ "boolean":+ type: BooleanEvaluationRuleFilter+ "null":+ type: NullEvaluationRuleFilter+ examples:+ - name: ObservationTypeFilter+ value:+ type: stringOptions+ column: type+ operator: any of+ value:+ - GENERATION+ - name: ObservationMetadataFilter+ value:+ type: stringObject+ column: metadata+ key: customerTier+ operator: "="+ value: enterprise+ - name: ObservationRootOnlyFilter+ value:+ type: "null"+ column: parentObservationId+ operator: is null+ - name: ObservationTagsFilter+ value:+ type: arrayOptions+ column: tags+ operator: any of+ value:+ - production+ - name: ExperimentDatasetFilter+ value:+ type: stringOptions+ column: datasetId+ operator: any of+ value:+ - "550e8400-e29b-41d4-a716-446655440000"diff --git a/fern/apis/server/definition/unstable/errors.yml b/fern/apis/server/definition/unstable/errors.ymlnew file mode 100644index 0000000000..d2a7ec77c7--- /dev/null+++ b/fern/apis/server/definition/unstable/errors.yml@@ -0,0 +1,269 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+types:+ PublicApiErrorCode:+ docs: |+ Machine-readable error code returned by the unstable evaluators API.++ SDKs, CLIs, and agents should branch on `code` rather than parsing the human-readable `message`.+ The HTTP status still indicates the broad error class, while `code` gives the specific failure reason.+ enum:+ - authentication_failed+ - access_denied+ - invalid_request+ - invalid_query+ - invalid_body+ - invalid_filter_value+ - invalid_json_path+ - invalid_variable_mapping+ - missing_variable_mapping+ - duplicate_variable_mapping+ - resource_not_found+ - name_conflict+ - evaluator_preflight_failed+ - conflict+ - unprocessable_content+ - rate_limited+ - method_not_allowed+ - internal_error++ PublicApiValidationIssue:+ docs: |+ One validation issue returned for malformed request bodies or query parameters.++ This mirrors the most important parts of a Zod issue: a machine-readable `code`,+ a human-readable `message`, and a structured `path`.+ properties:+ code:+ type: string+ docs: Machine-readable validation issue code emitted by the server validator.+ message:+ type: string+ docs: Human-readable explanation of the validation failure.+ path:+ type: list<unknown>+ docs: Path to the invalid field, for example `["mapping", 0, "jsonPath"]`.++ PublicApiErrorDetails:+ docs: |+ Optional structured context attached to an unstable-evals error.++ The populated fields depend on the error `code`:+ - request parsing failures populate `issues`+ - filter validation failures populate `field`, `column`, `invalidValues`, and `allowedValues`+ - variable mapping failures populate `field`, `variable`, or `variables`+ - JSONPath validation failures populate `field`, `variable`, and `value`+ - evaluator preflight failures populate `evaluatorName`, `provider`, and `model`+ - rate limiting populates `retryAfterSeconds`, `limit`, `remaining`, and `resetAt`+ properties:+ issues:+ type: optional<list<PublicApiValidationIssue>>+ docs: Validation issues for malformed request bodies or query parameters.+ field:+ type: optional<string>+ docs: Path-like reference to the failing field, for example `mapping[1].jsonPath`.+ column:+ type: optional<string>+ docs: Filter column that failed validation.+ invalidValues:+ type: optional<list<string>>+ docs: Unsupported values supplied by the caller.+ allowedValues:+ type: optional<list<string>>+ docs: Allowed values for the failing filter column.+ variable:+ type: optional<string>+ docs: Evaluator variable involved in the failure.+ variables:+ type: optional<list<string>>+ docs: Multiple evaluator variables involved in the failure, for example missing mappings.+ value:+ type: optional<string>+ docs: Raw invalid value supplied by the caller.+ evaluatorName:+ type: optional<string>+ docs: Evaluator name used during preflight validation.+ provider:+ type: optional<nullable<string>>+ docs: Provider resolved during evaluator preflight, if any.+ model:+ type: optional<nullable<string>>+ docs: Model resolved during evaluator preflight, if any.+ retryAfterSeconds:+ type: optional<integer>+ docs: Suggested retry delay for rate-limited requests.+ limit:+ type: optional<integer>+ docs: Numeric limit associated with the failure, for example the active evaluation-rule cap or the current rate-limit window.+ remaining:+ type: optional<integer>+ docs: Remaining requests in the current rate-limit window.+ resetAt:+ type: optional<string>+ docs: ISO-8601 timestamp when the current rate-limit window resets.++ PublicApiError:+ docs: |+ Standard error envelope for the unstable evaluators API.++ Response handling guidance:+ - Use the HTTP status code for the broad class of failure.+ - Use `code` for precise branching in SDKs, CLIs, or agents.+ - Inspect `details` for field-level validation context such as invalid filter values, malformed JSONPath expressions, or missing variable mappings.+ - Retry only after fixing the specific issue described by `code` and `details`.+ properties:+ message:+ type: string+ docs: Human-readable description of the failure.+ code:+ type: PublicApiErrorCode+ docs: Stable machine-readable error code.+ details:+ type: optional<PublicApiErrorDetails>+ docs: Optional structured error context. Inspect the populated fields based on `code`.+ examples:+ - name: InvalidFilterValue+ value:+ message: 'Filter column "type" contains unsupported value(s): INVALID'+ code: invalid_filter_value+ details:+ field: filter[0].value+ column: type+ invalidValues:+ - INVALID+ allowedValues:+ - GENERATION+ - SPAN+ - EVENT+ - name: InvalidExperimentDatasetFilterValue+ value:+ message: 'Filter column "datasetId" contains dataset id(s) that do not exist in this project: dataset-prod'+ code: invalid_filter_value+ details:+ field: filter[0].value+ column: datasetId+ invalidValues:+ - dataset-prod+ - name: EvaluatorPreflightFailed+ value:+ message: 'No valid LLM model found for evaluator "answer-correctness". No default model or custom model configured for project project_123'+ code: evaluator_preflight_failed+ details:+ evaluatorName: answer-correctness+ provider: null+ model: null+ - name: MissingVariableMapping+ value:+ message: "Missing mappings for evaluator variable(s): output"+ code: missing_variable_mapping+ details:+ field: mapping+ variables:+ - output+ - name: InvalidJsonPath+ value:+ message: 'Mapping for variable "customer_tier" has an invalid jsonPath "$[". JSONPath expressions must use balanced quotes, brackets, and parentheses.'+ code: invalid_json_path+ details:+ field: mapping[0].jsonPath+ variable: customer_tier+ value: "$["+ - name: NameConflict+ value:+ message: 'An evaluation rule named "answer-quality-live" already exists in this project. Use PATCH /api/public/unstable/evaluation-rules/erule_123 to update it instead of creating a duplicate.'+ code: name_conflict+ details:+ field: name+ - name: ActiveEvaluationRuleLimit+ value:+ message: This project already has the maximum number of active evaluation rules (50). Disable an existing active evaluation rule before enabling another one.+ code: conflict+ details:+ limit: 50+ - name: RateLimited+ value:+ message: Rate limit exceeded+ code: rate_limited+ details:+ retryAfterSeconds: 60+ limit: 1000+ remaining: 0+ resetAt: "2026-03-30T10:00:00.000Z"++errors:+ BadRequestError:+ docs: |+ Request parsing or validation failed.++ Typical unstable-eval examples:+ - malformed request body or query parameters+ - unsupported filter value+ - invalid JSONPath selector+ - missing or duplicate variable mappings++ Recovery guidance:+ - read `details.issues` for malformed bodies or queries+ - read `details.column`, `details.invalidValues`, and `details.allowedValues` for filter problems+ - for `details.column=datasetId`, call `GET /api/public/v2/datasets` and retry with dataset `id` values from that response+ - read `details.variable` or `details.variables` for mapping problems+ status-code: 400+ type: PublicApiError+ UnauthorizedError:+ docs: |+ Authentication failed.++ Typical unstable-eval examples:+ - the API key or secret key is invalid+ - the request uses the wrong host or stale credentials+ status-code: 401+ type: PublicApiError+ AccessDeniedError:+ docs: |+ Authenticated, but the caller is not allowed to access the requested resource.++ Typical unstable-eval examples:+ - using an organization-scoped key against project-scoped evaluator endpoints+ - using a valid key that lacks the required access level for this resource+ status-code: 403+ type: PublicApiError+ NotFoundError:+ docs: The requested evaluator or evaluation rule does not exist within the authorized project.+ status-code: 404+ type: PublicApiError+ MethodNotAllowedError:+ docs: The HTTP method is not supported for this endpoint.+ status-code: 405+ type: PublicApiError+ ConflictError:+ docs: |+ The request conflicts with existing state.++ Typical unstable-eval examples:+ - evaluator version changed during concurrent creation+ - an evaluation rule name already exists in the project, so the caller should PATCH the existing resource instead+ - enabling another evaluation rule would exceed the project limit of 50 active evaluation rules+ - the underlying state changed between read and write operations, so the client should retry++ Recovery guidance:+ - for `name_conflict`, PATCH the existing evaluation rule instead of creating another one+ - for the active-limit conflict, disable another active evaluation rule before enabling a new one+ status-code: 409+ type: PublicApiError+ UnprocessableContentError:+ docs: |+ The request is syntactically valid, but Langfuse cannot accept it in its current form.++ The most important unstable-eval case is `code=evaluator_preflight_failed`, which means the evaluator cannot currently run with the resolved model configuration.++ Recovery guidance:+ - configure the project's default evaluation model, or send a valid explicit evaluator `modelConfig`+ - once the model configuration is valid, retry the same request+ status-code: 422+ type: PublicApiError+ TooManyRequestsError:+ docs: The project is rate limited. Retry after the interval described in the response headers and error details.+ status-code: 429+ type: PublicApiError+ InternalServerError:+ docs: An unexpected server-side error occurred.+ status-code: 500+ type: PublicApiErrordiff --git a/fern/apis/server/definition/unstable/evaluation-rules.yml b/fern/apis/server/definition/unstable/evaluation-rules.ymlnew file mode 100644index 0000000000..655ad24cf4--- /dev/null+++ b/fern/apis/server/definition/unstable/evaluation-rules.yml@@ -0,0 +1,494 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+imports:+ commons: ./commons.yml+ errors: ./errors.yml+ pagination: ../utils/pagination.yml++service:+ auth: true+ base-path: /api/public/unstable+ endpoints:+ create:+ docs: |+ Create an evaluation rule.++ An evaluation rule defines **what** incoming data should be evaluated and **how prompt variables should be populated** from that data.++ Use this resource after choosing an evaluator from the evaluator endpoints.++ Key rules:+ - `name` must be unique within the project for public evaluation rules+ - `target` must be `observation` or `experiment`+ - `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` mappings 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++ If an evaluation rule with the same `name` already exists in the project, the API returns `409`.+ In that case, update the existing resource with `PATCH /api/public/unstable/evaluation-rules/{evaluationRuleId}` instead of creating a second one.++ If enabling this resource would exceed the 50-active limit, the API also returns `409`.+ In that case, disable or pause another active evaluation rule before enabling a new one.++ Current scope:+ - evaluation rules are live-ingestion rules only+ - they do not trigger historical backfills++ 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 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_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+ path: /evaluation-rules+ request: CreateEvaluationRuleRequest+ response: EvaluationRule+ errors:+ - errors.BadRequestError+ - errors.UnauthorizedError+ - errors.AccessDeniedError+ - errors.NotFoundError+ - errors.ConflictError+ - errors.MethodNotAllowedError+ - errors.UnprocessableContentError+ - errors.TooManyRequestsError+ - errors.InternalServerError+ examples:+ - name: CreateObservationEvaluationRule+ docs: Deploy an evaluator to score live generations only.+ request:+ name: answer-correctness-live+ evaluator:+ name: answer-correctness+ scope: project+ target: observation+ enabled: true+ sampling: 1+ filter:+ - type: stringOptions+ column: type+ operator: any of+ value:+ - GENERATION+ mapping:+ - variable: input+ source: input+ - variable: output+ source: output+ response:+ body:+ id: erule_123+ name: answer-correctness-live+ evaluator:+ id: evaltmpl_123+ name: answer-correctness+ scope: project+ 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+ createdAt: "2026-03-30T09:20:00.000Z"+ updatedAt: "2026-03-30T09:20: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:+ name: experiment-expected-output-match+ evaluator:+ name: expected-output-match+ scope: project+ target: experiment+ enabled: true+ sampling: 0.5+ filter:+ - type: stringOptions+ column: datasetId+ operator: any of+ value:+ - "550e8400-e29b-41d4-a716-446655440000"+ mapping:+ - variable: output+ source: output+ - variable: expected_output+ source: expected_output+ response:+ body:+ id: erule_456+ name: experiment-expected-output-match+ evaluator:+ id: evaltmpl_456+ name: expected-output-match+ scope: project+ target: experiment+ enabled: true+ status: active+ pausedReason: null+ pausedMessage: null+ sampling: 0.5+ filter:+ - type: stringOptions+ column: datasetId+ operator: any of+ value:+ - "550e8400-e29b-41d4-a716-446655440000"+ mapping:+ - variable: output+ source: output+ - variable: expected_output+ source: expected_output+ createdAt: "2026-03-30T09:30:00.000Z"+ updatedAt: "2026-03-30T09:30:00.000Z"++ list:+ docs: |+ List evaluation rules in the authenticated project.++ Each item describes one live evaluation rule and its effective runtime status.+ method: GET+ path: /evaluation-rules+ request:+ name: ListEvaluationRulesRequest+ query-parameters:+ page:+ type: optional<integer>+ docs: 1-based page number. Defaults to `1`.+ limit:+ type: optional<integer>+ docs: Maximum number of items per page. Defaults to `50`.+ response: EvaluationRules+ errors:+ - errors.BadRequestError+ - errors.UnauthorizedError+ - errors.AccessDeniedError+ - errors.MethodNotAllowedError+ - errors.TooManyRequestsError+ - errors.InternalServerError++ get:+ docs: |+ Get one evaluation rule by its identifier.++ Use this endpoint to inspect the current evaluator, target, mapping, filters, and effective runtime status.+ method: GET+ path: /evaluation-rules/{evaluationRuleId}+ path-parameters:+ evaluationRuleId:+ type: string+ docs: Evaluation rule identifier returned by the evaluation rule endpoints.+ response: EvaluationRule+ errors:+ - errors.BadRequestError+ - errors.UnauthorizedError+ - errors.AccessDeniedError+ - errors.NotFoundError+ - errors.MethodNotAllowedError+ - errors.TooManyRequestsError+ - errors.InternalServerError++ update:+ docs: |+ Update an evaluation rule.++ Typical uses:+ - enable or disable live execution+ - switch to another evaluator+ - adjust sampling+ - change filters+ - update 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+ - 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 the update fails with `invalid_filter_value` after changing `target`, resend the request with a target-compatible `filter`+ method: PATCH+ path: /evaluation-rules/{evaluationRuleId}+ path-parameters:+ evaluationRuleId:+ type: string+ docs: Evaluation rule identifier.+ request: UpdateEvaluationRuleRequest+ response: EvaluationRule+ errors:+ - errors.BadRequestError+ - errors.UnauthorizedError+ - errors.AccessDeniedError+ - errors.NotFoundError+ - errors.MethodNotAllowedError+ - errors.UnprocessableContentError+ - errors.TooManyRequestsError+ - errors.InternalServerError++ delete:+ docs: |+ Delete an evaluation rule.++ This removes the live-ingestion rule only. It does not delete the referenced evaluator.+ method: DELETE+ path: /evaluation-rules/{evaluationRuleId}+ path-parameters:+ evaluationRuleId:+ type: string+ docs: Evaluation rule identifier.+ response: DeleteEvaluationRuleResponse+ errors:+ - errors.BadRequestError+ - errors.UnauthorizedError+ - errors.AccessDeniedError+ - errors.NotFoundError+ - errors.MethodNotAllowedError+ - errors.TooManyRequestsError+ - errors.InternalServerError++types:+ EvaluationRule:+ docs: |+ Live evaluation rule for incoming data.++ An evaluation rule answers:+ - which evaluator should be used+ - which target objects should trigger scoring+ - how often scoring should run+ - which target fields should populate each evaluator variable+ - whether the deployment is active, inactive, or paused++ Important status semantics:+ - `enabled` is the desired on/off setting from the client+ - `status` is the effective runtime state after Langfuse applies validation and blocking rules+ - `enabled=true` with `status=paused` means the rule should run, but Langfuse has paused it until the underlying problem is fixed+ properties:+ id:+ type: string+ docs: Stable evaluation rule identifier.+ name:+ type: string+ docs: Human-readable deployment name. This is independent from the evaluator name.+ evaluator:+ type: EvaluationRuleEvaluator+ docs: |+ Evaluator currently used by this rule.++ `name` and `scope` identify the evaluator family conceptually.+ `id` is the currently active evaluator version in that family.+ If you create a newer project version with the same evaluator name later, existing evaluation rules are moved to it automatically.+ target:+ type: commons.EvaluationRuleTarget+ docs: Target object type that should trigger scoring.+ enabled:+ type: boolean+ docs: Desired enabled state configured by the client.+ status:+ type: commons.EvaluationRuleStatus+ docs: Effective runtime status after Langfuse applies validation and blocking rules.+ pausedReason:+ type: nullable<string>+ docs: Machine-readable reason when `status=paused`, otherwise `null`.+ pausedMessage:+ type: nullable<string>+ docs: Human-readable explanation when `status=paused`, otherwise `null`.+ sampling:+ type: double+ docs: |+ Fraction of matching target objects that should be evaluated.++ Must be greater than `0` and less than or equal to `1`.+ - `1` means evaluate every matching target.+ - `0.25` means evaluate approximately 25% of matching targets.+ filter:+ type: list<commons.EvaluationRuleFilter>+ 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.+ createdAt:+ type: datetime+ docs: Timestamp when the evaluation rule was created.+ updatedAt:+ type: datetime+ docs: Timestamp when the evaluation rule was last updated.+ examples:+ - value:+ id: erule_123+ name: answer-correctness-live+ evaluator:+ id: evaltmpl_123+ name: answer-correctness+ scope: project+ 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+ createdAt: "2026-03-30T09:20:00.000Z"+ updatedAt: "2026-03-30T09:20:00.000Z"++ EvaluationRules:+ docs: Paginated list of evaluation rules.+ properties:+ data:+ type: list<EvaluationRule>+ docs: Evaluation rules in the current page.+ meta:+ type: pagination.MetaResponse+ docs: Standard pagination metadata.++ CreateEvaluationRuleRequest:+ docs: |+ Request body for creating an evaluation rule.++ Checklist for agents and SDK clients:+ - 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`+ - optionally narrow execution with `filter`+ - set `enabled=true` only when you want live execution immediately+ properties:+ name:+ type: string+ docs: Human-readable deployment name.+ evaluator:+ type: EvaluationRuleEvaluatorReference+ docs: |+ Evaluator family to use.++ Use `name` and `scope` 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.+ mapping:+ type: list<commons.EvaluationRuleMapping>+ docs: |+ Required variable mappings.++ Every evaluator variable must appear exactly once.+ Build this list from the evaluator `variables` array returned by the evaluator endpoints.++ UpdateEvaluationRuleRequest:+ docs: |+ Partial update body for an evaluation rule.++ Provide only the fields you want to change.+ An empty body is rejected.++ 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 an experiment `datasetId` filter, call `GET /api/public/v2/datasets` and use dataset `id` values from that response.+ properties:+ name:+ type: optional<string>+ docs: Updated deployment name.+ evaluator:+ type: optional<EvaluationRuleEvaluatorReference>+ docs: |+ Updated evaluator family.++ Langfuse resolves the provided evaluator family to its latest version before saving the rule.+ target:+ type: optional<commons.EvaluationRuleTarget>+ docs: Updated target object type.+ enabled:+ type: optional<boolean>+ docs: Updated desired enabled state.+ sampling:+ type: optional<double>+ docs: Updated sampling fraction.+ filter:+ type: optional<list<commons.EvaluationRuleFilter>>+ docs: |+ Updated filter list.++ 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.++ DeleteEvaluationRuleResponse:+ docs: Confirmation response returned after successful deletion.+ properties:+ message:+ type: string+ docs: Always `Evaluation rule successfully deleted`.++ EvaluationRuleEvaluatorReference:+ docs: |+ Evaluator family reference used when creating or updating an evaluation rule.++ `name` and `scope` are enough to identify the evaluator family in the authenticated project context.+ properties:+ name:+ type: string+ docs: Evaluator family name.+ scope:+ type: commons.EvaluatorScope+ docs: Whether the evaluator family is project-owned or Langfuse-managed.++ 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.+ properties:+ id:+ type: string+ docs: Identifier of the exact evaluator version currently used by the rule.+ name:+ type: string+ docs: Evaluator family name.+ scope:+ type: commons.EvaluatorScope+ docs: Whether the evaluator family is project-owned or Langfuse-managed.diff --git a/fern/apis/server/definition/unstable/evaluators.yml b/fern/apis/server/definition/unstable/evaluators.ymlnew file mode 100644index 0000000000..5fa89d7972--- /dev/null+++ b/fern/apis/server/definition/unstable/evaluators.yml@@ -0,0 +1,250 @@+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json+imports:+ commons: ./commons.yml+ errors: ./errors.yml+ pagination: ../utils/pagination.yml++service:+ auth: true+ base-path: /api/public/unstable+ endpoints:+ create:+ 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.++ Naming behavior:+ - If this is a new evaluator name in your project, Langfuse creates version `1`.+ - If the name already exists in your project, Langfuse creates the next version and returns it.+ - When a new project version is created, existing evaluation rules in that project automatically move to the newest version for that evaluator name.++ Recommended workflow:+ 1. Create the evaluator.+ 2. Read the returned `variables` array.+ 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`.++ 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.++ Unstable API note:+ - This surface may evolve while the underlying evaluation data model is being redesigned.+ method: POST+ path: /evaluators+ request: CreateEvaluatorRequest+ response: Evaluator+ errors:+ - errors.BadRequestError+ - errors.UnauthorizedError+ - errors.AccessDeniedError+ - errors.MethodNotAllowedError+ - errors.ConflictError+ - errors.UnprocessableContentError+ - errors.TooManyRequestsError+ - errors.InternalServerError+ examples:+ - name: CreateEvaluatorVersion+ docs: Create a new version of an evaluator named `answer-correctness`.+ request:+ name: answer-correctness+ prompt: |+ You are grading an answer.++ Input:+ {{input}}++ Output:+ {{output}}++ Return a score between 0 and 1.+ outputDefinition:+ dataType: NUMERIC+ reasoning:+ description: Explain why the score was assigned.+ score:+ description: Correctness score between 0 and 1.+ modelConfig:+ provider: openai+ model: gpt-4.1-mini+ response:+ body:+ id: evaltmpl_123+ name: answer-correctness+ version: 2+ scope: project+ type: llm_as_judge+ prompt: |+ You are grading an answer.++ Input:+ {{input}}++ Output:+ {{output}}++ Return a score between 0 and 1.+ variables:+ - input+ - output+ outputDefinition:+ dataType: NUMERIC+ reasoning:+ description: Explain why the score was assigned.+ score:+ description: Correctness score between 0 and 1.+ modelConfig:+ provider: openai+ model: gpt-4.1-mini+ evaluationRuleCount: 0+ createdAt: "2026-03-30T09:00:00.000Z"+ updatedAt: "2026-03-30T09:00:00.000Z"++ list:+ docs: |+ List the evaluators available to the authenticated project.++ Important behavior:+ - This endpoint returns the latest version of each available evaluator.+ - Results can include evaluators from your project and Langfuse-managed evaluators.+ - If the same evaluator name exists in both places, both are returned as separate items with different `scope` values.+ method: GET+ path: /evaluators+ request:+ name: ListEvaluatorsRequest+ query-parameters:+ page:+ type: optional<integer>+ docs: 1-based page number. Defaults to `1`.+ limit:+ type: optional<integer>+ docs: Maximum number of items per page. Defaults to `50`.+ response: Evaluators+ errors:+ - errors.BadRequestError+ - errors.UnauthorizedError+ - errors.AccessDeniedError+ - errors.MethodNotAllowedError+ - errors.TooManyRequestsError+ - errors.InternalServerError++ get:+ docs: |+ Get one evaluator by `id`.++ Use this endpoint when you want the prompt, output definition, model configuration, and derived variables for the evaluator you plan to use in an evaluation rule.+ method: GET+ path: /evaluators/{evaluatorId}+ path-parameters:+ evaluatorId:+ type: string+ docs: Evaluator identifier returned by the evaluator endpoints.+ response: Evaluator+ errors:+ - errors.BadRequestError+ - errors.UnauthorizedError+ - errors.AccessDeniedError+ - errors.NotFoundError+ - errors.MethodNotAllowedError+ - errors.TooManyRequestsError+ - errors.InternalServerError++types:+ Evaluator:+ 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++ 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++ 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`).+ properties:+ id:+ type: string+ docs: Identifier of this evaluator.+ name:+ type: string+ docs: Evaluator name.+ version:+ type: integer+ docs: Version number of this evaluator.+ 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.++ Every variable in this list must be mapped exactly once when creating an evaluation rule.+ outputDefinition:+ type: commons.PublicEvaluatorOutputDefinition+ docs: |+ 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:+ 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.++ Evaluators:+ properties:+ data:+ type: list<Evaluator>+ meta:+ type: pagination.MetaResponse++ CreateEvaluatorRequest:+ docs: |+ Request body for creating an evaluator.++ 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.+ properties:+ name:+ type: string+ docs: Evaluator name within the authenticated project.+ prompt:+ type: string+ docs: Prompt template used by the evaluator.+ outputDefinition:+ type: commons.EvaluatorOutputDefinition+ docs: |+ Structured output schema the evaluator must return.++ Always send `dataType`.+ Do not send `version`; it is an internal storage detail and not part of the public request contract.+ modelConfig:+ type: optional<nullable<commons.EvaluatorModelConfig>>+ docs: Optional explicit model configuration. Omit or set to `null` to use the project default evaluation model.diff --git a/packages/shared/AGENTS.md b/packages/shared/AGENTS.mdindex 8657234a8d..6c56c604e6 100644--- a/packages/shared/AGENTS.md+++ b/packages/shared/AGENTS.md@@ -31,6 +31,9 @@ Use root [AGENTS.md](../../AGENTS.md) for monorepo-level rules.- Queue payload schemas: `src/server/queues.ts`- Queue helpers: `src/server/redis/*`- Postgres schema: `prisma/schema.prisma`+- For unstable public eval APIs, the public `evaluatorId` is currently the+ exact `EvalTemplate.id`. Latest-version family grouping is derived from+ `(projectId, name)` rather than stored on extra evaluator identity fields.- Prisma migrations: `prisma/migrations/*`- ClickHouse migrations: `clickhouse/migrations/{clustered,unclustered}/*`- Seeder and support scripts: `scripts/seeder/*`, `clickhouse/scripts/*`diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 6dad38b481..789fd0bf7e 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -915,9 +915,9 @@ model EvalTemplate {projectId String? @map("project_id")project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)- name String- version Int- prompt String+ name String+ version Int+ prompt Stringpartner String? // e.g. "ragas", describes the partner that created the templatediff --git a/packages/shared/src/features/batchAction/applyFieldMapping.ts b/packages/shared/src/features/batchAction/applyFieldMapping.tsindex 1f9071d11d..217f6b2d85 100644--- a/packages/shared/src/features/batchAction/applyFieldMapping.ts+++ b/packages/shared/src/features/batchAction/applyFieldMapping.ts@@ -51,6 +51,7 @@ export function evaluateJsonPath(data: unknown, jsonPath: string): unknown {path: jsonPath,json: parsed as string | object,wrap: false,+ eval: false,});return result;diff --git a/packages/shared/src/features/evals/utilities.ts b/packages/shared/src/features/evals/utilities.tsindex 5ca3b2482b..2e9c88897c 100644--- a/packages/shared/src/features/evals/utilities.ts+++ b/packages/shared/src/features/evals/utilities.ts@@ -61,6 +61,7 @@ function parseJsonDefault(selectedColumn: unknown, jsonSelector: string) {const result = JSONPath({path: jsonSelector,json: selectedColumn as any, // JSONPath accepts unknown but types are strict+ eval: false,});if (!Array.isArray(result) || result.length === 0) {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 79162c5cdb..047c90b9d2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -602,6 +602,9 @@ importers:json-schema-faker:specifier: 0.6.1version: 0.6.1+ jsonpath-plus:+ specifier: 10.3.0+ version: 10.3.0langchain:specifier: ^1.3.0version: 1.3.0(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]([email protected]))([email protected])([email protected])([email protected]([email protected]))diff --git a/web/AGENTS.md b/web/AGENTS.mdindex bb3d9feaea..be43284614 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -4,10 +4,12 @@ This file covers package-local guidance for this package.Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.## Purpose+- Next.js 15 application with UI, tRPC backend, and public REST API routes.- Primary package for frontend and most request/response surface changes.## Maintenance Contract+- `AGENTS.md` is a living document.- Update this file in the same PR when material web-local changes occur:- new/renamed web entry points@@ -17,15 +19,18 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.`AGENTS.md` too.## High-Signal Entry Points+- App shell/providers: `src/pages/_app.tsx`- tRPC context/procedures: `src/server/api/trpc.ts`- tRPC router registry: `src/server/api/root.ts`- tRPC routers: `src/server/api/routers/*`, `src/features/*/server/*`- Public REST API routes: `src/pages/api/public/*`+- Unstable public eval APIs: `src/pages/api/public/unstable/{evaluators,evaluation-rules}/*`- Feature modules: `src/features/*`- Reusable UI components: `src/components/*`- Tests:- - Server tests: `src/__tests__/server/*.servertest.ts`+ - Server integration tests: `src/__tests__/server/*.servertest.ts`+ - Server unit tests: `src/__tests__/server/unit/*.servertest.ts`- Client tests: `src/**/*.clienttest.ts(x)`- E2E: `src/__e2e__/*`@@ -66,6 +71,7 @@ performance, bundle size, React/Next.js performance patterns, or browser-basedsignoff of user-visible changes.## Web Conventions+- Put net-new feature code under `src/features/<feature>/*`; put broadly reusablecomponents under `src/components/*`.- We use tRPC for full-stack web features; register routers in@@ -84,10 +90,16 @@ signoff of user-visible changes.`src/features/public-api/server/withMiddlewares.ts`, define strict request andresponse types in `src/features/public-api/types/*`, add server tests, andupdate Fern sources when the contract changes.+- Public eval endpoints should keep the split between reusable `evaluators`+ and ingestion-scoped `evaluation-rules`; do not leak `EvalTemplate` or+ `JobConfiguration` naming into the public contract.- Keep tests independent; in `src/__tests__/server/**`, prefer scoped cleanup orunique test data over global reset helpers.+- Put pure server unit tests that do not need Postgres bootstrap under+ `src/__tests__/server/unit/**` so they skip the shared DB setup hook.## Quick Commands+- Dev: `pnpm --filter web run dev`- Lint: `pnpm --filter web run lint`- Lint fix: `pnpm --filter web run lint:fix`@@ -101,6 +113,7 @@ signoff of user-visible changes.## Playbooks### Add/Change tRPC endpoint+1. Implement router/procedure in `src/server/api/routers/*` or`src/features/<feature>/server/*`.2. Register in `src/server/api/root.ts`.@@ -108,6 +121,7 @@ signoff of user-visible changes.4. Add/adjust server tests under `src/__tests__/server/*`.### Add/Change public API endpoint+1. Add route in `src/pages/api/public/*`.2. Define/update contract types in `src/features/public-api/types/*`.3. Add/adjust server tests in `src/__tests__/server/*`.@@ -115,6 +129,7 @@ signoff of user-visible changes.outputs (do not hand-edit `../generated/**`).### Add frontend feature+1. Prefer `src/features/<feature>/*` for feature-local code.2. Put broadly reusable components in `src/components/*`.3. Keep server logic near feature server folders when possible.@@ -123,6 +138,7 @@ signoff of user-visible changes.`../.agents/skills/frontend-browser-review/SKILL.md`.### Agent browser loop+1. Start the app with `pnpm run dev:web` unless an existing local server is already running.2. Install Chromium with `pnpm run playwright:install` if Playwright has not been set up on this machine yet.3. Use the workspace `playwright` MCP server from `.mcp.json`, `.cursor/mcp.json`, or `.vscode/mcp.json` for browser-driven review of user-visible frontend changes, not just debugging.@@ -130,6 +146,7 @@ signoff of user-visible changes.5. Inspect traces and other artifacts under `../.playwright-mcp/` when a browser session fails.## Package-Specific Rules+- Router style is Pages Router-centric; follow existing routing patterns.- Keep tests independent; no reliance on test execution order.- Confirm the target `*.clienttest.*` or `*.servertest.*` file exists before passing a pattern to `vitest run`; source files do not always have a matching colocated test file.diff --git a/web/package.json b/web/package.jsonindex 0d1b32766d..af5120d9a4 100644--- a/web/package.json+++ b/web/package.json@@ -118,6 +118,7 @@"https-proxy-agent": "^7.0.6","ioredis": "^5.10.1","ip-address": "^9.0.5",+ "jsonpath-plus": "10.3.0","json-schema-faker": "0.6.1","langchain": "^1.3.0","langfuse": "3.38.4",diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex f5955638de..e12fae2408 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -6155,6 +6155,890 @@ paths:description: List of trace IDs to deleterequired:- traceIds+ /api/public/unstable/evaluation-rules:+ post:+ description: >-+ Create an evaluation rule.+++ An evaluation rule defines **what** incoming data should be evaluated+ and **how prompt variables should be populated** from that data.+++ Use this resource after choosing an evaluator from the evaluator+ endpoints.+++ Key rules:++ - `name` must be unique within the project for public evaluation rules++ - `target` must be `observation` or `experiment`++ - `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` mappings 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+++ If an evaluation rule with the same `name` already exists in the+ project, the API returns `409`.++ In that case, update the existing resource with `PATCH+ /api/public/unstable/evaluation-rules/{evaluationRuleId}` instead of+ creating a second one.+++ If enabling this resource would exceed the 50-active limit, the API also+ returns `409`.++ In that case, disable or pause another active evaluation rule before+ enabling a new one.+++ Current scope:++ - evaluation rules are live-ingestion rules only++ - they do not trigger historical backfills+++ 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 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_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.+ operationId: unstable_evaluationRules_create+ tags:+ - UnstableEvaluationRules+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableEvaluationRule'+ examples:+ CreateObservationEvaluationRule:+ value:+ id: erule_123+ name: answer-correctness-live+ evaluator:+ id: evaltmpl_123+ name: answer-correctness+ scope: project+ 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+ createdAt: '2026-03-30T09:20:00.000Z'+ updatedAt: '2026-03-30T09:20:00.000Z'+ CreateExperimentEvaluationRule:+ value:+ id: erule_456+ name: experiment-expected-output-match+ evaluator:+ id: evaltmpl_456+ name: expected-output-match+ scope: project+ target: experiment+ enabled: true+ status: active+ sampling: 0.5+ filter:+ - type: stringOptions+ column: datasetId+ operator: any of+ value:+ - 550e8400-e29b-41d4-a716-446655440000+ mapping:+ - variable: output+ source: output+ - variable: expected_output+ source: expected_output+ createdAt: '2026-03-30T09:30:00.000Z'+ updatedAt: '2026-03-30T09:30:00.000Z'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '409':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '422':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '429':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '500':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ security:+ - BasicAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableCreateEvaluationRuleRequest'+ examples:+ CreateObservationEvaluationRule:+ value:+ name: answer-correctness-live+ evaluator:+ name: answer-correctness+ scope: project+ target: observation+ enabled: true+ sampling: 1+ filter:+ - type: stringOptions+ column: type+ operator: any of+ value:+ - GENERATION+ mapping:+ - variable: input+ source: input+ - variable: output+ source: output+ CreateExperimentEvaluationRule:+ value:+ name: experiment-expected-output-match+ evaluator:+ name: expected-output-match+ scope: project+ target: experiment+ enabled: true+ sampling: 0.5+ filter:+ - type: stringOptions+ column: datasetId+ operator: any of+ value:+ - 550e8400-e29b-41d4-a716-446655440000+ mapping:+ - variable: output+ source: output+ - variable: expected_output+ source: expected_output+ get:+ description: >-+ List evaluation rules in the authenticated project.+++ Each item describes one live evaluation rule and its effective runtime+ status.+ operationId: unstable_evaluationRules_list+ tags:+ - UnstableEvaluationRules+ parameters:+ - name: page+ in: query+ description: 1-based page number. Defaults to `1`.+ required: false+ schema:+ type: integer+ nullable: true+ - name: limit+ in: query+ description: Maximum number of items per page. Defaults to `50`.+ required: false+ schema:+ type: integer+ nullable: true+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableEvaluationRules'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '429':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '500':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ security:+ - BasicAuth: []+ /api/public/unstable/evaluation-rules/{evaluationRuleId}:+ get:+ description: >-+ Get one evaluation rule by its identifier.+++ Use this endpoint to inspect the current evaluator, target, mapping,+ filters, and effective runtime status.+ operationId: unstable_evaluationRules_get+ tags:+ - UnstableEvaluationRules+ parameters:+ - name: evaluationRuleId+ in: path+ description: >-+ Evaluation rule identifier returned by the evaluation rule+ endpoints.+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableEvaluationRule'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '429':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '500':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ security:+ - BasicAuth: []+ patch:+ description: >-+ Update an evaluation rule.+++ Typical uses:++ - enable or disable live execution++ - switch to another evaluator++ - adjust sampling++ - change filters++ - update 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++ - 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 the update fails with `invalid_filter_value` after changing+ `target`, resend the request with a target-compatible `filter`+ operationId: unstable_evaluationRules_update+ tags:+ - UnstableEvaluationRules+ parameters:+ - name: evaluationRuleId+ in: path+ description: Evaluation rule identifier.+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableEvaluationRule'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '422':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '429':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '500':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ security:+ - BasicAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableUpdateEvaluationRuleRequest'+ delete:+ description: >-+ Delete an evaluation rule.+++ This removes the live-ingestion rule only. It does not delete the+ referenced evaluator.+ operationId: unstable_evaluationRules_delete+ tags:+ - UnstableEvaluationRules+ parameters:+ - name: evaluationRuleId+ in: path+ description: Evaluation rule identifier.+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableDeleteEvaluationRuleResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '429':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '500':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ security:+ - BasicAuth: []+ /api/public/unstable/evaluators:+ post:+ description: >-+ 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.+++ Naming behavior:++ - If this is a new evaluator name in your project, Langfuse creates+ version `1`.++ - If the name already exists in your project, Langfuse creates the next+ version and returns it.++ - When a new project version is created, existing evaluation rules in+ that project automatically move to the newest version for that evaluator+ name.+++ Recommended workflow:++ 1. Create the evaluator.++ 2. Read the returned `variables` array.++ 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`.+++ 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.+++ Unstable API note:++ - This surface may evolve while the underlying evaluation data model is+ being redesigned.+ operationId: unstable_evaluators_create+ tags:+ - UnstableEvaluators+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableEvaluator'+ examples:+ CreateEvaluatorVersion:+ value:+ id: evaltmpl_123+ name: answer-correctness+ version: 2+ scope: project+ type: llm_as_judge+ prompt: |+ You are grading an answer.++ Input:+ {{input}}++ Output:+ {{output}}++ Return a score between 0 and 1.+ variables:+ - input+ - output+ outputDefinition:+ dataType: NUMERIC+ reasoning:+ description: Explain why the score was assigned.+ score:+ description: Correctness score between 0 and 1.+ modelConfig:+ provider: openai+ model: gpt-4.1-mini+ evaluationRuleCount: 0+ createdAt: '2026-03-30T09:00:00.000Z'+ updatedAt: '2026-03-30T09:00:00.000Z'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '409':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '422':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '429':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '500':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ security:+ - BasicAuth: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableCreateEvaluatorRequest'+ examples:+ CreateEvaluatorVersion:+ value:+ name: answer-correctness+ prompt: |+ You are grading an answer.++ Input:+ {{input}}++ Output:+ {{output}}++ Return a score between 0 and 1.+ outputDefinition:+ dataType: NUMERIC+ reasoning:+ description: Explain why the score was assigned.+ score:+ description: Correctness score between 0 and 1.+ modelConfig:+ provider: openai+ model: gpt-4.1-mini+ get:+ description: >-+ List the evaluators available to the authenticated project.+++ Important behavior:++ - This endpoint returns the latest version of each available evaluator.++ - Results can include evaluators from your project and Langfuse-managed+ evaluators.++ - If the same evaluator name exists in both places, both are returned as+ separate items with different `scope` values.+ operationId: unstable_evaluators_list+ tags:+ - UnstableEvaluators+ parameters:+ - name: page+ in: query+ description: 1-based page number. Defaults to `1`.+ required: false+ schema:+ type: integer+ nullable: true+ - name: limit+ in: query+ description: Maximum number of items per page. Defaults to `50`.+ required: false+ schema:+ type: integer+ nullable: true+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableEvaluators'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '429':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '500':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ security:+ - BasicAuth: []+ /api/public/unstable/evaluators/{evaluatorId}:+ get:+ description: >-+ Get one evaluator by `id`.+++ Use this endpoint when you want the prompt, output definition, model+ configuration, and derived variables for the evaluator you plan to use+ in an evaluation rule.+ operationId: unstable_evaluators_get+ tags:+ - UnstableEvaluators+ parameters:+ - name: evaluatorId+ in: path+ description: Evaluator identifier returned by the evaluator endpoints.+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstableEvaluator'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ '429':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ '500':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/unstablePublicApiError'+ security:+ - BasicAuth: []components:schemas:AnnotationQueueStatus:@@ -8688,272 +9572,604 @@ components:promptTokens:type: integernullable: true- completionTokens:- type: integer+ completionTokens:+ type: integer+ nullable: true+ totalTokens:+ type: integer+ nullable: true+ OptionalObservationBody:+ title: OptionalObservationBody+ type: object+ properties:+ traceId:+ type: string+ nullable: true+ name:+ type: string+ nullable: true+ startTime:+ type: string+ format: date-time+ nullable: true+ metadata:+ nullable: true+ input:+ nullable: true+ output:+ nullable: true+ level:+ $ref: '#/components/schemas/ObservationLevel'+ nullable: true+ statusMessage:+ type: string+ nullable: true+ parentObservationId:+ type: string+ nullable: true+ version:+ type: string+ nullable: true+ environment:+ type: string+ nullable: true+ CreateEventBody:+ title: CreateEventBody+ type: object+ properties:+ id:+ type: string+ nullable: true+ allOf:+ - $ref: '#/components/schemas/OptionalObservationBody'+ UpdateEventBody:+ title: UpdateEventBody+ type: object+ properties:+ id:+ type: string+ required:+ - id+ allOf:+ - $ref: '#/components/schemas/OptionalObservationBody'+ CreateSpanBody:+ title: CreateSpanBody+ type: object+ properties:+ endTime:+ type: string+ format: date-time+ nullable: true+ allOf:+ - $ref: '#/components/schemas/CreateEventBody'+ UpdateSpanBody:+ title: UpdateSpanBody+ type: object+ properties:+ endTime:+ type: string+ format: date-time+ nullable: true+ allOf:+ - $ref: '#/components/schemas/UpdateEventBody'+ CreateGenerationBody:+ title: CreateGenerationBody+ type: object+ properties:+ completionStartTime:+ type: string+ format: date-time+ nullable: true+ model:+ type: string+ nullable: true+ modelParameters:+ type: object+ additionalProperties:+ $ref: '#/components/schemas/MapValue'+ nullable: true+ usage:+ $ref: '#/components/schemas/IngestionUsage'+ nullable: true+ usageDetails:+ $ref: '#/components/schemas/UsageDetails'+ nullable: true+ costDetails:+ type: object+ additionalProperties:+ type: number+ format: double+ nullable: true+ promptName:+ type: string+ nullable: true+ promptVersion:+ type: integer+ nullable: true+ allOf:+ - $ref: '#/components/schemas/CreateSpanBody'+ UpdateGenerationBody:+ title: UpdateGenerationBody+ type: object+ properties:+ completionStartTime:+ type: string+ format: date-time+ nullable: true+ model:+ type: string+ nullable: true+ modelParameters:+ type: object+ additionalProperties:+ $ref: '#/components/schemas/MapValue'+ nullable: true+ usage:+ $ref: '#/components/schemas/IngestionUsage'+ nullable: true+ promptName:+ type: string+ nullable: true+ usageDetails:+ $ref: '#/components/schemas/UsageDetails'+ nullable: true+ costDetails:+ type: object+ additionalProperties:+ type: number+ format: double+ nullable: true+ promptVersion:+ type: integer+ nullable: true+ allOf:+ - $ref: '#/components/schemas/UpdateSpanBody'+ ObservationBody:+ title: ObservationBody+ type: object+ properties:+ id:+ type: string+ nullable: true+ traceId:+ type: string+ nullable: true+ type:+ $ref: '#/components/schemas/ObservationType'+ name:+ type: string+ nullable: true+ startTime:+ type: string+ format: date-time+ nullable: true+ endTime:+ type: string+ format: date-time+ nullable: true+ completionStartTime:+ type: string+ format: date-time+ nullable: true+ model:+ type: string+ nullable: true+ modelParameters:+ type: object+ additionalProperties:+ $ref: '#/components/schemas/MapValue'+ nullable: true+ input:+ nullable: true+ version:+ type: string+ nullable: true+ metadata:+ nullable: true+ output:+ nullable: true+ usage:+ $ref: '#/components/schemas/Usage'+ nullable: true+ level:+ $ref: '#/components/schemas/ObservationLevel'+ nullable: true+ statusMessage:+ type: string+ nullable: true+ parentObservationId:+ type: string+ nullable: true+ environment:+ type: string+ nullable: true+ required:+ - type+ TraceBody:+ title: TraceBody+ type: object+ properties:+ id:+ type: string+ nullable: true+ timestamp:+ type: string+ format: date-time+ nullable: true+ name:+ type: string+ nullable: true+ userId:+ type: string+ nullable: true+ input:+ nullable: true+ output:+ nullable: true+ sessionId:+ type: string+ nullable: true+ release:+ type: string+ nullable: true+ version:+ type: string+ nullable: true+ metadata:+ nullable: true+ tags:+ type: array+ items:+ type: string+ nullable: true+ environment:+ type: stringnullable: true- totalTokens:- type: integer+ public:+ type: booleannullable: true- OptionalObservationBody:- title: OptionalObservationBody+ description: Make trace publicly accessible via url+ SDKLogBody:+ title: SDKLogBodytype: objectproperties:- traceId:+ log: {}+ required:+ - log+ ScoreBody:+ title: ScoreBody+ type: object+ properties:+ id:type: stringnullable: true- name:+ traceId:type: stringnullable: true- startTime:+ sessionId:type: string- format: date-time- nullable: true- metadata:nullable: true- input:- nullable: true- output:+ observationId:+ type: stringnullable: true- level:- $ref: '#/components/schemas/ObservationLevel'+ datasetRunId:+ type: stringnullable: true- statusMessage:+ name:+ type: string+ description: >-+ The name of the score. Always overrides "output" for correction+ scores.+ example: novelty+ environment:type: stringnullable: true- parentObservationId:+ queueId:type: stringnullable: true- version:+ description: >-+ The annotation queue referenced by the score. Indicates if score was+ initially created while processing annotation queue.+ value:+ $ref: '#/components/schemas/CreateScoreValue'+ description: >-+ The value of the score. Must be passed as string for categorical and+ text scores, and numeric for boolean and numeric scores. Boolean+ score values must equal either 1 or 0 (true or false). Text score+ values must be between 1 and 500 characters.+ comment:type: stringnullable: true- environment:+ metadata:+ nullable: true+ dataType:+ $ref: '#/components/schemas/ScoreDataType'+ nullable: true+ description: >-+ When set, must match the score value's type. If not set, will be+ inferred from the score value or config+ configId:type: stringnullable: true- CreateEventBody:- title: CreateEventBody+ description: >-+ Reference a score config on a score. When set, the score name must+ equal the config name and scores must comply with the config's range+ and data type. For categorical scores, the value must map to a+ config category. Numeric scores might be constrained by the score+ config's max and min values+ required:+ - name+ - value+ BaseEvent:+ title: BaseEventtype: objectproperties:id:type: string+ description: UUID v4 that identifies the event+ timestamp:+ type: string+ description: >-+ Datetime (ISO 8601) of event creation in client. Should be as close+ to actual event creation in client as possible, this timestamp will+ be used for ordering of events in future release. Resolution:+ milliseconds (required), microseconds (optimal).+ metadata:nullable: true+ description: Optional. Metadata field used by the Langfuse SDKs for debugging.+ required:+ - id+ - timestamp+ TraceEvent:+ title: TraceEvent+ type: object+ properties:+ body:+ $ref: '#/components/schemas/TraceBody'+ required:+ - bodyallOf:- - $ref: '#/components/schemas/OptionalObservationBody'- UpdateEventBody:- title: UpdateEventBody+ - $ref: '#/components/schemas/BaseEvent'+ CreateObservationEvent:+ title: CreateObservationEventtype: objectproperties:- id:- type: string+ body:+ $ref: '#/components/schemas/ObservationBody'required:- - id+ - bodyallOf:- - $ref: '#/components/schemas/OptionalObservationBody'- CreateSpanBody:- title: CreateSpanBody+ - $ref: '#/components/schemas/BaseEvent'+ UpdateObservationEvent:+ title: UpdateObservationEventtype: objectproperties:- endTime:- type: string- format: date-time- nullable: true+ body:+ $ref: '#/components/schemas/ObservationBody'+ required:+ - bodyallOf:- - $ref: '#/components/schemas/CreateEventBody'- UpdateSpanBody:- title: UpdateSpanBody+ - $ref: '#/components/schemas/BaseEvent'+ ScoreEvent:+ title: ScoreEventtype: objectproperties:- endTime:- type: string- format: date-time- nullable: true+ body:+ $ref: '#/components/schemas/ScoreBody'+ required:+ - bodyallOf:- - $ref: '#/components/schemas/UpdateEventBody'- CreateGenerationBody:- title: CreateGenerationBody+ - $ref: '#/components/schemas/BaseEvent'+ SDKLogEvent:+ title: SDKLogEventtype: objectproperties:- completionStartTime:+ body:+ $ref: '#/components/schemas/SDKLogBody'+ required:+ - body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'+ CreateGenerationEvent:+ title: CreateGenerationEvent+ type: object+ properties:+ body:+ $ref: '#/components/schemas/CreateGenerationBody'+ required:+ - body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'+ UpdateGenerationEvent:+ title: UpdateGenerationEvent+ type: object+ properties:+ body:+ $ref: '#/components/schemas/UpdateGenerationBody'+ required:+ - body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'+ CreateSpanEvent:+ title: CreateSpanEvent+ type: object+ properties:+ body:+ $ref: '#/components/schemas/CreateSpanBody'+ required:+ - body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'+ UpdateSpanEvent:+ title: UpdateSpanEvent+ type: object+ properties:+ body:+ $ref: '#/components/schemas/UpdateSpanBody'+ required:+ - body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'+ CreateEventEvent:+ title: CreateEventEvent+ type: object+ properties:+ body:+ $ref: '#/components/schemas/CreateEventBody'+ required:+ - body+ allOf:+ - $ref: '#/components/schemas/BaseEvent'+ IngestionSuccess:+ title: IngestionSuccess+ type: object+ properties:+ id:type: string- format: date-time- nullable: true- model:+ status:+ type: integer+ required:+ - id+ - status+ IngestionError:+ title: IngestionError+ type: object+ properties:+ id:+ type: string+ status:+ type: integer+ message:type: stringnullable: true- modelParameters:+ error:+ nullable: true+ required:+ - id+ - status+ IngestionResponse:+ title: IngestionResponse+ type: object+ properties:+ successes:+ type: array+ items:+ $ref: '#/components/schemas/IngestionSuccess'+ errors:+ type: array+ items:+ $ref: '#/components/schemas/IngestionError'+ required:+ - successes+ - errors+ OpenAICompletionUsageSchema:+ title: OpenAICompletionUsageSchema+ type: object+ description: OpenAI Usage schema from (Chat-)Completion APIs+ properties:+ prompt_tokens:+ type: integer+ completion_tokens:+ type: integer+ total_tokens:+ type: integer+ prompt_tokens_details:type: objectadditionalProperties:- $ref: '#/components/schemas/MapValue'- nullable: true- usage:- $ref: '#/components/schemas/IngestionUsage'- nullable: true- usageDetails:- $ref: '#/components/schemas/UsageDetails'+ type: integer+ nullable: truenullable: true- costDetails:+ completion_tokens_details:type: objectadditionalProperties:- type: number- format: double- nullable: true- promptName:- type: string- nullable: true- promptVersion:- type: integer+ type: integer+ nullable: truenullable: true- allOf:- - $ref: '#/components/schemas/CreateSpanBody'- UpdateGenerationBody:- title: UpdateGenerationBody+ required:+ - prompt_tokens+ - completion_tokens+ - total_tokens+ OpenAIResponseUsageSchema:+ title: OpenAIResponseUsageSchematype: object+ description: OpenAI Usage schema from Response APIproperties:- completionStartTime:- type: string- format: date-time- nullable: true- model:- type: string- nullable: true- modelParameters:+ input_tokens:+ type: integer+ output_tokens:+ type: integer+ total_tokens:+ type: integer+ input_tokens_details:type: objectadditionalProperties:- $ref: '#/components/schemas/MapValue'- nullable: true- usage:- $ref: '#/components/schemas/IngestionUsage'- nullable: true- promptName:- type: string- nullable: true- usageDetails:- $ref: '#/components/schemas/UsageDetails'+ type: integer+ nullable: truenullable: true- costDetails:+ output_tokens_details:type: objectadditionalProperties:- type: number- format: double- nullable: true- promptVersion:- type: integer+ type: integer+ nullable: truenullable: true- allOf:- - $ref: '#/components/schemas/UpdateSpanBody'- ObservationBody:- title: ObservationBody+ required:+ - input_tokens+ - output_tokens+ - total_tokens+ UsageDetails:+ title: UsageDetails+ oneOf:+ - type: object+ additionalProperties:+ type: integer+ - $ref: '#/components/schemas/OpenAICompletionUsageSchema'+ - $ref: '#/components/schemas/OpenAIResponseUsageSchema'+ legacyMetricsResponse:+ title: legacyMetricsResponsetype: objectproperties:- id:- type: string- nullable: true- traceId:- type: string- nullable: true- type:- $ref: '#/components/schemas/ObservationType'- name:- type: string- nullable: true- startTime:- type: string- format: date-time- nullable: true- endTime:- type: string- format: date-time- nullable: true- completionStartTime:- type: string- format: date-time- nullable: true- model:- type: string- nullable: true- modelParameters:- type: object- additionalProperties:- $ref: '#/components/schemas/MapValue'- nullable: true- input:- nullable: true- version:- type: string- nullable: true- metadata:- nullable: true- output:- nullable: true- usage:- $ref: '#/components/schemas/Usage'- nullable: true- level:- $ref: '#/components/schemas/ObservationLevel'- nullable: true- statusMessage:- type: string- nullable: true- parentObservationId:- type: string- nullable: true- environment:- type: string- nullable: true+ data:+ type: array+ items:+ type: object+ additionalProperties: true+ description: >-+ The metrics data. Each item in the list contains the metric values+ and dimensions requested in the query.++ Format varies based on the query parameters.++ Histograms will return an array with [lower, upper, height] tuples.required:- - type- TraceBody:- title: TraceBody+ - data+ legacyObservations:+ title: legacyObservationstype: objectproperties:- id:- type: string- nullable: true- timestamp:- type: string- format: date-time- nullable: true- name:- type: string- nullable: true- userId:- type: string- nullable: true- input:- nullable: true- output:- nullable: true- sessionId:- type: string- nullable: true- release:- type: string- nullable: true- version:- type: string- nullable: true- metadata:- nullable: true- tags:+ data:type: arrayitems:- type: string- nullable: true- environment:- type: string- nullable: true- public:- type: boolean- nullable: true- description: Make trace publicly accessible via url- SDKLogBody:- title: SDKLogBody+ $ref: '#/components/schemas/Observation'+ meta:+ $ref: '#/components/schemas/utilsMetaResponse'+ required:+ - data+ - meta+ legacyObservationsViews:+ title: legacyObservationsViewstype: objectproperties:- log: {}+ data:+ type: array+ items:+ $ref: '#/components/schemas/ObservationsView'+ meta:+ $ref: '#/components/schemas/utilsMetaResponse'required:- - log- ScoreBody:- title: ScoreBody+ - data+ - meta+ legacyCreateScoreRequest:+ title: legacyCreateScoreRequesttype: objectproperties:id:@@ -8973,19 +10189,7 @@ components:nullable: truename:type: string- description: >-- The name of the score. Always overrides "output" for correction- scores.example: novelty- environment:- type: string- nullable: true- queueId:- type: string- nullable: true- description: >-- The annotation queue referenced by the score. Indicates if score was- initially created while processing annotation queue.value:$ref: '#/components/schemas/CreateScoreValue'description: >-@@ -8997,251 +10201,351 @@ components:type: stringnullable: truemetadata:+ type: object+ additionalProperties: true+ nullable: true+ environment:+ type: stringnullable: true+ description: >-+ The environment of the score. Can be any lowercase alphanumeric+ string with hyphens and underscores that does not start with+ 'langfuse'.+ queueId:+ type: string+ nullable: true+ description: >-+ The annotation queue referenced by the score. Indicates if score was+ initially created while processing annotation queue.dataType:$ref: '#/components/schemas/ScoreDataType'nullable: truedescription: >-- When set, must match the score value's type. If not set, will be- inferred from the score value or config+ The data type of the score. When passing a configId this field is+ inferred. Otherwise, this field must be passed or will default to+ numeric.configId:type: stringnullable: truedescription: >-- Reference a score config on a score. When set, the score name must- equal the config name and scores must comply with the config's range- and data type. For categorical scores, the value must map to a- config category. Numeric scores might be constrained by the score- config's max and min values+ Reference a score config on a score. The unique langfuse identifier+ of a score config. When passing this field, the dataType and+ stringValue fields are automatically populated.required:- name- value- BaseEvent:- title: BaseEvent+ legacyCreateScoreResponse:+ title: legacyCreateScoreResponsetype: objectproperties:id:type: string- description: UUID v4 that identifies the event- timestamp:- type: string- description: >-- Datetime (ISO 8601) of event creation in client. Should be as close- to actual event creation in client as possible, this timestamp will- be used for ordering of events in future release. Resolution:- milliseconds (required), microseconds (optimal).- metadata:- nullable: true- description: Optional. Metadata field used by the Langfuse SDKs for debugging.+ description: The id of the created object in Langfuserequired:- id- - timestamp- TraceEvent:- title: TraceEvent- type: object- properties:- body:- $ref: '#/components/schemas/TraceBody'- required:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- CreateObservationEvent:- title: CreateObservationEvent- type: object- properties:- body:- $ref: '#/components/schemas/ObservationBody'- required:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- UpdateObservationEvent:- title: UpdateObservationEvent- type: object- properties:- body:- $ref: '#/components/schemas/ObservationBody'- required:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- ScoreEvent:- title: ScoreEvent- type: object- properties:- body:- $ref: '#/components/schemas/ScoreBody'- required:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- SDKLogEvent:- title: SDKLogEvent- type: object- properties:- body:- $ref: '#/components/schemas/SDKLogBody'- required:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- CreateGenerationEvent:- title: CreateGenerationEvent- type: object- properties:- body:- $ref: '#/components/schemas/CreateGenerationBody'- required:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- UpdateGenerationEvent:- title: UpdateGenerationEvent+ LlmConnection:+ title: LlmConnectiontype: object+ description: LLM API connection configuration (secrets excluded)properties:- body:- $ref: '#/components/schemas/UpdateGenerationBody'+ id:+ type: string+ provider:+ type: string+ description: >-+ Provider name (e.g., 'openai', 'my-gateway'). Must be unique in+ project, used for upserting.+ adapter:+ type: string+ description: The adapter used to interface with the LLM+ displaySecretKey:+ type: string+ description: Masked version of the secret key for display purposes+ baseURL:+ type: string+ nullable: true+ description: Custom base URL for the LLM API+ customModels:+ type: array+ items:+ type: string+ description: List of custom model names available for this connection+ withDefaultModels:+ type: boolean+ description: Whether to include default models for this adapter+ extraHeaderKeys:+ type: array+ items:+ type: string+ description: >-+ Keys of extra headers sent with requests (values excluded for+ security)+ config:+ type: object+ additionalProperties: true+ nullable: true+ description: >-+ Adapter-specific configuration. Required for Bedrock+ (`{"region":"us-east-1"}`), optional for VertexAI+ (`{"location":"us-central1"}`), not used by other adapters.+ createdAt:+ type: string+ format: date-time+ updatedAt:+ type: string+ format: date-timerequired:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- CreateSpanEvent:- title: CreateSpanEvent+ - id+ - provider+ - adapter+ - displaySecretKey+ - customModels+ - withDefaultModels+ - extraHeaderKeys+ - createdAt+ - updatedAt+ PaginatedLlmConnections:+ title: PaginatedLlmConnectionstype: objectproperties:- body:- $ref: '#/components/schemas/CreateSpanBody'+ data:+ type: array+ items:+ $ref: '#/components/schemas/LlmConnection'+ meta:+ $ref: '#/components/schemas/utilsMetaResponse'required:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- UpdateSpanEvent:- title: UpdateSpanEvent+ - data+ - meta+ UpsertLlmConnectionRequest:+ title: UpsertLlmConnectionRequesttype: object+ description: Request to create or update an LLM connection (upsert)properties:- body:- $ref: '#/components/schemas/UpdateSpanBody'+ provider:+ type: string+ description: >-+ Provider name (e.g., 'openai', 'my-gateway'). Must be unique in+ project, used for upserting.+ adapter:+ $ref: '#/components/schemas/LlmAdapter'+ description: The adapter used to interface with the LLM+ secretKey:+ type: string+ description: Secret key for the LLM API.+ baseURL:+ type: string+ nullable: true+ description: Custom base URL for the LLM API+ customModels:+ type: array+ items:+ type: string+ nullable: true+ description: List of custom model names+ withDefaultModels:+ type: boolean+ nullable: true+ description: Whether to include default models. Default is true.+ extraHeaders:+ type: object+ additionalProperties:+ type: string+ nullable: true+ description: Extra headers to send with requests+ config:+ type: object+ additionalProperties: true+ nullable: true+ description: >-+ Adapter-specific configuration. Validation rules: - **Bedrock**:+ Required. Must be `{"region": "<aws-region>"}` (e.g.,+ `{"region":"us-east-1"}`) - **VertexAI**: Optional. If provided,+ must be `{"location": "<gcp-location>"}` (e.g.,+ `{"location":"us-central1"}`) - **Other adapters**: Not supported.+ Omit this field or set to null.required:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- CreateEventEvent:- title: CreateEventEvent+ - provider+ - adapter+ - secretKey+ DeleteLlmConnectionResponse:+ title: DeleteLlmConnectionResponsetype: objectproperties:- body:- $ref: '#/components/schemas/CreateEventBody'+ message:+ type: stringrequired:- - body- allOf:- - $ref: '#/components/schemas/BaseEvent'- IngestionSuccess:- title: IngestionSuccess+ - message+ LlmAdapter:+ title: LlmAdapter+ type: string+ enum:+ - anthropic+ - openai+ - azure+ - bedrock+ - google-vertex-ai+ - google-ai-studio+ GetMediaResponse:+ title: GetMediaResponsetype: objectproperties:- id:+ mediaId:type: string- status:+ description: The unique langfuse identifier of a media record+ contentType:+ type: string+ description: The MIME type of the media record+ contentLength:type: integer+ description: The size of the media record in bytes+ uploadedAt:+ type: string+ format: date-time+ description: The date and time when the media record was uploaded+ url:+ type: string+ description: The download URL of the media record+ urlExpiry:+ type: string+ description: The expiry date and time of the media record download URLrequired:- - id- - status- IngestionError:- title: IngestionError+ - mediaId+ - contentType+ - contentLength+ - uploadedAt+ - url+ - urlExpiry+ PatchMediaBody:+ title: PatchMediaBodytype: objectproperties:- id:+ uploadedAt:type: string- status:+ format: date-time+ description: The date and time when the media record was uploaded+ uploadHttpStatus:type: integer- message:+ description: The HTTP status code of the upload+ uploadHttpError:type: stringnullable: true- error:+ description: The HTTP error message of the upload+ uploadTimeMs:+ type: integernullable: true+ description: The time in milliseconds it took to upload the media recordrequired:- - id- - status- IngestionResponse:- title: IngestionResponse- type: object- properties:- successes:- type: array- items:- $ref: '#/components/schemas/IngestionSuccess'- errors:- type: array- items:- $ref: '#/components/schemas/IngestionError'- required:- - successes- - errors- OpenAICompletionUsageSchema:- title: OpenAICompletionUsageSchema+ - uploadedAt+ - uploadHttpStatus+ GetMediaUploadUrlRequest:+ title: GetMediaUploadUrlRequesttype: object- description: OpenAI Usage schema from (Chat-)Completion APIsproperties:- prompt_tokens:- type: integer- completion_tokens:- type: integer- total_tokens:- type: integer- prompt_tokens_details:- type: object- additionalProperties:- type: integer- nullable: true- nullable: true- completion_tokens_details:- type: object- additionalProperties:- type: integer- nullable: true+ traceId:+ type: string+ description: The trace ID associated with the media record+ observationId:+ type: stringnullable: true+ description: >-+ The observation ID associated with the media record. If the media+ record is associated directly with a trace, this will be null.+ contentType:+ $ref: '#/components/schemas/MediaContentType'+ contentLength:+ type: integer+ description: The size of the media record in bytes+ sha256Hash:+ type: string+ description: The SHA-256 hash of the media record+ field:+ type: string+ description: >-+ The trace / observation field the media record is associated with.+ This can be one of `input`, `output`, `metadata`required:- - prompt_tokens- - completion_tokens- - total_tokens- OpenAIResponseUsageSchema:- title: OpenAIResponseUsageSchema+ - traceId+ - contentType+ - contentLength+ - sha256Hash+ - field+ GetMediaUploadUrlResponse:+ title: GetMediaUploadUrlResponsetype: object- description: OpenAI Usage schema from Response APIproperties:- input_tokens:- type: integer- output_tokens:- type: integer- total_tokens:- type: integer- input_tokens_details:- type: object- additionalProperties:- type: integer- nullable: true- nullable: true- output_tokens_details:- type: object- additionalProperties:- type: integer- nullable: true+ uploadUrl:+ type: stringnullable: true+ description: >-+ The presigned upload URL. If the asset is already uploaded, this+ will be null+ mediaId:+ type: string+ description: The unique langfuse identifier of a media recordrequired:- - input_tokens- - output_tokens- - total_tokens- UsageDetails:- title: UsageDetails- oneOf:- - type: object- additionalProperties:- type: integer- - $ref: '#/components/schemas/OpenAICompletionUsageSchema'- - $ref: '#/components/schemas/OpenAIResponseUsageSchema'- legacyMetricsResponse:- title: legacyMetricsResponse+ - mediaId+ MediaContentType:+ title: MediaContentType+ type: string+ enum:+ - image/png+ - image/jpeg+ - image/jpg+ - image/webp+ - image/gif+ - image/svg+xml+ - image/tiff+ - image/bmp+ - image/avif+ - image/heic+ - audio/mpeg+ - audio/mp3+ - audio/wav+ - audio/ogg+ - audio/oga+ - audio/aac+ - audio/mp4+ - audio/flac+ - audio/opus+ - audio/webm+ - video/mp4+ - video/webm+ - video/ogg+ - video/mpeg+ - video/quicktime+ - video/x-msvideo+ - video/x-matroska+ - text/plain+ - text/html+ - text/css+ - text/csv+ - text/markdown+ - text/x-python+ - application/javascript+ - text/x-typescript+ - application/x-yaml+ - application/pdf+ - application/msword+ - application/vnd.ms-excel+ - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet+ - application/zip+ - application/json+ - application/xml+ - application/octet-stream+ - >-+ application/vnd.openxmlformats-officedocument.wordprocessingml.document+ - >-+ application/vnd.openxmlformats-officedocument.presentationml.presentation+ - application/rtf+ - application/x-ndjson+ - application/vnd.apache.parquet+ - application/gzip+ - application/x-tar+ - application/x-7z-compressed+ description: The MIME type of the media record+ MetricsV2Response:+ title: MetricsV2Responsetype: objectproperties:data:@@ -9258,1826 +10562,2975 @@ components:Histograms will return an array with [lower, upper, height] tuples.required:- data- legacyObservations:- title: legacyObservations- type: object- properties:- data:- type: array- items:- $ref: '#/components/schemas/Observation'- meta:- $ref: '#/components/schemas/utilsMetaResponse'- required:- - data- - meta- legacyObservationsViews:- title: legacyObservationsViews+ PaginatedModels:+ title: PaginatedModelstype: objectproperties:data:type: arrayitems:- $ref: '#/components/schemas/ObservationsView'+ $ref: '#/components/schemas/Model'meta:$ref: '#/components/schemas/utilsMetaResponse'required:- data- meta- legacyCreateScoreRequest:- title: legacyCreateScoreRequest- type: object- properties:- id:- type: string- nullable: true- traceId:- type: string- nullable: true- sessionId:- type: string- nullable: true- observationId:- type: string- nullable: true- datasetRunId:+ CreateModelRequest:+ title: CreateModelRequest+ type: object+ properties:+ modelName:type: string- nullable: true- name:+ description: >-+ Name of the model definition. If multiple with the same name exist,+ they are applied in the following order: (1) custom over built-in,+ (2) newest according to startTime where+ model.startTime<observation.startTime+ matchPattern:type: string- example: novelty- value:- $ref: '#/components/schemas/CreateScoreValue'description: >-- The value of the score. Must be passed as string for categorical and- text scores, and numeric for boolean and numeric scores. Boolean- score values must equal either 1 or 0 (true or false). Text score- values must be between 1 and 500 characters.- comment:+ Regex pattern which matches this model definition to+ generation.model. Useful in case of fine-tuned models. If you want+ to exact match, use `(?i)^modelname$`+ startDate:type: string+ format: date-timenullable: true- metadata:- type: object- additionalProperties: true+ description: Apply only to generations which are newer than this ISO date.+ unit:+ $ref: '#/components/schemas/ModelUsageUnit'nullable: true- environment:- type: string+ description: Unit used by this model.+ inputPrice:+ type: number+ format: doublenullable: truedescription: >-- The environment of the score. Can be any lowercase alphanumeric- string with hyphens and underscores that does not start with- 'langfuse'.- queueId:- type: string+ Deprecated. Use 'pricingTiers' instead. Price (USD) per input unit.+ Creates a default tier if pricingTiers not provided.+ outputPrice:+ type: number+ format: doublenullable: truedescription: >-- The annotation queue referenced by the score. Indicates if score was- initially created while processing annotation queue.- dataType:- $ref: '#/components/schemas/ScoreDataType'+ Deprecated. Use 'pricingTiers' instead. Price (USD) per output unit.+ Creates a default tier if pricingTiers not provided.+ totalPrice:+ type: number+ format: doublenullable: truedescription: >-- The data type of the score. When passing a configId this field is- inferred. Otherwise, this field must be passed or will default to- numeric.- configId:- type: string+ Deprecated. Use 'pricingTiers' instead. Price (USD) per total units.+ Cannot be set if input or output price is set. Creates a default+ tier if pricingTiers not provided.+ pricingTiers:+ type: array+ items:+ $ref: '#/components/schemas/PricingTierInput'nullable: truedescription: >-- Reference a score config on a score. The unique langfuse identifier- of a score config. When passing this field, the dataType and- stringValue fields are automatically populated.- required:- - name- - value- legacyCreateScoreResponse:- title: legacyCreateScoreResponse- type: object- properties:- id:- type: string- description: The id of the created object in Langfuse- required:- - id- LlmConnection:- title: LlmConnection- type: object- description: LLM API connection configuration (secrets excluded)- properties:- id:- type: string- provider:- type: string- description: >-- Provider name (e.g., 'openai', 'my-gateway'). Must be unique in- project, used for upserting.- adapter:- type: string- description: The adapter used to interface with the LLM- displaySecretKey:- type: string- description: Masked version of the secret key for display purposes- baseURL:+ Optional. Array of pricing tiers for this model.+++ Use pricing tiers for all models - both those with threshold-based+ pricing variations and those with simple flat pricing:+++ - For models with standard flat pricing: Create a single default+ tier with your prices+ (e.g., one tier with isDefault=true, priority=0, conditions=[], and your standard prices)++ - For models with threshold-based pricing: Create a default tier+ plus additional conditional tiers+ (e.g., default tier for standard usage + high-volume tier for usage above certain thresholds)++ Requirements:++ - Cannot be provided with flat prices+ (inputPrice/outputPrice/totalPrice) - use one approach or the other++ - Must include exactly one default tier with isDefault=true,+ priority=0, and conditions=[]++ - All tier names and priorities must be unique within the model++ - Each tier must define at least one price+++ If omitted, you must provide flat prices instead+ (inputPrice/outputPrice/totalPrice),++ which will automatically create a single default tier named+ "Standard".+ tokenizerId:type: stringnullable: true- description: Custom base URL for the LLM API- customModels:- type: array- items:- type: string- description: List of custom model names available for this connection- withDefaultModels:- type: boolean- description: Whether to include default models for this adapter- extraHeaderKeys:- type: array- items:- type: stringdescription: >-- Keys of extra headers sent with requests (values excluded for- security)- config:- type: object- additionalProperties: true+ Optional. Tokenizer to be applied to observations which match to+ this model. See docs for more details.+ tokenizerConfig:nullable: truedescription: >-- Adapter-specific configuration. Required for Bedrock- (`{"region":"us-east-1"}`), optional for VertexAI- (`{"location":"us-central1"}`), not used by other adapters.- createdAt:- type: string- format: date-time- updatedAt:- type: string- format: date-time+ Optional. Configuration for the selected tokenizer. Needs to be+ JSON. See docs for more details.required:- - id- - provider- - adapter- - displaySecretKey- - customModels- - withDefaultModels- - extraHeaderKeys- - createdAt- - updatedAt- PaginatedLlmConnections:- title: PaginatedLlmConnections+ - modelName+ - matchPattern+ ObservationsV2Response:+ title: ObservationsV2Responsetype: object+ description: >-+ Response containing observations with field-group-based filtering and+ cursor-based pagination.+++ The `data` array contains observation objects with only the requested+ field groups included.++ Use the `cursor` in `meta` to retrieve the next page of results.properties:data:type: arrayitems:- $ref: '#/components/schemas/LlmConnection'+ $ref: '#/components/schemas/ObservationV2'+ description: >-+ Array of observation objects. Fields included depend on the `fields`+ parameter in the request.meta:- $ref: '#/components/schemas/utilsMetaResponse'+ $ref: '#/components/schemas/ObservationsV2Meta'required:- data- meta- UpsertLlmConnectionRequest:- title: UpsertLlmConnectionRequest+ ObservationsV2Meta:+ title: ObservationsV2Metatype: object- description: Request to create or update an LLM connection (upsert)+ description: Metadata for cursor-based paginationproperties:- provider:+ cursor:type: string+ nullable: truedescription: >-- Provider name (e.g., 'openai', 'my-gateway'). Must be unique in- project, used for upserting.- adapter:- $ref: '#/components/schemas/LlmAdapter'- description: The adapter used to interface with the LLM- secretKey:+ Base64-encoded cursor to use for retrieving the next page. If not+ present, there are no more results.+ OtelResourceSpan:+ title: OtelResourceSpan+ type: object+ description: >-+ Represents a collection of spans from a single resource as per OTLP+ specification+ properties:+ resource:+ $ref: '#/components/schemas/OtelResource'+ nullable: true+ description: Resource information+ scopeSpans:+ type: array+ items:+ $ref: '#/components/schemas/OtelScopeSpan'+ nullable: true+ description: Array of scope spans+ OtelResource:+ title: OtelResource+ type: object+ description: Resource attributes identifying the source of telemetry+ properties:+ attributes:+ type: array+ items:+ $ref: '#/components/schemas/OtelAttribute'+ nullable: true+ description: Resource attributes like service.name, service.version, etc.+ OtelScopeSpan:+ title: OtelScopeSpan+ type: object+ description: Collection of spans from a single instrumentation scope+ properties:+ scope:+ $ref: '#/components/schemas/OtelScope'+ nullable: true+ description: Instrumentation scope information+ spans:+ type: array+ items:+ $ref: '#/components/schemas/OtelSpan'+ nullable: true+ description: Array of spans+ OtelScope:+ title: OtelScope+ type: object+ description: Instrumentation scope information+ properties:+ name:type: string- description: Secret key for the LLM API.- baseURL:+ nullable: true+ description: Instrumentation scope name+ version:type: stringnullable: true- description: Custom base URL for the LLM API- customModels:+ description: Instrumentation scope version+ attributes:type: arrayitems:- type: string+ $ref: '#/components/schemas/OtelAttribute'nullable: true- description: List of custom model names- withDefaultModels:- type: boolean+ description: Additional scope attributes+ OtelSpan:+ title: OtelSpan+ type: object+ description: Individual span representing a unit of work or operation+ properties:+ traceId:nullable: true- description: Whether to include default models. Default is true.- extraHeaders:- type: object- additionalProperties:- type: string+ description: Trace ID (16 bytes, hex-encoded string in JSON or Buffer in binary)+ spanId:nullable: true- description: Extra headers to send with requests- config:- type: object- additionalProperties: true+ description: Span ID (8 bytes, hex-encoded string in JSON or Buffer in binary)+ parentSpanId:+ nullable: true+ description: Parent span ID if this is a child span+ name:+ type: string+ nullable: true+ description: Span name describing the operation+ kind:+ type: integer+ nullable: true+ description: Span kind (1=INTERNAL, 2=SERVER, 3=CLIENT, 4=PRODUCER, 5=CONSUMER)+ startTimeUnixNano:+ nullable: true+ description: Start time in nanoseconds since Unix epoch+ endTimeUnixNano:+ nullable: true+ description: End time in nanoseconds since Unix epoch+ attributes:+ type: array+ items:+ $ref: '#/components/schemas/OtelAttribute'nullable: truedescription: >-- Adapter-specific configuration. Validation rules: - **Bedrock**:- Required. Must be `{"region": "<aws-region>"}` (e.g.,- `{"region":"us-east-1"}`) - **VertexAI**: Optional. If provided,- must be `{"location": "<gcp-location>"}` (e.g.,- `{"location":"us-central1"}`) - **Other adapters**: Not supported.- Omit this field or set to null.- required:- - provider- - adapter- - secretKey- DeleteLlmConnectionResponse:- title: DeleteLlmConnectionResponse+ Span attributes including Langfuse-specific attributes+ (langfuse.observation.*)+ status:+ nullable: true+ description: Span status object+ OtelAttribute:+ title: OtelAttributetype: object+ description: Key-value attribute pair for resources, scopes, or spansproperties:- message:+ key:type: string- required:- - message- LlmAdapter:- title: LlmAdapter+ nullable: true+ description: Attribute key (e.g., "service.name", "langfuse.observation.type")+ value:+ $ref: '#/components/schemas/OtelAttributeValue'+ nullable: true+ description: Attribute value+ OtelAttributeValue:+ title: OtelAttributeValue+ type: object+ description: Attribute value wrapper supporting different value types+ properties:+ stringValue:+ type: string+ nullable: true+ description: String value+ intValue:+ type: integer+ nullable: true+ description: Integer value+ doubleValue:+ type: number+ format: double+ nullable: true+ description: Double value+ boolValue:+ type: boolean+ nullable: true+ description: Boolean value+ OtelTraceResponse:+ title: OtelTraceResponse+ type: object+ description: Response from trace export request. Empty object indicates success.+ properties: {}+ MembershipRole:+ title: MembershipRoletype: stringenum:- - anthropic- - openai- - azure- - bedrock- - google-vertex-ai- - google-ai-studio- GetMediaResponse:- title: GetMediaResponse+ - OWNER+ - ADMIN+ - MEMBER+ - VIEWER+ MembershipRequest:+ title: MembershipRequesttype: objectproperties:- mediaId:+ userId:type: string- description: The unique langfuse identifier of a media record- contentType:+ role:+ $ref: '#/components/schemas/MembershipRole'+ required:+ - userId+ - role+ DeleteMembershipRequest:+ title: DeleteMembershipRequest+ type: object+ properties:+ userId:type: string- description: The MIME type of the media record- contentLength:- type: integer- description: The size of the media record in bytes- uploadedAt:+ required:+ - userId+ MembershipResponse:+ title: MembershipResponse+ type: object+ properties:+ userId:type: string- format: date-time- description: The date and time when the media record was uploaded- url:+ role:+ $ref: '#/components/schemas/MembershipRole'+ email:type: string- description: The download URL of the media record- urlExpiry:+ name:type: string- description: The expiry date and time of the media record download URLrequired:- - mediaId- - contentType- - contentLength- - uploadedAt- - url- - urlExpiry- PatchMediaBody:- title: PatchMediaBody+ - userId+ - role+ - name+ MembershipDeletionResponse:+ title: MembershipDeletionResponsetype: objectproperties:- uploadedAt:+ message:type: string- format: date-time- description: The date and time when the media record was uploaded- uploadHttpStatus:- type: integer- description: The HTTP status code of the upload- uploadHttpError:+ userId:type: string- nullable: true- description: The HTTP error message of the upload- uploadTimeMs:- type: integer- nullable: true- description: The time in milliseconds it took to upload the media recordrequired:- - uploadedAt- - uploadHttpStatus- GetMediaUploadUrlRequest:- title: GetMediaUploadUrlRequest+ - message+ - userId+ MembershipsResponse:+ title: MembershipsResponsetype: objectproperties:- traceId:+ memberships:+ type: array+ items:+ $ref: '#/components/schemas/MembershipResponse'+ required:+ - memberships+ OrganizationProject:+ title: OrganizationProject+ type: object+ properties:+ id:type: string- description: The trace ID associated with the media record- observationId:+ name:type: string+ metadata:+ type: object+ additionalProperties: truenullable: true- description: >-- The observation ID associated with the media record. If the media- record is associated directly with a trace, this will be null.- contentType:- $ref: '#/components/schemas/MediaContentType'- contentLength:- type: integer- description: The size of the media record in bytes- sha256Hash:+ createdAt:type: string- description: The SHA-256 hash of the media record- field:+ format: date-time+ updatedAt:type: string- description: >-- The trace / observation field the media record is associated with.- This can be one of `input`, `output`, `metadata`+ format: date-time+ required:+ - id+ - name+ - createdAt+ - updatedAt+ OrganizationProjectsResponse:+ title: OrganizationProjectsResponse+ type: object+ properties:+ projects:+ type: array+ items:+ $ref: '#/components/schemas/OrganizationProject'required:- - traceId- - contentType- - contentLength- - sha256Hash- - field- GetMediaUploadUrlResponse:- title: GetMediaUploadUrlResponse+ - projects+ OrganizationApiKey:+ title: OrganizationApiKeytype: objectproperties:- uploadUrl:+ id:type: string+ createdAt:+ type: string+ format: date-time+ expiresAt:+ type: string+ format: date-timenullable: true- description: >-- The presigned upload URL. If the asset is already uploaded, this- will be null- mediaId:+ lastUsedAt:+ type: string+ format: date-time+ nullable: true+ note:+ type: string+ nullable: true+ publicKey:+ type: string+ displaySecretKey:type: string- description: The unique langfuse identifier of a media recordrequired:- - mediaId- MediaContentType:- title: MediaContentType- type: string- enum:- - image/png- - image/jpeg- - image/jpg- - image/webp- - image/gif- - image/svg+xml- - image/tiff- - image/bmp- - image/avif- - image/heic- - audio/mpeg- - audio/mp3- - audio/wav- - audio/ogg- - audio/oga- - audio/aac- - audio/mp4- - audio/flac- - audio/opus- - audio/webm- - video/mp4- - video/webm- - video/ogg- - video/mpeg- - video/quicktime- - video/x-msvideo- - video/x-matroska- - text/plain- - text/html- - text/css- - text/csv- - text/markdown- - text/x-python- - application/javascript- - text/x-typescript- - application/x-yaml- - application/pdf- - application/msword- - application/vnd.ms-excel- - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet- - application/zip- - application/json- - application/xml- - application/octet-stream- - >-- application/vnd.openxmlformats-officedocument.wordprocessingml.document- - >-- application/vnd.openxmlformats-officedocument.presentationml.presentation- - application/rtf- - application/x-ndjson- - application/vnd.apache.parquet- - application/gzip- - application/x-tar- - application/x-7z-compressed- description: The MIME type of the media record- MetricsV2Response:- title: MetricsV2Response+ - id+ - createdAt+ - publicKey+ - displaySecretKey+ OrganizationApiKeysResponse:+ title: OrganizationApiKeysResponsetype: objectproperties:- data:+ apiKeys:type: arrayitems:- type: object- additionalProperties: true- description: >-- The metrics data. Each item in the list contains the metric values- and dimensions requested in the query.-- Format varies based on the query parameters.-- Histograms will return an array with [lower, upper, height] tuples.+ $ref: '#/components/schemas/OrganizationApiKey'required:- - data- PaginatedModels:- title: PaginatedModels+ - apiKeys+ Projects:+ title: Projectstype: objectproperties:data:type: arrayitems:- $ref: '#/components/schemas/Model'- meta:- $ref: '#/components/schemas/utilsMetaResponse'+ $ref: '#/components/schemas/Project'required:- data- - meta- CreateModelRequest:- title: CreateModelRequest+ Organization:+ title: Organizationtype: objectproperties:- modelName:+ id:type: string- description: >-- Name of the model definition. If multiple with the same name exist,- they are applied in the following order: (1) custom over built-in,- (2) newest according to startTime where- model.startTime<observation.startTime- matchPattern:+ description: The unique identifier of the organization+ name:type: string- description: >-- Regex pattern which matches this model definition to- generation.model. Useful in case of fine-tuned models. If you want- to exact match, use `(?i)^modelname$`- startDate:+ description: The name of the organization+ required:+ - id+ - name+ Project:+ title: Project+ type: object+ properties:+ id:type: string- format: date-time- nullable: true- description: Apply only to generations which are newer than this ISO date.- unit:- $ref: '#/components/schemas/ModelUsageUnit'- nullable: true- description: Unit used by this model.- inputPrice:- type: number- format: double- nullable: true- description: >-- Deprecated. Use 'pricingTiers' instead. Price (USD) per input unit.- Creates a default tier if pricingTiers not provided.- outputPrice:- type: number- format: double- nullable: true- description: >-- Deprecated. Use 'pricingTiers' instead. Price (USD) per output unit.- Creates a default tier if pricingTiers not provided.- totalPrice:- type: number- format: double- nullable: true- description: >-- Deprecated. Use 'pricingTiers' instead. Price (USD) per total units.- Cannot be set if input or output price is set. Creates a default- tier if pricingTiers not provided.- pricingTiers:- type: array- items:- $ref: '#/components/schemas/PricingTierInput'+ name:+ type: string+ organization:+ $ref: '#/components/schemas/Organization'+ description: The organization this project belongs to+ metadata:+ type: object+ additionalProperties: true+ description: Metadata for the project+ retentionDays:+ type: integernullable: truedescription: >-- Optional. Array of pricing tiers for this model.--- Use pricing tiers for all models - both those with threshold-based- pricing variations and those with simple flat pricing:--- - For models with standard flat pricing: Create a single default- tier with your prices- (e.g., one tier with isDefault=true, priority=0, conditions=[], and your standard prices)-- - For models with threshold-based pricing: Create a default tier- plus additional conditional tiers- (e.g., default tier for standard usage + high-volume tier for usage above certain thresholds)-- Requirements:-- - Cannot be provided with flat prices- (inputPrice/outputPrice/totalPrice) - use one approach or the other-- - Must include exactly one default tier with isDefault=true,- priority=0, and conditions=[]-- - All tier names and priorities must be unique within the model-- - Each tier must define at least one price--- If omitted, you must provide flat prices instead- (inputPrice/outputPrice/totalPrice),-- which will automatically create a single default tier named- "Standard".- tokenizerId:+ Number of days to retain data. Null or 0 means no retention. Omitted+ if no retention is configured.+ required:+ - id+ - name+ - organization+ - metadata+ ProjectDeletionResponse:+ title: ProjectDeletionResponse+ type: object+ properties:+ success:+ type: boolean+ message:+ type: string+ required:+ - success+ - message+ ApiKeyList:+ title: ApiKeyList+ type: object+ description: List of API keys for a project+ properties:+ apiKeys:+ type: array+ items:+ $ref: '#/components/schemas/ApiKeySummary'+ required:+ - apiKeys+ ApiKeySummary:+ title: ApiKeySummary+ type: object+ description: Summary of an API key+ properties:+ id:+ type: string+ createdAt:+ type: string+ format: date-time+ expiresAt:type: string+ format: date-timenullable: true- description: >-- Optional. Tokenizer to be applied to observations which match to- this model. See docs for more details.- tokenizerConfig:+ lastUsedAt:+ type: string+ format: date-timenullable: true- description: >-- Optional. Configuration for the selected tokenizer. Needs to be- JSON. See docs for more details.+ note:+ type: string+ nullable: true+ publicKey:+ type: string+ displaySecretKey:+ type: stringrequired:- - modelName- - matchPattern- ObservationsV2Response:- title: ObservationsV2Response+ - id+ - createdAt+ - publicKey+ - displaySecretKey+ ApiKeyResponse:+ title: ApiKeyResponse+ type: object+ description: Response for API key creation+ properties:+ id:+ type: string+ createdAt:+ type: string+ format: date-time+ publicKey:+ type: string+ secretKey:+ type: string+ displaySecretKey:+ type: string+ note:+ type: string+ nullable: true+ required:+ - id+ - createdAt+ - publicKey+ - secretKey+ - displaySecretKey+ ApiKeyDeletionResponse:+ title: ApiKeyDeletionResponse+ type: object+ description: Response for API key deletion+ properties:+ success:+ type: boolean+ required:+ - success+ PromptMetaListResponse:+ title: PromptMetaListResponsetype: object- description: >-- Response containing observations with field-group-based filtering and- cursor-based pagination.--- The `data` array contains observation objects with only the requested- field groups included.-- Use the `cursor` in `meta` to retrieve the next page of results.properties:data:type: arrayitems:- $ref: '#/components/schemas/ObservationV2'- description: >-- Array of observation objects. Fields included depend on the `fields`- parameter in the request.+ $ref: '#/components/schemas/PromptMeta'meta:- $ref: '#/components/schemas/ObservationsV2Meta'+ $ref: '#/components/schemas/utilsMetaResponse'required:- data- meta- ObservationsV2Meta:- title: ObservationsV2Meta+ PromptMeta:+ title: PromptMetatype: object- description: Metadata for cursor-based paginationproperties:- cursor:+ name:type: string- nullable: true+ type:+ $ref: '#/components/schemas/PromptType'+ description: Indicates whether the prompt is a text or chat prompt.+ versions:+ type: array+ items:+ type: integer+ labels:+ type: array+ items:+ type: string+ tags:+ type: array+ items:+ type: string+ lastUpdatedAt:+ type: string+ format: date-time+ lastConfig:description: >-- Base64-encoded cursor to use for retrieving the next page. If not- present, there are no more results.- OtelResourceSpan:- title: OtelResourceSpan+ Config object of the most recent prompt version that matches the+ filters (if any are provided)+ required:+ - name+ - type+ - versions+ - labels+ - tags+ - lastUpdatedAt+ - lastConfig+ CreatePromptRequest:+ title: CreatePromptRequest+ oneOf:+ - $ref: '#/components/schemas/CreateChatPromptRequest'+ - $ref: '#/components/schemas/CreateTextPromptRequest'+ CreateChatPromptRequest:+ title: CreateChatPromptRequesttype: object- description: >-- Represents a collection of spans from a single resource as per OTLP- specificationproperties:- resource:- $ref: '#/components/schemas/OtelResource'- nullable: true- description: Resource information- scopeSpans:+ name:+ type: string+ prompt:type: arrayitems:- $ref: '#/components/schemas/OtelScopeSpan'+ $ref: '#/components/schemas/ChatMessageWithPlaceholders'+ config:nullable: true- description: Array of scope spans- OtelResource:- title: OtelResource- type: object- description: Resource attributes identifying the source of telemetry- properties:- attributes:+ type:+ $ref: '#/components/schemas/CreateChatPromptType'+ labels:type: arrayitems:- $ref: '#/components/schemas/OtelAttribute'- nullable: true- description: Resource attributes like service.name, service.version, etc.- OtelScopeSpan:- title: OtelScopeSpan- type: object- description: Collection of spans from a single instrumentation scope- properties:- scope:- $ref: '#/components/schemas/OtelScope'+ type: stringnullable: true- description: Instrumentation scope information- spans:+ description: List of deployment labels of this prompt version.+ tags:type: arrayitems:- $ref: '#/components/schemas/OtelSpan'+ type: stringnullable: true- description: Array of spans- OtelScope:- title: OtelScope+ description: List of tags to apply to all versions of this prompt.+ commitMessage:+ type: string+ nullable: true+ description: Commit message for this prompt version.+ required:+ - name+ - prompt+ - type+ CreateTextPromptRequest:+ title: CreateTextPromptRequesttype: object- description: Instrumentation scope informationproperties:name:type: string- nullable: true- description: Instrumentation scope name- version:+ prompt:type: string+ config:nullable: true- description: Instrumentation scope version- attributes:+ type:+ $ref: '#/components/schemas/CreateTextPromptType'+ nullable: true+ labels:type: arrayitems:- $ref: '#/components/schemas/OtelAttribute'+ type: stringnullable: true- description: Additional scope attributes- OtelSpan:- title: OtelSpan+ description: List of deployment labels of this prompt version.+ tags:+ type: array+ items:+ type: string+ nullable: true+ description: List of tags to apply to all versions of this prompt.+ commitMessage:+ type: string+ nullable: true+ description: Commit message for this prompt version.+ required:+ - name+ - prompt+ Prompt:+ title: Prompt+ oneOf:+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - chat+ - $ref: '#/components/schemas/ChatPrompt'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - text+ - $ref: '#/components/schemas/TextPrompt'+ required:+ - type+ PromptType:+ title: PromptType+ type: string+ enum:+ - chat+ - text+ BasePrompt:+ title: BasePrompttype: object- description: Individual span representing a unit of work or operationproperties:- traceId:- nullable: true- description: Trace ID (16 bytes, hex-encoded string in JSON or Buffer in binary)- spanId:- nullable: true- description: Span ID (8 bytes, hex-encoded string in JSON or Buffer in binary)- parentSpanId:- nullable: true- description: Parent span ID if this is a child spanname:type: string- nullable: true- description: Span name describing the operation- kind:+ version:type: integer- nullable: true- description: Span kind (1=INTERNAL, 2=SERVER, 3=CLIENT, 4=PRODUCER, 5=CONSUMER)- startTimeUnixNano:- nullable: true- description: Start time in nanoseconds since Unix epoch- endTimeUnixNano:- nullable: true- description: End time in nanoseconds since Unix epoch- attributes:+ config: {}+ labels:type: arrayitems:- $ref: '#/components/schemas/OtelAttribute'- nullable: true+ type: string+ description: List of deployment labels of this prompt version.+ tags:+ type: array+ items:+ type: stringdescription: >-- Span attributes including Langfuse-specific attributes- (langfuse.observation.*)- status:+ List of tags. Used to filter via UI and API. The same across+ versions of a prompt.+ commitMessage:+ type: stringnullable: true- description: Span status object- OtelAttribute:- title: OtelAttribute+ description: Commit message for this prompt version.+ resolutionGraph:+ type: object+ additionalProperties: true+ nullable: true+ description: >-+ The dependency resolution graph for the current prompt. Null if the+ prompt has no dependencies or if `resolve=false` was used.+ required:+ - name+ - version+ - config+ - labels+ - tags+ ChatMessageWithPlaceholders:+ title: ChatMessageWithPlaceholders+ oneOf:+ - $ref: '#/components/schemas/ChatMessage'+ - $ref: '#/components/schemas/PlaceholderMessage'+ ChatMessage:+ title: ChatMessagetype: object- description: Key-value attribute pair for resources, scopes, or spansproperties:- key:+ role:type: string+ content:+ type: string+ type:+ $ref: '#/components/schemas/ChatMessageType'nullable: true- description: Attribute key (e.g., "service.name", "langfuse.observation.type")- value:- $ref: '#/components/schemas/OtelAttributeValue'- nullable: true- description: Attribute value- OtelAttributeValue:- title: OtelAttributeValue+ required:+ - role+ - content+ ChatMessageType:+ title: ChatMessageType+ type: string+ enum:+ - chatmessage+ PlaceholderMessage:+ title: PlaceholderMessagetype: object- description: Attribute value wrapper supporting different value typesproperties:- stringValue:+ name:type: string+ type:+ $ref: '#/components/schemas/PlaceholderMessageType'nullable: true- description: String value- intValue:- type: integer- nullable: true- description: Integer value- doubleValue:- type: number- format: double- nullable: true- description: Double value- boolValue:- type: boolean- nullable: true- description: Boolean value- OtelTraceResponse:- title: OtelTraceResponse- type: object- description: Response from trace export request. Empty object indicates success.- properties: {}- MembershipRole:- title: MembershipRole+ required:+ - name+ PlaceholderMessageType:+ title: PlaceholderMessageTypetype: stringenum:- - OWNER- - ADMIN- - MEMBER- - VIEWER- MembershipRequest:- title: MembershipRequest+ - placeholder+ TextPrompt:+ title: TextPrompttype: objectproperties:- userId:+ prompt:type: string- role:- $ref: '#/components/schemas/MembershipRole'required:- - userId- - role- DeleteMembershipRequest:- title: DeleteMembershipRequest+ - prompt+ allOf:+ - $ref: '#/components/schemas/BasePrompt'+ ChatPrompt:+ title: ChatPrompttype: objectproperties:- userId:- type: string+ prompt:+ type: array+ items:+ $ref: '#/components/schemas/ChatMessageWithPlaceholders'required:- - userId- MembershipResponse:- title: MembershipResponse+ - prompt+ allOf:+ - $ref: '#/components/schemas/BasePrompt'+ CreateChatPromptType:+ title: CreateChatPromptType+ type: string+ enum:+ - chat+ CreateTextPromptType:+ title: CreateTextPromptType+ type: string+ enum:+ - text+ ServiceProviderConfig:+ title: ServiceProviderConfigtype: objectproperties:- userId:- type: string- role:- $ref: '#/components/schemas/MembershipRole'- email:- type: string- name:+ schemas:+ type: array+ items:+ type: string+ documentationUri:type: string+ patch:+ $ref: '#/components/schemas/ScimFeatureSupport'+ bulk:+ $ref: '#/components/schemas/BulkConfig'+ filter:+ $ref: '#/components/schemas/FilterConfig'+ changePassword:+ $ref: '#/components/schemas/ScimFeatureSupport'+ sort:+ $ref: '#/components/schemas/ScimFeatureSupport'+ etag:+ $ref: '#/components/schemas/ScimFeatureSupport'+ authenticationSchemes:+ type: array+ items:+ $ref: '#/components/schemas/AuthenticationScheme'+ meta:+ $ref: '#/components/schemas/ResourceMeta'required:- - userId- - role- - name- MembershipDeletionResponse:- title: MembershipDeletionResponse+ - schemas+ - documentationUri+ - patch+ - bulk+ - filter+ - changePassword+ - sort+ - etag+ - authenticationSchemes+ - meta+ ScimFeatureSupport:+ title: ScimFeatureSupporttype: objectproperties:- message:- type: string- userId:- type: string+ supported:+ type: booleanrequired:- - message- - userId- MembershipsResponse:- title: MembershipsResponse+ - supported+ BulkConfig:+ title: BulkConfig+ type: object+ properties:+ supported:+ type: boolean+ maxOperations:+ type: integer+ maxPayloadSize:+ type: integer+ required:+ - supported+ - maxOperations+ - maxPayloadSize+ FilterConfig:+ title: FilterConfig+ type: object+ properties:+ supported:+ type: boolean+ maxResults:+ type: integer+ required:+ - supported+ - maxResults+ ResourceMeta:+ title: ResourceMetatype: objectproperties:- memberships:- type: array- items:- $ref: '#/components/schemas/MembershipResponse'+ resourceType:+ type: string+ location:+ type: stringrequired:- - memberships- OrganizationProject:- title: OrganizationProject+ - resourceType+ - location+ AuthenticationScheme:+ title: AuthenticationSchemetype: objectproperties:- id:- type: stringname:type: string- metadata:- type: object- additionalProperties: true- nullable: true- createdAt:+ description:type: string- format: date-time- updatedAt:+ specUri:type: string- format: date-time+ type:+ type: string+ primary:+ type: booleanrequired:- - id- name- - createdAt- - updatedAt- OrganizationProjectsResponse:- title: OrganizationProjectsResponse+ - description+ - specUri+ - type+ - primary+ ResourceTypesResponse:+ title: ResourceTypesResponsetype: objectproperties:- projects:+ schemas:type: arrayitems:- $ref: '#/components/schemas/OrganizationProject'+ type: string+ totalResults:+ type: integer+ Resources:+ type: array+ items:+ $ref: '#/components/schemas/ResourceType'required:- - projects- OrganizationApiKey:- title: OrganizationApiKey+ - schemas+ - totalResults+ - Resources+ ResourceType:+ title: ResourceTypetype: objectproperties:+ schemas:+ type: array+ items:+ type: string+ nullable: trueid:type: string- createdAt:- type: string- format: date-time- expiresAt:- type: string- format: date-time- nullable: true- lastUsedAt:+ name:type: string- format: date-time- nullable: true- note:+ endpoint:type: string- nullable: true- publicKey:+ description:type: string- displaySecretKey:+ schema:type: string+ schemaExtensions:+ type: array+ items:+ $ref: '#/components/schemas/SchemaExtension'+ meta:+ $ref: '#/components/schemas/ResourceMeta'required:- id- - createdAt- - publicKey- - displaySecretKey- OrganizationApiKeysResponse:- title: OrganizationApiKeysResponse+ - name+ - endpoint+ - description+ - schema+ - schemaExtensions+ - meta+ SchemaExtension:+ title: SchemaExtensiontype: objectproperties:- apiKeys:- type: array- items:- $ref: '#/components/schemas/OrganizationApiKey'+ schema:+ type: string+ required:+ type: booleanrequired:- - apiKeys- Projects:- title: Projects+ - schema+ - required+ SchemasResponse:+ title: SchemasResponsetype: objectproperties:- data:+ schemas:type: arrayitems:- $ref: '#/components/schemas/Project'+ type: string+ totalResults:+ type: integer+ Resources:+ type: array+ items:+ $ref: '#/components/schemas/SchemaResource'required:- - data- Organization:- title: Organization+ - schemas+ - totalResults+ - Resources+ SchemaResource:+ title: SchemaResourcetype: objectproperties:id:type: string- description: The unique identifier of the organizationname:type: string- description: The name of the organization- required:- - id- - name- Project:- title: Project- type: object- properties:- id:- type: string- name:+ description:type: string- organization:- $ref: '#/components/schemas/Organization'- description: The organization this project belongs to- metadata:- type: object- additionalProperties: true- description: Metadata for the project- retentionDays:- type: integer- nullable: true- description: >-- Number of days to retain data. Null or 0 means no retention. Omitted- if no retention is configured.+ attributes:+ type: array+ items: {}+ meta:+ $ref: '#/components/schemas/ResourceMeta'required:- id- name- - organization- - metadata- ProjectDeletionResponse:- title: ProjectDeletionResponse- type: object- properties:- success:- type: boolean- message:- type: string- required:- - success- - message- ApiKeyList:- title: ApiKeyList+ - description+ - attributes+ - meta+ ScimUsersListResponse:+ title: ScimUsersListResponsetype: object- description: List of API keys for a projectproperties:- apiKeys:+ schemas:type: arrayitems:- $ref: '#/components/schemas/ApiKeySummary'+ type: string+ totalResults:+ type: integer+ startIndex:+ type: integer+ itemsPerPage:+ type: integer+ Resources:+ type: array+ items:+ $ref: '#/components/schemas/ScimUser'required:- - apiKeys- ApiKeySummary:- title: ApiKeySummary+ - schemas+ - totalResults+ - startIndex+ - itemsPerPage+ - Resources+ ScimUser:+ title: ScimUsertype: object- description: Summary of an API keyproperties:+ schemas:+ type: array+ items:+ type: stringid:type: string- createdAt:- type: string- format: date-time- expiresAt:- type: string- format: date-time- nullable: true- lastUsedAt:- type: string- format: date-time- nullable: true- note:- type: string- nullable: true- publicKey:- type: string- displaySecretKey:+ userName:type: string+ name:+ $ref: '#/components/schemas/ScimName'+ emails:+ type: array+ items:+ $ref: '#/components/schemas/ScimEmail'+ meta:+ $ref: '#/components/schemas/UserMeta'required:+ - schemas- id- - createdAt- - publicKey- - displaySecretKey- ApiKeyResponse:- title: ApiKeyResponse+ - userName+ - name+ - emails+ - meta+ UserMeta:+ title: UserMetatype: object- description: Response for API key creationproperties:- id:- type: string- createdAt:- type: string- format: date-time- publicKey:- type: string- secretKey:+ resourceType:type: string- displaySecretKey:+ created:type: string- note:+ nullable: true+ lastModified:type: stringnullable: truerequired:- - id- - createdAt- - publicKey- - secretKey- - displaySecretKey- ApiKeyDeletionResponse:- title: ApiKeyDeletionResponse+ - resourceType+ ScimName:+ title: ScimNametype: object- description: Response for API key deletionproperties:- success:+ formatted:+ type: string+ nullable: true+ ScimEmail:+ title: ScimEmail+ type: object+ properties:+ primary:type: boolean+ value:+ type: string+ type:+ type: stringrequired:- - success- PromptMetaListResponse:- title: PromptMetaListResponse+ - primary+ - value+ - type+ EmptyResponse:+ title: EmptyResponse+ type: object+ description: Empty response for 204 No Content responses+ properties: {}+ ScoreConfigs:+ title: ScoreConfigstype: objectproperties:data:type: arrayitems:- $ref: '#/components/schemas/PromptMeta'+ $ref: '#/components/schemas/ScoreConfig'meta:$ref: '#/components/schemas/utilsMetaResponse'required:- data- meta- PromptMeta:- title: PromptMeta+ CreateScoreConfigRequest:+ title: CreateScoreConfigRequesttype: objectproperties:name:type: string- type:- $ref: '#/components/schemas/PromptType'- description: Indicates whether the prompt is a text or chat prompt.- versions:- type: array- items:- type: integer- labels:- type: array- items:- type: string- tags:+ description: >-+ Name of the score config. Max 35 characters. Only letters, numbers,+ underscores, spaces, periods, parentheses, and hyphens are allowed.+ dataType:+ $ref: '#/components/schemas/ScoreConfigDataType'+ categories:type: arrayitems:- type: string- lastUpdatedAt:+ $ref: '#/components/schemas/ConfigCategory'+ nullable: true+ description: >-+ Configure custom categories for categorical scores. Pass a list of+ objects with `label` and `value` properties. Categories are+ autogenerated for boolean configs and cannot be passed+ minValue:+ type: number+ format: double+ nullable: true+ description: >-+ Configure a minimum value for numerical scores. If not set, the+ minimum value defaults to -∞+ maxValue:+ type: number+ format: double+ nullable: true+ description: >-+ Configure a maximum value for numerical scores. If not set, the+ maximum value defaults to +∞+ description:type: string- format: date-time- lastConfig:+ nullable: truedescription: >-- Config object of the most recent prompt version that matches the- filters (if any are provided)+ Description is shown across the Langfuse UI and can be used to e.g.+ explain the config categories in detail, why a numeric range was+ set, or provide additional context on config name or usagerequired:- name- - type- - versions- - labels- - tags- - lastUpdatedAt- - lastConfig- CreatePromptRequest:- title: CreatePromptRequest- oneOf:- - $ref: '#/components/schemas/CreateChatPromptRequest'- - $ref: '#/components/schemas/CreateTextPromptRequest'- CreateChatPromptRequest:- title: CreateChatPromptRequest+ - dataType+ UpdateScoreConfigRequest:+ title: UpdateScoreConfigRequesttype: objectproperties:+ isArchived:+ type: boolean+ nullable: true+ description: The status of the score config showing if it is archived or notname:type: string- prompt:- type: array- items:- $ref: '#/components/schemas/ChatMessageWithPlaceholders'- config:nullable: true- type:- $ref: '#/components/schemas/CreateChatPromptType'- labels:+ description: >-+ Name of the score config. Max 35 characters. Only letters, numbers,+ underscores, spaces, periods, parentheses, and hyphens are allowed.+ categories:type: arrayitems:- type: string+ $ref: '#/components/schemas/ConfigCategory'nullable: true- description: List of deployment labels of this prompt version.- tags:- type: array- items:- type: string+ description: >-+ Configure custom categories for categorical scores. Pass a list of+ objects with `label` and `value` properties. Categories are+ autogenerated for boolean configs and cannot be passed+ minValue:+ type: number+ format: doublenullable: true- description: List of tags to apply to all versions of this prompt.- commitMessage:+ description: >-+ Configure a minimum value for numerical scores. If not set, the+ minimum value defaults to -∞+ maxValue:+ type: number+ format: double+ nullable: true+ description: >-+ Configure a maximum value for numerical scores. If not set, the+ maximum value defaults to +∞+ description:type: stringnullable: true- description: Commit message for this prompt version.- required:- - name- - prompt- - type- CreateTextPromptRequest:- title: CreateTextPromptRequest+ description: >-+ Description is shown across the Langfuse UI and can be used to e.g.+ explain the config categories in detail, why a numeric range was+ set, or provide additional context on config name or usage+ GetScoresResponseTraceData:+ title: GetScoresResponseTraceDatatype: objectproperties:- name:- type: string- prompt:+ userId:type: string- config:- nullable: true- type:- $ref: '#/components/schemas/CreateTextPromptType'- nullable: true- labels:- type: array- items:- type: stringnullable: true- description: List of deployment labels of this prompt version.+ description: The user ID associated with the trace referenced by scoretags:type: arrayitems:type: stringnullable: true- description: List of tags to apply to all versions of this prompt.- commitMessage:+ description: A list of tags associated with the trace referenced by score+ environment:type: stringnullable: true- description: Commit message for this prompt version.- required:- - name- - prompt- Prompt:- title: Prompt+ description: The environment of the trace referenced by score+ sessionId:+ type: string+ nullable: true+ description: The session ID associated with the trace referenced by score+ GetScoresResponseDataNumeric:+ title: GetScoresResponseDataNumeric+ type: object+ properties:+ trace:+ $ref: '#/components/schemas/GetScoresResponseTraceData'+ nullable: true+ allOf:+ - $ref: '#/components/schemas/NumericScore'+ GetScoresResponseDataCategorical:+ title: GetScoresResponseDataCategorical+ type: object+ properties:+ trace:+ $ref: '#/components/schemas/GetScoresResponseTraceData'+ nullable: true+ allOf:+ - $ref: '#/components/schemas/CategoricalScore'+ GetScoresResponseDataBoolean:+ title: GetScoresResponseDataBoolean+ type: object+ properties:+ trace:+ $ref: '#/components/schemas/GetScoresResponseTraceData'+ nullable: true+ allOf:+ - $ref: '#/components/schemas/BooleanScore'+ GetScoresResponseDataCorrection:+ title: GetScoresResponseDataCorrection+ type: object+ properties:+ trace:+ $ref: '#/components/schemas/GetScoresResponseTraceData'+ nullable: true+ allOf:+ - $ref: '#/components/schemas/CorrectionScore'+ GetScoresResponseDataText:+ title: GetScoresResponseDataText+ type: object+ properties:+ trace:+ $ref: '#/components/schemas/GetScoresResponseTraceData'+ nullable: true+ allOf:+ - $ref: '#/components/schemas/TextScore'+ GetScoresResponseData:+ title: GetScoresResponseDataoneOf:- type: objectallOf:- type: objectproperties:- type:+ dataType:+ type: string+ enum:+ - NUMERIC+ - $ref: '#/components/schemas/GetScoresResponseDataNumeric'+ required:+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:type: stringenum:- - chat- - $ref: '#/components/schemas/ChatPrompt'+ - CATEGORICAL+ - $ref: '#/components/schemas/GetScoresResponseDataCategorical'required:- - type+ - dataType- type: objectallOf:- type: objectproperties:- type:+ dataType:type: stringenum:- - text- - $ref: '#/components/schemas/TextPrompt'+ - BOOLEAN+ - $ref: '#/components/schemas/GetScoresResponseDataBoolean'required:- - type- PromptType:- title: PromptType- type: string- enum:- - chat- - text- BasePrompt:- title: BasePrompt+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - CORRECTION+ - $ref: '#/components/schemas/GetScoresResponseDataCorrection'+ required:+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - TEXT+ - $ref: '#/components/schemas/GetScoresResponseDataText'+ required:+ - dataType+ GetScoresResponse:+ title: GetScoresResponsetype: objectproperties:- name:- type: string- version:- type: integer- config: {}- labels:+ data:type: arrayitems:- type: string- description: List of deployment labels of this prompt version.- tags:+ $ref: '#/components/schemas/GetScoresResponseData'+ meta:+ $ref: '#/components/schemas/utilsMetaResponse'+ required:+ - data+ - meta+ PaginatedSessions:+ title: PaginatedSessions+ type: object+ properties:+ data:type: arrayitems:- type: string- description: >-- List of tags. Used to filter via UI and API. The same across- versions of a prompt.- commitMessage:+ $ref: '#/components/schemas/Session'+ meta:+ $ref: '#/components/schemas/utilsMetaResponse'+ required:+ - data+ - meta+ Traces:+ title: Traces+ type: object+ properties:+ data:+ type: array+ items:+ $ref: '#/components/schemas/TraceWithDetails'+ meta:+ $ref: '#/components/schemas/utilsMetaResponse'+ required:+ - data+ - meta+ DeleteTraceResponse:+ title: DeleteTraceResponse+ type: object+ properties:+ message:type: string- nullable: true- description: Commit message for this prompt version.- resolutionGraph:- type: object- additionalProperties: true- nullable: true- description: >-- The dependency resolution graph for the current prompt. Null if the- prompt has no dependencies or if `resolve=false` was used.required:- - name- - version- - config- - labels- - tags- ChatMessageWithPlaceholders:- title: ChatMessageWithPlaceholders- oneOf:- - $ref: '#/components/schemas/ChatMessage'- - $ref: '#/components/schemas/PlaceholderMessage'- ChatMessage:- title: ChatMessage+ - message+ Sort:+ title: Sorttype: objectproperties:- role:+ id:type: string- content:+ required:+ - id+ unstableEvaluatorType:+ title: unstableEvaluatorType+ type: string+ enum:+ - llm_as_judge+ description: >-+ The evaluator engine type.+++ The unstable public API currently supports only LLM-as-a-judge+ evaluators.+ unstableEvaluatorScope:+ title: unstableEvaluatorScope+ type: string+ enum:+ - project+ - managed+ description: |-+ Where an evaluator comes from.++ - `project`: created in your project+ - `managed`: provided by Langfuse+ unstableEvaluationRuleTarget:+ title: unstableEvaluationRuleTarget+ type: string+ enum:+ - observation+ - experiment+ description: >-+ The ingestion object type that should trigger evaluation runs.+++ Choose the target first, because it changes both the valid filter+ columns and the valid variable-mapping sources:++ - `observation` evaluates live-ingested observations such as+ generations, spans, and events.+ It supports mapping from `input`, `output`, and `metadata`.+ - `experiment` evaluates live experiment executions and can additionally+ map `expected_output`.+ It currently supports filtering by `datasetId`.+ Discover valid dataset IDs with `GET /api/public/v2/datasets`, then use the returned dataset `id` values in your filter.+ unstableEvaluationRuleStatus:+ title: unstableEvaluationRuleStatus+ type: string+ enum:+ - active+ - inactive+ - paused+ description: >-+ Effective runtime status of the evaluation rule.+++ - `active`: enabled and currently runnable.++ - `inactive`: disabled by configuration.++ - `paused`: enabled, but Langfuse has blocked execution until the+ underlying issue is resolved.+ unstableEvaluationRuleMappingSource:+ title: unstableEvaluationRuleMappingSource+ type: string+ enum:+ - input+ - output+ - metadata+ - expected_output+ description: >-+ Source field used to populate a prompt variable.+++ Use these values when mapping evaluator prompt variables to live data.+++ Target-specific rules:++ - `target=observation` supports `input`, `output`, and `metadata`++ - `target=experiment` supports `input`, `output`, `metadata`, and+ `expected_output`+++ Source semantics:++ - `input`: the observation or experiment input payload++ - `output`: the observation or experiment output payload++ - `metadata`: the metadata object for the target. Combine with+ `jsonPath` when you need one nested field instead of the whole object.++ - `expected_output`: the experiment item's expected output. Only valid+ for `target=experiment`.+ unstableEvaluatorModelConfig:+ title: unstableEvaluatorModelConfig+ type: object+ description: >-+ Optional explicit model configuration for an evaluator.+++ If omitted, Langfuse uses the project's default evaluation model.++ If provided, the model must be available to the project when the+ evaluator or evaluation rule is enabled.+++ To discover valid configured `provider` values for a project, call `GET+ /api/public/llm-connections` and read the `provider` field from the+ returned connections.++ Use a `provider` value that matches one of the connections already+ configured in the same project.+++ Recovery guidance:++ - If evaluator creation returns `422` with+ `code=evaluator_preflight_failed`, either provide a valid explicit+ `modelConfig` here or configure the project's default evaluation model,+ then retry the same request.+ properties:+ provider:type: string- type:- $ref: '#/components/schemas/ChatMessageType'- nullable: true+ description: >-+ Provider identifier to use for this evaluator, for example `openai`+ or `anthropic`.+++ To discover valid values for the current project, call `GET+ /api/public/llm-connections` and use one of the returned `provider`+ values.+ example: openai+ model:+ type: string+ description: >-+ Model identifier exposed by the provider, for example+ `gpt-4.1-mini`.+ example: gpt-4.1-minirequired:- - role- - content- ChatMessageType:- title: ChatMessageType+ - provider+ - model+ unstableEvaluatorOutputDataType:+ title: unstableEvaluatorOutputDataTypetype: stringenum:- - chatmessage- PlaceholderMessage:- title: PlaceholderMessage+ - NUMERIC+ - BOOLEAN+ - CATEGORICAL+ description: >-+ Structured score type returned by an evaluator.+++ This controls the type of score value Langfuse stores for evaluation+ results:++ - `NUMERIC`: a numeric score such as `0.82`++ - `BOOLEAN`: a boolean score such as `true`++ - `CATEGORICAL`: one or more category labels from a fixed list+ unstableEvaluatorOutputFieldDefinition:+ title: unstableEvaluatorOutputFieldDefinition+ type: object+ properties:+ description:+ type: string+ description: >-+ Human-readable instructions for what the evaluator should return in+ this field.+ required:+ - description+ unstableEvaluatorOutputDefinition:+ title: unstableEvaluatorOutputDefinition+ oneOf:+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - NUMERIC+ - $ref: >-+ #/components/schemas/unstablePublicNumericEvaluatorOutputDefinition+ required:+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - BOOLEAN+ - $ref: >-+ #/components/schemas/unstablePublicBooleanEvaluatorOutputDefinition+ required:+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - CATEGORICAL+ - $ref: >-+ #/components/schemas/unstablePublicCategoricalEvaluatorOutputDefinition+ required:+ - dataType+ description: >-+ Structured output definition to send when creating an evaluator.+++ Agent guidance:++ - `dataType` is required.++ - Do not send `version`; that is an internal storage detail and is not+ part of the public request contract.++ - For `NUMERIC` and `BOOLEAN`, provide `reasoning.description` and+ `score.description`.++ - For `CATEGORICAL`, also provide `score.categories` and+ `score.shouldAllowMultipleMatches`.+ unstablePublicNumericEvaluatorOutputDefinition:+ title: unstablePublicNumericEvaluatorOutputDefinitiontype: objectproperties:- name:- type: string- type:- $ref: '#/components/schemas/PlaceholderMessageType'- nullable: true+ dataType:+ $ref: '#/components/schemas/unstableEvaluatorOutputDataType'+ description: Always `NUMERIC`.+ reasoning:+ $ref: '#/components/schemas/unstableEvaluatorOutputFieldDefinition'+ score:+ $ref: '#/components/schemas/unstableEvaluatorOutputFieldDefinition'required:- - name- PlaceholderMessageType:- title: PlaceholderMessageType- type: string- enum:- - placeholder- TextPrompt:- title: TextPrompt+ - dataType+ - reasoning+ - score+ unstablePublicBooleanEvaluatorOutputDefinition:+ title: unstablePublicBooleanEvaluatorOutputDefinitiontype: objectproperties:- prompt:- type: string+ dataType:+ $ref: '#/components/schemas/unstableEvaluatorOutputDataType'+ description: Always `BOOLEAN`.+ reasoning:+ $ref: '#/components/schemas/unstableEvaluatorOutputFieldDefinition'+ score:+ $ref: '#/components/schemas/unstableEvaluatorOutputFieldDefinition'required:- - prompt- allOf:- - $ref: '#/components/schemas/BasePrompt'- ChatPrompt:- title: ChatPrompt+ - dataType+ - reasoning+ - score+ unstablePublicCategoricalEvaluatorOutputScoreDefinition:+ title: unstablePublicCategoricalEvaluatorOutputScoreDefinitiontype: objectproperties:- prompt:+ description:+ type: string+ categories:type: arrayitems:- $ref: '#/components/schemas/ChatMessageWithPlaceholders'+ type: string+ shouldAllowMultipleMatches:+ type: booleanrequired:- - prompt- allOf:- - $ref: '#/components/schemas/BasePrompt'- CreateChatPromptType:- title: CreateChatPromptType+ - description+ - categories+ - shouldAllowMultipleMatches+ unstablePublicCategoricalEvaluatorOutputDefinition:+ title: unstablePublicCategoricalEvaluatorOutputDefinition+ type: object+ properties:+ dataType:+ $ref: '#/components/schemas/unstableEvaluatorOutputDataType'+ description: Always `CATEGORICAL`.+ reasoning:+ $ref: '#/components/schemas/unstableEvaluatorOutputFieldDefinition'+ score:+ $ref: >-+ #/components/schemas/unstablePublicCategoricalEvaluatorOutputScoreDefinition+ required:+ - dataType+ - reasoning+ - score+ unstablePublicEvaluatorOutputDefinition:+ title: unstablePublicEvaluatorOutputDefinition+ oneOf:+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - NUMERIC+ - $ref: >-+ #/components/schemas/unstablePublicNumericEvaluatorOutputDefinition+ required:+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - BOOLEAN+ - $ref: >-+ #/components/schemas/unstablePublicBooleanEvaluatorOutputDefinition+ required:+ - dataType+ - type: object+ allOf:+ - type: object+ properties:+ dataType:+ type: string+ enum:+ - CATEGORICAL+ - $ref: >-+ #/components/schemas/unstablePublicCategoricalEvaluatorOutputDefinition+ required:+ - dataType+ description: >-+ Evaluator output definition returned by the public API.+++ This response always includes `dataType` and never includes an internal+ output-definition `version`.++ Legacy stored evaluator definitions are normalized into this shape+ before they are returned.+++ Use this response shape when deciding how to interpret future evaluation+ scores:++ - `NUMERIC`: expect numeric score values++ - `BOOLEAN`: expect `true` / `false`++ - `CATEGORICAL`: expect one or more values from `score.categories`+ unstableEvaluationRuleStringFilterOperator:+ title: unstableEvaluationRuleStringFilterOperatortype: stringenum:- - chat- CreateTextPromptType:- title: CreateTextPromptType+ - '='+ - contains+ - does not contain+ - starts with+ - ends with+ unstableEvaluationRuleNumberFilterOperator:+ title: unstableEvaluationRuleNumberFilterOperatortype: stringenum:- - text- ServiceProviderConfig:- title: ServiceProviderConfig+ - '='+ - '>'+ - <+ - '>='+ - <=+ unstableEvaluationRuleOptionsFilterOperator:+ title: unstableEvaluationRuleOptionsFilterOperator+ type: string+ enum:+ - any of+ - none of+ unstableEvaluationRuleArrayOptionsFilterOperator:+ title: unstableEvaluationRuleArrayOptionsFilterOperator+ type: string+ enum:+ - any of+ - none of+ - all of+ unstableEvaluationRuleBooleanFilterOperator:+ title: unstableEvaluationRuleBooleanFilterOperator+ type: string+ enum:+ - '='+ - <>+ unstableEvaluationRuleNullFilterOperator:+ title: unstableEvaluationRuleNullFilterOperator+ type: string+ enum:+ - is null+ - is not null+ unstableDateTimeEvaluationRuleFilter:+ title: unstableDateTimeEvaluationRuleFiltertype: objectproperties:- schemas:- type: array- items:- type: string- documentationUri:+ column:type: string- patch:- $ref: '#/components/schemas/ScimFeatureSupport'- bulk:- $ref: '#/components/schemas/BulkConfig'- filter:- $ref: '#/components/schemas/FilterConfig'- changePassword:- $ref: '#/components/schemas/ScimFeatureSupport'- sort:- $ref: '#/components/schemas/ScimFeatureSupport'- etag:- $ref: '#/components/schemas/ScimFeatureSupport'- authenticationSchemes:- type: array- items:- $ref: '#/components/schemas/AuthenticationScheme'- meta:- $ref: '#/components/schemas/ResourceMeta'+ description: Column to filter on.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleNumberFilterOperator'+ description: Comparison operator for datetime values.+ value:+ type: string+ format: date-time+ description: Datetime value to compare against.required:- - schemas- - documentationUri- - patch- - bulk- - filter- - changePassword- - sort- - etag- - authenticationSchemes- - meta- ScimFeatureSupport:- title: ScimFeatureSupport+ - column+ - operator+ - value+ unstableStringEvaluationRuleFilter:+ title: unstableStringEvaluationRuleFiltertype: objectproperties:- supported:- type: boolean+ column:+ type: string+ description: Column to filter on.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleStringFilterOperator'+ value:+ type: stringrequired:- - supported- BulkConfig:- title: BulkConfig+ - column+ - operator+ - value+ unstableNumberEvaluationRuleFilter:+ title: unstableNumberEvaluationRuleFiltertype: objectproperties:- supported:- type: boolean- maxOperations:- type: integer- maxPayloadSize:- type: integer+ column:+ type: string+ description: Column to filter on.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleNumberFilterOperator'+ value:+ type: number+ format: doublerequired:- - supported- - maxOperations- - maxPayloadSize- FilterConfig:- title: FilterConfig+ - column+ - operator+ - value+ unstableStringOptionsEvaluationRuleFilter:+ title: unstableStringOptionsEvaluationRuleFiltertype: objectproperties:- supported:- type: boolean- maxResults:- type: integer+ column:+ type: string+ description: Column to filter on.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleOptionsFilterOperator'+ value:+ type: array+ items:+ type: string+ description: One or more allowed string values.required:- - supported- - maxResults- ResourceMeta:- title: ResourceMeta+ - column+ - operator+ - value+ unstableArrayOptionsEvaluationRuleFilter:+ title: unstableArrayOptionsEvaluationRuleFiltertype: objectproperties:- resourceType:- type: string- location:+ column:type: string+ description: Column to filter on.+ operator:+ $ref: >-+ #/components/schemas/unstableEvaluationRuleArrayOptionsFilterOperator+ value:+ type: array+ items:+ type: string+ description: One or more array elements to match.required:- - resourceType- - location- AuthenticationScheme:- title: AuthenticationScheme+ - column+ - operator+ - value+ unstableStringObjectEvaluationRuleFilter:+ title: unstableStringObjectEvaluationRuleFiltertype: objectproperties:- name:- type: string- description:+ column:type: string- specUri:+ description: >-+ Object-valued column to filter on. In the unstable public API this+ is currently `metadata`.+ key:type: string- type:+ description: Top-level key inside the object-valued column to filter on.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleStringFilterOperator'+ value:type: string- primary:- type: booleanrequired:- - name- - description- - specUri- - type- - primary- ResourceTypesResponse:- title: ResourceTypesResponse+ - column+ - key+ - operator+ - value+ unstableNumberObjectEvaluationRuleFilter:+ title: unstableNumberObjectEvaluationRuleFiltertype: objectproperties:- schemas:- type: array- items:- type: string- totalResults:- type: integer- Resources:- type: array- items:- $ref: '#/components/schemas/ResourceType'+ column:+ type: string+ description: Object-valued column to filter on.+ key:+ type: string+ description: Key inside the object-valued column to filter on.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleNumberFilterOperator'+ value:+ type: number+ format: doublerequired:- - schemas- - totalResults- - Resources- ResourceType:- title: ResourceType+ - column+ - key+ - operator+ - value+ unstableCategoryOptionsEvaluationRuleFilter:+ title: unstableCategoryOptionsEvaluationRuleFiltertype: objectproperties:- schemas:- type: array- items:- type: string- nullable: true- id:- type: string- name:- type: string- endpoint:- type: string- description:+ column:type: string- schema:+ description: Object-valued column to filter on.+ key:type: string- schemaExtensions:+ description: Key inside the object-valued column to filter on.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleOptionsFilterOperator'+ value:type: arrayitems:- $ref: '#/components/schemas/SchemaExtension'- meta:- $ref: '#/components/schemas/ResourceMeta'+ type: stringrequired:- - id- - name- - endpoint- - description- - schema- - schemaExtensions- - meta- SchemaExtension:- title: SchemaExtension+ - column+ - key+ - operator+ - value+ unstableBooleanEvaluationRuleFilter:+ title: unstableBooleanEvaluationRuleFiltertype: objectproperties:- schema:+ column:type: string- required:+ description: Column to filter on.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleBooleanFilterOperator'+ value:type: booleanrequired:- - schema- - required- SchemasResponse:- title: SchemasResponse+ - column+ - operator+ - value+ unstableNullEvaluationRuleFilter:+ title: unstableNullEvaluationRuleFiltertype: objectproperties:- schemas:- type: array- items:- type: string- totalResults:- type: integer- Resources:- type: array- items:- $ref: '#/components/schemas/SchemaResource'+ column:+ type: string+ description: >-+ Column to filter on. In the unstable public API this is currently+ `parentObservationId`.+ operator:+ $ref: '#/components/schemas/unstableEvaluationRuleNullFilterOperator'+ value:+ type: string+ nullable: true+ description: >-+ Ignored placeholder value. Clients may omit it or send an empty+ string.required:- - schemas- - totalResults- - Resources- SchemaResource:- title: SchemaResource+ - column+ - operator+ unstableEvaluationRuleMapping:+ title: unstableEvaluationRuleMappingtype: object+ description: >-+ Maps one evaluator prompt variable to one source field from the target+ object.+++ How to build a valid mapping list:++ 1. Create the evaluator or fetch it with `GET /evaluators/{id}`.++ 2. Read the evaluator `variables` array.++ 3. Add exactly one mapping object for each variable in that array.++ 4. Use the variable name exactly as returned, without braces such as+ `{{` or `}}`.++ 5. Choose a `source` that is valid for the selected `target`.+++ `jsonPath` is optional. Use it only when the selected source is a JSON+ object and you want to extract one nested field before inserting it into+ the evaluator prompt.+++ 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++ - `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:- id:+ variable:type: string- name:+ description: >-+ Prompt variable name without braces.+++ Example: for the prompt `Judge {{input}} against {{output}}`, use+ `input` and `output`.+ example: input+ source:+ $ref: '#/components/schemas/unstableEvaluationRuleMappingSource'+ description: >-+ Source field that should populate the prompt variable.+++ Quick reference:++ - `target=observation`: `input`, `output`, `metadata`++ - `target=experiment`: `input`, `output`, `metadata`,+ `expected_output`+ jsonPath:type: string- description:+ nullable: true+ description: >-+ Optional JSONPath selector applied to the selected source before it+ is passed to the evaluator prompt.+++ Requirements:++ - Must start with `$`++ - Must be a syntactically valid JSONPath expression++ - Most useful with `source=metadata`+ required:+ - variable+ - source+ unstableEvaluationRuleFilter:+ title: unstableEvaluationRuleFilter+ oneOf:+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - datetime+ - $ref: '#/components/schemas/unstableDateTimeEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - string+ - $ref: '#/components/schemas/unstableStringEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - number+ - $ref: '#/components/schemas/unstableNumberEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - stringOptions+ - $ref: '#/components/schemas/unstableStringOptionsEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - categoryOptions+ - $ref: '#/components/schemas/unstableCategoryOptionsEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - arrayOptions+ - $ref: '#/components/schemas/unstableArrayOptionsEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - stringObject+ - $ref: '#/components/schemas/unstableStringObjectEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - numberObject+ - $ref: '#/components/schemas/unstableNumberObjectEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - boolean+ - $ref: '#/components/schemas/unstableBooleanEvaluationRuleFilter'+ required:+ - type+ - type: object+ allOf:+ - type: object+ properties:+ type:+ type: string+ enum:+ - 'null'+ - $ref: '#/components/schemas/unstableNullEvaluationRuleFilter'+ required:+ - type+ description: >-+ One filter condition used to decide whether a live-ingested target+ should be evaluated.+++ An evaluation rule can include zero or more filter objects. All filters+ must be satisfied for the target to run.+++ How to build a valid filter object:++ - Pick the `target` first, because it changes the supported columns.++ - Pick the filter `type`. That determines which fields are required.++ - Use `key` only for object filters such as `metadata`.++ - Use the correct `value` shape for the chosen filter `type`.+++ Operator quick reference by filter `type`:++ - `string`: `"="`, `contains`, `does not contain`, `starts with`, `ends+ with`++ - `number`: `"="`, `">"`, `"<"`, `">="`, `"<="`++ - `datetime`: `"="`, `">"`, `"<"`, `">="`, `"<="`++ - `stringOptions`: `any of`, `none of`++ - `arrayOptions`: `any of`, `none of`, `all of`++ - `stringObject`: same operators as `string`++ - `null`: `is null`, `is not null`+++ Supported columns by target:++ - `target=observation`+ - `type`: `stringOptions`, operators `any of` / `none of`, values `GENERATION`, `SPAN`, `EVENT`+ - `name`: `stringOptions`, operators `any of` / `none of`+ - `environment`: `stringOptions`, operators `any of` / `none of`+ - `level`: `stringOptions`, operators `any of` / `none of`, values `DEBUG`, `DEFAULT`, `WARNING`, `ERROR`+ - `version`: `string`+ - `traceName`: `stringOptions`, operators `any of` / `none of`+ - `userId`: `string`+ - `sessionId`: `string`+ - `tags`: `arrayOptions`, operators `any of` / `none of` / `all of`+ - `metadata`: `stringObject` with `key`+ - `parentObservationId`: `null`, operators `is null` / `is not null`+ - `calledToolNames`: `arrayOptions`, operators `any of` / `none of` / `all of`+ - `toolCalls`: `number`+ - `target=experiment`+ - `datasetId`: `stringOptions`, operators `any of` / `none of`+ Use dataset `id` values from `GET /api/public/v2/datasets`, not dataset names.++ Recovery guidance:++ - `invalid_filter_value` with `details.column` but no `invalidValues`:+ the selected `column` is not supported for the chosen `target`++ - `invalid_filter_value` with `details.invalidValues`: the selected+ values are not allowed for that column. Replace them with one of+ `details.allowedValues` when provided.++ - `invalid_filter_value` for `column=datasetId`: call `GET+ /api/public/v2/datasets`, then retry with dataset `id` values from that+ response.+ unstablePublicApiErrorCode:+ title: unstablePublicApiErrorCode+ type: string+ enum:+ - authentication_failed+ - access_denied+ - invalid_request+ - invalid_query+ - invalid_body+ - invalid_filter_value+ - invalid_json_path+ - invalid_variable_mapping+ - missing_variable_mapping+ - duplicate_variable_mapping+ - resource_not_found+ - name_conflict+ - evaluator_preflight_failed+ - conflict+ - unprocessable_content+ - rate_limited+ - method_not_allowed+ - internal_error+ description: >-+ Machine-readable error code returned by the unstable evaluators API.+++ SDKs, CLIs, and agents should branch on `code` rather than parsing the+ human-readable `message`.++ The HTTP status still indicates the broad error class, while `code`+ gives the specific failure reason.+ unstablePublicApiValidationIssue:+ title: unstablePublicApiValidationIssue+ type: object+ description: >-+ One validation issue returned for malformed request bodies or query+ parameters.+++ This mirrors the most important parts of a Zod issue: a machine-readable+ `code`,++ a human-readable `message`, and a structured `path`.+ properties:+ code:type: string- attributes:+ description: >-+ Machine-readable validation issue code emitted by the server+ validator.+ message:+ type: string+ description: Human-readable explanation of the validation failure.+ path:type: arrayitems: {}- meta:- $ref: '#/components/schemas/ResourceMeta'+ description: Path to the invalid field, for example `["mapping", 0, "jsonPath"]`.required:- - id- - name- - description- - attributes- - meta- ScimUsersListResponse:- title: ScimUsersListResponse+ - code+ - message+ - path+ unstablePublicApiErrorDetails:+ title: unstablePublicApiErrorDetailstype: object+ description: >-+ Optional structured context attached to an unstable-evals error.+++ The populated fields depend on the error `code`:++ - request parsing failures populate `issues`++ - filter validation failures populate `field`, `column`,+ `invalidValues`, and `allowedValues`++ - variable mapping failures populate `field`, `variable`, or `variables`++ - JSONPath validation failures populate `field`, `variable`, and `value`++ - evaluator preflight failures populate `evaluatorName`, `provider`, and+ `model`++ - rate limiting populates `retryAfterSeconds`, `limit`, `remaining`, and+ `resetAt`properties:- schemas:+ issues:type: arrayitems:- type: string- totalResults:- type: integer- startIndex:- type: integer- itemsPerPage:- type: integer- Resources:+ $ref: '#/components/schemas/unstablePublicApiValidationIssue'+ nullable: true+ description: Validation issues for malformed request bodies or query parameters.+ field:+ type: string+ nullable: true+ description: >-+ Path-like reference to the failing field, for example+ `mapping[1].jsonPath`.+ column:+ type: string+ nullable: true+ description: Filter column that failed validation.+ invalidValues:type: arrayitems:- $ref: '#/components/schemas/ScimUser'- required:- - schemas- - totalResults- - startIndex- - itemsPerPage- - Resources- ScimUser:- title: ScimUser- type: object- properties:- schemas:+ type: string+ nullable: true+ description: Unsupported values supplied by the caller.+ allowedValues:type: arrayitems:type: string- id:- type: string- userName:+ nullable: true+ description: Allowed values for the failing filter column.+ variable:type: string- name:- $ref: '#/components/schemas/ScimName'- emails:+ nullable: true+ description: Evaluator variable involved in the failure.+ variables:type: arrayitems:- $ref: '#/components/schemas/ScimEmail'- meta:- $ref: '#/components/schemas/UserMeta'- required:- - schemas- - id- - userName- - name- - emails- - meta- UserMeta:- title: UserMeta- type: object- properties:- resourceType:+ type: string+ nullable: true+ description: >-+ Multiple evaluator variables involved in the failure, for example+ missing mappings.+ value:type: string- created:+ nullable: true+ description: Raw invalid value supplied by the caller.+ evaluatorName:type: stringnullable: true- lastModified:+ description: Evaluator name used during preflight validation.+ provider:type: stringnullable: true- required:- - resourceType- ScimName:- title: ScimName+ description: Provider resolved during evaluator preflight, if any.+ model:+ type: string+ nullable: true+ description: Model resolved during evaluator preflight, if any.+ retryAfterSeconds:+ type: integer+ nullable: true+ description: Suggested retry delay for rate-limited requests.+ limit:+ type: integer+ nullable: true+ description: >-+ Numeric limit associated with the failure, for example the active+ evaluation-rule cap or the current rate-limit window.+ remaining:+ type: integer+ nullable: true+ description: Remaining requests in the current rate-limit window.+ resetAt:+ type: string+ nullable: true+ description: ISO-8601 timestamp when the current rate-limit window resets.+ unstablePublicApiError:+ title: unstablePublicApiErrortype: object+ description: >-+ Standard error envelope for the unstable evaluators API.+++ Response handling guidance:++ - Use the HTTP status code for the broad class of failure.++ - Use `code` for precise branching in SDKs, CLIs, or agents.++ - Inspect `details` for field-level validation context such as invalid+ filter values, malformed JSONPath expressions, or missing variable+ mappings.++ - Retry only after fixing the specific issue described by `code` and+ `details`.properties:- formatted:+ message:type: string+ description: Human-readable description of the failure.+ example: 'Filter column "type" contains unsupported value(s): INVALID'+ code:+ $ref: '#/components/schemas/unstablePublicApiErrorCode'+ description: Stable machine-readable error code.+ details:+ $ref: '#/components/schemas/unstablePublicApiErrorDetails'nullable: true- ScimEmail:- title: ScimEmail+ description: >-+ Optional structured error context. Inspect the populated fields+ based on `code`.+ required:+ - message+ - code+ unstableEvaluationRule:+ title: unstableEvaluationRuletype: object+ description: >-+ Live evaluation rule for incoming data.+++ An evaluation rule answers:++ - which evaluator should be used++ - which target objects should trigger scoring++ - how often scoring should run++ - which target fields should populate each evaluator variable++ - whether the deployment is active, inactive, or paused+++ Important status semantics:++ - `enabled` is the desired on/off setting from the client++ - `status` is the effective runtime state after Langfuse applies+ validation and blocking rules++ - `enabled=true` with `status=paused` means the rule should run, but+ Langfuse has paused it until the underlying problem is fixedproperties:- primary:+ id:+ type: string+ description: Stable evaluation rule identifier.+ example: erule_123+ name:+ type: string+ description: >-+ Human-readable deployment name. This is independent from the+ evaluator name.+ example: answer-correctness-live+ evaluator:+ $ref: '#/components/schemas/unstableEvaluationRuleEvaluator'+ description: >-+ Evaluator currently used by this rule.+++ `name` and `scope` identify the evaluator family conceptually.++ `id` is the currently active evaluator version in that family.++ If you create a newer project version with the same evaluator name+ later, existing evaluation rules are moved to it automatically.+ target:+ $ref: '#/components/schemas/unstableEvaluationRuleTarget'+ description: Target object type that should trigger scoring.+ enabled:type: boolean- value:+ description: Desired enabled state configured by the client.+ example: true+ status:+ $ref: '#/components/schemas/unstableEvaluationRuleStatus'+ description: >-+ Effective runtime status after Langfuse applies validation and+ blocking rules.+ pausedReason:type: string- type:+ nullable: true+ description: Machine-readable reason when `status=paused`, otherwise `null`.+ pausedMessage:+ type: string+ nullable: true+ description: Human-readable explanation when `status=paused`, otherwise `null`.+ sampling:+ type: number+ format: double+ description: |-+ Fraction of matching target objects that should be evaluated.++ Must be greater than `0` and less than or equal to `1`.+ - `1` means evaluate every matching target.+ - `0.25` means evaluate approximately 25% of matching targets.+ example: 1+ filter:+ type: array+ items:+ $ref: '#/components/schemas/unstableEvaluationRuleFilter'+ description: >-+ List of filter conditions used to decide whether a target should be+ evaluated.+ mapping:+ type: array+ items:+ $ref: '#/components/schemas/unstableEvaluationRuleMapping'+ description: >-+ Variable mappings used to populate the evaluator prompt from the+ live target object.+ createdAt:+ type: string+ format: date-time+ description: Timestamp when the evaluation rule was created.+ example: '2026-03-30T09:20:00.000Z'+ updatedAt:type: string+ format: date-time+ description: Timestamp when the evaluation rule was last updated.+ example: '2026-03-30T09:20:00.000Z'required:- - primary- - value- - type- EmptyResponse:- title: EmptyResponse- type: object- description: Empty response for 204 No Content responses- properties: {}- ScoreConfigs:- title: ScoreConfigs+ - id+ - name+ - evaluator+ - target+ - enabled+ - status+ - sampling+ - filter+ - mapping+ - createdAt+ - updatedAt+ unstableEvaluationRules:+ title: unstableEvaluationRulestype: object+ description: Paginated list of evaluation rules.properties:data:type: arrayitems:- $ref: '#/components/schemas/ScoreConfig'+ $ref: '#/components/schemas/unstableEvaluationRule'+ description: Evaluation rules in the current page.meta:$ref: '#/components/schemas/utilsMetaResponse'+ description: Standard pagination metadata.required:- data- meta- CreateScoreConfigRequest:- title: CreateScoreConfigRequest+ unstableCreateEvaluationRuleRequest:+ title: unstableCreateEvaluationRuleRequesttype: object+ description: >-+ Request body for creating an evaluation rule.+++ Checklist for agents and SDK clients:++ - 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`++ - optionally narrow execution with `filter`++ - set `enabled=true` only when you want live execution immediatelyproperties:name:type: string+ description: Human-readable deployment name.+ example: answer-correctness-live+ evaluator:+ $ref: '#/components/schemas/unstableEvaluationRuleEvaluatorReference'description: >-- Name of the score config. Max 35 characters. Only letters, numbers,- underscores, spaces, periods, parentheses, and hyphens are allowed.- dataType:- $ref: '#/components/schemas/ScoreConfigDataType'- categories:- type: array- items:- $ref: '#/components/schemas/ConfigCategory'- nullable: true- description: >-- Configure custom categories for categorical scores. Pass a list of- objects with `label` and `value` properties. Categories are- autogenerated for boolean configs and cannot be passed- minValue:- type: number- format: double- nullable: true- description: >-- Configure a minimum value for numerical scores. If not set, the- minimum value defaults to -∞- maxValue:+ Evaluator family to use.+++ Use `name` and `scope` 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.+ example: true+ sampling:type: numberformat: doublenullable: true- description: >-- Configure a maximum value for numerical scores. If not set, the- maximum value defaults to +∞- description:- type: string- nullable: true- description: >-- Description is shown across the Langfuse UI and can be used to e.g.- explain the config categories in detail, why a numeric range was- set, or provide additional context on config name or usage- required:- - name- - dataType- UpdateScoreConfigRequest:- title: UpdateScoreConfigRequest- type: object- properties:- isArchived:- type: boolean- nullable: true- description: The status of the score config showing if it is archived or not- name:- type: string- nullable: true- description: >-- Name of the score config. Max 35 characters. Only letters, numbers,- underscores, spaces, periods, parentheses, and hyphens are allowed.- categories:+ description: Optional sampling fraction. Defaults to `1`.+ filter:type: arrayitems:- $ref: '#/components/schemas/ConfigCategory'- nullable: true- description: >-- Configure custom categories for categorical scores. Pass a list of- objects with `label` and `value` properties. Categories are- autogenerated for boolean configs and cannot be passed- minValue:- type: number- format: double- nullable: true- description: >-- Configure a minimum value for numerical scores. If not set, the- minimum value defaults to -∞- maxValue:- type: number- format: double+ $ref: '#/components/schemas/unstableEvaluationRuleFilter'nullable: truedescription: >-- Configure a maximum value for numerical scores. If not set, the- maximum value defaults to +∞- description:- type: string- nullable: true+ 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.+ mapping:+ type: array+ items:+ $ref: '#/components/schemas/unstableEvaluationRuleMapping'description: >-- Description is shown across the Langfuse UI and can be used to e.g.- explain the config categories in detail, why a numeric range was- set, or provide additional context on config name or usage- GetScoresResponseTraceData:- title: GetScoresResponseTraceData+ Required variable mappings.+++ Every evaluator variable must appear exactly once.++ Build this list from the evaluator `variables` array returned by the+ evaluator endpoints.+ required:+ - name+ - evaluator+ - target+ - enabled+ - mapping+ unstableUpdateEvaluationRuleRequest:+ title: unstableUpdateEvaluationRuleRequesttype: object+ description: >-+ Partial update body for an evaluation rule.+++ Provide only the fields you want to change.++ An empty body is rejected.+++ 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 an experiment `datasetId` filter, call `GET+ /api/public/v2/datasets` and use dataset `id` values from that response.properties:- userId:+ name:type: stringnullable: true- description: The user ID associated with the trace referenced by score- tags:- type: array- items:- type: string+ description: Updated deployment name.+ evaluator:+ $ref: '#/components/schemas/unstableEvaluationRuleEvaluatorReference'nullable: true- description: A list of tags associated with the trace referenced by score- environment:- type: string+ description: >-+ Updated evaluator family.+++ Langfuse resolves the provided evaluator family to its latest+ version before saving the rule.+ target:+ $ref: '#/components/schemas/unstableEvaluationRuleTarget'nullable: true- description: The environment of the trace referenced by score- sessionId:- type: string+ description: Updated target object type.+ enabled:+ type: booleannullable: true- description: The session ID associated with the trace referenced by score- GetScoresResponseDataNumeric:- title: GetScoresResponseDataNumeric- type: object- properties:- trace:- $ref: '#/components/schemas/GetScoresResponseTraceData'+ description: Updated desired enabled state.+ sampling:+ type: number+ format: doublenullable: true- allOf:- - $ref: '#/components/schemas/NumericScore'- GetScoresResponseDataCategorical:- title: GetScoresResponseDataCategorical- type: object- properties:- trace:- $ref: '#/components/schemas/GetScoresResponseTraceData'+ description: Updated sampling fraction.+ filter:+ type: array+ items:+ $ref: '#/components/schemas/unstableEvaluationRuleFilter'nullable: true- allOf:- - $ref: '#/components/schemas/CategoricalScore'- GetScoresResponseDataBoolean:- title: GetScoresResponseDataBoolean- type: object- properties:- trace:- $ref: '#/components/schemas/GetScoresResponseTraceData'+ description: >-+ Updated filter list.+++ For `target=experiment`, `column=datasetId` expects dataset `id`+ values from `GET /api/public/v2/datasets`, not dataset names.+ mapping:+ type: array+ items:+ $ref: '#/components/schemas/unstableEvaluationRuleMapping'nullable: true- allOf:- - $ref: '#/components/schemas/BooleanScore'- GetScoresResponseDataCorrection:- title: GetScoresResponseDataCorrection+ description: Updated variable mappings.+ unstableDeleteEvaluationRuleResponse:+ title: unstableDeleteEvaluationRuleResponsetype: object+ description: Confirmation response returned after successful deletion.properties:- trace:- $ref: '#/components/schemas/GetScoresResponseTraceData'- nullable: true- allOf:- - $ref: '#/components/schemas/CorrectionScore'- GetScoresResponseDataText:- title: GetScoresResponseDataText+ message:+ type: string+ description: Always `Evaluation rule successfully deleted`.+ required:+ - message+ unstableEvaluationRuleEvaluatorReference:+ title: unstableEvaluationRuleEvaluatorReferencetype: object+ description: >-+ Evaluator family reference used when creating or updating an evaluation+ rule.+++ `name` and `scope` are enough to identify the evaluator family in the+ authenticated project context.properties:- trace:- $ref: '#/components/schemas/GetScoresResponseTraceData'- nullable: true- allOf:- - $ref: '#/components/schemas/TextScore'- GetScoresResponseData:- title: GetScoresResponseData- oneOf:- - type: object- allOf:- - type: object- properties:- dataType:- type: string- enum:- - NUMERIC- - $ref: '#/components/schemas/GetScoresResponseDataNumeric'- required:- - dataType- - type: object- allOf:- - type: object- properties:- dataType:- type: string- enum:- - CATEGORICAL- - $ref: '#/components/schemas/GetScoresResponseDataCategorical'- required:- - dataType- - type: object- allOf:- - type: object- properties:- dataType:- type: string- enum:- - BOOLEAN- - $ref: '#/components/schemas/GetScoresResponseDataBoolean'- required:- - dataType- - type: object- allOf:- - type: object- properties:- dataType:- type: string- enum:- - CORRECTION- - $ref: '#/components/schemas/GetScoresResponseDataCorrection'- required:- - dataType- - type: object- allOf:- - type: object- properties:- dataType:- type: string- enum:- - TEXT- - $ref: '#/components/schemas/GetScoresResponseDataText'- required:- - dataType- GetScoresResponse:- title: GetScoresResponse+ name:+ type: string+ description: Evaluator family name.+ scope:+ $ref: '#/components/schemas/unstableEvaluatorScope'+ description: Whether the evaluator family is project-owned or Langfuse-managed.+ required:+ - name+ - scope+ unstableEvaluationRuleEvaluator:+ title: unstableEvaluationRuleEvaluatortype: object+ description: |-+ Resolved evaluator currently used by the evaluation rule.++ `id` is the exact active evaluator version.+ `name` and `scope` identify the evaluator family conceptually.properties:- data:- type: array- items:- $ref: '#/components/schemas/GetScoresResponseData'- meta:- $ref: '#/components/schemas/utilsMetaResponse'+ id:+ type: string+ description: >-+ Identifier of the exact evaluator version currently used by the+ rule.+ name:+ type: string+ description: Evaluator family name.+ scope:+ $ref: '#/components/schemas/unstableEvaluatorScope'+ description: Whether the evaluator family is project-owned or Langfuse-managed.required:- - data- - meta- PaginatedSessions:- title: PaginatedSessions+ - id+ - name+ - scope+ unstableEvaluator:+ title: unstableEvaluatortype: object+ 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+++ 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+++ 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`).properties:- data:+ 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: arrayitems:- $ref: '#/components/schemas/Session'- meta:- $ref: '#/components/schemas/utilsMetaResponse'+ type: string+ description: >-+ Variables extracted from the evaluator prompt.+++ 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.+ 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:- - data- - meta- Traces:- title: Traces+ - id+ - name+ - version+ - scope+ - type+ - prompt+ - variables+ - outputDefinition+ - evaluationRuleCount+ - createdAt+ - updatedAt+ unstableEvaluators:+ title: unstableEvaluatorstype: objectproperties:data:type: arrayitems:- $ref: '#/components/schemas/TraceWithDetails'+ $ref: '#/components/schemas/unstableEvaluator'meta:$ref: '#/components/schemas/utilsMetaResponse'required:- data- meta- DeleteTraceResponse:- title: DeleteTraceResponse+ unstableCreateEvaluatorRequest:+ title: unstableCreateEvaluatorRequesttype: object+ description: >-+ Request body for creating an evaluator.+++ 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.properties:- message:+ name:type: string- required:- - message- Sort:- title: Sort- type: object- properties:- id:+ 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: >-+ Structured output schema the evaluator must return.+++ Always send `dataType`.++ Do not send `version`; it is an internal storage detail and not part+ of the public request contract.+ modelConfig:+ $ref: '#/components/schemas/unstableEvaluatorModelConfig'+ nullable: true+ description: >-+ Optional explicit model configuration. Omit or set to `null` to use+ the project default evaluation model.required:- - id+ - name+ - prompt+ - outputDefinitionutilsMetaResponse:title: utilsMetaResponsetype: objectdiff --git a/web/src/__tests__/after-teardown.ts b/web/src/__tests__/after-teardown.tsindex 5c82e3695b..3bfe35b76d 100644--- a/web/src/__tests__/after-teardown.ts+++ b/web/src/__tests__/after-teardown.ts@@ -1,7 +1,24 @@+import path from "node:path";import teardown from "@/src/__tests__/teardown";import { ensureTestDatabaseExists } from "@/src/__tests__/test-utils";+function shouldSkipDatabaseBootstrap() {+ const testPath = expect.getState().testPath;++ if (!testPath) {+ return false;+ }++ return testPath.includes(+ `${path.sep}src${path.sep}__tests__${path.sep}server${path.sep}unit${path.sep}`,+ );+}+beforeAll(async () => {+ if (shouldSkipDatabaseBootstrap()) {+ return;+ }+await ensureTestDatabaseExists();});diff --git a/web/src/__tests__/server/scores-api-v1.servertest.ts b/web/src/__tests__/server/scores-api-v1.servertest.tsindex e314afc5fa..6621468b3f 100644--- a/web/src/__tests__/server/scores-api-v1.servertest.ts+++ b/web/src/__tests__/server/scores-api-v1.servertest.ts@@ -1349,7 +1349,7 @@ describe("/api/public/scores API Endpoint", () => {`Bearer ${publicKey}`,);- expect(response.status).toBe(401);+ expect(response.status).toBe(403);});it("should reject GET /api/public/scores/:scoreId with Bearer public key", async () => {@@ -1362,7 +1362,7 @@ describe("/api/public/scores API Endpoint", () => {`Bearer ${publicKey}`,);- expect(response.status).toBe(401);+ expect(response.status).toBe(403);});it("should reject DELETE /api/public/scores/:scoreId with Bearer public key", async () => {@@ -1375,7 +1375,7 @@ describe("/api/public/scores API Endpoint", () => {`Bearer ${publicKey}`,);- expect(response.status).toBe(401);+ expect(response.status).toBe(403);});it("should reject POST /api/public/scores with invalid Bearer token", async () => {@@ -1417,9 +1417,9 @@ describe("/api/public/scores API Endpoint", () => {),]);- expect(tracesRes.status).toBe(401);- expect(observationsRes.status).toBe(401);- expect(sessionsRes.status).toBe(401);+ expect(tracesRes.status).toBe(403);+ expect(observationsRes.status).toBe(403);+ expect(sessionsRes.status).toBe(403);});});});diff --git a/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts b/web/src/__tests__/server/unit/evaluator-preflight.servertest.tsnew file mode 100644index 0000000000..7fdbce5b76--- /dev/null+++ b/web/src/__tests__/server/unit/evaluator-preflight.servertest.ts@@ -0,0 +1,84 @@+/** @jest-environment node */++jest.mock("@langfuse/shared/src/server", () => {+ const actual = jest.requireActual("@langfuse/shared/src/server");+ return {+ ...actual,+ DefaultEvalModelService: {+ fetchValidModelConfig: jest.fn(),+ },+ logger: {+ debug: jest.fn(),+ },+ testModelCall: jest.fn(),+ };+});++import {+ createNumericEvalOutputDefinition,+ LLMAdapter,+} from "@langfuse/shared";+import {+ DefaultEvalModelService,+ testModelCall,+} from "@langfuse/shared/src/server";+import { getEvaluatorDefinitionPreflightError } from "@/src/features/evals/server/evaluator-preflight";++const numericOutputDefinition = createNumericEvalOutputDefinition({+ reasoningDescription: "Why the score was assigned",+ scoreDescription: "A score between 0 and 1",+});++describe("evaluator preflight", () => {+ const mockFetchValidModelConfig = jest.mocked(+ DefaultEvalModelService.fetchValidModelConfig,+ );+ const mockTestModelCall = jest.mocked(testModelCall);+ const originalSkipFlag =+ process.env.LANGFUSE_SKIP_EVALUATOR_MODEL_CALL_VALIDATION;++ beforeEach(() => {+ jest.resetAllMocks();+ delete process.env.LANGFUSE_SKIP_EVALUATOR_MODEL_CALL_VALIDATION;+ mockFetchValidModelConfig.mockResolvedValue({+ valid: true,+ config: {+ provider: "openai-test",+ model: "gpt-4.1-mini",+ modelParams: undefined,+ apiKey: {+ secretKey: "encrypted",+ extraHeaders: null,+ baseURL: "http://127.0.0.1:4011/v1",+ config: null,+ adapter: LLMAdapter.OpenAI,+ },+ },+ });+ });++ afterAll(() => {+ if (originalSkipFlag === undefined) {+ delete process.env.LANGFUSE_SKIP_EVALUATOR_MODEL_CALL_VALIDATION;+ return;+ }++ process.env.LANGFUSE_SKIP_EVALUATOR_MODEL_CALL_VALIDATION =+ originalSkipFlag;+ });++ it("skips the live provider call when the explicit test flag is enabled", async () => {+ process.env.LANGFUSE_SKIP_EVALUATOR_MODEL_CALL_VALIDATION = "true";++ const result = await getEvaluatorDefinitionPreflightError({+ projectId: "project_test",+ template: {+ name: "Answer correctness",+ outputDefinition: numericOutputDefinition,+ },+ });++ expect(result).toBeNull();+ expect(mockTestModelCall).not.toHaveBeenCalled();+ });+});diff --git a/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-contract.servertest.tsnew file mode 100644index 0000000000..dcd7f19c28--- /dev/null+++ b/web/src/__tests__/server/unit/unstable-evals-contract.servertest.ts@@ -0,0 +1,580 @@+/** @jest-environment node */++import {+ createNumericEvalOutputDefinition,+ EvalTargetObject,+ JobConfigState,+} from "@langfuse/shared";+import {+ toApiEvaluationRule,+ toApiEvaluator,+ toJobConfigurationInput,+} from "@/src/features/evals/server/unstable-public-api/adapters";+import { UnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";+import type {+ StoredPublicEvaluationRuleConfig,+ StoredPublicEvaluatorTemplate,+} from "@/src/features/evals/server/unstable-public-api/types";+import {+ GetUnstableEvaluationRulesQuery,+ PatchUnstableEvaluationRuleBody,+ PostUnstableEvaluationRuleBody,+} from "@/src/features/public-api/types/unstable-evaluation-rules";+import {+ GetUnstableEvaluatorsQuery,+ PostUnstableEvaluatorBody,+} from "@/src/features/public-api/types/unstable-evaluators";++const numericOutputDefinition = createNumericEvalOutputDefinition({+ reasoningDescription: "Why the score was assigned",+ scoreDescription: "A score between 0 and 1",+});++const expectUnstablePublicApiError = (+ fn: () => unknown,+ params: {+ code: UnstablePublicApiError["code"];+ message?: string;+ details?: Record<string, unknown>;+ },+) => {+ try {+ fn();+ throw new Error("Expected function to throw UnstablePublicApiError");+ } catch (error) {+ expect(error).toBeInstanceOf(UnstablePublicApiError);++ const unstableError = error as UnstablePublicApiError;+ expect(unstableError.code).toBe(params.code);++ if (params.message) {+ expect(unstableError.message).toContain(params.message);+ }++ if (params.details) {+ expect(unstableError.details).toMatchObject(params.details);+ }+ }+};++describe("unstable public eval contracts", () => {+ it("ignores unknown evaluator creation fields for forward compatibility", () => {+ const parsed = PostUnstableEvaluatorBody.parse({+ name: "Answer correctness",+ description: "future field",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: numericOutputDefinition,+ modelConfig: {+ provider: "openai",+ model: "gpt-4.1-mini",+ futureSetting: "ignored",+ },+ });++ expect(parsed).toEqual({+ name: "Answer correctness",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: {+ dataType: "NUMERIC",+ reasoning: {+ description: "Why the score was assigned",+ },+ score: {+ description: "A score between 0 and 1",+ },+ },+ modelConfig: {+ provider: "openai",+ model: "gpt-4.1-mini",+ },+ });+ });++ it("requires outputDefinition.dataType for evaluator creation", () => {+ const parsed = PostUnstableEvaluatorBody.safeParse({+ name: "Answer correctness",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: {+ reasoning: "Explain why the answer is correct or incorrect.",+ score: "Return a score between 0 and 1.",+ },+ });++ expect(parsed.success).toBe(false);+ expect(parsed.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ path: ["outputDefinition", "dataType"],+ }),+ ]),+ );+ });++ it("rejects observation evaluation rules that use expected_output mappings", () => {+ const parsed = PostUnstableEvaluationRuleBody.safeParse({+ name: "answer_quality",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [+ { variable: "output", source: "output" },+ { variable: "expected_output", source: "expected_output" },+ ],+ });++ expect(parsed.success).toBe(false);+ expect(parsed.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ path: ["mapping", 1, "source"],+ }),+ ]),+ );+ });++ it("rejects experiment filter updates unless target is provided", () => {+ const parsed = PatchUnstableEvaluationRuleBody.safeParse({+ filter: [+ {+ type: "stringOptions",+ column: "datasetId",+ operator: "any of",+ value: ["dataset-1"],+ },+ ],+ });++ expect(parsed.success).toBe(false);+ expect(parsed.error?.issues.length).toBeGreaterThan(0);+ });++ it("rejects non-positive unstable pagination limits", () => {+ expect(+ GetUnstableEvaluatorsQuery.safeParse({+ page: 1,+ limit: 0,+ }).success,+ ).toBe(false);+ expect(+ GetUnstableEvaluationRulesQuery.safeParse({+ page: 1,+ limit: -1,+ }).success,+ ).toBe(false);+ });++ it("rejects non-integer unstable pagination values", () => {+ expect(+ GetUnstableEvaluatorsQuery.safeParse({+ page: 1.5,+ limit: 10,+ }).success,+ ).toBe(false);+ expect(+ GetUnstableEvaluationRulesQuery.safeParse({+ page: 1,+ limit: 1.5,+ }).success,+ ).toBe(false);+ });++ it("ignores unknown evaluation rule update fields for forward compatibility", () => {+ const parsed = PatchUnstableEvaluationRuleBody.parse({+ name: "answer_quality",+ newFieldFromFutureVersion: true,+ });++ expect(parsed).toEqual({+ name: "answer_quality",+ });+ });++ it("preserves target-specific patch fields instead of dropping them into the untargeted schema", () => {+ const parsed = PatchUnstableEvaluationRuleBody.parse({+ name: "experiment-expected-output-match",+ target: "experiment",+ filter: [+ {+ type: "stringOptions",+ column: "datasetId",+ operator: "any of",+ value: ["dataset-prod"],+ },+ ],+ mapping: [+ { variable: "output", source: "output" },+ { variable: "expected_output", source: "expected_output" },+ ],+ });++ expect(parsed).toEqual({+ name: "experiment-expected-output-match",+ target: "experiment",+ filter: [+ {+ type: "stringOptions",+ column: "datasetId",+ operator: "any of",+ value: ["dataset-prod"],+ },+ ],+ mapping: [+ { variable: "output", source: "output" },+ { variable: "expected_output", source: "expected_output" },+ ],+ });+ });++ it("rejects invalid target-specific patch payloads instead of silently parsing a name-only subset", () => {+ const parsed = PatchUnstableEvaluationRuleBody.safeParse({+ name: "experiment-expected-output-match",+ target: "experiment",+ filter: [+ {+ type: "stringOptions",+ column: "type",+ operator: "any of",+ value: ["GENERATION"],+ },+ ],+ });++ expect(parsed.success).toBe(false);+ expect(parsed.error?.issues.length).toBeGreaterThan(0);+ });+});++describe("unstable public eval adapters", () => {+ it("translates evaluation rule writes into job configuration inputs", () => {+ const writeModel = toJobConfigurationInput({+ input: {+ name: "expected_output_match",+ target: "experiment",+ enabled: false,+ sampling: 0.25,+ filter: [+ {+ type: "stringOptions",+ column: "datasetId",+ operator: "any of",+ value: ["dataset-1"],+ },+ ],+ mapping: [+ { variable: "output", source: "output" },+ { variable: "expected_output", source: "expected_output" },+ ],+ },+ evaluatorVariables: ["output", "expected_output"],+ });++ expect(writeModel).toMatchObject({+ scoreName: "expected_output_match",+ targetObject: EvalTargetObject.EXPERIMENT,+ sampling: 0.25,+ status: JobConfigState.INACTIVE,+ filter: [+ {+ type: "stringOptions",+ column: "experimentDatasetId",+ operator: "any of",+ value: ["dataset-1"],+ },+ ],+ variableMapping: [+ {+ templateVariable: "output",+ selectedColumnId: "output",+ jsonSelector: null,+ },+ {+ templateVariable: "expected_output",+ selectedColumnId: "experimentItemExpectedOutput",+ jsonSelector: null,+ },+ ],+ });+ });++ it("reads legacy expected output mapping column ids without failing", () => {+ const evaluationRule = toApiEvaluationRule({+ id: "ceval_123",+ projectId: "project_123",+ evalTemplateId: "tmpl_project_v2",+ scoreName: "expected_output_match",+ targetObject: EvalTargetObject.EXPERIMENT,+ filter: [],+ variableMapping: [+ {+ templateVariable: "expected_output",+ selectedColumnId: "experiment_item_expected_output",+ jsonSelector: null,+ },+ ],+ sampling: 1,+ status: JobConfigState.ACTIVE,+ blockedAt: null,+ blockReason: null,+ blockMessage: null,+ createdAt: new Date("2026-03-30T08:00:00.000Z"),+ updatedAt: new Date("2026-03-30T08:00:00.000Z"),+ evalTemplate: {+ id: "tmpl_project_v2",+ projectId: "project_123",+ name: "Answer correctness",+ vars: ["expected_output"],+ prompt: "Judge {{expected_output}}",+ },+ } as unknown as StoredPublicEvaluationRuleConfig);++ expect(evaluationRule.mapping).toEqual([+ {+ variable: "expected_output",+ source: "expected_output",+ },+ ]);+ });++ it("rejects invalid static filter option values", () => {+ expectUnstablePublicApiError(+ () =>+ toJobConfigurationInput({+ input: {+ name: "answer_quality",+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [+ {+ type: "stringOptions",+ column: "type",+ operator: "any of",+ value: ["NOT_A_REAL_TYPE"],+ },+ ],+ mapping: [{ variable: "input", source: "input" }],+ },+ evaluatorVariables: ["input"],+ }),+ {+ code: "invalid_filter_value",+ details: {+ field: "filter[0].value",+ column: "type",+ invalidValues: ["NOT_A_REAL_TYPE"],+ },+ },+ );+ });++ it("rejects malformed jsonPath selectors", () => {+ expectUnstablePublicApiError(+ () =>+ toJobConfigurationInput({+ input: {+ name: "metadata_projection",+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [+ {+ variable: "input",+ source: "metadata",+ jsonPath: "$[",+ },+ ],+ },+ evaluatorVariables: ["input"],+ }),+ {+ code: "invalid_json_path",+ details: {+ field: "mapping[0].jsonPath",+ variable: "input",+ value: "$[",+ },+ },+ );+ });++ it("rejects mapping sources that are incompatible with the selected target", () => {+ expectUnstablePublicApiError(+ () =>+ toJobConfigurationInput({+ input: {+ name: "answer_quality",+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [+ { variable: "expected_output", source: "expected_output" },+ ],+ },+ evaluatorVariables: ["expected_output"],+ }),+ {+ code: "invalid_variable_mapping",+ details: {+ field: "mapping[0].source",+ variable: "expected_output",+ },+ },+ );+ });++ it("rejects missing evaluator variable mappings", () => {+ expectUnstablePublicApiError(+ () =>+ toJobConfigurationInput({+ input: {+ name: "answer_quality",+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [{ variable: "input", source: "input" }],+ },+ evaluatorVariables: ["input", "output"],+ }),+ {+ code: "missing_variable_mapping",+ details: {+ field: "mapping",+ variables: ["output"],+ },+ },+ );+ });++ it("maps evaluator records to exact template versions", () => {+ const template: StoredPublicEvaluatorTemplate = {+ id: "tmpl_latest",+ projectId: null,+ name: "answer-correctness",+ version: 7,+ prompt: "Judge {{input}} against {{output}}",+ partner: "ragas",+ provider: "openai",+ model: "gpt-4.1-mini",+ modelParams: { temperature: 0 },+ vars: ["input", "output"],+ outputDefinition: numericOutputDefinition,+ createdAt: new Date("2026-03-30T08:00:00.000Z"),+ updatedAt: new Date("2026-03-30T09:00:00.000Z"),+ };++ expect(+ toApiEvaluator({+ template,+ evaluationRuleCount: 2,+ }),+ ).toMatchObject({+ id: "tmpl_latest",+ name: "answer-correctness",+ version: 7,+ scope: "managed",+ type: "llm_as_judge",+ outputDefinition: {+ dataType: "NUMERIC",+ reasoning: {+ description: "Why the score was assigned",+ },+ score: {+ description: "A score between 0 and 1",+ },+ },+ modelConfig: {+ provider: "openai",+ model: "gpt-4.1-mini",+ },+ variables: ["input", "output"],+ evaluationRuleCount: 2,+ });+ });++ 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,+ prompt: "Judge {{input}} against {{output}}",+ partner: null,+ provider: null,+ model: null,+ modelParams: null,+ vars: ["input", "output"],+ outputDefinition: {+ reasoning: "Explain why the answer is correct or incorrect.",+ score: "Return a score between 0 and 1.",+ },+ createdAt: new Date("2026-03-30T08:00:00.000Z"),+ updatedAt: new Date("2026-03-30T09:00:00.000Z"),+ };++ expect(+ 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.",+ },+ });+ });++ it("maps evaluation rules to exact referenced template ids", () => {+ const config: StoredPublicEvaluationRuleConfig = {+ id: "ceval_123",+ projectId: "project_123",+ evalTemplateId: "tmpl_exact",+ scoreName: "answer_quality",+ targetObject: EvalTargetObject.EVENT,+ filter: [],+ variableMapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ ],+ sampling: 1,+ status: JobConfigState.ACTIVE,+ blockedAt: null,+ blockReason: null,+ blockMessage: null,+ createdAt: new Date("2026-03-30T08:00:00.000Z"),+ updatedAt: new Date("2026-03-30T09:00:00.000Z"),+ evalTemplate: {+ id: "tmpl_exact",+ projectId: "project_123",+ name: "Answer correctness",+ vars: ["input"],+ prompt: "Judge {{input}}",+ },+ };++ expect(toApiEvaluationRule(config)).toMatchObject({+ evaluator: {+ id: "tmpl_exact",+ name: "Answer correctness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ status: "active",+ });+ });+});diff --git a/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-queries.servertest.tsnew file mode 100644index 0000000000..910fdf9893--- /dev/null+++ b/web/src/__tests__/server/unit/unstable-evals-queries.servertest.ts@@ -0,0 +1,211 @@+/** @jest-environment node */++jest.mock("@langfuse/shared/src/db", () => {+ return {+ Prisma: {+ sql: (strings: TemplateStringsArray, ...values: unknown[]) => ({+ strings,+ values,+ }),+ },+ prisma: {+ $queryRaw: jest.fn(),+ evalTemplate: {+ findMany: jest.fn(),+ findFirst: jest.fn(),+ },+ jobConfiguration: {+ count: jest.fn(),+ groupBy: jest.fn(),+ },+ },+ };+});++import { prisma } from "@langfuse/shared/src/db";+import {+ countActiveEvaluationRules,+ countEvaluationRulesForEvaluatorIds,+ loadEvaluatorForEvaluationRule,+ listPublicEvaluatorTemplates,+} from "@/src/features/evals/server/unstable-public-api/queries";++const mockQueryRaw = prisma.$queryRaw as jest.Mock;+const mockEvalTemplateFindMany = prisma.evalTemplate.findMany as jest.Mock;+const mockEvalTemplateFindFirst = prisma.evalTemplate.findFirst as jest.Mock;+const mockJobConfigurationCount = prisma.jobConfiguration.count as jest.Mock;+const mockJobConfigurationGroupBy = prisma.jobConfiguration+ .groupBy as jest.Mock;++describe("unstable public eval queries", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it("paginates latest evaluator versions per family before loading exact templates", async () => {+ mockQueryRaw+ .mockResolvedValueOnce([+ { id: "tmpl_project_v2" },+ { id: "tmpl_managed_v7" },+ ])+ .mockResolvedValueOnce([{ count: 3n }]);+ mockEvalTemplateFindMany.mockResolvedValueOnce([+ {+ id: "tmpl_managed_v7",+ projectId: null,+ name: "Answer correctness",+ version: 7,+ },+ {+ id: "tmpl_project_v2",+ projectId: "project_123",+ name: "Answer correctness",+ version: 2,+ },+ ]);++ const result = await listPublicEvaluatorTemplates({+ projectId: "project_123",+ page: 2,+ limit: 2,+ });++ expect(mockQueryRaw).toHaveBeenCalledTimes(2);+ expect(mockEvalTemplateFindMany).toHaveBeenCalledWith({+ where: {+ id: {+ in: ["tmpl_project_v2", "tmpl_managed_v7"],+ },+ },+ });+ expect(result.totalItems).toBe(3);+ expect(result.templates.map((template) => template.id)).toEqual([+ "tmpl_project_v2",+ "tmpl_managed_v7",+ ]);+ });++ it("skips the groupBy lookup when no evaluator ids are requested", async () => {+ const result = await countEvaluationRulesForEvaluatorIds({+ projectId: "project_123",+ evaluatorIds: [],+ });++ expect(result).toEqual({});+ expect(mockJobConfigurationGroupBy).not.toHaveBeenCalled();+ });++ it("counts evaluation rules by exact evaluator template id", async () => {+ mockJobConfigurationGroupBy.mockResolvedValueOnce([+ {+ evalTemplateId: "tmpl_project_v2",+ _count: { _all: 2 },+ },+ {+ evalTemplateId: "tmpl_managed_v7",+ _count: { _all: 1 },+ },+ ]);++ const result = await countEvaluationRulesForEvaluatorIds({+ projectId: "project_123",+ evaluatorIds: ["tmpl_project_v2", "tmpl_managed_v7"],+ });++ expect(mockJobConfigurationGroupBy).toHaveBeenCalledWith({+ by: ["evalTemplateId"],+ where: {+ projectId: "project_123",+ targetObject: {+ in: ["event", "experiment"],+ },+ evalTemplateId: {+ in: ["tmpl_project_v2", "tmpl_managed_v7"],+ },+ },+ _count: {+ _all: true,+ },+ });+ expect(result).toEqual({+ tmpl_project_v2: 2,+ tmpl_managed_v7: 1,+ });+ });++ it("counts all active evaluation rules in the project", async () => {+ mockJobConfigurationCount.mockResolvedValueOnce(17);++ const result = await countActiveEvaluationRules({+ projectId: "project_123",+ });++ expect(mockJobConfigurationCount).toHaveBeenCalledWith({+ where: {+ projectId: "project_123",+ jobType: "EVAL",+ targetObject: {+ in: ["event", "experiment"],+ },+ status: "ACTIVE",+ blockedAt: null,+ },+ });+ expect(result).toBe(17);+ });++ it("resolves project evaluator families to the latest version by name and scope", async () => {+ mockEvalTemplateFindFirst.mockResolvedValueOnce({+ id: "tmpl_project_v3",+ projectId: "project_123",+ name: "Answer correctness",+ version: 3,+ });++ const result = await loadEvaluatorForEvaluationRule({+ projectId: "project_123",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ });+ expect(mockEvalTemplateFindFirst).toHaveBeenCalledWith({+ where: {+ projectId: "project_123",+ name: "Answer correctness",+ },+ orderBy: {+ version: "desc",+ },+ });+ expect(result.template.id).toBe("tmpl_project_v3");+ });++ it("resolves managed evaluator families by name and scope", async () => {+ mockEvalTemplateFindFirst.mockResolvedValueOnce({+ id: "tmpl_managed_v7",+ projectId: null,+ name: "Answer correctness",+ version: 7,+ });++ const result = await loadEvaluatorForEvaluationRule({+ projectId: "project_123",+ evaluator: {+ name: "Answer correctness",+ scope: "managed",+ },+ });++ expect(mockEvalTemplateFindFirst).toHaveBeenCalledWith({+ where: {+ projectId: null,+ name: "Answer correctness",+ },+ orderBy: {+ version: "desc",+ },+ });+ expect(result.template.id).toBe("tmpl_managed_v7");+ });+});diff --git a/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts b/web/src/__tests__/server/unit/unstable-evals-service.servertest.tsnew file mode 100644index 0000000000..75e628469c--- /dev/null+++ b/web/src/__tests__/server/unit/unstable-evals-service.servertest.ts@@ -0,0 +1,1033 @@+/** @jest-environment node */++const mockEvalTemplateCreate = jest.fn();+const mockEvalTemplateFindMany = jest.fn();+const mockJobConfigurationFindMany = jest.fn();+const mockJobConfigurationUpdate = jest.fn();++jest.mock(+ "../../../features/evals/server/unstable-public-api/validation",+ () => {+ const actual = jest.requireActual(+ "../../../features/evals/server/unstable-public-api/validation",+ );++ return {+ ...actual,+ assertEvaluatorDefinitionCanRunForPublicApi: jest.fn(),+ };+ },+);++jest.mock("../../../features/evals/server/unstable-public-api/queries", () => ({+ countActiveEvaluationRules: jest.fn(),+ findPublicEvaluatorTemplateOrThrow: jest.fn(),+ countEvaluationRulesForEvaluator: jest.fn(),+ countEvaluationRulesForEvaluatorIds: jest.fn(),+ listPublicEvaluatorTemplates: jest.fn(),+ loadEvaluatorForEvaluationRule: jest.fn(),+ findPublicEvaluationRuleOrThrow: jest.fn(),+}));++jest.mock("@langfuse/shared/src/server", () => ({+ ...jest.requireActual("@langfuse/shared/src/server"),+ invalidateProjectEvalConfigCaches: jest.fn(),+ ClickHouseClientManager: {+ getInstance: () => ({+ closeAllConnections: jest.fn().mockResolvedValue(undefined),+ }),+ },+ logger: {+ debug: jest.fn(),+ },+}));++jest.mock("@langfuse/shared/src/db", () => ({+ Prisma: {+ PrismaClientKnownRequestError: class PrismaClientKnownRequestError extends Error {+ code: string;+ clientVersion: string;++ constructor(+ message: string,+ {+ code,+ clientVersion,+ }: {+ code: string;+ clientVersion: string;+ },+ ) {+ super(message);+ this.code = code;+ this.clientVersion = clientVersion;+ }+ },+ },+ prisma: {+ $transaction: jest.fn(),+ dataset: {+ findMany: jest.fn(),+ },+ jobConfiguration: {+ findFirst: jest.fn(),+ create: jest.fn(),+ update: jest.fn(),+ },+ },+}));++import {+ createNumericEvalOutputDefinition,+ EvalTargetObject,+ JobConfigState,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { createUnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";+import {+ createPublicEvaluationRule,+ updatePublicEvaluationRule,+} from "@/src/features/evals/server/unstable-public-api/evaluation-rule-service";+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";++const numericOutputDefinition = createNumericEvalOutputDefinition({+ reasoningDescription: "Why the score was assigned",+ scoreDescription: "A score between 0 and 1",+});++const projectTemplate = {+ id: "tmpl_project_v2",+ projectId: "project_123",+ name: "Answer correctness",+ version: 2,+ prompt: "Judge {{input}}",+ partner: null,+ provider: null,+ model: null,+ modelParams: null,+ vars: ["input"],+ outputDefinition: numericOutputDefinition,+ createdAt: new Date("2026-03-30T08:00:00.000Z"),+ updatedAt: new Date("2026-03-30T08:00:00.000Z"),+};++const managedTemplate = {+ id: "tmpl_managed",+ projectId: null,+ name: "Answer correctness",+ version: 7,+ prompt: "Judge {{input}}",+ partner: "ragas",+ provider: null,+ model: null,+ modelParams: null,+ vars: ["input"],+ outputDefinition: numericOutputDefinition,+ createdAt: new Date("2026-03-30T08:00:00.000Z"),+ updatedAt: new Date("2026-03-30T08:00:00.000Z"),+};++const mockedPrisma = prisma as unknown as {+ $transaction: jest.Mock;+ dataset: {+ findMany: jest.Mock;+ };+ jobConfiguration: {+ findFirst: jest.Mock;+ create: jest.Mock;+ update: jest.Mock;+ };+};+const mockAssertEvaluatorDefinitionCanRunForPublicApi = jest.mocked(+ validationModule.assertEvaluatorDefinitionCanRunForPublicApi,+);+const mockLoadEvaluatorForEvaluationRule = jest.mocked(+ queryModule.loadEvaluatorForEvaluationRule,+);+const mockCountActiveEvaluationRules = jest.mocked(+ queryModule.countActiveEvaluationRules,+);+const mockFindPublicEvaluationRuleOrThrow = jest.mocked(+ queryModule.findPublicEvaluationRuleOrThrow,+);+const mockCountEvaluationRulesForEvaluator = jest.mocked(+ queryModule.countEvaluationRulesForEvaluator,+);++const createEvaluationRuleRecord = (overrides?: Record<string, unknown>) =>+ ({+ id: "ceval_123",+ projectId: "project_123",+ evalTemplateId: "tmpl_project_v2",+ scoreName: "answer_quality",+ targetObject: EvalTargetObject.EVENT,+ filter: [],+ variableMapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ ],+ sampling: 1,+ status: JobConfigState.ACTIVE,+ blockedAt: null,+ blockReason: null,+ blockMessage: null,+ createdAt: new Date("2026-03-30T08:00:00.000Z"),+ updatedAt: new Date("2026-03-30T09:00:00.000Z"),+ evalTemplate: {+ id: "tmpl_project_v2",+ projectId: "project_123",+ name: "Answer correctness",+ vars: ["input"],+ prompt: "Judge {{input}}",+ },+ ...overrides,+ }) as any;++describe("unstable public eval services", () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockCountActiveEvaluationRules.mockResolvedValue(0);+ mockCountEvaluationRulesForEvaluator.mockResolvedValue(0);+ mockedPrisma.dataset.findMany.mockResolvedValue([]);++ mockedPrisma.$transaction.mockImplementation(async (callback) =>+ callback({+ evalTemplate: {+ create: mockEvalTemplateCreate,+ findMany: mockEvalTemplateFindMany,+ },+ jobConfiguration: {+ findMany: mockJobConfigurationFindMany,+ update: mockJobConfigurationUpdate,+ },+ }),+ );+ });++ it("rejects unrunnable evaluator submissions before writing", async () => {+ mockAssertEvaluatorDefinitionCanRunForPublicApi.mockRejectedValueOnce(+ createUnstablePublicApiError({+ httpCode: 422,+ code: "evaluator_preflight_failed",+ message: "No valid LLM model found for evaluator",+ }),+ );++ await expect(+ createPublicEvaluator({+ projectId: "project_123",+ input: {+ name: "Answer correctness",+ prompt: "Judge {{input}}",+ outputDefinition: numericOutputDefinition,+ },+ }),+ ).rejects.toThrow("No valid LLM model found for evaluator");++ expect(mockedPrisma.$transaction).not.toHaveBeenCalled();+ expect(mockEvalTemplateCreate).not.toHaveBeenCalled();+ });++ it("creates a new project-owned evaluator family at version 1", async () => {+ mockEvalTemplateFindMany.mockResolvedValueOnce([]);+ mockEvalTemplateCreate.mockResolvedValueOnce({+ ...projectTemplate,+ id: "tmpl_project_v1",+ 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: "Answer correctness",+ prompt: "Judge {{input}}",+ outputDefinition: numericOutputDefinition,+ },+ });++ expect(mockEvalTemplateFindMany).toHaveBeenCalledWith({+ where: {+ projectId: "project_123",+ name: "Answer correctness",+ },+ select: {+ id: true,+ version: true,+ },+ orderBy: [+ {+ version: "desc",+ },+ {+ createdAt: "desc",+ },+ {+ id: "desc",+ },+ ],+ });+ expect(mockEvalTemplateCreate).toHaveBeenCalledWith({+ data: expect.objectContaining({+ projectId: "project_123",+ name: "Answer correctness",+ version: 1,+ }),+ });+ expect(mockJobConfigurationFindMany).not.toHaveBeenCalled();+ expect(mockJobConfigurationUpdate).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ id: "tmpl_project_v1",+ version: 1,+ scope: "project",+ });+ });++ it("creates a new evaluator version when the project name already exists", async () => {+ mockCountEvaluationRulesForEvaluator.mockResolvedValueOnce(2);+ mockEvalTemplateFindMany.mockResolvedValueOnce([+ {+ id: "tmpl_project_v2",+ version: 2,+ },+ {+ id: "tmpl_project_v1",+ version: 1,+ },+ ]);+ mockJobConfigurationFindMany.mockResolvedValueOnce([+ {+ id: "ceval_123",+ scoreName: "answer_quality",+ variableMapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ ],+ },+ ]);+ mockEvalTemplateCreate.mockResolvedValueOnce({+ ...projectTemplate,+ id: "tmpl_project_v3",+ version: 3,+ });++ const result = await createPublicEvaluator({+ projectId: "project_123",+ input: {+ name: "Answer correctness",+ prompt: "Judge {{input}}",+ outputDefinition: numericOutputDefinition,+ },+ });++ expect(mockEvalTemplateCreate).toHaveBeenCalledWith({+ data: expect.objectContaining({+ projectId: "project_123",+ name: "Answer correctness",+ version: 3,+ }),+ });+ expect(mockJobConfigurationFindMany).toHaveBeenCalledWith({+ where: {+ projectId: "project_123",+ evalTemplateId: {+ in: ["tmpl_project_v2", "tmpl_project_v1"],+ },+ },+ select: {+ id: true,+ scoreName: true,+ variableMapping: true,+ },+ });+ expect(mockJobConfigurationUpdate).toHaveBeenCalledWith({+ where: {+ id: "ceval_123",+ projectId: "project_123",+ },+ data: {+ evalTemplateId: "tmpl_project_v3",+ variableMapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ ],+ },+ });+ expect(result).toMatchObject({+ id: "tmpl_project_v3",+ version: 3,+ scope: "project",+ evaluationRuleCount: 2,+ });+ });++ it("drops obsolete variable mappings when auto-upgrading linked evaluation rules", async () => {+ mockEvalTemplateFindMany.mockResolvedValueOnce([+ {+ id: "tmpl_project_v2",+ version: 2,+ },+ ]);+ mockJobConfigurationFindMany.mockResolvedValueOnce([+ {+ id: "ceval_123",+ scoreName: "answer_quality",+ variableMapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ {+ templateVariable: "output",+ selectedColumnId: "output",+ jsonSelector: null,+ },+ ],+ },+ ]);+ mockEvalTemplateCreate.mockResolvedValueOnce({+ ...projectTemplate,+ id: "tmpl_project_v3",+ prompt: "Judge {{input}}",+ vars: ["input"],+ version: 3,+ });++ await createPublicEvaluator({+ projectId: "project_123",+ input: {+ name: "Answer correctness",+ prompt: "Judge {{input}}",+ outputDefinition: numericOutputDefinition,+ },+ });++ expect(mockJobConfigurationUpdate).toHaveBeenCalledWith({+ where: {+ id: "ceval_123",+ projectId: "project_123",+ },+ data: {+ evalTemplateId: "tmpl_project_v3",+ variableMapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ ],+ },+ });+ });++ it("rejects evaluator version creation when linked evaluation rules need new mappings", async () => {+ mockEvalTemplateFindMany.mockResolvedValueOnce([+ {+ id: "tmpl_project_v2",+ version: 2,+ },+ ]);+ mockJobConfigurationFindMany.mockResolvedValueOnce([+ {+ id: "ceval_123",+ scoreName: "answer_quality",+ variableMapping: [+ {+ templateVariable: "input",+ selectedColumnId: "input",+ jsonSelector: null,+ },+ ],+ },+ ]);++ await expect(+ createPublicEvaluator({+ projectId: "project_123",+ input: {+ name: "Answer correctness",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ }),+ ).rejects.toThrow(+ 'Creating a new evaluator version would invalidate the evaluation rule "answer_quality"',+ );++ expect(mockEvalTemplateCreate).not.toHaveBeenCalled();+ expect(mockJobConfigurationUpdate).not.toHaveBeenCalled();+ });++ it("resolves an older evaluator version to the latest version when creating an evaluation rule", async () => {+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: {+ ...projectTemplate,+ id: "tmpl_project_v3",+ version: 3,+ },+ });+ mockedPrisma.jobConfiguration.create.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ evalTemplateId: "tmpl_project_v3",+ evalTemplate: {+ id: "tmpl_project_v3",+ projectId: "project_123",+ name: "Answer correctness",+ vars: ["input"],+ prompt: "Judge {{input}}",+ },+ }),+ );++ const result = await createPublicEvaluationRule({+ projectId: "project_123",+ input: {+ name: "answer_quality_latest",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [{ variable: "input", source: "input" }],+ },+ });++ expect(mockLoadEvaluatorForEvaluationRule).toHaveBeenCalledWith({+ projectId: "project_123",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ });+ expect(mockedPrisma.jobConfiguration.create).toHaveBeenCalledWith({+ data: expect.objectContaining({+ evalTemplateId: "tmpl_project_v3",+ }),+ include: expect.any(Object),+ });+ expect(result).toMatchObject({+ evaluator: {+ id: "tmpl_project_v3",+ name: "Answer correctness",+ scope: "project",+ },+ });+ });++ it("rejects unrunnable enabled evaluation rules before writing", async () => {+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: projectTemplate,+ });+ mockAssertEvaluatorDefinitionCanRunForPublicApi.mockRejectedValueOnce(+ createUnstablePublicApiError({+ httpCode: 422,+ code: "evaluator_preflight_failed",+ message: "Model configuration not valid for evaluator",+ }),+ );++ await expect(+ createPublicEvaluationRule({+ projectId: "project_123",+ input: {+ name: "answer_quality",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [{ variable: "input", source: "input" }],+ },+ }),+ ).rejects.toThrow("Model configuration not valid for evaluator");++ 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",+ });++ await expect(+ createPublicEvaluationRule({+ projectId: "project_123",+ input: {+ name: "answer_quality",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [{ variable: "input", source: "input" }],+ },+ }),+ ).rejects.toThrow(+ 'An evaluation rule named "answer_quality" already exists in this project.',+ );++ expect(mockLoadEvaluatorForEvaluationRule).not.toHaveBeenCalled();+ expect(mockedPrisma.jobConfiguration.create).not.toHaveBeenCalled();+ });++ it("rejects creating more than 50 active evaluation rules", async () => {+ mockCountActiveEvaluationRules.mockResolvedValueOnce(50);++ await expect(+ createPublicEvaluationRule({+ projectId: "project_123",+ input: {+ name: "answer_quality",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [{ variable: "input", source: "input" }],+ },+ }),+ ).rejects.toThrow(+ "This project already has the maximum number of active evaluation rules (50).",+ );++ expect(mockLoadEvaluatorForEvaluationRule).not.toHaveBeenCalled();+ expect(mockedPrisma.jobConfiguration.create).not.toHaveBeenCalled();+ });++ it("rejects experiment evaluation rules that reference unknown dataset ids", async () => {+ mockedPrisma.dataset.findMany.mockResolvedValueOnce([+ { id: "dataset_valid" },+ ]);++ await expect(+ createPublicEvaluationRule({+ projectId: "project_123",+ input: {+ name: "experiment_answer_quality",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ target: "experiment",+ enabled: true,+ sampling: 1,+ filter: [+ {+ type: "stringOptions",+ column: "datasetId",+ operator: "any of",+ value: ["dataset_valid", "dataset_missing"],+ },+ ],+ mapping: [{ variable: "input", source: "input" }],+ },+ }),+ ).rejects.toThrow(+ 'Filter column "datasetId" contains dataset id(s) that do not exist in this project: dataset_missing',+ );++ expect(mockedPrisma.dataset.findMany).toHaveBeenCalledWith({+ where: {+ projectId: "project_123",+ id: {+ in: ["dataset_valid", "dataset_missing"],+ },+ },+ select: {+ id: true,+ },+ });+ expect(mockLoadEvaluatorForEvaluationRule).not.toHaveBeenCalled();+ expect(mockedPrisma.jobConfiguration.create).not.toHaveBeenCalled();+ });++ it("passes stored modelParams into create-time evaluator preflight", async () => {+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: {+ ...projectTemplate,+ provider: "openai",+ model: "gpt-4.1-mini",+ modelParams: { temperature: 0.2 },+ },+ });+ mockedPrisma.jobConfiguration.create.mockResolvedValueOnce(+ createEvaluationRuleRecord(),+ );++ await createPublicEvaluationRule({+ projectId: "project_123",+ input: {+ name: "answer_quality",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [{ variable: "input", source: "input" }],+ },+ });++ expect(+ mockAssertEvaluatorDefinitionCanRunForPublicApi,+ ).toHaveBeenCalledWith({+ projectId: "project_123",+ template: expect.objectContaining({+ name: "Answer correctness",+ provider: "openai",+ model: "gpt-4.1-mini",+ modelParams: { temperature: 0.2 },+ }),+ });+ });++ it("allows disabled evaluation rules without preflight", async () => {+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: projectTemplate,+ });+ mockedPrisma.jobConfiguration.create.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ status: JobConfigState.INACTIVE,+ }),+ );++ const result = await createPublicEvaluationRule({+ projectId: "project_123",+ input: {+ name: "answer_quality",+ evaluator: {+ name: "Answer correctness",+ scope: "project",+ },+ target: "observation",+ enabled: false,+ sampling: 1,+ filter: [],+ mapping: [{ variable: "input", source: "input" }],+ },+ });++ expect(+ mockAssertEvaluatorDefinitionCanRunForPublicApi,+ ).not.toHaveBeenCalled();+ expect(result).toMatchObject({+ evaluator: {+ id: "tmpl_project_v2",+ name: "Answer correctness",+ scope: "project",+ },+ enabled: false,+ status: "inactive",+ });+ });++ it("allows evaluation rules to reference managed evaluators by exact template id", async () => {+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: managedTemplate,+ });+ mockedPrisma.jobConfiguration.create.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ evalTemplateId: "tmpl_managed",+ evalTemplate: {+ id: "tmpl_managed",+ projectId: null,+ name: "Answer correctness",+ vars: ["input"],+ prompt: "Judge {{input}}",+ },+ }),+ );++ const result = await createPublicEvaluationRule({+ projectId: "project_123",+ input: {+ name: "managed_answer_quality",+ evaluator: {+ name: "Answer correctness",+ scope: "managed",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [{ variable: "input", source: "input" }],+ },+ });++ expect(mockedPrisma.jobConfiguration.create).toHaveBeenCalledWith({+ data: expect.objectContaining({+ evalTemplateId: "tmpl_managed",+ }),+ include: expect.any(Object),+ });+ expect(result).toMatchObject({+ evaluator: {+ id: "tmpl_managed",+ name: "Answer correctness",+ scope: "managed",+ },+ enabled: true,+ status: "active",+ });+ });++ it("preserves block metadata when updating without a fresh successful preflight", async () => {+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ blockedAt: new Date("2026-03-30T10:00:00.000Z"),+ blockReason: "EVAL_MODEL_CONFIG_INVALID",+ blockMessage: "Evaluator paused",+ }),+ );+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: projectTemplate,+ });+ mockedPrisma.jobConfiguration.update.mockImplementationOnce(+ async ({ data }: any) =>+ createEvaluationRuleRecord({+ status: data.status,+ sampling: data.sampling,+ filter: data.filter,+ variableMapping: data.variableMapping,+ blockedAt: new Date("2026-03-30T10:00:00.000Z"),+ blockReason: "EVAL_MODEL_CONFIG_INVALID",+ blockMessage: "Evaluator paused",+ }),+ );++ const result = await updatePublicEvaluationRule({+ projectId: "project_123",+ evaluationRuleId: "ceval_123",+ input: {+ enabled: false,+ },+ });++ const updateArgs = mockedPrisma.jobConfiguration.update.mock.calls[0]?.[0];++ expect(+ mockAssertEvaluatorDefinitionCanRunForPublicApi,+ ).not.toHaveBeenCalled();+ expect(updateArgs?.data).not.toHaveProperty("blockedAt");+ expect(updateArgs?.data).not.toHaveProperty("blockReason");+ expect(updateArgs?.data).not.toHaveProperty("blockMessage");+ expect(result).toMatchObject({+ enabled: false,+ status: "inactive",+ pausedReason: "EVAL_MODEL_CONFIG_INVALID",+ });+ });++ it("passes stored modelParams into update-time evaluator preflight", async () => {+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(+ createEvaluationRuleRecord(),+ );+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: {+ ...projectTemplate,+ provider: "openai",+ model: "gpt-4.1-mini",+ modelParams: { temperature: 0.4 },+ },+ });+ mockedPrisma.jobConfiguration.update.mockResolvedValueOnce(+ createEvaluationRuleRecord(),+ );++ await updatePublicEvaluationRule({+ projectId: "project_123",+ evaluationRuleId: "ceval_123",+ input: {+ name: "renamed_answer_quality",+ },+ });++ expect(+ mockAssertEvaluatorDefinitionCanRunForPublicApi,+ ).toHaveBeenCalledWith({+ projectId: "project_123",+ template: expect.objectContaining({+ name: "Answer correctness",+ provider: "openai",+ model: "gpt-4.1-mini",+ modelParams: { temperature: 0.4 },+ }),+ });+ });++ it("rejects enabling a non-active evaluation rule when the active limit is reached", async () => {+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ status: JobConfigState.INACTIVE,+ }),+ );+ mockCountActiveEvaluationRules.mockResolvedValueOnce(50);++ await expect(+ updatePublicEvaluationRule({+ projectId: "project_123",+ evaluationRuleId: "ceval_123",+ input: {+ enabled: true,+ },+ }),+ ).rejects.toThrow(+ "This project already has the maximum number of active evaluation rules (50).",+ );++ expect(mockLoadEvaluatorForEvaluationRule).not.toHaveBeenCalled();+ expect(mockedPrisma.jobConfiguration.update).not.toHaveBeenCalled();+ });++ it("rejects experiment filter updates that reference unknown dataset ids", async () => {+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ targetObject: EvalTargetObject.EXPERIMENT,+ }),+ );+ mockedPrisma.dataset.findMany.mockResolvedValueOnce([]);++ await expect(+ updatePublicEvaluationRule({+ projectId: "project_123",+ evaluationRuleId: "ceval_123",+ input: {+ target: "experiment",+ filter: [+ {+ type: "stringOptions",+ column: "datasetId",+ operator: "any of",+ value: ["dataset_missing"],+ },+ ],+ mapping: [{ variable: "input", source: "input" }],+ },+ }),+ ).rejects.toThrow(+ 'Filter column "datasetId" contains dataset id(s) that do not exist in this project: dataset_missing',+ );++ expect(mockedPrisma.dataset.findMany).toHaveBeenCalledWith({+ where: {+ projectId: "project_123",+ id: {+ in: ["dataset_missing"],+ },+ },+ select: {+ id: true,+ },+ });+ expect(mockLoadEvaluatorForEvaluationRule).not.toHaveBeenCalled();+ expect(mockedPrisma.jobConfiguration.update).not.toHaveBeenCalled();+ });++ it("allows unrelated experiment updates without revalidating stale stored dataset filters", async () => {+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ targetObject: EvalTargetObject.EXPERIMENT,+ filter: [+ {+ type: "stringOptions",+ column: "experimentDatasetId",+ operator: "any of",+ value: ["dataset_deleted"],+ },+ ],+ }),+ );+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: projectTemplate,+ });+ mockedPrisma.jobConfiguration.update.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ targetObject: EvalTargetObject.EXPERIMENT,+ scoreName: "renamed_experiment_answer_quality",+ filter: [+ {+ type: "stringOptions",+ column: "experimentDatasetId",+ operator: "any of",+ value: ["dataset_deleted"],+ },+ ],+ }),+ );++ const result = await updatePublicEvaluationRule({+ projectId: "project_123",+ evaluationRuleId: "ceval_123",+ input: {+ name: "renamed_experiment_answer_quality",+ },+ });++ expect(mockedPrisma.dataset.findMany).not.toHaveBeenCalled();+ expect(mockedPrisma.jobConfiguration.update).toHaveBeenCalled();+ expect(result).toMatchObject({+ name: "renamed_experiment_answer_quality",+ target: "experiment",+ filter: [+ {+ type: "stringOptions",+ column: "datasetId",+ operator: "any of",+ value: ["dataset_deleted"],+ },+ ],+ });+ });++ it("does not re-check the active limit for already-active evaluation rules", async () => {+ mockFindPublicEvaluationRuleOrThrow.mockResolvedValueOnce(+ createEvaluationRuleRecord(),+ );+ mockLoadEvaluatorForEvaluationRule.mockResolvedValueOnce({+ template: projectTemplate,+ });+ mockedPrisma.jobConfiguration.update.mockResolvedValueOnce(+ createEvaluationRuleRecord({+ scoreName: "renamed_answer_quality",+ }),+ );++ await updatePublicEvaluationRule({+ projectId: "project_123",+ evaluationRuleId: "ceval_123",+ input: {+ name: "renamed_answer_quality",+ },+ });++ expect(mockCountActiveEvaluationRules).not.toHaveBeenCalled();+ expect(mockedPrisma.jobConfiguration.update).toHaveBeenCalled();+ });+});diff --git a/web/src/__tests__/server/unstable-evals-api.servertest.ts b/web/src/__tests__/server/unstable-evals-api.servertest.tsnew file mode 100644index 0000000000..7b18e021c9--- /dev/null+++ b/web/src/__tests__/server/unstable-evals-api.servertest.ts@@ -0,0 +1,505 @@+/** @jest-environment node */++import {+ makeAPICall,+ makeZodVerifiedAPICall,+} from "@/src/__tests__/test-utils";+import {+ DeleteUnstableEvaluationRuleResponse,+ GetUnstableEvaluationRuleResponse,+ PostUnstableEvaluationRuleResponse,+} from "@/src/features/public-api/types/unstable-evaluation-rules";+import {+ GetUnstableEvaluatorResponse,+ GetUnstableEvaluatorsResponse,+ PostUnstableEvaluatorResponse,+} from "@/src/features/public-api/types/unstable-evaluators";+import { createNumericEvalOutputDefinition } from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import {+ createAndAddApiKeysToDb,+ createBasicAuthHeader,+ createOrgProjectAndApiKey,+} from "@langfuse/shared/src/server";+import { ApiKeyScope } from "@prisma/client";+import { UnstablePublicApiErrorResponse } from "@/src/features/public-api/types/unstable-public-evals-contract";+import type { z } from "zod";+import { LLMAdapter } from "@langfuse/shared";+import { encrypt } from "@langfuse/shared/encryption";++const __orgIds: string[] = [];+const __managedTemplateIds: string[] = [];++const numericOutputDefinition = createNumericEvalOutputDefinition({+ reasoningDescription: "Why the score was assigned",+ scoreDescription: "A score between 0 and 1",+});++const provisionDefaultEvalModel = async (projectId: string) => {+ const provider = `openai-${projectId}`;++ const llmApiKey = await prisma.llmApiKeys.create({+ data: {+ projectId,+ provider,+ adapter: LLMAdapter.OpenAI,+ secretKey: encrypt("sk-test"),+ displaySecretKey: "...test",+ baseURL: "https://api.openai.com/v1",+ customModels: [],+ withDefaultModels: true,+ extraHeaders: null,+ extraHeaderKeys: [],+ },+ });++ await prisma.defaultLlmModel.create({+ data: {+ projectId,+ llmApiKeyId: llmApiKey.id,+ provider,+ adapter: LLMAdapter.OpenAI,+ model: "gpt-4.1-mini",+ },+ });+};++const expectUnstableError = (+ response: Awaited<ReturnType<typeof makeAPICall>>,+ params: {+ status: number;+ code: z.infer<typeof UnstablePublicApiErrorResponse>["code"];+ },+) => {+ expect(response.status).toBe(params.status);+ const body = UnstablePublicApiErrorResponse.parse(response.body);+ expect(body.code).toBe(params.code);+ return body;+};++const createManagedEvaluator = async (params: {+ name: string;+ version: number;+ prompt?: string;+}) => {+ const template = await prisma.evalTemplate.create({+ data: {+ projectId: null,+ name: params.name,+ version: params.version,+ prompt: params.prompt ?? "Judge {{input}} against {{output}}",+ partner: "ragas",+ vars: ["input", "output"],+ outputDefinition: numericOutputDefinition,+ },+ });++ __managedTemplateIds.push(template.id);+ return template;+};++describe("/api/public/unstable evaluators API", () => {+ let auth: string;++ beforeEach(async () => {+ const result = await createOrgProjectAndApiKey();+ auth = result.auth;+ __orgIds.push(result.orgId);+ await provisionDefaultEvalModel(result.projectId);+ });++ afterAll(async () => {+ await prisma.jobConfiguration.deleteMany({+ where: {+ evalTemplateId: {+ in: __managedTemplateIds,+ },+ },+ });+ await prisma.evalTemplate.deleteMany({+ where: {+ id: {+ in: __managedTemplateIds,+ },+ },+ });+ await prisma.organization.deleteMany({+ where: {+ id: {+ in: __orgIds,+ },+ },+ });+ });++ it("creates exact evaluator versions and lists only the latest project version per family", async () => {+ const v1 = await makeZodVerifiedAPICall(+ PostUnstableEvaluatorResponse,+ "POST",+ "/api/public/unstable/evaluators",+ {+ name: "Answer correctness",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ auth,+ );++ const v2 = await makeZodVerifiedAPICall(+ PostUnstableEvaluatorResponse,+ "POST",+ "/api/public/unstable/evaluators",+ {+ name: "Answer correctness",+ prompt: "Judge {{input}} versus {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ auth,+ );++ expect(v1.body).toMatchObject({+ id: expect.any(String),+ name: "Answer correctness",+ version: 1,+ scope: "project",+ });+ expect(v2.body).toMatchObject({+ id: expect.any(String),+ name: "Answer correctness",+ version: 2,+ scope: "project",+ });+ expect(v2.body.id).not.toBe(v1.body.id);++ const fetchedV1 = await makeZodVerifiedAPICall(+ GetUnstableEvaluatorResponse,+ "GET",+ `/api/public/unstable/evaluators/${v1.body.id}`,+ undefined,+ auth,+ );+ const fetchedV2 = await makeZodVerifiedAPICall(+ GetUnstableEvaluatorResponse,+ "GET",+ `/api/public/unstable/evaluators/${v2.body.id}`,+ undefined,+ auth,+ );++ expect(fetchedV1.body.version).toBe(1);+ expect(fetchedV2.body.version).toBe(2);++ const listed = await makeZodVerifiedAPICall(+ GetUnstableEvaluatorsResponse,+ "GET",+ "/api/public/unstable/evaluators?page=1&limit=50",+ undefined,+ auth,+ );++ const projectFamilyEntries = listed.body.data.filter(+ (evaluator) =>+ evaluator.name === "Answer correctness" &&+ evaluator.scope === "project",+ );++ expect(projectFamilyEntries).toEqual([+ expect.objectContaining({+ id: v2.body.id,+ name: "Answer correctness",+ version: 2,+ scope: "project",+ }),+ ]);+ expect(+ listed.body.data.some((evaluator) => evaluator.id === v1.body.id),+ ).toBe(false);+ });++ it("automatically moves existing evaluation rules to the newest project evaluator version", async () => {+ await makeZodVerifiedAPICall(+ PostUnstableEvaluatorResponse,+ "POST",+ "/api/public/unstable/evaluators",+ {+ name: "Faithfulness",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ auth,+ );++ const created = await makeZodVerifiedAPICall(+ PostUnstableEvaluationRuleResponse,+ "POST",+ "/api/public/unstable/evaluation-rules",+ {+ name: "faithfulness-live",+ evaluator: {+ name: "Faithfulness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [+ { variable: "input", source: "input" },+ { variable: "output", source: "output" },+ ],+ },+ auth,+ );++ const v2 = await makeZodVerifiedAPICall(+ PostUnstableEvaluatorResponse,+ "POST",+ "/api/public/unstable/evaluators",+ {+ name: "Faithfulness",+ prompt: "Judge {{input}} versus {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ auth,+ );++ const fetched = await makeZodVerifiedAPICall(+ GetUnstableEvaluationRuleResponse,+ "GET",+ `/api/public/unstable/evaluation-rules/${created.body.id}`,+ undefined,+ auth,+ );++ expect(v2.body.version).toBe(2);+ expect(fetched.body.evaluator).toEqual({+ id: v2.body.id,+ name: "Faithfulness",+ scope: "project",+ });+ });++ it("resolves project evaluator families to the latest version when creating an evaluation rule", async () => {+ await makeZodVerifiedAPICall(+ PostUnstableEvaluatorResponse,+ "POST",+ "/api/public/unstable/evaluators",+ {+ name: "Answer groundedness",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ auth,+ );++ const v2 = await makeZodVerifiedAPICall(+ PostUnstableEvaluatorResponse,+ "POST",+ "/api/public/unstable/evaluators",+ {+ name: "Answer groundedness",+ prompt: "Judge {{input}} versus {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ auth,+ );++ const created = await makeZodVerifiedAPICall(+ PostUnstableEvaluationRuleResponse,+ "POST",+ "/api/public/unstable/evaluation-rules",+ {+ name: "answer_groundedness_live",+ evaluator: {+ name: "Answer groundedness",+ scope: "project",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [+ { variable: "input", source: "input" },+ { variable: "output", source: "output" },+ ],+ },+ auth,+ );++ expect(created.body.evaluator).toEqual({+ id: v2.body.id,+ name: "Answer groundedness",+ scope: "project",+ });+ });++ it("lists managed and project evaluator families separately when names overlap", async () => {+ const managed = await createManagedEvaluator({+ name: "Groundedness",+ version: 7,+ });++ const projectEvaluator = await makeZodVerifiedAPICall(+ PostUnstableEvaluatorResponse,+ "POST",+ "/api/public/unstable/evaluators",+ {+ name: "Groundedness",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ auth,+ );++ expect(projectEvaluator.body.version).toBe(1);++ const listed = await makeZodVerifiedAPICall(+ GetUnstableEvaluatorsResponse,+ "GET",+ "/api/public/unstable/evaluators?page=1&limit=50",+ undefined,+ auth,+ );++ expect(listed.body.data).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: managed.id,+ name: "Groundedness",+ version: 7,+ scope: "managed",+ }),+ expect.objectContaining({+ id: projectEvaluator.body.id,+ name: "Groundedness",+ version: 1,+ scope: "project",+ }),+ ]),+ );+ });++ it("allows evaluation rules to reference managed evaluators by exact id", async () => {+ const managed = await createManagedEvaluator({+ name: "Answer relevance",+ version: 3,+ });++ const created = await makeZodVerifiedAPICall(+ PostUnstableEvaluationRuleResponse,+ "POST",+ "/api/public/unstable/evaluation-rules",+ {+ name: "answer_relevance_managed",+ evaluator: {+ name: "Answer relevance",+ scope: "managed",+ },+ target: "observation",+ enabled: true,+ sampling: 1,+ filter: [],+ mapping: [+ { variable: "input", source: "input" },+ { variable: "output", source: "output" },+ ],+ },+ auth,+ );++ expect(created.body).toMatchObject({+ evaluator: {+ id: managed.id,+ name: "Answer relevance",+ scope: "managed",+ },+ target: "observation",+ enabled: true,+ status: "active",+ });++ const fetched = await makeZodVerifiedAPICall(+ GetUnstableEvaluationRuleResponse,+ "GET",+ `/api/public/unstable/evaluation-rules/${created.body.id}`,+ undefined,+ auth,+ );++ expect(fetched.body.evaluator).toEqual({+ id: managed.id,+ name: "Answer relevance",+ scope: "managed",+ });++ const deleted = await makeZodVerifiedAPICall(+ DeleteUnstableEvaluationRuleResponse,+ "DELETE",+ `/api/public/unstable/evaluation-rules/${created.body.id}`,+ undefined,+ auth,+ );++ expect(deleted.body.message).toBe("Evaluation rule successfully deleted");+ });++ it("returns method_not_allowed for evaluator patch and delete", async () => {+ const evaluator = await makeZodVerifiedAPICall(+ PostUnstableEvaluatorResponse,+ "POST",+ "/api/public/unstable/evaluators",+ {+ name: "Correctness",+ prompt: "Judge {{input}} against {{output}}",+ outputDefinition: numericOutputDefinition,+ },+ auth,+ );++ const patchRes = await makeAPICall(+ "PATCH",+ `/api/public/unstable/evaluators/${evaluator.body.id}`,+ {+ prompt: "Updated",+ },+ auth,+ );+ const deleteRes = await makeAPICall(+ "DELETE",+ `/api/public/unstable/evaluators/${evaluator.body.id}`,+ undefined,+ auth,+ );++ expectUnstableError(patchRes, {+ status: 405,+ code: "method_not_allowed",+ });+ expectUnstableError(deleteRes, {+ status: 405,+ code: "method_not_allowed",+ });+ });++ it("still rejects invalid auth with the unstable error envelope", async () => {+ const result = await createOrgProjectAndApiKey();+ __orgIds.push(result.orgId);+ const orgApiKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: result.orgId,+ scope: ApiKeyScope.ORGANIZATION,+ });++ const response = await makeAPICall(+ "GET",+ "/api/public/unstable/evaluators?page=1&limit=10",+ undefined,+ createBasicAuthHeader(orgApiKey.publicKey, orgApiKey.secretKey),+ );++ expectUnstableError(response, {+ status: 403,+ code: "access_denied",+ });+ });+});diff --git a/web/src/features/evals/server/audit-log-resource-types.ts b/web/src/features/evals/server/audit-log-resource-types.tsnew file mode 100644index 0000000000..2cd1b7372c--- /dev/null+++ b/web/src/features/evals/server/audit-log-resource-types.ts@@ -0,0 +1,2 @@+export const JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE = "job" as const;+export const EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE = "evalTemplate" as const;diff --git a/web/src/features/evals/server/evaluator-preflight.ts b/web/src/features/evals/server/evaluator-preflight.tsnew file mode 100644index 0000000000..d2b4c874ec--- /dev/null+++ b/web/src/features/evals/server/evaluator-preflight.ts@@ -0,0 +1,65 @@+import {+ compilePersistedEvalOutputDefinition,+ PersistedEvalOutputDefinitionSchema,+} from "@langfuse/shared";+import {+ DefaultEvalModelService,+ testModelCall,+} from "@langfuse/shared/src/server";++export type EvaluatorPreflightDefinition = {+ name: string;+ provider?: string | null;+ model?: string | null;+ modelParams?: unknown;+ outputDefinition: unknown;+};++export async function getEvaluatorDefinitionPreflightError(params: {+ projectId: string;+ template: EvaluatorPreflightDefinition;+}): Promise<string | null> {+ const modelConfig = await DefaultEvalModelService.fetchValidModelConfig(+ params.projectId,+ params.template.provider ?? undefined,+ params.template.model ?? undefined,+ params.template.modelParams,+ );++ if (!modelConfig.valid) {+ return `No valid LLM model found for evaluator "${params.template.name}". ${modelConfig.error}`;+ }++ try {+ const parsedOutputDefinition = PersistedEvalOutputDefinitionSchema.parse(+ params.template.outputDefinition,+ );+ const compiledOutputDefinition = compilePersistedEvalOutputDefinition(+ parsedOutputDefinition,+ );++ // Some test environments run a built app against seeded local data. In+ // those cases we still want to validate model selection and schema+ // compilation without depending on live provider credentials.+ if (+ process.env.LANGFUSE_SKIP_EVALUATOR_MODEL_CALL_VALIDATION === "true" ||+ process.env.NODE_ENV === "test" ||+ process.env.DATABASE_URL?.includes("langfuse_test")+ ) {+ return null;+ }++ await testModelCall({+ provider: modelConfig.config.provider,+ model: modelConfig.config.model,+ apiKey: modelConfig.config.apiKey,+ modelConfig: modelConfig.config.modelParams,+ structuredOutputSchema: compiledOutputDefinition.outputResultSchema,+ });+ } catch (err) {+ const message = err instanceof Error ? err.message : "Unknown error";+ return `Model configuration not valid for evaluator "${params.template.name}". ${message}`;+ }++ return null;+}diff --git a/web/src/features/evals/server/router.ts b/web/src/features/evals/server/router.tsindex b543702c02..067109c9d1 100644--- a/web/src/features/evals/server/router.ts+++ b/web/src/features/evals/server/router.ts@@ -7,8 +7,9 @@ import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAcimport { auditLog } from "@/src/features/audit-logs/auditLog";import {DEFAULT_TRACE_JOB_DELAY,- compilePersistedEvalOutputDefinition,ZodModelConfig,+ PersistedEvalOutputDefinitionSchema,+ compilePersistedEvalOutputDefinition,deriveEvaluatorDisplayStateFromExecutionCounts,type OrderByState,singleFilter,@@ -25,7 +26,6 @@ import {orderBy,jsonSchema,EvalTargetObject,- PersistedEvalOutputDefinitionSchema,} from "@langfuse/shared";import {getQueue,@@ -60,6 +60,11 @@ import {selectDatasetEvaluatorsForStatusChange,shouldValidateBeforeActivation,} from "@/src/features/evals/server/evalConfigState";+import {+ EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE,+ JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,+} from "@/src/features/evals/server/audit-log-resource-types";+import { getEvaluatorDefinitionPreflightError } from "@/src/features/evals/server/evaluator-preflight";const ConfigWithTemplateSchema = z.object({id: z.string(),@@ -194,40 +199,21 @@ const validateEvalTemplateCanRun = async ({});}- const modelConfig = await DefaultEvalModelService.fetchValidModelConfig(+ const error = await getEvaluatorDefinitionPreflightError({projectId,- template.provider ?? undefined,- template.model ?? undefined,- template.modelParams,- );-- if (!modelConfig.valid) {- throw new TRPCError({- code: "PRECONDITION_FAILED",- message: `No valid LLM model found for evaluator "${template.name}". ${modelConfig.error}`,- });- }+ template: {+ name: template.name,+ provider: template.provider,+ model: template.model,+ modelParams: template.modelParams,+ outputDefinition: template.outputDefinition,+ },+ });- try {- const parsedOutputDefinition = PersistedEvalOutputDefinitionSchema.parse(- template.outputDefinition,- );- const compiledOutputDefinition = compilePersistedEvalOutputDefinition(- parsedOutputDefinition,- );-- await testModelCall({- provider: modelConfig.config.provider,- model: modelConfig.config.model,- apiKey: modelConfig.config.apiKey,- modelConfig: modelConfig.config.modelParams,- structuredOutputSchema: compiledOutputDefinition.outputResultSchema,- });- } catch (err) {- const message = err instanceof Error ? err.message : "Unknown error";+ if (error) {throw new TRPCError({code: "PRECONDITION_FAILED",- message: `Model configuration not valid for evaluator "${template.name}". ${message}`,+ message: error,});}};@@ -746,7 +732,7 @@ export const evalRouter = createTRPCRouter({const jobId = uuidv4();await auditLog({session: ctx.session,- resourceType: "job",+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,resourceId: jobId,action: "create",});@@ -984,7 +970,7 @@ export const evalRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "evalTemplate",+ resourceType: EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE,resourceId: evalTemplate.id,action: "create",});@@ -1152,7 +1138,7 @@ export const evalRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "job",+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,resourceId: evalConfigId,action: "update",});@@ -1267,7 +1253,7 @@ export const evalRouter = createTRPCRouter({await auditLog({session: ctx.session,- resourceType: "job",+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,resourceId: evalConfigId,action: "delete",});diff --git a/web/src/features/evals/server/unstable-public-api/adapters.ts b/web/src/features/evals/server/unstable-public-api/adapters.tsnew file mode 100644index 0000000000..684e05474f--- /dev/null+++ b/web/src/features/evals/server/unstable-public-api/adapters.ts@@ -0,0 +1,401 @@+import {+ createBooleanEvalOutputDefinition,+ createCategoricalEvalOutputDefinition,+ createNumericEvalOutputDefinition,+ EvalTargetObject,+ extractVariables,+ JobConfigState,+ observationVariableMappingList,+ PersistedEvalOutputDefinitionSchema,+ resolvePersistedEvalOutputDefinition,+ singleFilter,+ type ObservationVariableMapping,+ type PersistedEvalOutputDefinition,+} from "@langfuse/shared";+import { InternalServerError } from "@langfuse/shared";+import { logger } from "@langfuse/shared/src/server";+import { z } from "zod";+import {+ ExperimentEvaluationRuleFilter,+ ObservationEvaluationRuleFilter,+ type PublicEvaluationRuleFilterType,+ type PublicEvaluationRuleMappingType,+ type PublicEvaluationRuleTargetType,+ type PublicEvaluatorModelConfigType,+ type PublicEvaluatorOutputDefinitionType,+} from "@/src/features/public-api/types/unstable-public-evals-contract";+import type {+ ApiEvaluationRuleRecord,+ ApiEvaluatorRecord,+ StoredPublicEvaluationRuleConfig,+ StoredPublicEvaluatorTemplate,+} from "./types";+import {+ validateEvaluationRuleFilters,+ validateEvaluatorVariableMappings,+} from "./validation";++const PUBLIC_TARGET_TO_INTERNAL_TARGET_OBJECT: Record<+ PublicEvaluationRuleTargetType,+ string+> = {+ observation: EvalTargetObject.EVENT,+ experiment: EvalTargetObject.EXPERIMENT,+};++const INTERNAL_TARGET_OBJECT_TO_PUBLIC_TARGET: Record<+ string,+ PublicEvaluationRuleTargetType+> = {+ [EvalTargetObject.EVENT]: "observation",+ [EvalTargetObject.EXPERIMENT]: "experiment",+};++const PUBLIC_MAPPING_SOURCE_TO_INTERNAL_COLUMN: Record<+ PublicEvaluationRuleMappingType["source"],+ ObservationVariableMapping["selectedColumnId"]+> = {+ input: "input",+ output: "output",+ metadata: "metadata",+ expected_output: "experimentItemExpectedOutput",+};++const INTERNAL_MAPPING_COLUMN_TO_PUBLIC_SOURCE: Record<+ string,+ PublicEvaluationRuleMappingType["source"]+> = {+ input: "input",+ output: "output",+ metadata: "metadata",+ expected_output: "expected_output",+ expectedOutput: "expected_output",+ experiment_item_expected_output: "expected_output",+ experimentItemExpectedOutput: "expected_output",+};++function getPublicFilterArraySchema(target: PublicEvaluationRuleTargetType) {+ return z.array(+ target === "observation"+ ? ObservationEvaluationRuleFilter+ : ExperimentEvaluationRuleFilter,+ );+}++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);+}++export function parseStoredOutputDefinition(+ template: Pick<StoredPublicEvaluatorTemplate, "outputDefinition">,+): PublicEvaluatorOutputDefinitionType {+ const parsed = PersistedEvalOutputDefinitionSchema.safeParse(+ template.outputDefinition,+ );++ if (!parsed.success) {+ logger.error(+ "Failed to parse unstable public evaluator output definition",+ {+ issues: parsed.error.issues,+ templateId: "id" in template ? template.id : undefined,+ },+ );+ throw new InternalServerError("Evaluator output definition is corrupted");+ }++ const resolvedOutputDefinition = resolvePersistedEvalOutputDefinition(+ parsed.data,+ );++ if (resolvedOutputDefinition.dataType === "CATEGORICAL") {+ return {+ dataType: "CATEGORICAL",+ reasoning: {+ description: resolvedOutputDefinition.reasoningDescription,+ },+ score: {+ description: resolvedOutputDefinition.scoreDescription,+ categories: resolvedOutputDefinition.categories,+ shouldAllowMultipleMatches:+ resolvedOutputDefinition.shouldAllowMultipleMatches,+ },+ };+ }++ return {+ dataType: resolvedOutputDefinition.dataType,+ reasoning: {+ description: resolvedOutputDefinition.reasoningDescription,+ },+ score: {+ description: resolvedOutputDefinition.scoreDescription,+ },+ };+}++export function toStoredOutputDefinition(+ outputDefinition: PublicEvaluatorOutputDefinitionType,+): PersistedEvalOutputDefinition {+ switch (outputDefinition.dataType) {+ case "NUMERIC":+ return createNumericEvalOutputDefinition({+ reasoningDescription: outputDefinition.reasoning.description,+ scoreDescription: outputDefinition.score.description,+ });+ case "BOOLEAN":+ return createBooleanEvalOutputDefinition({+ reasoningDescription: outputDefinition.reasoning.description,+ scoreDescription: outputDefinition.score.description,+ });+ case "CATEGORICAL":+ return createCategoricalEvalOutputDefinition({+ reasoningDescription: outputDefinition.reasoning.description,+ scoreDescription: outputDefinition.score.description,+ categories: outputDefinition.score.categories,+ shouldAllowMultipleMatches:+ outputDefinition.score.shouldAllowMultipleMatches,+ });+ }+}++export function toApiModelConfig(+ template: Pick<+ StoredPublicEvaluatorTemplate,+ "provider" | "model" | "modelParams"+ >,+): PublicEvaluatorModelConfigType | null {+ if (!template.provider || !template.model) {+ return null;+ }++ return {+ provider: template.provider,+ model: template.model,+ };+}++function toApiEvaluationRuleStatus(+ config: Pick<StoredPublicEvaluationRuleConfig, "status" | "blockedAt">,+): ApiEvaluationRuleRecord["status"] {+ if (config.status === JobConfigState.INACTIVE) {+ return "inactive";+ }++ if (config.blockedAt) {+ return "paused";+ }++ return "active";+}++function assertPublicTarget(+ targetObject: string,+): PublicEvaluationRuleTargetType {+ const publicTarget = INTERNAL_TARGET_OBJECT_TO_PUBLIC_TARGET[targetObject];++ if (!publicTarget) {+ throw new InternalServerError("Evaluation rule target is corrupted");+ }++ return publicTarget;+}++function toStoredFilter(+ filter: PublicEvaluationRuleFilterType,+ target: PublicEvaluationRuleTargetType,+): PublicEvaluationRuleFilterType {+ if (target === "experiment" && filter.column === "datasetId") {+ return {+ ...filter,+ column: "experimentDatasetId",+ };+ }++ return filter;+}++function toApiFilter(+ filter: z.infer<typeof singleFilter>,+ target: PublicEvaluationRuleTargetType,+): PublicEvaluationRuleFilterType {+ if (target === "experiment" && filter.column === "experimentDatasetId") {+ return {+ ...filter,+ column: "datasetId",+ } as PublicEvaluationRuleFilterType;+ }++ return filter as PublicEvaluationRuleFilterType;+}++function toApiMappings(mappings: unknown): ApiEvaluationRuleRecord["mapping"] {+ const parsed = observationVariableMappingList.safeParse(mappings);++ if (!parsed.success) {+ logger.error("Failed to parse unstable public evaluation rule mappings", {+ issues: parsed.error.issues,+ });+ throw new InternalServerError("Evaluation rule mapping is corrupted");+ }++ return parsed.data.map((mapping) => {+ const source =+ INTERNAL_MAPPING_COLUMN_TO_PUBLIC_SOURCE[mapping.selectedColumnId];++ if (!source) {+ throw new InternalServerError("Evaluation rule mapping is corrupted");+ }++ return {+ variable: mapping.templateVariable,+ source,+ ...(mapping.jsonSelector ? { jsonPath: mapping.jsonSelector } : {}),+ };+ });+}++function toApiFilters(+ filters: unknown,+ target: PublicEvaluationRuleTargetType,+): ApiEvaluationRuleRecord["filter"] {+ const storedFilters = z.array(singleFilter).safeParse(filters);++ if (!storedFilters.success) {+ logger.error("Failed to parse unstable public evaluation rule filters", {+ issues: storedFilters.error.issues,+ });+ throw new InternalServerError("Evaluation rule filter is corrupted");+ }++ const publicFilters = storedFilters.data.map((filter) =>+ toApiFilter(filter, target),+ );+ const parsedPublicFilters =+ getPublicFilterArraySchema(target).safeParse(publicFilters);++ if (!parsedPublicFilters.success) {+ logger.error("Failed to parse unstable public evaluation rule filters", {+ issues: parsedPublicFilters.error.issues,+ });+ throw new InternalServerError("Evaluation rule filter is corrupted");+ }++ return parsedPublicFilters.data;+}++export function toApiEvaluator(params: {+ template: StoredPublicEvaluatorTemplate;+ evaluationRuleCount: number;+}): ApiEvaluatorRecord {+ const template = params.template;++ return {+ 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,+ };+}++export function toApiEvaluationRule(+ config: StoredPublicEvaluationRuleConfig,+): ApiEvaluationRuleRecord {+ if (!config.evalTemplate?.id) {+ throw new InternalServerError("Evaluation rule evaluator is corrupted");+ }++ const target = assertPublicTarget(config.targetObject);++ return {+ id: config.id,+ name: config.scoreName,+ evaluator: {+ id: config.evalTemplate.id,+ name: config.evalTemplate.name,+ scope: config.evalTemplate.projectId === null ? "managed" : "project",+ },+ target,+ enabled: config.status === JobConfigState.ACTIVE,+ status: toApiEvaluationRuleStatus(config),+ pausedReason: config.blockReason ?? null,+ pausedMessage: config.blockMessage ?? null,+ sampling: Number(config.sampling),+ filter: toApiFilters(config.filter, target),+ mapping: toApiMappings(config.variableMapping),+ createdAt: config.createdAt,+ updatedAt: config.updatedAt,+ };+}++export function toJobConfigurationInput(params: {+ input: {+ name: string;+ target: PublicEvaluationRuleTargetType;+ enabled: boolean;+ sampling: number;+ filter: PublicEvaluationRuleFilterType[];+ mapping: PublicEvaluationRuleMappingType[];+ };+ evaluatorVariables: string[];+}) {+ validateEvaluationRuleFilters({+ target: params.input.target,+ filters: params.input.filter,+ });+ validateEvaluatorVariableMappings({+ mappings: params.input.mapping,+ variables: params.evaluatorVariables,+ target: params.input.target,+ });++ return {+ scoreName: params.input.name,+ targetObject: PUBLIC_TARGET_TO_INTERNAL_TARGET_OBJECT[params.input.target],+ 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,+ })),+ ),+ sampling: params.input.sampling,+ status: params.input.enabled+ ? JobConfigState.ACTIVE+ : JobConfigState.INACTIVE,+ };+}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.tsnew file mode 100644index 0000000000..9af66d4de6--- /dev/null+++ b/web/src/features/evals/server/unstable-public-api/evaluation-rule-service.ts@@ -0,0 +1,301 @@+import { invalidateProjectEvalConfigCaches } from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { EvalTargetObject, JobConfigState } from "@langfuse/shared";+import type {+ PatchUnstableEvaluationRuleBodyType,+ PostUnstableEvaluationRuleBodyType,+} from "@/src/features/public-api/types/unstable-evaluation-rules";+import {+ deriveEvaluatorVariables,+ toApiEvaluationRule,+ toJobConfigurationInput,+} from "./adapters";+import {+ countActiveEvaluationRules,+ findPublicEvaluationRuleOrThrow,+ listPublicEvaluationRuleConfigs,+ loadEvaluatorForEvaluationRule,+} from "./queries";+import {+ assertEvaluationRuleFilterValuesExistForProject,+ assertEvaluatorDefinitionCanRunForPublicApi,+} from "./validation";+import { createUnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";++const MAX_ACTIVE_EVALUATION_RULES = 50;++async function assertActivePublicApiEvaluationRuleLimitNotExceeded(+ projectId: string,+) {+ const activeCount = await countActiveEvaluationRules({ projectId });++ if (activeCount >= MAX_ACTIVE_EVALUATION_RULES) {+ throw createUnstablePublicApiError({+ httpCode: 409,+ code: "conflict",+ message: `This project already has the maximum number of active evaluation rules (${MAX_ACTIVE_EVALUATION_RULES}). Disable an existing active evaluation rule before enabling another one.`,+ details: {+ limit: MAX_ACTIVE_EVALUATION_RULES,+ },+ });+ }+}++export async function listPublicEvaluationRules(params: {+ projectId: string;+ page: number;+ limit: number;+}) {+ const { configs, totalItems } = await listPublicEvaluationRuleConfigs(params);++ return {+ data: configs.map((config) => toApiEvaluationRule(config)),+ meta: {+ page: params.page,+ limit: params.limit,+ totalItems,+ totalPages: Math.ceil(totalItems / params.limit),+ },+ };+}++export async function getPublicEvaluationRule(params: {+ projectId: string;+ evaluationRuleId: string;+}) {+ const config = await findPublicEvaluationRuleOrThrow(params);+ return toApiEvaluationRule(config);+}++export async function createPublicEvaluationRule(params: {+ projectId: string;+ input: PostUnstableEvaluationRuleBodyType;+}) {+ const existing = await prisma.jobConfiguration.findFirst({+ where: {+ projectId: params.projectId,+ jobType: "EVAL",+ targetObject: {+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],+ },+ scoreName: params.input.name,+ },+ select: {+ id: true,+ },+ });++ if (existing) {+ throw createUnstablePublicApiError({+ httpCode: 409,+ code: "name_conflict",+ message: `An evaluation rule named "${params.input.name}" already exists in this project. Use PATCH /api/public/unstable/evaluation-rules/${existing.id} to update it instead of creating a duplicate.`,+ details: {+ field: "name",+ },+ });+ }++ if (params.input.enabled) {+ await assertActivePublicApiEvaluationRuleLimitNotExceeded(params.projectId);+ }++ await assertEvaluationRuleFilterValuesExistForProject({+ projectId: params.projectId,+ target: params.input.target,+ filters: params.input.filter,+ });++ const { template } = await loadEvaluatorForEvaluationRule({+ projectId: params.projectId,+ evaluator: params.input.evaluator,+ });++ const data = toJobConfigurationInput({+ input: {+ name: params.input.name,+ target: params.input.target,+ enabled: params.input.enabled,+ sampling: params.input.sampling,+ filter: params.input.filter,+ mapping: params.input.mapping,+ },+ evaluatorVariables: deriveEvaluatorVariables(template),+ });++ if (data.status === JobConfigState.ACTIVE) {+ await assertEvaluatorDefinitionCanRunForPublicApi({+ projectId: params.projectId,+ template: {+ name: template.name,+ provider: template.provider,+ model: template.model,+ modelParams: template.modelParams,+ outputDefinition: template.outputDefinition,+ },+ });+ }++ const created = await prisma.jobConfiguration.create({+ data: {+ projectId: params.projectId,+ jobType: "EVAL",+ evalTemplateId: template.id,+ scoreName: data.scoreName,+ targetObject: data.targetObject,+ filter: data.filter,+ variableMapping: data.variableMapping,+ sampling: data.sampling,+ delay: 0,+ status: data.status,+ timeScope: ["NEW"],+ },+ include: {+ evalTemplate: {+ select: {+ id: true,+ projectId: true,+ name: true,+ vars: true,+ prompt: true,+ },+ },+ },+ });++ if (created.status === JobConfigState.ACTIVE) {+ await invalidateProjectEvalConfigCaches(params.projectId);+ }++ return toApiEvaluationRule(created);+}++export async function updatePublicEvaluationRule(params: {+ projectId: string;+ evaluationRuleId: string;+ input: PatchUnstableEvaluationRuleBodyType;+}) {+ const existing = await findPublicEvaluationRuleOrThrow({+ projectId: params.projectId,+ evaluationRuleId: params.evaluationRuleId,+ });+ const existingPublic = toApiEvaluationRule(existing);+ const nextEnabled = params.input.enabled ?? existingPublic.enabled;+ const shouldCountAgainstActiveLimit =+ nextEnabled && existingPublic.status !== "active";++ if (shouldCountAgainstActiveLimit) {+ await assertActivePublicApiEvaluationRuleLimitNotExceeded(params.projectId);+ }++ const nextTarget =+ "target" in params.input && params.input.target !== undefined+ ? params.input.target+ : existingPublic.target;+ if ("filter" in params.input && params.input.filter !== undefined) {+ await assertEvaluationRuleFilterValuesExistForProject({+ projectId: params.projectId,+ target: nextTarget,+ filters: params.input.filter,+ });+ }++ const nextEvaluator = params.input.evaluator ?? {+ name: existingPublic.evaluator.name,+ scope: existingPublic.evaluator.scope,+ };+ const { template } = await loadEvaluatorForEvaluationRule({+ projectId: params.projectId,+ evaluator: nextEvaluator,+ });+ const nextFilter =+ "filter" in params.input && params.input.filter !== undefined+ ? params.input.filter+ : existingPublic.filter;+ const nextMapping =+ "mapping" in params.input && params.input.mapping !== undefined+ ? params.input.mapping+ : existingPublic.mapping;++ const data = toJobConfigurationInput({+ input: {+ name: params.input.name ?? existingPublic.name,+ target: nextTarget,+ enabled: params.input.enabled ?? existingPublic.enabled,+ sampling: params.input.sampling ?? existingPublic.sampling,+ filter: nextFilter,+ mapping: nextMapping,+ },+ evaluatorVariables: deriveEvaluatorVariables(template),+ });+ const shouldResetBlockState = data.status === JobConfigState.ACTIVE;++ if (shouldResetBlockState) {+ await assertEvaluatorDefinitionCanRunForPublicApi({+ projectId: params.projectId,+ template: {+ name: template.name,+ provider: template.provider,+ model: template.model,+ modelParams: template.modelParams,+ outputDefinition: template.outputDefinition,+ },+ });+ }++ const updated = await prisma.jobConfiguration.update({+ where: {+ id: params.evaluationRuleId,+ projectId: params.projectId,+ },+ data: {+ evalTemplateId: template.id,+ scoreName: data.scoreName,+ targetObject: data.targetObject,+ filter: data.filter,+ variableMapping: data.variableMapping,+ sampling: data.sampling,+ status: data.status,+ ...(shouldResetBlockState+ ? {+ blockedAt: null,+ blockReason: null,+ blockMessage: null,+ }+ : {}),+ },+ include: {+ evalTemplate: {+ select: {+ id: true,+ projectId: true,+ name: true,+ vars: true,+ prompt: true,+ },+ },+ },+ });++ await invalidateProjectEvalConfigCaches(params.projectId);++ return toApiEvaluationRule(updated);+}++export async function deletePublicEvaluationRule(params: {+ projectId: string;+ evaluationRuleId: string;+}) {+ const existing = await findPublicEvaluationRuleOrThrow(params);++ await prisma.jobConfiguration.delete({+ where: {+ id: params.evaluationRuleId,+ projectId: params.projectId,+ },+ });++ await invalidateProjectEvalConfigCaches(params.projectId);++ return existing;+}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.tsnew file mode 100644index 0000000000..9c4b3a9b23--- /dev/null+++ b/web/src/features/evals/server/unstable-public-api/evaluator-service.ts@@ -0,0 +1,242 @@+import {+ extractVariables,+ InternalServerError,+ observationVariableMappingList,+ variableMappingList,+} from "@langfuse/shared";+import { invalidateProjectEvalConfigCaches } from "@langfuse/shared/src/server";+import { Prisma, prisma } from "@langfuse/shared/src/db";+import { z } from "zod";+import type { PostUnstableEvaluatorBodyType } from "@/src/features/public-api/types/unstable-evaluators";+import {+ toApiEvaluator,+ toStoredModelConfig,+ toStoredOutputDefinition,+} from "./adapters";+import {+ countEvaluationRulesForEvaluator,+ countEvaluationRulesForEvaluatorIds,+ findPublicEvaluatorTemplateOrThrow,+ listPublicEvaluatorTemplates,+} from "./queries";+import { assertEvaluatorDefinitionCanRunForPublicApi } from "./validation";+import { createUnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";+import type { StoredPublicEvaluatorTemplate } from "./types";++function prepareVariableMappingForEvaluatorUpgrade(params: {+ scoreName: string;+ variableMapping: unknown;+ nextVariables: string[];+}) {+ const mappingParseResult = z+ .union([observationVariableMappingList, variableMappingList])+ .safeParse(params.variableMapping);++ if (!mappingParseResult.success) {+ throw new InternalServerError("Evaluation rule mapping is corrupted");+ }++ const migratedVariableMapping = mappingParseResult.data.filter((mapping) =>+ params.nextVariables.includes(mapping.templateVariable),+ );+ const mappedVariables = new Set(+ migratedVariableMapping.map((mapping) => mapping.templateVariable),+ );+ const missingVariables = params.nextVariables.filter(+ (variable) => !mappedVariables.has(variable),+ );++ if (missingVariables.length > 0) {+ throw createUnstablePublicApiError({+ httpCode: 409,+ code: "conflict",+ message: `Creating a new evaluator version would invalidate the evaluation rule "${params.scoreName}" because it is missing mappings for new evaluator variables: ${missingVariables.join(", ")}.`,+ details: {+ field: "mapping",+ variables: missingVariables,+ },+ });+ }++ return migratedVariableMapping;+}++export async function listPublicEvaluators(params: {+ projectId: string;+ page: number;+ limit: number;+}) {+ const { templates, totalItems } = await listPublicEvaluatorTemplates(params);+ const evaluationRuleCounts = await countEvaluationRulesForEvaluatorIds({+ projectId: params.projectId,+ evaluatorIds: templates.map((template) => template.id),+ });++ return {+ data: templates.map((template) =>+ toApiEvaluator({+ template,+ evaluationRuleCount: evaluationRuleCounts[template.id] ?? 0,+ }),+ ),+ meta: {+ page: params.page,+ limit: params.limit,+ totalItems,+ totalPages: Math.ceil(totalItems / params.limit),+ },+ };+}++export async function getPublicEvaluator(params: {+ projectId: string;+ evaluatorId: string;+}) {+ const template = await findPublicEvaluatorTemplateOrThrow(params);+ const evaluationRuleCount = await countEvaluationRulesForEvaluator(params);++ return toApiEvaluator({+ template,+ evaluationRuleCount,+ });+}++export async function createPublicEvaluator(params: {+ projectId: string;+ input: PostUnstableEvaluatorBodyType;+}) {+ const storedOutputDefinition = toStoredOutputDefinition(+ params.input.outputDefinition,+ );++ await assertEvaluatorDefinitionCanRunForPublicApi({+ projectId: params.projectId,+ template: {+ name: params.input.name,+ provider: params.input.modelConfig?.provider ?? null,+ model: params.input.modelConfig?.model ?? null,+ outputDefinition: storedOutputDefinition,+ },+ });++ try {+ const { template, upgradedConfigCount } = await prisma.$transaction(+ async (tx) => {+ const existingProjectTemplates = await tx.evalTemplate.findMany({+ where: {+ projectId: params.projectId,+ name: params.input.name,+ },+ orderBy: [+ {+ version: "desc",+ },+ {+ createdAt: "desc",+ },+ {+ id: "desc",+ },+ ],+ select: {+ id: true,+ version: true,+ },+ });+ const nextVariables = extractVariables(params.input.prompt);+ const configsToUpgrade =+ existingProjectTemplates.length > 0+ ? await tx.jobConfiguration.findMany({+ where: {+ projectId: params.projectId,+ evalTemplateId: {+ in: existingProjectTemplates.map(+ (existingTemplate) => existingTemplate.id,+ ),+ },+ },+ select: {+ id: true,+ scoreName: true,+ variableMapping: true,+ },+ })+ : [];+ const upgradedConfigs = configsToUpgrade.map((config) => ({+ id: config.id,+ variableMapping: prepareVariableMappingForEvaluatorUpgrade({+ scoreName: config.scoreName,+ variableMapping: config.variableMapping,+ 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,+ version: (latestProjectTemplate?.version ?? 0) + 1,+ prompt: params.input.prompt,+ provider: modelConfig.provider,+ model: modelConfig.model,+ modelParams: modelConfig.modelParams,+ vars: nextVariables,+ outputDefinition: storedOutputDefinition,+ },+ });++ if (upgradedConfigs.length > 0) {+ await Promise.all(+ upgradedConfigs.map((config) =>+ tx.jobConfiguration.update({+ where: {+ id: config.id,+ projectId: params.projectId,+ },+ data: {+ evalTemplateId: template.id,+ variableMapping: config.variableMapping,+ },+ }),+ ),+ );+ }++ return {+ template,+ upgradedConfigCount: upgradedConfigs.length,+ };+ },+ );++ if (upgradedConfigCount > 0) {+ await invalidateProjectEvalConfigCaches(params.projectId);+ }++ const evaluationRuleCount = await countEvaluationRulesForEvaluator({+ projectId: params.projectId,+ evaluatorId: template.id,+ });++ return toApiEvaluator({+ template: template as StoredPublicEvaluatorTemplate,+ evaluationRuleCount,+ });+ } catch (error) {+ if (+ error instanceof Prisma.PrismaClientKnownRequestError &&+ error.code === "P2002"+ ) {+ throw createUnstablePublicApiError({+ httpCode: 409,+ code: "conflict",+ message:+ "Evaluator version changed during creation. Retry the request.",+ });+ }++ throw error;+ }+}diff --git a/web/src/features/evals/server/unstable-public-api/index.ts b/web/src/features/evals/server/unstable-public-api/index.tsnew file mode 100644index 0000000000..c2a8f3c2ad--- /dev/null+++ b/web/src/features/evals/server/unstable-public-api/index.ts@@ -0,0 +1,12 @@+export {+ createPublicEvaluationRule,+ deletePublicEvaluationRule,+ getPublicEvaluationRule,+ listPublicEvaluationRules,+ updatePublicEvaluationRule,+} from "./evaluation-rule-service";+export {+ createPublicEvaluator,+ getPublicEvaluator,+ listPublicEvaluators,+} from "./evaluator-service";diff --git a/web/src/features/evals/server/unstable-public-api/queries.ts b/web/src/features/evals/server/unstable-public-api/queries.tsnew file mode 100644index 0000000000..8476f3f542--- /dev/null+++ b/web/src/features/evals/server/unstable-public-api/queries.ts@@ -0,0 +1,328 @@+import {+ EvalTargetObject,+ JobConfigState,+ LangfuseNotFoundError,+} from "@langfuse/shared";+import { Prisma, prisma } from "@langfuse/shared/src/db";+import type {+ EvaluationRuleEvaluatorFamilyReference,+ PrismaClientLike,+ StoredPublicEvaluationRuleConfig,+ StoredPublicEvaluatorTemplate,+} from "./types";++export function getPrismaClient(client?: PrismaClientLike) {+ return client ?? prisma;+}++export async function findPublicEvaluatorTemplateOrThrow(params: {+ client?: PrismaClientLike;+ projectId: string;+ evaluatorId: string;+}) {+ const client = getPrismaClient(params.client);++ const template = await client.evalTemplate.findUnique({+ where: {+ id: params.evaluatorId,+ },+ });++ if (+ !template ||+ (template.projectId !== params.projectId && template.projectId !== null)+ ) {+ throw new LangfuseNotFoundError(+ "Evaluator not found within authorized project",+ );+ }++ return template as StoredPublicEvaluatorTemplate;+}++export async function findLatestPublicEvaluatorTemplateInFamilyOrThrow(params: {+ client?: PrismaClientLike;+ projectId: string;+ evaluator: EvaluationRuleEvaluatorFamilyReference;+}) {+ const client = getPrismaClient(params.client);+ const latestTemplate = await client.evalTemplate.findFirst({+ where: {+ name: params.evaluator.name,+ projectId: params.evaluator.scope === "project" ? params.projectId : null,+ },+ orderBy: {+ version: "desc",+ },+ });++ if (!latestTemplate) {+ throw new LangfuseNotFoundError(+ "Latest evaluator version not found within authorized project",+ );+ }++ return latestTemplate as StoredPublicEvaluatorTemplate;+}++export async function countEvaluationRulesForEvaluator(params: {+ client?: PrismaClientLike;+ projectId: string;+ evaluatorId: string;+}) {+ const client = getPrismaClient(params.client);++ return client.jobConfiguration.count({+ where: {+ projectId: params.projectId,+ targetObject: {+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],+ },+ evalTemplateId: params.evaluatorId,+ },+ });+}++export async function countEvaluationRulesForEvaluatorIds(params: {+ client?: PrismaClientLike;+ projectId: string;+ evaluatorIds: string[];+}) {+ if (params.evaluatorIds.length === 0) {+ return {};+ }++ const client = getPrismaClient(params.client);+ const groups = await client.jobConfiguration.groupBy({+ by: ["evalTemplateId"],+ where: {+ projectId: params.projectId,+ targetObject: {+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],+ },+ evalTemplateId: {+ in: params.evaluatorIds,+ },+ },+ _count: {+ _all: true,+ },+ });++ return groups.reduce<Record<string, number>>((counts, group) => {+ if (!group.evalTemplateId) {+ return counts;+ }++ counts[group.evalTemplateId] = group._count._all;+ return counts;+ }, {});+}++export async function listPublicEvaluatorTemplates(params: {+ projectId: string;+ page: number;+ limit: number;+}) {+ const offset = (params.page - 1) * params.limit;+ const [evaluatorRows, totalItemsRes] = await Promise.all([+ prisma.$queryRaw<Array<{ id: string }>>(+ Prisma.sql`+ WITH latest_templates AS (+ SELECT DISTINCT ON (project_id, name)+ id,+ project_id,+ name,+ updated_at+ FROM eval_templates+ WHERE project_id = ${params.projectId} OR project_id IS NULL+ ORDER BY project_id, name, version DESC+ )+ SELECT id+ FROM latest_templates+ ORDER BY+ CASE WHEN project_id IS NULL THEN 1 ELSE 0 END ASC,+ name ASC,+ updated_at DESC,+ id ASC+ LIMIT ${params.limit}+ OFFSET ${offset}+ `,+ ),+ prisma.$queryRaw<Array<{ count: bigint }>>(+ Prisma.sql`+ SELECT COUNT(*) as count+ FROM (+ SELECT DISTINCT project_id, name+ FROM eval_templates+ WHERE project_id = ${params.projectId} OR project_id IS NULL+ ) latest_template_families+ `,+ ),+ ]);++ const totalItems =+ totalItemsRes[0] !== undefined ? Number(totalItemsRes[0].count) : 0;+ const templateIds = evaluatorRows.map((row) => row.id);++ if (templateIds.length === 0) {+ return {+ totalItems,+ templates: [],+ };+ }++ const templates = await prisma.evalTemplate.findMany({+ where: {+ id: {+ in: templateIds,+ },+ },+ });++ const templateById = new Map(+ templates.map((template) => [+ template.id,+ template as StoredPublicEvaluatorTemplate,+ ]),+ );++ return {+ totalItems,+ templates: templateIds+ .map((id) => templateById.get(id))+ .filter(+ (template): template is StoredPublicEvaluatorTemplate =>+ template !== undefined,+ ),+ };+}++export async function findPublicEvaluationRuleOrThrow(params: {+ client?: PrismaClientLike;+ projectId: string;+ evaluationRuleId: string;+}) {+ const client = getPrismaClient(params.client);++ const config = await client.jobConfiguration.findFirst({+ where: {+ id: params.evaluationRuleId,+ projectId: params.projectId,+ targetObject: {+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],+ },+ evalTemplate: {+ is: {+ OR: [{ projectId: params.projectId }, { projectId: null }],+ },+ },+ },+ include: {+ evalTemplate: {+ select: {+ id: true,+ projectId: true,+ name: true,+ vars: true,+ prompt: true,+ },+ },+ },+ });++ if (!config) {+ throw new LangfuseNotFoundError(+ "Evaluation rule not found within authorized project",+ );+ }++ return config as StoredPublicEvaluationRuleConfig;+}++export async function loadEvaluatorForEvaluationRule(params: {+ client?: PrismaClientLike;+ projectId: string;+ evaluator: EvaluationRuleEvaluatorFamilyReference;+}) {+ const template =+ await findLatestPublicEvaluatorTemplateInFamilyOrThrow(params);++ return {+ template,+ };+}++export async function countActiveEvaluationRules(params: {+ client?: PrismaClientLike;+ projectId: string;+}) {+ const client = getPrismaClient(params.client);+ return client.jobConfiguration.count({+ where: {+ projectId: params.projectId,+ jobType: "EVAL",+ targetObject: {+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],+ },+ status: JobConfigState.ACTIVE,+ blockedAt: null,+ },+ });+}++export async function listPublicEvaluationRuleConfigs(params: {+ projectId: string;+ page: number;+ limit: number;+}) {+ const [configs, totalItems] = await Promise.all([+ prisma.jobConfiguration.findMany({+ where: {+ projectId: params.projectId,+ targetObject: {+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],+ },+ evalTemplate: {+ is: {+ OR: [{ projectId: params.projectId }, { projectId: null }],+ },+ },+ },+ include: {+ evalTemplate: {+ select: {+ id: true,+ projectId: true,+ name: true,+ vars: true,+ prompt: true,+ },+ },+ },+ orderBy: {+ createdAt: "desc",+ },+ take: params.limit,+ skip: (params.page - 1) * params.limit,+ }),+ prisma.jobConfiguration.count({+ where: {+ projectId: params.projectId,+ targetObject: {+ in: [EvalTargetObject.EVENT, EvalTargetObject.EXPERIMENT],+ },+ evalTemplate: {+ is: {+ OR: [{ projectId: params.projectId }, { projectId: null }],+ },+ },+ },+ }),+ ]);++ return {+ configs: configs as StoredPublicEvaluationRuleConfig[],+ totalItems,+ };+}diff --git a/web/src/features/evals/server/unstable-public-api/types.ts b/web/src/features/evals/server/unstable-public-api/types.tsnew file mode 100644index 0000000000..4dd4537168--- /dev/null+++ b/web/src/features/evals/server/unstable-public-api/types.ts@@ -0,0 +1,95 @@+import type {+ EvalTemplate,+ JobConfiguration,+ Prisma as PrismaNamespace,+ prisma,+} from "@langfuse/shared/src/db";+import type {+ PublicEvaluationRuleEvaluatorReferenceType,+ PublicEvaluationRuleEvaluatorType,+ PublicEvaluationRuleFilterType,+ PublicEvaluationRuleMappingType,+ PublicEvaluationRuleStatusType,+ PublicEvaluationRuleTargetType,+ PublicEvaluatorModelConfigType,+ PublicEvaluatorOutputDefinitionType,+ PublicEvaluatorScopeType,+} from "@/src/features/public-api/types/unstable-public-evals-contract";++export type PrismaClientLike =+ | typeof prisma+ | PrismaNamespace.TransactionClient;++export type ApiEvaluatorRecord = {+ 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 ApiEvaluationRuleRecord = {+ id: string;+ name: string;+ evaluator: PublicEvaluationRuleEvaluatorType;+ target: PublicEvaluationRuleTargetType;+ enabled: boolean;+ status: PublicEvaluationRuleStatusType;+ pausedReason: string | null;+ pausedMessage: string | null;+ sampling: number;+ filter: PublicEvaluationRuleFilterType[];+ mapping: PublicEvaluationRuleMappingType[];+ createdAt: Date;+ updatedAt: Date;+};++export type EvaluationRuleEvaluatorFamilyReference =+ PublicEvaluationRuleEvaluatorReferenceType;++export type StoredPublicEvaluatorTemplate = Pick<+ EvalTemplate,+ | "id"+ | "projectId"+ | "name"+ | "version"+ | "prompt"+ | "partner"+ | "provider"+ | "model"+ | "modelParams"+ | "vars"+ | "outputDefinition"+ | "createdAt"+ | "updatedAt"+>;++export type StoredPublicEvaluationRuleConfig = Pick<+ JobConfiguration,+ | "id"+ | "projectId"+ | "evalTemplateId"+ | "scoreName"+ | "targetObject"+ | "filter"+ | "variableMapping"+ | "sampling"+ | "status"+ | "blockedAt"+ | "blockReason"+ | "blockMessage"+ | "createdAt"+ | "updatedAt"+> & {+ evalTemplate: Pick<+ EvalTemplate,+ "id" | "projectId" | "name" | "vars" | "prompt"+ > | null;+};diff --git a/web/src/features/evals/server/unstable-public-api/validation.ts b/web/src/features/evals/server/unstable-public-api/validation.tsnew file mode 100644index 0000000000..ed61a2822b--- /dev/null+++ b/web/src/features/evals/server/unstable-public-api/validation.ts@@ -0,0 +1,399 @@+import {+ experimentEvalFilterColumns,+ observationEvalFilterColumns,+} from "@langfuse/shared";+import { prisma } from "@langfuse/shared/src/db";+import { JSONPath } from "jsonpath-plus";+import type {+ PublicEvaluationRuleFilterType,+ PublicEvaluationRuleMappingType,+ PublicEvaluationRuleTargetType,+} from "@/src/features/public-api/types/unstable-public-evals-contract";+import { getEvaluatorDefinitionPreflightError } from "@/src/features/evals/server/evaluator-preflight";+import { createUnstablePublicApiError } from "@/src/features/public-api/server/unstable-public-api-error-contract";++const STATIC_FILTER_OPTIONS_BY_TARGET = {+ observation: new Map(+ observationEvalFilterColumns.flatMap((column) => {+ if (!("options" in column) || !Array.isArray(column.options)) {+ return [];+ }++ if (column.options.length === 0) {+ return [];+ }++ return [+ [+ column.id,+ new Set(+ column.options.flatMap((option) =>+ "value" in option ? [String(option.value)] : option.values,+ ),+ ),+ ] as const,+ ];+ }),+ ),+ experiment: new Map(+ experimentEvalFilterColumns.flatMap((column) => {+ if (!("options" in column) || !Array.isArray(column.options)) {+ return [];+ }++ if (column.options.length === 0) {+ return [];+ }++ return [+ [+ column.id === "experimentDatasetId" ? "datasetId" : column.id,+ new Set(+ column.options.flatMap((option) =>+ "value" in option ? [String(option.value)] : option.values,+ ),+ ),+ ] as const,+ ];+ }),+ ),+} as const satisfies Record<+ PublicEvaluationRuleTargetType,+ Map<string, Set<string>>+>;++const SUPPORTED_FILTER_COLUMNS_BY_TARGET = {+ observation: new Set(observationEvalFilterColumns.map((column) => column.id)),+ experiment: new Set(+ experimentEvalFilterColumns.map((column) =>+ column.id === "experimentDatasetId" ? "datasetId" : column.id,+ ),+ ),+} as const satisfies Record<PublicEvaluationRuleTargetType, Set<string>>;++const SUPPORTED_MAPPING_SOURCES_BY_TARGET = {+ observation: new Set(["input", "output", "metadata"]),+ experiment: new Set(["input", "output", "metadata", "expected_output"]),+} as const satisfies Record<PublicEvaluationRuleTargetType, Set<string>>;++export function validateEvaluationRuleFilters(params: {+ target: PublicEvaluationRuleTargetType;+ filters: PublicEvaluationRuleFilterType[];+}) {+ const knownOptionValues = STATIC_FILTER_OPTIONS_BY_TARGET[params.target];+ const supportedColumns = SUPPORTED_FILTER_COLUMNS_BY_TARGET[params.target];++ for (const [filterIndex, filter] of params.filters.entries()) {+ if (!supportedColumns.has(filter.column)) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_filter_value",+ message: `Filter column "${filter.column}" is not supported for target "${params.target}"`,+ details: {+ field: `filter[${filterIndex}].column`,+ column: filter.column,+ allowedValues: Array.from(supportedColumns),+ },+ });+ }++ const allowedValues = knownOptionValues.get(filter.column);++ if (+ !allowedValues ||+ !("value" in filter) ||+ !Array.isArray(filter.value)+ ) {+ continue;+ }++ const invalidValues = filter.value.filter(+ (value) => !allowedValues.has(value),+ );++ if (invalidValues.length > 0) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_filter_value",+ message: `Filter column "${filter.column}" contains unsupported value(s): ${invalidValues.join(", ")}`,+ details: {+ field: `filter[${filterIndex}].value`,+ column: filter.column,+ invalidValues,+ allowedValues: Array.from(allowedValues),+ },+ });+ }+ }+}++export async function assertEvaluationRuleFilterValuesExistForProject(params: {+ projectId: string;+ target: PublicEvaluationRuleTargetType;+ filters: PublicEvaluationRuleFilterType[];+}) {+ if (params.target !== "experiment") {+ return;+ }++ const datasetFilters = params.filters.flatMap((filter, filterIndex) => {+ if (+ filter.column !== "datasetId" ||+ !("value" in filter) ||+ !Array.isArray(filter.value)+ ) {+ return [];+ }++ return [{ filterIndex, values: filter.value }] as const;+ });++ if (datasetFilters.length === 0) {+ return;+ }++ const requestedDatasetIds = Array.from(+ new Set(datasetFilters.flatMap((filter) => filter.values)),+ );+ const existingDatasets = await prisma.dataset.findMany({+ where: {+ projectId: params.projectId,+ id: {+ in: requestedDatasetIds,+ },+ },+ select: {+ id: true,+ },+ });+ const existingDatasetIds = new Set(+ existingDatasets.map((dataset) => dataset.id),+ );++ for (const filter of datasetFilters) {+ const invalidValues = filter.values.filter(+ (value) => !existingDatasetIds.has(value),+ );++ if (invalidValues.length > 0) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_filter_value",+ message: `Filter column "datasetId" contains dataset id(s) that do not exist in this project: ${invalidValues.join(", ")}`,+ details: {+ field: `filter[${filter.filterIndex}].value`,+ column: "datasetId",+ invalidValues,+ },+ });+ }+ }+}++function validateJsonPath(params: {+ jsonPath: string;+ variable: string;+ mappingIndex: number;+}) {+ const { jsonPath, variable, mappingIndex } = params;++ if (!jsonPath.startsWith("$")) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_json_path",+ message: `Mapping for variable "${variable}" has an invalid jsonPath "${jsonPath}". JSONPath expressions must start with "$".`,+ details: {+ field: `mapping[${mappingIndex}].jsonPath`,+ variable,+ value: jsonPath,+ },+ });+ }++ let openQuote: "'" | '"' | null = null;+ let isEscaped = false;+ const delimiterStack: Array<"[" | "("> = [];++ for (const character of jsonPath) {+ if (openQuote) {+ if (isEscaped) {+ isEscaped = false;+ continue;+ }++ if (character === "\\") {+ isEscaped = true;+ continue;+ }++ if (character === openQuote) {+ openQuote = null;+ }++ continue;+ }++ if (character === "'" || character === '"') {+ openQuote = character;+ continue;+ }++ if (character === "[" || character === "(") {+ delimiterStack.push(character);+ continue;+ }++ if (character === "]" || character === ")") {+ const expectedDelimiter = character === "]" ? "[" : "(";++ if (delimiterStack.pop() !== expectedDelimiter) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_json_path",+ message: `Mapping for variable "${variable}" has an invalid jsonPath "${jsonPath}". JSONPath expressions must use balanced brackets and parentheses.`,+ details: {+ field: `mapping[${mappingIndex}].jsonPath`,+ variable,+ value: jsonPath,+ },+ });+ }+ }+ }++ if (openQuote || delimiterStack.length > 0) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_json_path",+ message: `Mapping for variable "${variable}" has an invalid jsonPath "${jsonPath}". JSONPath expressions must use balanced quotes, brackets, and parentheses.`,+ details: {+ field: `mapping[${mappingIndex}].jsonPath`,+ variable,+ value: jsonPath,+ },+ });+ }++ try {+ JSONPath({+ path: jsonPath,+ json: {},+ eval: false,+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : "Unknown error";+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_json_path",+ message: `Mapping for variable "${variable}" has an invalid jsonPath "${jsonPath}". ${message}`,+ details: {+ field: `mapping[${mappingIndex}].jsonPath`,+ variable,+ value: jsonPath,+ },+ });+ }+}++export function validateEvaluatorVariableMappings(params: {+ mappings: PublicEvaluationRuleMappingType[];+ variables: string[];+ target: PublicEvaluationRuleTargetType;+}) {+ const variableSet = new Set(params.variables);+ const mappedVariables = new Set<string>();+ const allowedSources = SUPPORTED_MAPPING_SOURCES_BY_TARGET[params.target];++ for (const [mappingIndex, mapping] of params.mappings.entries()) {+ if (!allowedSources.has(mapping.source)) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_variable_mapping",+ message: `Mapping source "${mapping.source}" is not supported for target "${params.target}"`,+ details: {+ field: `mapping[${mappingIndex}].source`,+ variable: mapping.variable,+ allowedValues: Array.from(allowedSources),+ },+ });+ }++ if (!variableSet.has(mapping.variable)) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_variable_mapping",+ message: `Mapping variable "${mapping.variable}" is not present in the evaluator prompt`,+ details: {+ field: `mapping[${mappingIndex}].variable`,+ variable: mapping.variable,+ },+ });+ }++ if (mappedVariables.has(mapping.variable)) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "duplicate_variable_mapping",+ message: `Mapping variable "${mapping.variable}" can only be mapped once`,+ details: {+ field: "mapping",+ variable: mapping.variable,+ },+ });+ }++ mappedVariables.add(mapping.variable);+ }++ const missingVariables = params.variables.filter(+ (variable) => !mappedVariables.has(variable),+ );++ if (missingVariables.length > 0) {+ throw createUnstablePublicApiError({+ httpCode: 400,+ code: "missing_variable_mapping",+ message: `Missing mappings for evaluator variables: ${missingVariables.join(", ")}`,+ details: {+ field: "mapping",+ variables: missingVariables,+ },+ });+ }++ for (const [mappingIndex, mapping] of params.mappings.entries()) {+ if (mapping.jsonPath) {+ validateJsonPath({+ jsonPath: mapping.jsonPath,+ variable: mapping.variable,+ mappingIndex,+ });+ }+ }+}++export async function assertEvaluatorDefinitionCanRunForPublicApi(params: {+ projectId: string;+ template: {+ name: string;+ provider?: string | null;+ model?: string | null;+ modelParams?: unknown;+ outputDefinition: unknown;+ };+}) {+ const error = await getEvaluatorDefinitionPreflightError(params);++ if (error) {+ throw createUnstablePublicApiError({+ httpCode: 422,+ code: "evaluator_preflight_failed",+ message: error,+ details: {+ evaluatorName: params.template.name,+ provider: params.template.provider ?? null,+ model: params.template.model ?? null,+ },+ });+ }+}diff --git a/web/src/features/public-api/server/RateLimitService.ts b/web/src/features/public-api/server/RateLimitService.tsindex eaabb369d4..79d017a49f 100644--- a/web/src/features/public-api/server/RateLimitService.ts+++ b/web/src/features/public-api/server/RateLimitService.ts@@ -17,6 +17,12 @@ import {} from "@langfuse/shared/src/server";import { env as sharedEnv } from "@langfuse/shared/src/env";import { type NextApiResponse } from "next";+import {+ createUnstablePublicApiRateLimitError,+ sendUnstablePublicApiErrorResponse,+ unstablePublicEvalsErrorContract,+ type PublicApiErrorContract,+} from "@/src/features/public-api/server/unstable-public-api-error-contract";// Business Logic// - rate limit strategy is based on org-id, org plan, and resources. Rate limits are applied in buckets of minutes.@@ -166,20 +172,24 @@ export class RateLimitHelper {return this.res ? this.res.remainingPoints < 1 : false;}- sendRestResponseIfLimited(nextResponse: NextApiResponse) {+ sendRestResponseIfLimited(+ nextResponse: NextApiResponse,+ errorContract?: PublicApiErrorContract,+ ) {if (!this.res || !this.isRateLimited()) {logger.error("Trying to send rate limit response without being limited.");throw new Error("Trying to send rate limit response without being limited.",);}- return sendRateLimitResponse(nextResponse, this.res);+ return sendRateLimitResponse(nextResponse, this.res, errorContract);}}export const sendRateLimitResponse = (res: NextApiResponse,rateLimitRes: RateLimitResult,+ errorContract?: PublicApiErrorContract,) => {const httpHeader = createHttpHeaderFromRateLimit(rateLimitRes);@@ -187,6 +197,13 @@ export const sendRateLimitResponse = (res.setHeader(header, value);}+ if (errorContract === unstablePublicEvalsErrorContract) {+ return sendUnstablePublicApiErrorResponse(+ res,+ createUnstablePublicApiRateLimitError(rateLimitRes),+ );+ }+res.status(429).end("429 - rate limit exceeded");};diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex 3473c9d7c1..d989cfcd8c 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -15,11 +15,19 @@ import { RateLimitService } from "@/src/features/public-api/server/RateLimitServimport { contextWithLangfuseProps } from "@langfuse/shared/src/server";import * as opentelemetry from "@opentelemetry/api";import { env } from "@/src/env.mjs";+import { isZodError } from "@/src/features/public-api/server/withMiddlewares";+import {+ createUnstablePublicApiAuthError,+ createUnstablePublicApiRequestValidationError,+ sendUnstablePublicApiErrorResponse,+ unstablePublicEvalsErrorContract,+ type PublicApiErrorContract,+} from "@/src/features/public-api/server/unstable-public-api-error-contract";/** Access levels that can be accepted by project-scoped API routes. */type RouteAccessLevel = Exclude<ApiAccessLevel, "organization">;-type RouteConfig<+export type AuthedProjectAPIRouteConfig<TQuery extends ZodType<any>,TBody extends ZodType<any>,TResponse extends ZodType<any>,@@ -44,6 +52,7 @@ type RouteConfig<* @default false*/isAdminApiKeyAuthAllowed?: boolean;+ errorContract?: PublicApiErrorContract;/*** Access levels accepted for this route. Defaults to ["project"] (Basic auth only).* Set to ["project", "scores"] to also allow Bearer auth with a public key@@ -96,14 +105,14 @@ async function verifyApiKeyAuth()) {throw {- status: 401,+ status: 403,message: "Access denied - insufficient permissions for this endpoint",};}if (!regularAuth.scope.projectId) {throw {- status: 401,+ status: 403,message:"Project ID not found for API token. Are you using an organization key?",};@@ -263,7 +272,7 @@ export const createAuthedProjectAPIRoute = <TBody extends ZodType<any>,TResponse extends ZodType<any>,>(- routeConfig: RouteConfig<TQuery, TBody, TResponse>,+ routeConfig: AuthedProjectAPIRouteConfig<TQuery, TBody, TResponse>,): ((req: NextApiRequest, res: NextApiResponse) => Promise<void>) => {return async (req: NextApiRequest, res: NextApiResponse) => {let auth: AuthHeaderValidVerificationResult & {@@ -281,6 +290,13 @@ export const createAuthedProjectAPIRoute = <const statusCode = error.status || 401;const message = error.message || "Authentication failed";+ if (routeConfig.errorContract === unstablePublicEvalsErrorContract) {+ return sendUnstablePublicApiErrorResponse(+ res,+ createUnstablePublicApiAuthError({ statusCode, message }),+ );+ }+res.status(statusCode).json({ message });return;@@ -293,7 +309,10 @@ export const createAuthedProjectAPIRoute = <);if (rateLimitResponse?.isRateLimited()) {- return rateLimitResponse.sendRestResponseIfLimited(res);+ return rateLimitResponse.sendRestResponseIfLimited(+ res,+ routeConfig.errorContract,+ );}logger.debug(@@ -304,12 +323,49 @@ export const createAuthedProjectAPIRoute = <},);- const query = routeConfig.querySchema- ? routeConfig.querySchema.parse(req.query)- : ({} as z.infer<TQuery>);- const body = routeConfig.bodySchema- ? routeConfig.bodySchema.parse(req.body)- : ({} as z.infer<TBody>);+ let query: z.infer<TQuery>;+ try {+ query = routeConfig.querySchema+ ? routeConfig.querySchema.parse(req.query)+ : ({} as z.infer<TQuery>);+ } catch (error) {+ if (+ routeConfig.errorContract === unstablePublicEvalsErrorContract &&+ isZodError(error)+ ) {+ return sendUnstablePublicApiErrorResponse(+ res,+ createUnstablePublicApiRequestValidationError({+ error,+ requestPart: "query",+ }),+ );+ }++ throw error;+ }++ let body: z.infer<TBody>;+ try {+ body = routeConfig.bodySchema+ ? routeConfig.bodySchema.parse(req.body)+ : ({} as z.infer<TBody>);+ } catch (error) {+ if (+ routeConfig.errorContract === unstablePublicEvalsErrorContract &&+ isZodError(error)+ ) {+ return sendUnstablePublicApiErrorResponse(+ res,+ createUnstablePublicApiRequestValidationError({+ error,+ requestPart: "body",+ }),+ );+ }++ throw error;+ }const ctx = contextWithLangfuseProps({headers: req.headers,diff --git a/web/src/features/public-api/server/unstable-public-api-error-contract.ts b/web/src/features/public-api/server/unstable-public-api-error-contract.tsnew file mode 100644index 0000000000..aeb086e186--- /dev/null+++ b/web/src/features/public-api/server/unstable-public-api-error-contract.ts@@ -0,0 +1,243 @@+import { type NextApiResponse } from "next";+import { type ZodError } from "zod";+import {+ BaseError,+ InvalidRequestError,+ InternalServerError,+ LangfuseConflictError,+ LangfuseNotFoundError,+ MethodNotAllowedError,+ UnauthorizedError,+ type RateLimitResult,+} from "@langfuse/shared";+import { ClickHouseResourceError } from "@langfuse/shared/src/server";+import type {+ UnstablePublicApiErrorCodeType,+ UnstablePublicApiErrorDetailsType,+} from "@/src/features/public-api/shared/unstable-public-api-error-schema";++export const unstablePublicEvalsErrorContract = "unstable-public-evals";+export type PublicApiErrorContract = typeof unstablePublicEvalsErrorContract;++type UnstablePublicApiErrorBody = {+ message: string;+ code: UnstablePublicApiErrorCodeType;+ details?: UnstablePublicApiErrorDetailsType;+};++export class UnstablePublicApiError extends BaseError {+ public readonly code: UnstablePublicApiErrorCodeType;+ public readonly details?: UnstablePublicApiErrorDetailsType;++ constructor(params: {+ httpCode: number;+ code: UnstablePublicApiErrorCodeType;+ message: string;+ details?: UnstablePublicApiErrorDetailsType;+ }) {+ super("UnstablePublicApiError", params.httpCode, params.message, true);+ this.code = params.code;+ this.details = params.details;+ }+}++function toBody(error: UnstablePublicApiError): UnstablePublicApiErrorBody {+ return {+ message: error.message,+ code: error.code,+ ...(error.details !== undefined ? { details: error.details } : {}),+ };+}++function toSerializableIssues(issues: ZodError["issues"]) {+ return issues.map((issue) => ({+ ...issue,+ path: issue.path.filter(+ (segment): segment is string | number =>+ typeof segment === "string" || typeof segment === "number",+ ),+ }));+}++export function sendUnstablePublicApiErrorResponse(+ res: NextApiResponse,+ error: UnstablePublicApiError,+) {+ return res.status(error.httpCode).json(toBody(error));+}++export function createUnstablePublicApiError(params: {+ httpCode: number;+ code: UnstablePublicApiErrorCodeType;+ message: string;+ details?: UnstablePublicApiErrorDetailsType;+}) {+ return new UnstablePublicApiError(params);+}++export function createUnstablePublicApiAuthError(params: {+ statusCode: number;+ message: string;+}) {+ switch (params.statusCode) {+ case 400:+ return createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_request",+ message: params.message,+ });+ case 401:+ return createUnstablePublicApiError({+ httpCode: 401,+ code: "authentication_failed",+ message: params.message,+ });+ case 403:+ return createUnstablePublicApiError({+ httpCode: 403,+ code: "access_denied",+ message: params.message,+ });+ case 404:+ return createUnstablePublicApiError({+ httpCode: 404,+ code: "resource_not_found",+ message: params.message,+ });+ default:+ return createUnstablePublicApiError({+ httpCode: params.statusCode,+ code: params.statusCode >= 500 ? "internal_error" : "invalid_request",+ message: params.message,+ });+ }+}++export function createUnstablePublicApiRateLimitError(+ rateLimitRes: RateLimitResult,+) {+ return createUnstablePublicApiError({+ httpCode: 429,+ code: "rate_limited",+ message: "Rate limit exceeded",+ details: {+ retryAfterSeconds: Math.ceil(rateLimitRes.msBeforeNext / 1000),+ limit: rateLimitRes.points,+ remaining: rateLimitRes.remainingPoints,+ resetAt: new Date(Date.now() + rateLimitRes.msBeforeNext).toISOString(),+ },+ });+}++export function createUnstablePublicApiRequestValidationError(params: {+ error: ZodError;+ requestPart: "query" | "body";+}) {+ return createUnstablePublicApiError({+ httpCode: 400,+ code: params.requestPart === "query" ? "invalid_query" : "invalid_body",+ message:+ params.requestPart === "query"+ ? "Invalid query parameters"+ : "Invalid request body",+ details: {+ issues: toSerializableIssues(params.error.issues),+ },+ });+}++export function toUnstablePublicApiError(+ error: unknown,+): UnstablePublicApiError {+ if (error instanceof UnstablePublicApiError) {+ return error;+ }++ if (+ error instanceof Object &&+ error.constructor.name === "ZodError" &&+ "issues" in error+ ) {+ return createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_request",+ message: "Invalid request data",+ details: {+ issues: toSerializableIssues(error.issues as ZodError["issues"]),+ },+ });+ }++ if (error instanceof LangfuseNotFoundError) {+ return createUnstablePublicApiError({+ httpCode: 404,+ code: "resource_not_found",+ message: error.message,+ });+ }++ if (error instanceof UnauthorizedError) {+ return createUnstablePublicApiError({+ httpCode: 403,+ code: "access_denied",+ message: error.message,+ });+ }++ if (error instanceof MethodNotAllowedError) {+ return createUnstablePublicApiError({+ httpCode: 405,+ code: "method_not_allowed",+ message: error.message,+ });+ }++ if (error instanceof LangfuseConflictError) {+ return createUnstablePublicApiError({+ httpCode: 409,+ code: "conflict",+ message: error.message,+ });+ }++ if (error instanceof InvalidRequestError) {+ return createUnstablePublicApiError({+ httpCode: 400,+ code: "invalid_request",+ message: error.message,+ });+ }++ if (error instanceof ClickHouseResourceError) {+ return createUnstablePublicApiError({+ httpCode: 422,+ code: "unprocessable_content",+ message: [+ ClickHouseResourceError.ERROR_ADVICE_MESSAGE,+ "See https://langfuse.com/docs/api-and-data-platform/features/public-api for more details.",+ ].join("\n"),+ });+ }++ if (error instanceof InternalServerError) {+ return createUnstablePublicApiError({+ httpCode: 500,+ code: "internal_error",+ message: error.message,+ });+ }++ if (error instanceof BaseError) {+ return createUnstablePublicApiError({+ httpCode: error.httpCode,+ code: error.httpCode >= 500 ? "internal_error" : "invalid_request",+ message: error.message,+ });+ }++ return createUnstablePublicApiError({+ httpCode: 500,+ code: "internal_error",+ message: "Internal Server Error",+ });+}diff --git a/web/src/features/public-api/server/unstable-public-evals-route.ts b/web/src/features/public-api/server/unstable-public-evals-route.tsnew file mode 100644index 0000000000..6a232ebe7f--- /dev/null+++ b/web/src/features/public-api/server/unstable-public-evals-route.ts@@ -0,0 +1,46 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { type ZodType } from "zod";+import {+ createAuthedProjectAPIRoute,+ type AuthedProjectAPIRouteConfig,+} from "@/src/features/public-api/server/createAuthedProjectAPIRoute";+import {+ withMiddlewares,+ type HttpMethod,+} from "@/src/features/public-api/server/withMiddlewares";+import { unstablePublicEvalsErrorContract } from "@/src/features/public-api/server/unstable-public-api-error-contract";++type UnstablePublicEvalsRouteConfig<+ TQuery extends ZodType<any>,+ TBody extends ZodType<any>,+ TResponse extends ZodType<any>,+> = Omit<+ AuthedProjectAPIRouteConfig<TQuery, TBody, TResponse>,+ "errorContract"+>;++type UnstablePublicEvalsHandlers = {+ [Method in HttpMethod]?: (+ req: NextApiRequest,+ res: NextApiResponse,+ ) => Promise<void>;+};++export const createUnstablePublicEvalsRoute = <+ TQuery extends ZodType<any>,+ TBody extends ZodType<any>,+ TResponse extends ZodType<any>,+>(+ routeConfig: UnstablePublicEvalsRouteConfig<TQuery, TBody, TResponse>,+) =>+ createAuthedProjectAPIRoute({+ ...routeConfig,+ errorContract: unstablePublicEvalsErrorContract,+ });++export const withUnstablePublicEvalsMiddlewares = (+ handlers: UnstablePublicEvalsHandlers,+) =>+ withMiddlewares(handlers, {+ errorContract: unstablePublicEvalsErrorContract,+ });diff --git a/web/src/features/public-api/server/withMiddlewares.ts b/web/src/features/public-api/server/withMiddlewares.tsindex e166d02a51..8e71e12a6a 100644--- a/web/src/features/public-api/server/withMiddlewares.ts+++ b/web/src/features/public-api/server/withMiddlewares.ts@@ -15,6 +15,12 @@ import {ClickHouseResourceError,} from "@langfuse/shared/src/server";import * as opentelemetry from "@opentelemetry/api";+import {+ sendUnstablePublicApiErrorResponse,+ toUnstablePublicApiError,+ unstablePublicEvalsErrorContract,+ type PublicApiErrorContract,+} from "@/src/features/public-api/server/unstable-public-api-error-contract";// Exported to silence @typescript-eslint/no-unused-vars v8 warning// (used for type extraction via typeof, which is a legitimate pattern)@@ -36,7 +42,14 @@ const CH_ERROR_ADVICE_FULL = ["See https://langfuse.com/docs/api-and-data-platform/features/public-api for more details.",].join("\n");-export function withMiddlewares(handlers: Handlers) {+type MiddlewareOptions = {+ errorContract?: PublicApiErrorContract;+};++export function withMiddlewares(+ handlers: Handlers,+ options?: MiddlewareOptions,+) {return async (req: NextApiRequest, res: NextApiResponse) => {const ctx = contextWithLangfuseProps({headers: req.headers,@@ -71,6 +84,33 @@ export function withMiddlewares(handlers: Handlers) {logger.error(error);}+ if (options?.errorContract === unstablePublicEvalsErrorContract) {+ if (+ error instanceof BaseError &&+ error.httpCode >= 500 &&+ error.httpCode < 600+ ) {+ traceException(error);+ }++ if (isPrismaException(error)) {+ traceException(error);+ }++ if (+ !(error instanceof BaseError) &&+ !(error instanceof ClickHouseResourceError) &&+ !isZodError(error)+ ) {+ traceException(error);+ }++ return sendUnstablePublicApiErrorResponse(+ res,+ toUnstablePublicApiError(error),+ );+ }+if (error instanceof BaseError) {if (error.httpCode >= 500 && error.httpCode < 600) {traceException(error);diff --git a/web/src/features/public-api/shared/unstable-public-api-error-schema.ts b/web/src/features/public-api/shared/unstable-public-api-error-schema.tsnew file mode 100644index 0000000000..d37cd7a047--- /dev/null+++ b/web/src/features/public-api/shared/unstable-public-api-error-schema.ts@@ -0,0 +1,68 @@+import { z } from "zod";++export const unstablePublicApiErrorCodes = [+ "authentication_failed",+ "access_denied",+ "invalid_request",+ "invalid_query",+ "invalid_body",+ "invalid_filter_value",+ "invalid_json_path",+ "invalid_variable_mapping",+ "missing_variable_mapping",+ "duplicate_variable_mapping",+ "resource_not_found",+ "name_conflict",+ "evaluator_in_use",+ "evaluator_preflight_failed",+ "conflict",+ "unprocessable_content",+ "rate_limited",+ "method_not_allowed",+ "internal_error",+] as const;++export const UnstablePublicApiErrorCode = z.enum(unstablePublicApiErrorCodes);++const UnstablePublicApiValidationIssue = z+ .object({+ code: z.string(),+ message: z.string(),+ path: z.array(z.union([z.string(), z.number()])),+ })+ .passthrough();++export const UnstablePublicApiErrorDetails = z+ .object({+ issues: z.array(UnstablePublicApiValidationIssue).optional(),+ field: z.string().optional(),+ column: z.string().optional(),+ invalidValues: z.array(z.string()).optional(),+ allowedValues: z.array(z.string()).optional(),+ variable: z.string().optional(),+ variables: z.array(z.string()).optional(),+ value: z.string().optional(),+ evaluatorName: z.string().optional(),+ provider: z.string().nullable().optional(),+ model: z.string().nullable().optional(),+ retryAfterSeconds: z.number().int().positive().optional(),+ limit: z.number().int().positive().optional(),+ remaining: z.number().int().nonnegative().optional(),+ resetAt: z.string().optional(),+ })+ .strict();++export const UnstablePublicApiErrorResponse = z+ .object({+ message: z.string(),+ code: UnstablePublicApiErrorCode,+ details: UnstablePublicApiErrorDetails.optional(),+ })+ .strict();++export type UnstablePublicApiErrorCodeType = z.infer<+ typeof UnstablePublicApiErrorCode+>;+export type UnstablePublicApiErrorDetailsType = z.infer<+ typeof UnstablePublicApiErrorDetails+>;diff --git a/web/src/features/public-api/types/unstable-evaluation-rules.ts b/web/src/features/public-api/types/unstable-evaluation-rules.tsnew file mode 100644index 0000000000..fa72aa363e--- /dev/null+++ b/web/src/features/public-api/types/unstable-evaluation-rules.ts@@ -0,0 +1,129 @@+import { z } from "zod";+import {+ ExperimentEvaluationRuleFilter,+ ExperimentEvaluationRuleMapping,+ ObservationEvaluationRuleFilter,+ ObservationEvaluationRuleMapping,+ PublicEvaluationRuleFilter,+ PublicEvaluationRuleEvaluator,+ PublicEvaluationRuleEvaluatorReference,+ PublicEvaluationRuleMapping,+ PublicEvaluationRuleStatus,+ PublicEvaluationRuleTarget,+ UnstablePublicApiPaginationQuery,+ UnstablePublicApiPaginationResponse,+} from "@/src/features/public-api/types/unstable-public-evals-contract";++export const APIEvaluationRule = z+ .object({+ id: z.string(),+ name: z.string(),+ evaluator: PublicEvaluationRuleEvaluator,+ target: PublicEvaluationRuleTarget,+ enabled: z.boolean(),+ status: PublicEvaluationRuleStatus,+ pausedReason: z.string().nullable(),+ pausedMessage: z.string().nullable(),+ sampling: z.number().gt(0).lte(1),+ filter: z.array(PublicEvaluationRuleFilter),+ mapping: z.array(PublicEvaluationRuleMapping),+ createdAt: z.coerce.date(),+ updatedAt: z.coerce.date(),+ })+ .strict();++export const GetUnstableEvaluationRulesQuery = UnstablePublicApiPaginationQuery;++export const GetUnstableEvaluationRulesResponse = z+ .object({+ data: z.array(APIEvaluationRule),+ meta: UnstablePublicApiPaginationResponse,+ })+ .strict();++export const GetUnstableEvaluationRuleQuery = z.object({+ evaluationRuleId: z.string(),+});++export const GetUnstableEvaluationRuleResponse = APIEvaluationRule;++const EvaluationRuleCreateBase = {+ name: z.string().min(1),+ evaluator: PublicEvaluationRuleEvaluatorReference,+ enabled: z.boolean(),+ 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),+ }),+]);+export type PostUnstableEvaluationRuleBodyType = z.infer<+ typeof PostUnstableEvaluationRuleBody+>;++export const PostUnstableEvaluationRuleResponse = APIEvaluationRule;++export const PatchUnstableEvaluationRuleQuery = GetUnstableEvaluationRuleQuery;++const EvaluationRulePatchBase = {+ name: z.string().min(1).optional(),+ evaluator: PublicEvaluationRuleEvaluatorReference.optional(),+ enabled: z.boolean().optional(),+ sampling: z.number().gt(0).lte(1).optional(),+};++const UntargetedEvaluationRulePatch = z.object({+ ...EvaluationRulePatchBase,+ target: z.undefined().optional(),+ filter: z.undefined().optional(),+ mapping: z.undefined().optional(),+});++const ObservationEvaluationRulePatch = z.object({+ ...EvaluationRulePatchBase,+ target: z.literal("observation"),+ filter: z.array(ObservationEvaluationRuleFilter).optional(),+ mapping: z.array(ObservationEvaluationRuleMapping).optional(),+});++const ExperimentEvaluationRulePatch = z.object({+ ...EvaluationRulePatchBase,+ target: z.literal("experiment"),+ filter: z.array(ExperimentEvaluationRuleFilter).optional(),+ mapping: z.array(ExperimentEvaluationRuleMapping).optional(),+});++export const PatchUnstableEvaluationRuleBody = z+ .union([+ ObservationEvaluationRulePatch,+ ExperimentEvaluationRulePatch,+ UntargetedEvaluationRulePatch,+ ])+ .refine((data) => Object.keys(data).length > 0, {+ message:+ "Request body cannot be empty. At least one field must be provided for update.",+ });+export type PatchUnstableEvaluationRuleBodyType = z.infer<+ typeof PatchUnstableEvaluationRuleBody+>;++export const PatchUnstableEvaluationRuleResponse = APIEvaluationRule;++export const DeleteUnstableEvaluationRuleQuery = GetUnstableEvaluationRuleQuery;++export const DeleteUnstableEvaluationRuleResponse = z+ .object({+ message: z.literal("Evaluation rule successfully deleted"),+ })+ .strict();diff --git a/web/src/features/public-api/types/unstable-evaluators.ts b/web/src/features/public-api/types/unstable-evaluators.tsnew file mode 100644index 0000000000..3df00dff98--- /dev/null+++ b/web/src/features/public-api/types/unstable-evaluators.ts@@ -0,0 +1,52 @@+import { z } from "zod";+import {+ PublicEvaluatorDefinitionInput,+ PublicEvaluatorModelConfig,+ PublicEvaluatorOutputDefinition,+ PublicEvaluatorScope,+ PublicEvaluatorType,+ UnstablePublicApiPaginationQuery,+ UnstablePublicApiPaginationResponse,+} from "@/src/features/public-api/types/unstable-public-evals-contract";++export const APIEvaluator = 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 GetUnstableEvaluatorsQuery = UnstablePublicApiPaginationQuery;++export const GetUnstableEvaluatorsResponse = z+ .object({+ data: z.array(APIEvaluator),+ meta: UnstablePublicApiPaginationResponse,+ })+ .strict();++export const GetUnstableEvaluatorQuery = z.object({+ evaluatorId: z.string(),+});++export const GetUnstableEvaluatorResponse = APIEvaluator;++export const PostUnstableEvaluatorBody = z.object({+ name: z.string().min(1),+ ...PublicEvaluatorDefinitionInput.shape,+});+export type PostUnstableEvaluatorBodyType = z.infer<+ typeof PostUnstableEvaluatorBody+>;++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.tsnew file mode 100644index 0000000000..0ee2691e6e--- /dev/null+++ b/web/src/features/public-api/types/unstable-public-evals-contract.ts@@ -0,0 +1,246 @@+import {+ arrayOptionsFilter,+ categoryOptionsFilter,+ nullFilter,+ numberFilter,+ numberObjectFilter,+ observationEvalFilterColumns,+ paginationMetaResponseZod,+ stringFilter,+ stringObjectFilter,+ stringOptionsFilter,+ timeFilter,+ experimentEvalFilterColumns,+ booleanFilter,+} from "@langfuse/shared";+import { z } from "zod";+export {+ UnstablePublicApiErrorCode,+ UnstablePublicApiErrorDetails,+ UnstablePublicApiErrorResponse,+} from "@/src/features/public-api/shared/unstable-public-api-error-schema";+import type {+ UnstablePublicApiErrorCodeType,+ UnstablePublicApiErrorDetailsType,+} from "@/src/features/public-api/shared/unstable-public-api-error-schema";++export const PublicEvaluatorType = z.literal("llm_as_judge");+export const PublicEvaluatorScope = z.enum(["project", "managed"]);++export const PublicEvaluatorModelConfig = z.object({+ provider: z.string().min(1),+ model: z.string().min(1),+});++export const PublicEvaluatorOutputFieldDefinition = z.object({+ description: z.string().trim().min(1),+});++export const PublicNumericEvaluatorOutputDefinition = z.object({+ dataType: z.literal("NUMERIC"),+ reasoning: PublicEvaluatorOutputFieldDefinition,+ score: PublicEvaluatorOutputFieldDefinition,+});++export const PublicBooleanEvaluatorOutputDefinition = z.object({+ dataType: z.literal("BOOLEAN"),+ reasoning: PublicEvaluatorOutputFieldDefinition,+ score: PublicEvaluatorOutputFieldDefinition,+});++export const PublicCategoricalEvaluatorOutputScoreDefinition = z.object({+ description: z.string().trim().min(1),+ categories: z.array(z.string().trim().min(1)).min(2),+ shouldAllowMultipleMatches: z.boolean(),+});++export const PublicCategoricalEvaluatorOutputDefinition = z.object({+ dataType: z.literal("CATEGORICAL"),+ reasoning: PublicEvaluatorOutputFieldDefinition,+ score: PublicCategoricalEvaluatorOutputScoreDefinition,+});++export const PublicEvaluatorOutputDefinition = z.discriminatedUnion(+ "dataType",+ [+ PublicNumericEvaluatorOutputDefinition,+ PublicBooleanEvaluatorOutputDefinition,+ PublicCategoricalEvaluatorOutputDefinition,+ ],+);++export const PublicEvaluationRuleTarget = z.enum(["observation", "experiment"]);++export const PublicEvaluationRuleStatus = z.enum([+ "active",+ "inactive",+ "paused",+]);++export const PublicEvaluationRuleEvaluatorReference = z.object({+ name: z.string().min(1),+ scope: PublicEvaluatorScope,+});++export const PublicEvaluationRuleEvaluator =+ PublicEvaluationRuleEvaluatorReference.extend({+ id: z.string(),+ });++export const ObservationEvaluationRuleMappingSource = z.enum([+ "input",+ "output",+ "metadata",+]);++export const ExperimentEvaluationRuleMappingSource = z.enum([+ "input",+ "output",+ "metadata",+ "expected_output",+]);++function createMappingSchema<+ TSource extends z.ZodType<+ "input" | "output" | "metadata" | "expected_output"+ >,+>(sourceSchema: TSource) {+ return z.object({+ variable: z.string().min(1),+ source: sourceSchema,+ jsonPath: z.string().min(1).optional(),+ });+}++export const ObservationEvaluationRuleMapping = createMappingSchema(+ ObservationEvaluationRuleMappingSource,+);++export const ExperimentEvaluationRuleMapping = createMappingSchema(+ ExperimentEvaluationRuleMappingSource,+);++export const PublicEvaluationRuleMapping = z.union([+ ObservationEvaluationRuleMapping,+ ExperimentEvaluationRuleMapping,+]);++const filterSchemaFactories = {+ datetime: (columnId: string) =>+ timeFilter.safeExtend({ column: z.literal(columnId) }),+ string: (columnId: string) =>+ stringFilter.safeExtend({ column: z.literal(columnId) }),+ number: (columnId: string) =>+ numberFilter.safeExtend({ column: z.literal(columnId) }),+ stringOptions: (columnId: string) =>+ stringOptionsFilter.safeExtend({ column: z.literal(columnId) }),+ categoryOptions: (columnId: string) =>+ categoryOptionsFilter.safeExtend({ column: z.literal(columnId) }),+ arrayOptions: (columnId: string) =>+ arrayOptionsFilter.safeExtend({ column: z.literal(columnId) }),+ stringObject: (columnId: string) =>+ stringObjectFilter.safeExtend({ column: z.literal(columnId) }),+ numberObject: (columnId: string) =>+ numberObjectFilter.safeExtend({ column: z.literal(columnId) }),+ boolean: (columnId: string) =>+ booleanFilter.safeExtend({ column: z.literal(columnId) }),+ null: (columnId: string) =>+ nullFilter.safeExtend({ column: z.literal(columnId) }),+} as const;++type SupportedFilterFactory = keyof typeof filterSchemaFactories;++function createTargetFilterSchema(+ columns: Array<{ id: string; type: SupportedFilterFactory }>,+) {+ const schemas = columns.map((column) =>+ filterSchemaFactories[column.type](column.id),+ );++ if (schemas.length === 1) {+ return schemas[0]!;+ }++ return z.union(+ schemas as [+ (typeof schemas)[number],+ (typeof schemas)[number],+ ...Array<(typeof schemas)[number]>,+ ],+ );+}++export const OBSERVATION_EVALUATION_RULE_FILTER_COLUMNS =+ observationEvalFilterColumns.map((column) => ({+ id: column.id,+ type: column.type as SupportedFilterFactory,+ }));++export const EXPERIMENT_EVALUATION_RULE_FILTER_COLUMNS = [+ {+ id: "datasetId",+ type: experimentEvalFilterColumns[0]!.type as SupportedFilterFactory,+ },+];++export const ObservationEvaluationRuleFilter = createTargetFilterSchema(+ OBSERVATION_EVALUATION_RULE_FILTER_COLUMNS,+);++export const ExperimentEvaluationRuleFilter = createTargetFilterSchema(+ EXPERIMENT_EVALUATION_RULE_FILTER_COLUMNS,+);++export const PublicEvaluationRuleFilter = z.union([+ ObservationEvaluationRuleFilter,+ ExperimentEvaluationRuleFilter,+]);++export type PublicEvaluatorModelConfigType = z.infer<+ typeof PublicEvaluatorModelConfig+>;+export type PublicEvaluatorOutputDefinitionType = z.infer<+ typeof PublicEvaluatorOutputDefinition+>;+export type PublicEvaluatorScopeType = z.infer<typeof PublicEvaluatorScope>;+export type PublicEvaluationRuleTargetType = z.infer<+ typeof PublicEvaluationRuleTarget+>;+export type PublicEvaluationRuleStatusType = z.infer<+ typeof PublicEvaluationRuleStatus+>;+export type PublicEvaluationRuleEvaluatorReferenceType = z.infer<+ typeof PublicEvaluationRuleEvaluatorReference+>;+export type PublicEvaluationRuleEvaluatorType = z.infer<+ typeof PublicEvaluationRuleEvaluator+>;+export type PublicEvaluationRuleMappingType = z.infer<+ typeof PublicEvaluationRuleMapping+>;+export type PublicEvaluationRuleFilterType = z.infer<+ typeof PublicEvaluationRuleFilter+>;+export type {+ UnstablePublicApiErrorCodeType,+ UnstablePublicApiErrorDetailsType,+};++export const UnstablePublicApiPaginationQuery = z.object({+ page: z.preprocess(+ (x) => (x === "" ? undefined : x),+ z.coerce.number().int().gt(0).default(1),+ ),+ limit: z.preprocess(+ (x) => (x === "" ? undefined : x),+ z.coerce.number().int().gt(0).lte(100).default(50),+ ),+});++export const UnstablePublicApiPaginationResponse = paginationMetaResponseZod;++export const PublicEvaluatorDefinitionInput = z.object({+ prompt: z.string().min(1),+ outputDefinition: PublicEvaluatorOutputDefinition,+ modelConfig: PublicEvaluatorModelConfig.nullable().optional(),+});diff --git a/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts b/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].tsnew file mode 100644index 0000000000..7cd7b31e00--- /dev/null+++ b/web/src/pages/api/public/unstable/evaluation-rules/[evaluationRuleId].ts@@ -0,0 +1,94 @@+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";+import {+ deletePublicEvaluationRule,+ getPublicEvaluationRule,+ updatePublicEvaluationRule,+} from "@/src/features/evals/server/unstable-public-api";+import {+ createUnstablePublicEvalsRoute,+ withUnstablePublicEvalsMiddlewares,+} from "@/src/features/public-api/server/unstable-public-evals-route";+import {+ DeleteUnstableEvaluationRuleQuery,+ DeleteUnstableEvaluationRuleResponse,+ GetUnstableEvaluationRuleQuery,+ GetUnstableEvaluationRuleResponse,+ PatchUnstableEvaluationRuleBody,+ PatchUnstableEvaluationRuleQuery,+ PatchUnstableEvaluationRuleResponse,+} from "@/src/features/public-api/types/unstable-evaluation-rules";++export default withUnstablePublicEvalsMiddlewares({+ GET: createUnstablePublicEvalsRoute({+ name: "Get Unstable Evaluation Rule",+ querySchema: GetUnstableEvaluationRuleQuery,+ responseSchema: GetUnstableEvaluationRuleResponse,+ fn: async ({ query, auth }) =>+ getPublicEvaluationRule({+ projectId: auth.scope.projectId,+ evaluationRuleId: query.evaluationRuleId,+ }),+ }),+ PATCH: createUnstablePublicEvalsRoute({+ name: "Update Unstable Evaluation Rule",+ querySchema: PatchUnstableEvaluationRuleQuery,+ bodySchema: PatchUnstableEvaluationRuleBody,+ responseSchema: PatchUnstableEvaluationRuleResponse,+ fn: async ({ query, body, auth }) => {+ const before = await getPublicEvaluationRule({+ projectId: auth.scope.projectId,+ evaluationRuleId: query.evaluationRuleId,+ });++ const evaluationRule = await updatePublicEvaluationRule({+ projectId: auth.scope.projectId,+ evaluationRuleId: query.evaluationRuleId,+ input: body,+ });++ await auditLog({+ action: "update",+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,+ resourceId: evaluationRule.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ before,+ after: evaluationRule,+ });++ return evaluationRule;+ },+ }),+ DELETE: createUnstablePublicEvalsRoute({+ name: "Delete Unstable Evaluation Rule",+ querySchema: DeleteUnstableEvaluationRuleQuery,+ responseSchema: DeleteUnstableEvaluationRuleResponse,+ fn: async ({ query, auth }) => {+ const before = await getPublicEvaluationRule({+ projectId: auth.scope.projectId,+ evaluationRuleId: query.evaluationRuleId,+ });++ await deletePublicEvaluationRule({+ projectId: auth.scope.projectId,+ evaluationRuleId: query.evaluationRuleId,+ });++ await auditLog({+ action: "delete",+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,+ resourceId: query.evaluationRuleId,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ before,+ });++ return {+ message: "Evaluation rule successfully deleted" as const,+ };+ },+ }),+});diff --git a/web/src/pages/api/public/unstable/evaluation-rules/index.ts b/web/src/pages/api/public/unstable/evaluation-rules/index.tsnew file mode 100644index 0000000000..96955cbe7b--- /dev/null+++ b/web/src/pages/api/public/unstable/evaluation-rules/index.ts@@ -0,0 +1,53 @@+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";+import {+ createPublicEvaluationRule,+ listPublicEvaluationRules,+} from "@/src/features/evals/server/unstable-public-api";+import {+ createUnstablePublicEvalsRoute,+ withUnstablePublicEvalsMiddlewares,+} from "@/src/features/public-api/server/unstable-public-evals-route";+import {+ GetUnstableEvaluationRulesQuery,+ GetUnstableEvaluationRulesResponse,+ PostUnstableEvaluationRuleBody,+ PostUnstableEvaluationRuleResponse,+} from "@/src/features/public-api/types/unstable-evaluation-rules";++export default withUnstablePublicEvalsMiddlewares({+ GET: createUnstablePublicEvalsRoute({+ name: "List Unstable Evaluation Rules",+ querySchema: GetUnstableEvaluationRulesQuery,+ responseSchema: GetUnstableEvaluationRulesResponse,+ fn: async ({ query, auth }) =>+ listPublicEvaluationRules({+ projectId: auth.scope.projectId,+ page: query.page,+ limit: query.limit,+ }),+ }),+ POST: createUnstablePublicEvalsRoute({+ name: "Create Unstable Evaluation Rule",+ bodySchema: PostUnstableEvaluationRuleBody,+ responseSchema: PostUnstableEvaluationRuleResponse,+ fn: async ({ body, auth }) => {+ const evaluationRule = await createPublicEvaluationRule({+ projectId: auth.scope.projectId,+ input: body,+ });++ await auditLog({+ action: "create",+ resourceType: JOB_CONFIGURATION_AUDIT_LOG_RESOURCE_TYPE,+ resourceId: evaluationRule.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ after: evaluationRule,+ });++ return evaluationRule;+ },+ }),+});diff --git a/web/src/pages/api/public/unstable/evaluators/[evaluatorId].ts b/web/src/pages/api/public/unstable/evaluators/[evaluatorId].tsnew file mode 100644index 0000000000..6164841926--- /dev/null+++ b/web/src/pages/api/public/unstable/evaluators/[evaluatorId].ts@@ -0,0 +1,22 @@+import { getPublicEvaluator } from "@/src/features/evals/server/unstable-public-api";+import {+ createUnstablePublicEvalsRoute,+ withUnstablePublicEvalsMiddlewares,+} from "@/src/features/public-api/server/unstable-public-evals-route";+import {+ GetUnstableEvaluatorQuery,+ GetUnstableEvaluatorResponse,+} from "@/src/features/public-api/types/unstable-evaluators";++export default withUnstablePublicEvalsMiddlewares({+ GET: createUnstablePublicEvalsRoute({+ name: "Get Unstable Evaluator",+ querySchema: GetUnstableEvaluatorQuery,+ responseSchema: GetUnstableEvaluatorResponse,+ fn: async ({ query, auth }) =>+ getPublicEvaluator({+ projectId: auth.scope.projectId,+ evaluatorId: query.evaluatorId,+ }),+ }),+});diff --git a/web/src/pages/api/public/unstable/evaluators/index.ts b/web/src/pages/api/public/unstable/evaluators/index.tsnew file mode 100644index 0000000000..3b9c2ef3bd--- /dev/null+++ b/web/src/pages/api/public/unstable/evaluators/index.ts@@ -0,0 +1,53 @@+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE } from "@/src/features/evals/server/audit-log-resource-types";+import {+ createPublicEvaluator,+ listPublicEvaluators,+} from "@/src/features/evals/server/unstable-public-api";+import {+ createUnstablePublicEvalsRoute,+ withUnstablePublicEvalsMiddlewares,+} from "@/src/features/public-api/server/unstable-public-evals-route";+import {+ GetUnstableEvaluatorsQuery,+ GetUnstableEvaluatorsResponse,+ PostUnstableEvaluatorBody,+ PostUnstableEvaluatorResponse,+} from "@/src/features/public-api/types/unstable-evaluators";++export default withUnstablePublicEvalsMiddlewares({+ GET: createUnstablePublicEvalsRoute({+ name: "List Unstable Evaluators",+ querySchema: GetUnstableEvaluatorsQuery,+ responseSchema: GetUnstableEvaluatorsResponse,+ fn: async ({ query, auth }) =>+ listPublicEvaluators({+ projectId: auth.scope.projectId,+ page: query.page,+ limit: query.limit,+ }),+ }),+ POST: createUnstablePublicEvalsRoute({+ name: "Create Unstable Evaluator",+ bodySchema: PostUnstableEvaluatorBody,+ responseSchema: PostUnstableEvaluatorResponse,+ fn: async ({ body, auth }) => {+ const evaluator = await createPublicEvaluator({+ projectId: auth.scope.projectId,+ input: body,+ });++ await auditLog({+ action: "create",+ resourceType: EVAL_TEMPLATE_AUDIT_LOG_RESOURCE_TYPE,+ resourceId: evaluator.id,+ projectId: auth.scope.projectId,+ orgId: auth.scope.orgId,+ apiKeyId: auth.scope.apiKeyId,+ after: evaluator,+ });++ return evaluator;+ },+ }),+});