The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(ui): expose both decisions playground endpoints (#45817)
devin-ai-integration[bot]33b9d846b039
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/DecisionFormControls.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/DecisionFormControls.tsxnew file mode 100644index 00000000000..af821e77916--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/DecisionFormControls.tsx@@ -0,0 +1,43 @@+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/cva.config";+import { Plus, Trash2 } from "lucide-react";+import { useId, type ReactNode } from "react";+import { IssueList, ValidationStatus } from "./JsonEditor";+import type { PayloadValidation } from "./lib/validatePayload";++export function RemoveButton({ label, onClick }: { label: string; onClick: () => void }) {+ return (+ <Button variant="ghost" size="icon" aria-label={label} title={label} onClick={onClick}>+ <Trash2 />+ </Button>+ );+}++export function AddButton({ children, onClick }: { children: ReactNode; onClick: () => void }) {+ return (+ <Button variant="outline" size="sm" className="w-fit" onClick={onClick}>+ <Plus />+ {children}+ </Button>+ );+}++export function FormFrame({ validation, children }: { validation: PayloadValidation<unknown>; children: ReactNode }) {+ const issuesId = useId();++ return (+ <div+ className={cn(+ "flex min-h-96 flex-1 flex-col overflow-hidden rounded-md border bg-background",+ !validation.isValid && "border-destructive/60",+ )}+ >+ <div className="flex items-center gap-2 border-b px-3 py-2">+ <span className="text-sm font-medium">Request form</span>+ <ValidationStatus validation={validation} />+ </div>+ <div className="grid min-h-80 flex-1 content-start gap-4 overflow-auto p-3">{children}</div>+ <IssueList id={issuesId} validation={validation} />+ </div>+ );+}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/JsonEditor.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/JsonEditor.tsxindex cc7bebb0bb8..7311c3a055a 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/JsonEditor.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/JsonEditor.tsx@@ -7,7 +7,7 @@ import { createElement, PrismLight as SyntaxHighlighter } from "react-syntax-higimport type { SyntaxHighlighterProps } from "react-syntax-highlighter";import json from "react-syntax-highlighter/dist/esm/languages/prism/json";import { vs, vscDarkPlus } from "react-syntax-highlighter/dist/esm/styles/prism";-import type { SystemOnePayloadValidation } from "./lib/validatePayload";+import type { PayloadValidation } from "./lib/validatePayload";SyntaxHighlighter.registerLanguage("json", json);@@ -57,10 +57,12 @@ const TRANSPARENT_PRE = {interface JsonEditorProps {value: string;onChange: (value: string) => void;- validation: SystemOnePayloadValidation;+ validation: PayloadValidation<unknown>;+ label?: string;+ placeholder?: string;}-export function ValidationStatus({ validation }: { validation: SystemOnePayloadValidation }) {+export function ValidationStatus({ validation }: { validation: PayloadValidation<unknown> }) {const errorCount = validation.issues.filter((issue) => issue.severity === "error").length;if (errorCount > 0) {return (@@ -72,7 +74,7 @@ export function ValidationStatus({ validation }: { validation: SystemOnePayloadVreturn <Badge variant="secondary">Valid payload</Badge>;}-export function IssueList({ id, validation }: { id: string; validation: SystemOnePayloadValidation }) {+export function IssueList({ id, validation }: { id: string; validation: PayloadValidation<unknown> }) {if (validation.issues.length === 0) {return (<p id={id} role="status" className="flex items-center gap-1.5 border-t px-3 py-2 text-xs text-muted-foreground">@@ -112,7 +114,13 @@ function LineRows({ rows, stylesheet, useInlineStyles }: LineRendererProps) {});}-export default function JsonEditor({ value, onChange, validation }: JsonEditorProps) {+export default function JsonEditor({+ value,+ onChange,+ validation,+ label = "System One JSON payload",+ placeholder = "Paste or write a System One request",+}: JsonEditorProps) {const issuesId = useId();const highlightRef = useRef<HTMLDivElement>(null);const syntaxTheme = useTheme().resolvedTheme === "dark" ? VS_CODE_DARK_PLUS : VS_CODE_LIGHT_PLUS;@@ -156,7 +164,7 @@ export default function JsonEditor({ value, onChange, validation }: JsonEditorPr</SyntaxHighlighter></div><textarea- aria-label="System One JSON payload"+ aria-label={label}aria-invalid={hasErrors}aria-describedby={issuesId}value={value}@@ -169,7 +177,7 @@ export default function JsonEditor({ value, onChange, validation }: JsonEditorPrspellCheck={false}autoCapitalize="off"autoComplete="off"- placeholder="Paste or write a System One request"+ placeholder={placeholder}className={cn(EDITOR_TEXT,CONTENT_INSET,diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/OpenAIDecisionsForm.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/OpenAIDecisionsForm.tsxnew file mode 100644index 00000000000..a88278e18e2--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/OpenAIDecisionsForm.tsx@@ -0,0 +1,267 @@+"use client";++import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Textarea } from "@/components/ui/textarea";+import { useId, useMemo } from "react";+import { AddButton, FormFrame, RemoveButton } from "./DecisionFormControls";+import { freeName, removeAt, replaceAt } from "./lib/formPayload";+import {+ readDecisionsForm,+ retypeDecisionQuestion,+ type DecisionsFormPayload,+ type DecisionsFormQuestion,+ type DecisionsQuestionType,+} from "./lib/openAIDecisionsForm";+import type { OpenAIDecisionsRequest } from "./lib/openAIDecisions";+import type { PayloadValidation } from "./lib/validatePayload";++const QUESTION_TYPES: readonly DecisionsQuestionType[] = ["predicate", "choice", "score"];+const TYPE_LABELS = { predicate: "Predicate", choice: "Choice", score: "Score" };++interface QuestionEditorProps<Q extends DecisionsFormQuestion = DecisionsFormQuestion> {+ question: Q;+ onChange: (question: DecisionsFormQuestion) => void;+}++function Choices({ question, onChange }: QuestionEditorProps<Extract<DecisionsFormQuestion, { type: "choice" }>>) {+ const choices = question.choices ?? [];+ const write = (next: typeof choices) => onChange({ ...question, choices: next });++ return (+ <div className="grid gap-2">+ <span className="text-sm font-medium">Choices</span>+ {choices.map((choice, index) => (+ <div key={index} className="grid gap-2 rounded-md border p-2">+ <div className="flex items-center gap-2">+ <Select+ value={typeof choice.value === "string" ? "text" : String(choice.value)}+ onValueChange={(type) => {+ if (type === "text" || type === "true" || type === "false") {+ const value = type === "text" ? String(choice.value) : type === "true";+ write(replaceAt(choices, index, { ...choice, value }));+ }+ }}+ >+ <SelectTrigger className="w-40" aria-label={`Choice ${index + 1} value type`}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="text">Text</SelectItem>+ <SelectItem value="true">true (boolean)</SelectItem>+ <SelectItem value="false">false (boolean)</SelectItem>+ </SelectContent>+ </Select>+ {typeof choice.value === "string" && (+ <Input+ aria-label={`Choice ${index + 1} value`}+ value={choice.value}+ onChange={(event) => write(replaceAt(choices, index, { ...choice, value: event.target.value }))}+ />+ )}+ <RemoveButton label={`Remove choice ${index + 1}`} onClick={() => write(removeAt(choices, index))} />+ </div>+ <Input+ aria-label={`Choice ${index + 1} description`}+ value={choice.description ?? ""}+ placeholder="Optional description"+ onChange={(event) => write(replaceAt(choices, index, { ...choice, description: event.target.value }))}+ />+ </div>+ ))}+ <AddButton+ onClick={() =>+ write([+ ...choices,+ {+ value: freeName(+ choices.map((c) => String(c.value)),+ "option",+ ),+ },+ ])+ }+ >+ Add choice+ </AddButton>+ </div>+ );+}++function Levels({ question, onChange }: QuestionEditorProps<Extract<DecisionsFormQuestion, { type: "score" }>>) {+ const levels = question.levels ?? [];+ const write = (next: typeof levels) => onChange({ ...question, levels: next });++ return (+ <div className="grid gap-2">+ <span className="text-sm font-medium">Levels, lowest first</span>+ {levels.map((level, index) => (+ <div key={index} className="flex items-center gap-2">+ <Input+ aria-label={`Level ${index + 1} label`}+ value={level.label}+ placeholder="Label"+ onChange={(event) => write(replaceAt(levels, index, { ...level, label: event.target.value }))}+ />+ <Input+ aria-label={`Level ${index + 1} description`}+ value={level.description ?? ""}+ placeholder="Optional description"+ onChange={(event) => write(replaceAt(levels, index, { ...level, description: event.target.value }))}+ />+ <RemoveButton label={`Remove level ${index + 1}`} onClick={() => write(removeAt(levels, index))} />+ </div>+ ))}+ <AddButton onClick={() => write([...levels, { label: String(levels.length) }])}>Add level</AddButton>+ </div>+ );+}++interface QuestionCardProps extends QuestionEditorProps {+ index: number;+ onRemove: () => void;+}++function QuestionCard({ question, index, onChange, onRemove }: QuestionCardProps) {+ const instructionsId = useId();++ return (+ <fieldset aria-label={`Question ${index + 1}`} className="grid gap-3 rounded-md border p-3">+ <div className="flex flex-wrap items-center gap-2">+ <Input+ aria-label="Question name"+ className="min-w-0 flex-1"+ value={question.name ?? ""}+ placeholder="Optional question name"+ onChange={(event) => onChange({ ...question, name: event.target.value })}+ />+ <Select+ value={question.type}+ onValueChange={(type) => {+ const next = QUESTION_TYPES.find((value) => value === type);+ if (next) onChange(retypeDecisionQuestion(question, next));+ }}+ >+ <SelectTrigger className="w-36" aria-label="Answer type">+ <SelectValue>{TYPE_LABELS[question.type]}</SelectValue>+ </SelectTrigger>+ <SelectContent>+ {QUESTION_TYPES.map((type) => (+ <SelectItem key={type} value={type}>+ {TYPE_LABELS[type]}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <RemoveButton label={`Remove question ${index + 1}`} onClick={onRemove} />+ </div>+ <div className="grid gap-1.5">+ <Label htmlFor={instructionsId}>Instructions</Label>+ <Textarea+ id={instructionsId}+ rows={2}+ value={question.instructions ?? ""}+ placeholder="What should the model decide?"+ onChange={(event) => onChange({ ...question, instructions: event.target.value })}+ />+ </div>+ {question.type === "choice" && <Choices question={question} onChange={onChange} />}+ {question.type === "score" && <Levels question={question} onChange={onChange} />}+ </fieldset>+ );+}++interface OpenAIDecisionsFormProps {+ value: string;+ onChange: (value: string) => void;+ validation: PayloadValidation<OpenAIDecisionsRequest>;+ onOpenJson: () => void;+}++export default function OpenAIDecisionsForm({ value, onChange, validation, onOpenJson }: OpenAIDecisionsFormProps) {+ const inputId = useId();+ const safetyId = useId();+ const form = useMemo(() => readDecisionsForm(value), [value]);++ if (form === undefined) {+ return (+ <FormFrame validation={validation}>+ <p className="text-sm text-muted-foreground">+ This request has JSON the form can't show. Edit it in JSON to fix its shape.+ </p>+ <Button variant="outline" className="w-fit" onClick={onOpenJson}>+ Edit in JSON+ </Button>+ </FormFrame>+ );+ }++ const questions = form.questions ?? [];+ const write = (next: DecisionsFormPayload) => onChange(JSON.stringify(next, null, 2));+ const writeQuestions = (next: DecisionsFormQuestion[]) => write({ ...form, questions: next });++ return (+ <FormFrame validation={validation}>+ <div className="grid gap-1.5">+ {Array.isArray(form.input) ? (+ <>+ <p className="text-sm text-muted-foreground">+ Input contains messages. Edit messages and image parts in JSON; form edits keep them unchanged.+ </p>+ <Button variant="outline" className="w-fit" onClick={onOpenJson}>+ Edit input in JSON+ </Button>+ </>+ ) : (+ <>+ <Label htmlFor={inputId}>Input</Label>+ <Textarea+ id={inputId}+ rows={4}+ value={form.input ?? ""}+ placeholder="Paste the text the model should decide about"+ onChange={(event) => write({ ...form, input: event.target.value })}+ />+ </>+ )}+ </div>+ {questions.map((question, index) => (+ <QuestionCard+ key={index}+ index={index}+ question={question}+ onChange={(next) => writeQuestions(replaceAt(questions, index, next))}+ onRemove={() => writeQuestions(removeAt(questions, index))}+ />+ ))}+ <AddButton+ onClick={() =>+ writeQuestions([+ ...questions,+ {+ type: "predicate",+ name: freeName(+ questions.map((q) => q.name ?? ""),+ "question",+ ),+ instructions: "",+ },+ ])+ }+ >+ Add question+ </AddButton>+ <div className="grid gap-1.5">+ <Label htmlFor={safetyId}>Safety identifier</Label>+ <Input+ id={safetyId}+ value={form.safety_identifier ?? ""}+ placeholder="Optional"+ onChange={(event) => write({ ...form, safety_identifier: event.target.value || undefined })}+ />+ </div>+ </FormFrame>+ );+}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.integration.test.tsxsimilarity index 57%rename from ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.test.tsxrename to ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.integration.test.tsxindex a64af1dc343..7cd303bbcd2 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.integration.test.tsx@@ -1,7 +1,9 @@import { render, screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import { describe, expect, it } from "vitest";import ResponseView from "./ResponseView";import type { SystemOneResponse } from "./lib/schemas";+import type { OpenAIDecisionsResponse } from "./lib/openAIDecisions";const sampleResponse: SystemOneResponse = {model: "jev-1.13.0",@@ -24,7 +26,68 @@ const sampleResponse: SystemOneResponse = {usage: { input_tokens: 378, output_tokens: 63 },};-describe("ResponseView", () => {+describe("ResponseView integration", () => {+ it("shows OpenAI Decisions answer cards in Form view and the complete response in JSON view", async () => {+ const response: OpenAIDecisionsResponse = {+ model: "jev-latest",+ answers: [+ { name: null, type: "predicate", probability: 0 },+ {+ name: "route",+ type: "choice",+ choice: false,+ confidence: 0.8,+ probabilities: [+ { value: false, probability: 0.8 },+ { value: "other", probability: 0.2 },+ ],+ },+ {+ name: "severity",+ type: "score",+ score: 0,+ confidence: 0,+ probabilities: [+ { value: 0, label: "low", probability: 1 },+ { value: 1, label: "high", probability: 0 },+ ],+ },+ { name: "blocked", type: "refusal" },+ { name: "blocked", type: "refusal" },+ ],+ usage: { input_tokens: 3, output_tokens: 4, total_tokens: 7 },+ request_id: "keep-extra-fields",+ };+ const { rerender } = render(<ResponseView response={response} isLoading={false} view="form" />);+ expect(screen.getByText("Question 1")).toBeInTheDocument();+ expect(screen.getByText("0% yes")).toBeInTheDocument();+ expect(screen.getByRole("meter", { name: "false probability" })).toHaveAttribute("aria-valuetext", "80%, selected");+ expect(screen.getByRole("meter", { name: "0: low probability" })).toHaveAttribute(+ "aria-valuetext",+ "100%, selected",+ );+ expect(screen.getByText("0% confidence")).toBeInTheDocument();+ expect(screen.getAllByText("Model refused to answer")).toHaveLength(2);+ expect(screen.queryByRole("region", { name: "Decisions response JSON" })).not.toBeInTheDocument();+ await userEvent.click(screen.getByRole("button", { name: "Raw response" }));+ expect(screen.getByRole("region", { name: "Decisions response JSON" })).toHaveTextContent("keep-extra-fields");+ rerender(<ResponseView response={response} isLoading={false} view="json" />);+ expect(screen.queryByRole("meter")).not.toBeInTheDocument();+ expect(JSON.parse(screen.getByRole("region", { name: "Decisions response JSON" }).textContent ?? "")).toEqual(+ response,+ );+ rerender(<ResponseView response={response} isLoading={false} view="form" />);+ expect(screen.getByRole("meter", { name: "false probability" })).toHaveAttribute("aria-valuenow", "80");+ });++ it("shows System One raw response instead of cards in JSON view", () => {+ render(<ResponseView response={sampleResponse} isLoading={false} view="json" />);+ expect(screen.queryByRole("meter")).not.toBeInTheDocument();+ expect(JSON.parse(screen.getByRole("region", { name: "Decisions response JSON" }).textContent ?? "")).toEqual(+ sampleResponse,+ );+ });+it("renders calibrated probabilities for choice, noul, and score answers", () => {render(<ResponseView response={sampleResponse} isLoading={false} latencyMs={120} />);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.tsxindex ac83589a2db..0754946f5f4 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/ResponseView.tsx@@ -6,11 +6,13 @@ import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/componentimport { ChevronDown, LoaderCircle } from "lucide-react";import { useState } from "react";import type { SystemOneAnswer, SystemOneResponse } from "./lib/schemas";+import type { OpenAIDecisionsResponse } from "./lib/openAIDecisions";const SCORE_FORMAT = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 });interface ResponseViewProps {- response?: SystemOneResponse;+ response?: SystemOneResponse | OpenAIDecisionsResponse;+ view?: "form" | "json";fallbackModel?: string;latencyMs?: number;error?: string;@@ -113,7 +115,87 @@ function AnswerDetails({ answer }: { answer: SystemOneAnswer }) {);}-export default function ResponseView({ response, fallbackModel, latencyMs, error, isLoading }: ResponseViewProps) {+function OpenAIAnswerDetails({ answer }: { answer: OpenAIDecisionsResponse["answers"][number] }) {+ switch (answer.type) {+ case "refusal":+ return <p className="text-sm text-muted-foreground">Model refused to answer</p>;+ case "predicate":+ return <AnswerDetails answer={{ type: "noul", noul: answer.probability }} />;+ case "choice":+ return (+ <AnswerDetails+ answer={{+ type: "choice",+ choice: String(answer.choice),+ confidence: answer.confidence,+ probabilities: Object.fromEntries(+ answer.probabilities.map(({ value, probability }) => [String(value), probability]),+ ),+ }}+ />+ );+ case "score":+ return (+ <AnswerDetails+ answer={{+ type: "score",+ score: answer.score,+ confidence: answer.confidence,+ probabilities: Object.fromEntries(+ answer.probabilities.map(({ value, probability }) => [String(value), probability]),+ ),+ legend: Object.fromEntries(answer.probabilities.map(({ value, label }) => [String(value), label])),+ }}+ />+ );+ }+}++function RawResponse({ response }: { response: NonNullable<ResponseViewProps["response"]> }) {+ return (+ <section aria-label="Decisions response JSON">+ <pre className="whitespace-pre-wrap wrap-anywhere rounded-md bg-muted p-3 font-mono text-xs">+ {JSON.stringify(response, null, 2)}+ </pre>+ </section>+ );+}++function AnswerCards({ answers }: { answers: SystemOneResponse["answers"] | OpenAIDecisionsResponse["answers"] }) {+ const cards = Array.isArray(answers)+ ? answers.map((answer, index) => ({+ id: index,+ name: answer.name ?? `Question ${index + 1}`,+ type: answer.type,+ details: <OpenAIAnswerDetails answer={answer} />,+ }))+ : Object.entries(answers).map(([id, answer]) => ({+ id,+ name: id,+ type: answer.type,+ details: <AnswerDetails answer={answer} />,+ }));+ return cards.map(({ id, name, type, details }) => (+ <Card key={id} size="sm">+ <CardHeader>+ <CardTitle className="font-mono">{name}</CardTitle>+ <CardAction>+ <Badge variant="secondary">{type}</Badge>+ </CardAction>+ </CardHeader>+ <CardContent>{details}</CardContent>+ </Card>+ ));+}++export default function ResponseView({+ response,+ view = "form",+ fallbackModel,+ latencyMs,+ error,+ isLoading,+}: ResponseViewProps) {const [showRaw, setShowRaw] = useState(false);if (isLoading) {@@ -154,7 +236,7 @@ export default function ResponseView({ response, fallbackModel, latencyMs, error<CardHeader><div className="flex flex-wrap items-start justify-between gap-3"><div className="grid gap-1">- <CardTitle>Calibrated probabilities</CardTitle>+ <CardTitle>{view === "json" ? "Response JSON" : "Calibrated probabilities"}</CardTitle>{model && <CardDescription>{model}</CardDescription>}</div><div className="flex flex-wrap items-center gap-2 text-xs">@@ -168,34 +250,22 @@ export default function ResponseView({ response, fallbackModel, latencyMs, error</div></CardHeader><CardContent className="grid gap-3">- {Object.entries(response.answers).map(([id, answer]) => (- <Card key={id} size="sm">- <CardHeader>- <CardTitle className="font-mono">{id}</CardTitle>- <CardAction>- <Badge variant="secondary">{answer.type}</Badge>- </CardAction>- </CardHeader>- <CardContent>- <AnswerDetails answer={answer} />- </CardContent>- </Card>- ))}- <Collapsible open={showRaw} onOpenChange={setShowRaw}>- <CollapsibleTrigger- render={- <Button variant="ghost" size="sm">- <ChevronDown className="size-4" />- Raw response- </Button>- }- />- <CollapsibleContent>- <pre className="whitespace-pre-wrap wrap-anywhere rounded-md bg-muted p-3 font-mono text-xs">- {JSON.stringify(response, null, 2)}- </pre>- </CollapsibleContent>- </Collapsible>+ {view === "json" ? <RawResponse response={response} /> : <AnswerCards answers={response.answers} />}+ {view === "form" && (+ <Collapsible open={showRaw} onOpenChange={setShowRaw}>+ <CollapsibleTrigger+ render={+ <Button variant="ghost" size="sm">+ <ChevronDown className="size-4" />+ Raw response+ </Button>+ }+ />+ <CollapsibleContent>+ <RawResponse response={response} />+ </CollapsibleContent>+ </Collapsible>+ )}</CardContent></Card>);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneForm.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneForm.tsxindex d799afd13ea..5d53bc2d620 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneForm.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneForm.tsx@@ -5,10 +5,8 @@ import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";import { Textarea } from "@/components/ui/textarea";-import { cn } from "@/lib/cva.config";-import { Plus, Trash2 } from "lucide-react";-import { useId, useMemo, useState, type ReactNode } from "react";-import { IssueList, ValidationStatus } from "./JsonEditor";+import { useId, useMemo, useState } from "react";+import { AddButton, FormFrame, RemoveButton } from "./DecisionFormControls";import {blankQuestion,freeName,@@ -97,23 +95,6 @@ function KeyInput({ value, taken, onCommit, label, placeholder }: KeyInputProps));}-function RemoveButton({ label, onClick }: { label: string; onClick: () => void }) {- return (- <Button variant="ghost" size="icon" aria-label={label} title={label} onClick={onClick}>- <Trash2 />- </Button>- );-}--function AddButton({ children, onClick }: { children: ReactNode; onClick: () => void }) {- return (- <Button variant="outline" size="sm" className="w-fit" onClick={onClick}>- <Plus />- {children}- </Button>- );-}-function ChoiceOptions({ question, onChange }: QuestionEditorProps<ChoiceQuestion>) {const labels = Object.keys(question.criteria);const writeCriteria = (criteria: Record<string, string>) => onChange({ ...question, criteria });@@ -261,26 +242,6 @@ function QuestionCard({ name, question, taken, onChange, onRename, onRemove }: Q);}-function FormFrame({ validation, children }: { validation: SystemOnePayloadValidation; children: ReactNode }) {- const issuesId = useId();-- return (- <div- className={cn(- "flex min-h-96 flex-1 flex-col overflow-hidden rounded-md border bg-background",- !validation.isValid && "border-destructive/60",- )}- >- <div className="flex items-center gap-2 border-b px-3 py-2">- <span className="text-sm font-medium">Request form</span>- <ValidationStatus validation={validation} />- </div>- <div className="grid min-h-80 flex-1 content-start gap-4 overflow-auto p-3">{children}</div>- <IssueList id={issuesId} validation={validation} />- </div>- );-}-export default function SystemOneForm({ value, onChange, validation, onOpenJson }: SystemOneFormProps) {const stateId = useId();const form = useMemo(() => readForm(value), [value]);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneUI.integration.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneUI.integration.test.tsxindex 55f007372d7..ab0a67dbbab 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneUI.integration.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneUI.integration.test.tsx@@ -13,6 +13,7 @@ import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import SystemOneUI from "./SystemOneUI";import type { SystemOneResponse } from "./lib/schemas";+import type { OpenAIDecisionsResponse } from "./lib/openAIDecisions";interface ModelGroupInfo {model_group: string;@@ -64,7 +65,13 @@ const openJsonEditor = async () => {return screen.getByRole("textbox", { name: "System One JSON payload" });};-const createResponse = (body: SystemOneResponse, status = 200, errorText = "") =>+const selectEndpoint = async (endpoint: "/v1/decisions" | "/v1/systemone") => {+ screen.getByRole("combobox", { name: "Decision endpoint" }).focus();+ await userEvent.keyboard("{ArrowDown}");+ await userEvent.click(await screen.findByRole("option", { name: endpoint, exact: true }));+};++const createResponse = (body: SystemOneResponse | OpenAIDecisionsResponse, status = 200, errorText = "") =>({ok: status >= 200 && status < 300,status,@@ -108,12 +115,17 @@ describe("SystemOneUI integration", () => {expect(resetButton).toBeDisabled();});- it("explains the native decision endpoint after opting in without announcing it as an alert", async () => {- const user = userEvent.setup();+ it("offers both literal proxy endpoints without TypeSafe or product prefixes", async () => {render(<SystemOneUI accessToken="session-key" />);++ expect(screen.getByRole("combobox", { name: "Decision endpoint" })).toHaveTextContent("/v1/systemone");screen.getByRole("combobox", { name: "Decision endpoint" }).focus();- await user.keyboard("{ArrowDown}");- await user.click(await screen.findByRole("option", { name: "Decisions · /v1/systemone" }));+ await userEvent.keyboard("{ArrowDown}");+ expect(await screen.findByRole("option", { name: "/v1/decisions", exact: true })).toBeInTheDocument();+ expect(screen.getByRole("option", { name: "/v1/systemone", exact: true })).toBeInTheDocument();+ expect(screen.getAllByRole("option")).toHaveLength(2);+ expect(screen.queryByText(/TypeSafe/)).not.toBeInTheDocument();+ await userEvent.keyboard("{Escape}");expect(screen.getByRole("note", { name: "Decision endpoint notice" })).toHaveTextContent("omit model to use the proxy's configured default.",@@ -134,7 +146,7 @@ describe("SystemOneUI integration", () => {mockModelLookup.mockResolvedValue(modelGroupInfoResponse(DECISION_AND_CHAT_MODELS));render(<SystemOneUI accessToken="session-key" />);- expect(await screen.findByRole("combobox", { name: "Decision model" })).toHaveValue("jev-latest");+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Decision model" })).toHaveValue("jev-latest"));expect(lookupAuthHeaders(mockModelLookup.mock.calls)).toEqual([expect.arrayContaining(["Bearer session-key"])]);await user.click(screen.getByRole("button", { name: "Send" }));@@ -147,6 +159,297 @@ describe("SystemOneUI integration", () => {});});+ it("sends each endpoint's real shape and switches existing responses between cards and JSON without resending", async () => {+ const user = userEvent.setup();+ mockModelLookup.mockResolvedValue(modelGroupInfoResponse(DECISION_AND_CHAT_MODELS));+ render(<SystemOneUI accessToken="session-key" />);+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Decision model" })).toHaveValue("jev-latest"));+ const systemOneEditor = await openJsonEditor();+ const systemOneDraft = JSON.stringify({+ model: "jev-latest",+ state: "An outage",+ questions: { urgent: { type: "noul", instructions: "Is it urgent?" } },+ });+ fireEvent.change(systemOneEditor, { target: { value: systemOneDraft } });++ await selectEndpoint("/v1/decisions");+ const editor = screen.getByRole("textbox", { name: "Decisions JSON payload" });+ const nativeExample = (editor as HTMLTextAreaElement).value;+ expect(JSON.parse(nativeExample)).toMatchObject({+ input: expect.any(String),+ questions: expect.arrayContaining([expect.objectContaining({ type: "predicate" })]),+ });+ expect(screen.getByRole("tab", { name: "Form" })).toBeInTheDocument();+ const payload = {+ model: "jev-latest",+ input: "An outage",+ questions: [{ name: "urgent", type: "predicate", instructions: "Is it urgent?" }],+ safety_identifier: "qa-session",+ };+ fireEvent.change(editor, { target: { value: JSON.stringify(payload) } });+ const response: OpenAIDecisionsResponse = {+ model: "jev-latest",+ answers: [{ name: "urgent", type: "predicate", probability: 0.95 }],+ usage: { input_tokens: 10, output_tokens: 1, total_tokens: 11 },+ };+ mockFetch.mockResolvedValueOnce(createResponse(response));+ await user.click(screen.getByRole("button", { name: "Send" }));++ const result = await screen.findByRole("region", { name: "Decisions response JSON" });+ expect(result).toHaveTextContent('"probability": 0.95');+ expect(result).toHaveTextContent('"answers": [');+ expect(mockFetch.mock.calls[0]?.[0]).toMatch(/\/v1\/decisions$/);+ expect(JSON.parse(mockFetch.mock.calls[0]?.[1]?.body as string)).toEqual(payload);++ expect(screen.queryByRole("meter")).not.toBeInTheDocument();+ await user.click(screen.getByRole("tab", { name: "Form" }));+ expect(screen.getByRole("meter", { name: "Yes probability" })).toHaveAttribute("aria-valuenow", "95");+ expect(screen.queryByRole("region", { name: "Decisions response JSON" })).not.toBeInTheDocument();+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ expect(screen.getByRole("region", { name: "Decisions response JSON" })).toHaveTextContent('"probability": 0.95');+ expect(mockFetch).toHaveBeenCalledTimes(1);++ await selectEndpoint("/v1/systemone");+ expect(screen.getByRole("textbox", { name: "System One JSON payload" })).toHaveValue(systemOneDraft);+ expect(screen.queryByRole("region", { name: "Decisions response JSON" })).not.toBeInTheDocument();+ await user.click(screen.getByRole("button", { name: "Send" }));+ expect(await screen.findByRole("region", { name: "Decisions response JSON" })).toHaveTextContent(+ '"choice": "technical"',+ );+ expect(screen.queryByRole("meter")).not.toBeInTheDocument();+ await user.click(screen.getByRole("tab", { name: "Form" }));+ expect(screen.getByText("Selected choice")).toBeInTheDocument();+ expect(screen.getByRole("meter", { name: "technical probability" })).toHaveAttribute("aria-valuenow", "90");+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ expect(mockFetch).toHaveBeenCalledTimes(2);+ expect(mockFetch.mock.calls[1]?.[0]).toMatch(/\/v1\/systemone$/);+ expect(JSON.parse(mockFetch.mock.calls[1]?.[1]?.body as string)).toEqual(JSON.parse(systemOneDraft));++ await selectEndpoint("/v1/decisions");+ expect(screen.getByRole("textbox", { name: "Decisions JSON payload" })).toHaveValue(JSON.stringify(payload));+ await user.click(screen.getByRole("button", { name: "Reset example" }));+ expect(screen.getByRole("textbox", { name: "Decisions JSON payload" })).toHaveValue(nativeExample);+ await selectEndpoint("/v1/systemone");+ expect(screen.getByRole("textbox", { name: "System One JSON payload" })).toHaveValue(systemOneDraft);+ });++ it("validates /v1/decisions independently and preserves an invalid draft across switches", async () => {+ render(<SystemOneUI accessToken="session-key" />);+ await selectEndpoint("/v1/decisions");+ await userEvent.click(screen.getByRole("tab", { name: "JSON" }));+ const editor = screen.getByRole("textbox", { name: "Decisions JSON payload" });+ fireEvent.change(editor, { target: { value: "{" } });+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();+ await selectEndpoint("/v1/systemone");+ expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();+ await selectEndpoint("/v1/decisions");+ expect(screen.getByRole("textbox", { name: "Decisions JSON payload" })).toHaveValue("{");+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();+ expect(mockFetch).not.toHaveBeenCalled();+ });++ it("offers a Decisions form that sends input and typed questions and stays in sync with JSON", async () => {+ const user = userEvent.setup();+ mockFetch.mockResolvedValueOnce(+ createResponse({+ model: "jev-latest",+ answers: [],+ usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },+ }),+ );+ render(<SystemOneUI accessToken="session-key" />);+ await selectEndpoint("/v1/decisions");+ expect(screen.getByRole("tab", { name: "Form" })).toHaveAttribute("aria-selected", "true");+ expect(screen.queryByRole("button", { name: "Format JSON" })).not.toBeInTheDocument();+ fireEvent.change(screen.getByRole("textbox", { name: "Input" }), { target: { value: "Login is broken" } });+ const firstQuestion = within(screen.getByRole("group", { name: "Question 1" }));+ fireEvent.change(firstQuestion.getByRole("textbox", { name: "Question name" }), { target: { value: "team" } });+ fireEvent.change(firstQuestion.getByRole("textbox", { name: "Instructions" }), {+ target: { value: "Which team owns this?" },+ });+ fireEvent.change(firstQuestion.getByRole("textbox", { name: "Choice 1 value" }), {+ target: { value: "infra" },+ });+ fireEvent.change(screen.getByRole("textbox", { name: "Safety identifier" }), {+ target: { value: "qa-session" },+ });+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ const editor = screen.getByRole("textbox", { name: "Decisions JSON payload" });+ const payload = JSON.parse((editor as HTMLTextAreaElement).value);+ expect(payload).toMatchObject({ input: "Login is broken", safety_identifier: "qa-session" });+ const expectedQuestion = {+ name: "team",+ type: "choice",+ instructions: "Which team owns this?",+ choices: expect.arrayContaining([expect.objectContaining({ value: "infra" })]),+ };+ expect(payload.questions[0]).toMatchObject(expectedQuestion);+ expect(payload).not.toHaveProperty("state");+ fireEvent.change(editor, { target: { value: JSON.stringify({ ...payload, input: "Fixed in JSON" }) } });+ await user.click(screen.getByRole("tab", { name: "Form" }));+ expect(screen.getByRole("textbox", { name: "Input" })).toHaveValue("Fixed in JSON");+ await user.click(screen.getByRole("button", { name: "Send" }));+ await waitFor(() => expect(mockFetch).toHaveBeenCalledTimes(1));+ expect(mockFetch.mock.calls[0]?.[0]).toMatch(/\/v1\/decisions$/);+ expect(JSON.parse(mockFetch.mock.calls[0]?.[1]?.body as string)).toEqual({ ...payload, input: "Fixed in JSON" });+ expect(await screen.findByRole("button", { name: "Raw response" })).toBeInTheDocument();+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ expect(screen.getByRole("region", { name: "Decisions response JSON" })).toBeInTheDocument();+ });++ it("adds and removes Decisions questions, boolean choices and score levels without stale fields", async () => {+ const user = userEvent.setup();+ render(<SystemOneUI accessToken="session-key" />);+ await selectEndpoint("/v1/decisions");+ const question = (index: number) => within(screen.getByRole("group", { name: `Question ${index}` }));+ const pick = async (control: HTMLElement, label: string) => {+ control.focus();+ await user.keyboard("{ArrowDown}");+ await user.click(await screen.findByRole("option", { name: label, exact: true }));+ };+ await user.click(screen.getByRole("button", { name: "Add question" }));+ fireEvent.change(question(4).getByRole("textbox", { name: "Instructions" }), {+ target: { value: "Should we escalate?" },+ });+ await pick(question(4).getByRole("combobox", { name: "Answer type" }), "Choice");+ await user.click(question(4).getByRole("button", { name: "Remove choice 1" }));+ expect(question(4).getByRole("textbox", { name: "Choice 1 value" })).toHaveValue("option_2");+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();+ await user.click(question(4).getByRole("button", { name: "Add choice" }));+ await pick(question(4).getByRole("combobox", { name: "Choice 1 value type" }), "false (boolean)");+ fireEvent.change(question(4).getByRole("textbox", { name: "Choice 1 description" }), {+ target: { value: "Not urgent" },+ });+ expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ const choicePayload = JSON.parse(+ (screen.getByRole("textbox", { name: "Decisions JSON payload" }) as HTMLTextAreaElement).value,+ );+ const expectedChoice = {+ type: "choice",+ name: "question_1",+ instructions: "Should we escalate?",+ choices: [{ value: false, description: "Not urgent" }, { value: "option_1" }],+ };+ expect(choicePayload.questions[3]).toEqual(expectedChoice);+ await user.click(screen.getByRole("tab", { name: "Form" }));+ await pick(question(4).getByRole("combobox", { name: "Answer type" }), "Score");+ fireEvent.change(question(4).getByRole("textbox", { name: "Level 1 label" }), { target: { value: "low" } });+ fireEvent.change(question(4).getByRole("textbox", { name: "Level 1 description" }), {+ target: { value: "No impact" },+ });+ await user.click(question(4).getByRole("button", { name: "Add level" }));+ await user.click(question(4).getByRole("button", { name: "Remove level 2" }));+ expect(question(4).getByRole("textbox", { name: "Level 2 label" })).toHaveValue("2");+ await user.click(question(2).getByRole("button", { name: "Remove question 2" }));+ expect(question(3).getByRole("textbox", { name: "Instructions" })).toHaveValue("Should we escalate?");+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ const scorePayload = JSON.parse(+ (screen.getByRole("textbox", { name: "Decisions JSON payload" }) as HTMLTextAreaElement).value,+ );+ expect(scorePayload.questions).toHaveLength(3);+ const expectedScore = {+ type: "score",+ name: "question_1",+ instructions: "Should we escalate?",+ levels: [{ label: "low", description: "No impact" }, { label: "2" }],+ };+ expect(scorePayload.questions[2]).toEqual(expectedScore);+ await user.click(screen.getByRole("tab", { name: "Form" }));+ await pick(question(3).getByRole("combobox", { name: "Answer type" }), "Predicate");+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ const predicatePayload = JSON.parse(+ (screen.getByRole("textbox", { name: "Decisions JSON payload" }) as HTMLTextAreaElement).value,+ );+ expect(predicatePayload.questions[2]).toEqual({+ type: "predicate",+ name: "question_1",+ instructions: "Should we escalate?",+ });+ });++ it("preserves message input and extra fields in the Decisions form, including across routes and reset", async () => {+ const user = userEvent.setup();+ render(<SystemOneUI accessToken="session-key" />);+ await selectEndpoint("/v1/decisions");+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ const payload = {+ model: "jev-latest",+ metadata: { source: "playground" },+ input: [+ {+ role: "user",+ content: [+ { type: "input_text", text: "Is this urgent?" },+ { type: "input_image", image_url: "https://example.com/image.png" },+ ],+ },+ ],+ questions: [{ type: "predicate", name: null, instructions: "Old instructions" }],+ };+ fireEvent.change(screen.getByRole("textbox", { name: "Decisions JSON payload" }), {+ target: { value: JSON.stringify(payload) },+ });+ await user.click(screen.getByRole("tab", { name: "Form" }));+ expect(screen.getByRole("button", { name: "Edit input in JSON" })).toBeInTheDocument();+ fireEvent.change(screen.getByRole("textbox", { name: "Instructions" }), { target: { value: "Is it urgent?" } });+ await selectEndpoint("/v1/systemone");+ const nativeInput = (screen.getByRole("textbox", { name: "Input" }) as HTMLTextAreaElement).value;+ await selectEndpoint("/v1/decisions");+ expect(screen.getByRole("textbox", { name: "Instructions" })).toHaveValue("Is it urgent?");+ await user.click(screen.getByRole("button", { name: "Edit input in JSON" }));+ const next = JSON.parse(+ (screen.getByRole("textbox", { name: "Decisions JSON payload" }) as HTMLTextAreaElement).value,+ );+ expect(next).toEqual({ ...payload, questions: [{ ...payload.questions[0], instructions: "Is it urgent?" }] });+ await user.click(screen.getByRole("tab", { name: "Form" }));+ await user.click(screen.getByRole("button", { name: "Reset example" }));+ expect(screen.getByRole("textbox", { name: "Input" })).toBeInTheDocument();+ expect(screen.getAllByRole("group", { name: /Question \d/ })).toHaveLength(3);+ await selectEndpoint("/v1/systemone");+ expect(screen.getByRole("textbox", { name: "Input" })).toHaveValue(nativeInput);+ });++ it("keeps malformed Decisions JSON intact when switching to its form", async () => {+ const user = userEvent.setup();+ render(<SystemOneUI accessToken="session-key" />);+ await selectEndpoint("/v1/decisions");+ await user.click(screen.getByRole("tab", { name: "JSON" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Decisions JSON payload" }), { target: { value: "{" } });+ await user.click(screen.getByRole("tab", { name: "Form" }));+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();+ await user.click(screen.getByRole("button", { name: "Edit in JSON" }));+ expect(screen.getByRole("textbox", { name: "Decisions JSON payload" })).toHaveValue("{");+ });++ it.each(["success", "error"])("cancels the previous endpoint request and ignores a late %s", async (outcome) => {+ const pending = Promise.withResolvers<Response>();+ mockFetch.mockReturnValueOnce(pending.promise);+ const queryClient = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+ rtlRender(+ <QueryClientProvider client={queryClient}>+ <SystemOneUI accessToken="session-key" />+ </QueryClientProvider>,+ );+ await userEvent.click(screen.getByRole("button", { name: "Send" }));+ await screen.findByRole("button", { name: "Cancel request" });+ await selectEndpoint("/v1/decisions");+ expect(mockFetch.mock.calls[0]?.[1]?.signal?.aborted).toBe(true);+ await act(async () => {+ if (outcome === "success") {+ pending.resolve(createResponse({ model: "stale-model", answers: {} }));+ } else {+ pending.reject(new Error("Stale request failed"));+ }+ await pending.promise.catch(() => undefined);+ });+ await waitFor(() => expect(queryClient.isMutating()).toBe(0));+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(screen.queryByText("stale-model")).not.toBeInTheDocument();+ expect(screen.getByRole("tab", { name: "Form" })).toHaveAttribute("aria-selected", "true");+ expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();+ });+it("offers only decision models and writes the picked one into the request", async () => {const user = userEvent.setup();mockModelLookup.mockResolvedValue(modelGroupInfoResponse(DECISION_AND_CHAT_MODELS));@@ -165,16 +468,31 @@ describe("SystemOneUI integration", () => {questions: { has_repro_steps: { type: "noul" } },});await user.click(screen.getByRole("button", { name: "Send" }));+ await user.click(screen.getByRole("tab", { name: "Form" }));expect(await screen.findByText("Selected choice")).toBeInTheDocument();expect(JSON.parse(mockFetch.mock.calls[0]?.[1]?.body as string).model).toBe("pplx-decider");});- it("links to Add Model when the key cannot call any decision model", async () => {+ it("routes a configured TypeSafe model through the same proxy endpoint", async () => {const user = userEvent.setup();+ mockModelLookup.mockResolvedValue(+ modelGroupInfoResponse([{ model_group: "typesafe/jev-latest", mode: "evaluation" }]),+ );+ render(<SystemOneUI accessToken="session-key" />);+ await waitFor(() =>+ expect(screen.getByRole("combobox", { name: "Decision model" })).toHaveValue("typesafe/jev-latest"),+ );++ await user.click(screen.getByRole("button", { name: "Send" }));++ expect(await screen.findByText("Selected choice")).toBeInTheDocument();+ expect(mockFetch.mock.calls[0]?.[0]).toMatch(/\/v1\/systemone$/);+ expect(mockFetch.mock.calls[0]?.[0]).not.toMatch(/\/typesafe\//);+ expect(JSON.parse(mockFetch.mock.calls[0]?.[1]?.body as string).model).toBe("typesafe/jev-latest");+ });++ it("links to Add Model when the key cannot call any decision model", async () => {render(<SystemOneUI accessToken="session-key" />);- screen.getByRole("combobox", { name: "Decision endpoint" }).focus();- await user.keyboard("{ArrowDown}");- await user.click(await screen.findByRole("option", { name: "Decisions · /v1/systemone" }));expect(await screen.findByRole("link", { name: "Add a decision model" })).toHaveAttribute("href",@@ -193,7 +511,7 @@ describe("SystemOneUI integration", () => {await user.type(screen.getByLabelText("Virtual Key", { exact: true }), "sk-typed-key");- expect(await screen.findByRole("combobox", { name: "Decision model" })).toHaveValue("jev-latest");+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Decision model" })).toHaveValue("jev-latest"));expect(lookupAuthHeaders(mockModelLookup.mock.calls)).toEqual([expect.arrayContaining(["Bearer sk-typed-key"])]);});@@ -209,10 +527,10 @@ describe("SystemOneUI integration", () => {await new Promise((resolve) => setTimeout(resolve, 0));});expect(document.cookie).toContain("token=ui-session");- expect(screen.getByRole("combobox", { name: "Decision endpoint" })).toHaveTextContent("/typesafe/v1/systemone");+ expect(screen.getByRole("combobox", { name: "Decision endpoint" })).toHaveTextContent("/v1/systemone");});- it("keeps an edited TypeSafe request in place when decision models load afterwards", async () => {+ it("keeps an edited request in place when decision models load afterwards", async () => {const models = Promise.withResolvers<Response>();mockModelLookup.mockReturnValue(models.promise);render(<SystemOneUI accessToken="session-key" />);@@ -226,9 +544,37 @@ describe("SystemOneUI integration", () => {});expect(editor).toHaveValue(draft);- expect(screen.queryByRole("combobox", { name: "Decision model" })).not.toBeInTheDocument();+ expect(screen.getByRole("combobox", { name: "Decision model" })).toHaveValue("");});+ it.each(["/v1/decisions", "/v1/systemone"] as const)(+ "omits model while discovery is pending on %s",+ async (endpoint) => {+ const models = Promise.withResolvers<Response>();+ mockModelLookup.mockReturnValue(models.promise);+ mockFetch.mockResolvedValueOnce(+ createResponse({+ model: "jev-latest",+ answers: endpoint === "/v1/decisions" ? [] : {},+ usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },+ }),+ );+ render(<SystemOneUI accessToken="session-key" />);+ if (endpoint === "/v1/decisions") {+ await selectEndpoint(endpoint);+ }+ await userEvent.click(screen.getByRole("button", { name: "Send" }));+ expect(await screen.findByText("jev-latest")).toBeInTheDocument();+ expect(mockFetch.mock.calls[0]?.[0]).toMatch(new RegExp(`${endpoint}$`));+ expect(JSON.parse(mockFetch.mock.calls[0]?.[1]?.body as string)).not.toHaveProperty("model");+ await act(async () => {+ models.resolve(modelGroupInfoResponse(DECISION_AND_CHAT_MODELS));+ await models.promise;+ });+ expect(screen.getByRole("combobox", { name: "Decision model" })).toHaveValue("");+ },+ );+it("shows invalid JSON and disables Send", async () => {render(<SystemOneUI accessToken="session-key" />);@@ -240,7 +586,7 @@ describe("SystemOneUI integration", () => {expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();});- it("preserves the untouched TypeSafe default and renders calibrated answers", async () => {+ it("sends to /v1/systemone even without discovered models and renders calibrated answers", async () => {const user = userEvent.setup();sessionStorage.setItem("customProxyBaseUrl", "https://stale.example.com/");render(<SystemOneUI accessToken="session-key" />);@@ -251,18 +597,19 @@ describe("SystemOneUI integration", () => {expect(await screen.findAllByText("technical")).toHaveLength(2);expect(mockFetch).toHaveBeenCalledTimes(1);const [url, options] = mockFetch.mock.calls[0] ?? [];- expect(url).toBe("https://tenant.example.com/typesafe/v1/systemone");+ expect(url).toBe("https://tenant.example.com/v1/systemone");expect(options?.method).toBe("POST");expect(options?.headers).toMatchObject({ "Content-Type": "application/json" });expect(Object.values(options?.headers as Record<string, string>)).toContain("Bearer session-key");expect(JSON.parse(options?.body as string)).toMatchObject({- model: "jev-latest",questions: { has_repro_steps: { type: "noul" } },});+ expect(JSON.parse(options?.body as string)).not.toHaveProperty("model");});it("uses the requested model when the response omits it", async () => {const user = userEvent.setup();+ mockModelLookup.mockResolvedValue(modelGroupInfoResponse(DECISION_AND_CHAT_MODELS));mockFetch.mockResolvedValueOnce(createResponse({answers: responseBody.answers,@@ -270,13 +617,15 @@ describe("SystemOneUI integration", () => {);render(<SystemOneUI accessToken="session-key" />);+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Decision model" })).toHaveValue("jev-latest"));+await user.click(screen.getByRole("button", { name: "Send" }));expect(await screen.findByText("jev-latest")).toBeInTheDocument();expect(screen.getByText("Selected choice")).toBeInTheDocument();});- it("keeps legacy validation when question values have invalid types", async () => {+ it("validates native question values before sending", async () => {render(<SystemOneUI accessToken="session-key" />);fireEvent.change(await openJsonEditor(), {@@ -286,25 +635,22 @@ describe("SystemOneUI integration", () => {questions: {category: {type: "choice",- instructions: { text: "Route the message" },- criteria: { support: { text: "Help" } },+ instructions: 1,+ criteria: { support: true },},},}),},});- expect(screen.getByText("Instructions must be a string.")).toBeInTheDocument();- expect(screen.getByText("Choice descriptions must be strings.")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Send" })).toBeDisabled();+ await userEvent.click(screen.getByRole("tab", { name: "Form" }));expect(screen.getByText("Enter a valid request to preview its state and questions.")).toBeInTheDocument();});- it("preserves each endpoint draft and sends legacy requests to TypeSafe", async () => {+ it("sends structured native questions without changing their payload", async () => {const user = userEvent.setup();render(<SystemOneUI accessToken="session-key" />);- screen.getByRole("combobox", { name: "Decision endpoint" }).focus();- await user.keyboard("{ArrowDown}");- await user.click(await screen.findByRole("option", { name: "Decisions · /v1/systemone" }));const editor = await openJsonEditor();const draft = JSON.stringify({model: "my-decider",@@ -315,33 +661,18 @@ describe("SystemOneUI integration", () => {});fireEvent.change(editor, { target: { value: draft } });expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();+ await user.click(screen.getByRole("tab", { name: "Form" }));expect(screen.getByText(/"text": "Help"/)).toBeInTheDocument();- screen.getByRole("combobox", { name: "Decision endpoint" }).focus();- await user.keyboard("{ArrowDown}");- await user.click(await screen.findByRole("option", { name: "TypeSafe · /typesafe/v1/systemone" }));- await user.click(screen.getByRole("button", { name: "Send" }));- expect(await screen.findByText("Selected choice")).toBeInTheDocument();- expect(mockFetch.mock.calls[0]?.[0]).toMatch(/\/typesafe\/v1\/systemone$/);- expect(JSON.parse(mockFetch.mock.calls[0]?.[1]?.body as string).model).toBe("jev-latest");-- screen.getByRole("combobox", { name: "Decision endpoint" }).focus();- await user.keyboard("{ArrowDown}");- await user.click(await screen.findByRole("option", { name: "Decisions · /v1/systemone" }));- expect(editor).toHaveValue(draft);- expect(screen.queryByText("Selected choice")).not.toBeInTheDocument();await user.click(screen.getByRole("button", { name: "Send" }));expect(await screen.findByText("Selected choice")).toBeInTheDocument();- expect(mockFetch.mock.calls[1]?.[0]).toMatch(/\/v1\/systemone$/);- expect(JSON.parse(mockFetch.mock.calls[1]?.[1]?.body as string)).toEqual(JSON.parse(draft));+ expect(mockFetch.mock.calls[0]?.[0]).toMatch(/\/v1\/systemone$/);+ expect(JSON.parse(mockFetch.mock.calls[0]?.[1]?.body as string)).toEqual(JSON.parse(draft));});it("sends a native request without model so the proxy can select its default", async () => {const user = userEvent.setup();render(<SystemOneUI accessToken="session-key" />);- screen.getByRole("combobox", { name: "Decision endpoint" }).focus();- await user.keyboard("{ArrowDown}");- await user.click(await screen.findByRole("option", { name: "Decisions · /v1/systemone" }));const payload = { state: "An outage", questions: { urgent: { type: "noul", instructions: "Is this urgent?" } } };fireEvent.change(await openJsonEditor(), {target: { value: JSON.stringify(payload) },@@ -355,7 +686,7 @@ describe("SystemOneUI integration", () => {expect(body).not.toHaveProperty("model");});- it.each(["success", "error"])("ignores a late %s after switching endpoints", async (outcome) => {+ it.each(["success", "error"])("ignores a late %s after editing the request", async (outcome) => {const user = userEvent.setup();const pending = Promise.withResolvers<Response>();mockFetch.mockReturnValueOnce(pending.promise);@@ -367,9 +698,7 @@ describe("SystemOneUI integration", () => {);await user.click(screen.getByRole("button", { name: "Send" }));await screen.findByRole("button", { name: "Cancel request" });- screen.getByRole("combobox", { name: "Decision endpoint" }).focus();- await user.keyboard("{ArrowDown}");- await user.click(await screen.findByRole("option", { name: "Decisions · /v1/systemone" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Input" }), { target: { value: "A new request" } });expect(mockFetch.mock.calls[0]?.[1]?.signal?.aborted).toBe(true);expect(screen.getByRole("button", { name: "Send" })).toBeEnabled();@@ -437,7 +766,7 @@ describe("SystemOneUI integration", () => {await user.click(screen.getByRole("button", { name: "Send" }));- expect(await screen.findByRole("alert")).toHaveTextContent("System One response has an invalid shape.");+ expect(await screen.findByRole("alert")).toHaveTextContent("/v1/systemone response has an invalid shape.");expect(screen.queryByText("jev-1.13.0")).not.toBeInTheDocument();});@@ -554,9 +883,8 @@ describe("SystemOneUI integration", () => {expect(await screen.findByText("Selected choice")).toBeInTheDocument();expect(screen.queryByRole("textbox", { name: "System One JSON payload" })).not.toBeInTheDocument();- expect(mockFetch.mock.calls[0]?.[0]).toMatch(/\/typesafe\/v1\/systemone$/);+ expect(mockFetch.mock.calls[0]?.[0]).toMatch(/\/v1\/systemone$/);expect(sentBody()).toEqual({- model: "jev-latest",state: "The login page is blank after the upgrade",questions: {team: {@@ -575,7 +903,7 @@ describe("SystemOneUI integration", () => {const user = userEvent.setup();mockModelLookup.mockResolvedValue(modelGroupInfoResponse(DECISION_AND_CHAT_MODELS));render(<SystemOneUI accessToken="session-key" />);- expect(await screen.findByRole("combobox", { name: "Decision model" })).toHaveValue("jev-latest");+ await waitFor(() => expect(screen.getByRole("combobox", { name: "Decision model" })).toHaveValue("jev-latest"));const level = question("severity").getByRole("textbox", { name: "Level 0" });fill(level, "Typo");diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneUI.tsx b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneUI.tsxindex 0ac39cb5ede..02d42851b8e 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneUI.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/SystemOneUI.tsx@@ -11,15 +11,15 @@ import { uiHref } from "@/utils/uiHref";import { useMutation } from "@tanstack/react-query";import { Code, Info, LoaderCircle, RotateCcw, Send } from "lucide-react";import { useEffect, useMemo, useRef, useState } from "react";-import { makeSystemOneRequest } from "../../llm_calls/system_one";-import { PLACEHOLDER_DECISION_MODEL, SYSTEM_ONE_EXAMPLE, decisionsExample } from "./lib/example";+import { makePlaygroundDecisionRequest, type PlaygroundDecisionRequest } from "../../llm_calls/system_one";+import { decisionsExample, openAIDecisionsExample } from "./lib/example";import { payloadModel, withPayloadModel } from "./lib/payloadModel";-import type { DecisionEndpoint, PlaygroundRequest } from "./lib/schemas";import JsonEditor from "./JsonEditor";import QuestionBreakdown from "./QuestionBreakdown";import ResponseView from "./ResponseView";import SystemOneForm from "./SystemOneForm";-import { validateSystemOnePayload } from "./lib/validatePayload";+import OpenAIDecisionsForm from "./OpenAIDecisionsForm";+import { validateSystemOnePayload, validateOpenAIDecisionsPayload } from "./lib/validatePayload";import { useDecisionModels, type ApiKeySource } from "./useDecisionModels";interface SystemOneUIProps {@@ -30,13 +30,11 @@ interface SystemOneUIProps {type EditorView = "form" | "json";interface SystemOneSendVariables {- payload: PlaygroundRequest;- endpoint: DecisionEndpoint;+ request: PlaygroundDecisionRequest;apiKey: string;signal: AbortSignal;}-const EXAMPLE_PAYLOAD = JSON.stringify(SYSTEM_ONE_EXAMPLE, null, 2);const DECISION_MODELS_DISCUSSION_URL = "https://github.com/BerriAI/litellm/discussions/44231";function getCustomProxyBaseUrl(): string | undefined {@@ -52,23 +50,26 @@ export default function SystemOneUI({ accessToken, disabledPersonalKeyCreation =effectiveApiKey,getCustomProxyBaseUrl(),);- const [chosenEndpoint, setChosenEndpoint] = useState<DecisionEndpoint | null>(null);- const endpoint: DecisionEndpoint =- chosenEndpoint ?? (decisionModels.length > 0 ? "/v1/systemone" : "/typesafe/v1/systemone");- const [drafts, setDrafts] = useState<Partial<Record<DecisionEndpoint, string>>>({});+ const [endpoint, setEndpoint] = useState<PlaygroundDecisionRequest["endpoint"]>("/v1/systemone");+ const [drafts, setDrafts] = useState<Partial<Record<PlaygroundDecisionRequest["endpoint"], string>>>({});const [view, setView] = useState<EditorView>("form");- const examplePayload =- endpoint === "/v1/systemone"- ? JSON.stringify(decisionsExample(decisionModels[0] ?? PLACEHOLDER_DECISION_MODEL), null, 2)- : EXAMPLE_PAYLOAD;+ const example = endpoint === "/v1/decisions" ? openAIDecisionsExample : decisionsExample;+ const examplePayload = JSON.stringify(example(decisionModels[0]), null, 2);const rawPayload = drafts[endpoint] ?? examplePayload;const activeController = useRef<AbortController | null>(null);- const validation = useMemo(() => validateSystemOnePayload(rawPayload, endpoint), [rawPayload, endpoint]);+ const validated = useMemo(+ () =>+ endpoint === "/v1/decisions"+ ? ({ endpoint, validation: validateOpenAIDecisionsPayload(rawPayload) } as const)+ : ({ endpoint, validation: validateSystemOnePayload(rawPayload, endpoint) } as const),+ [rawPayload, endpoint],+ );+ const validation = validated.validation;const hasSyntaxError = validation.issues.some((issue) => issue.path === "syntax");const systemOne = useMutation({- mutationFn: ({ payload, apiKey, signal, endpoint }: SystemOneSendVariables) =>- makeSystemOneRequest(payload, apiKey, getCustomProxyBaseUrl(), { signal, endpoint }),+ mutationFn: ({ request, apiKey, signal }: SystemOneSendVariables) =>+ makePlaygroundDecisionRequest(request, apiKey, getCustomProxyBaseUrl(), { signal }),});const isLoading = systemOne.isPending;const { reset: resetSystemOne } = systemOne;@@ -90,14 +91,12 @@ export default function SystemOneUI({ accessToken, disabledPersonalKeyCreation =function handlePayloadChange(value: string) {if (value !== rawPayload) {clearRequestState();- setChosenEndpoint(endpoint);setDrafts((current) => ({ ...current, [endpoint]: value }));}}function handleResetExample() {clearRequestState();- setChosenEndpoint(endpoint);setDrafts((current) => Object.fromEntries(Object.entries(current).filter(([key]) => key !== endpoint)));}@@ -115,14 +114,18 @@ export default function SystemOneUI({ accessToken, disabledPersonalKeyCreation =}function handleSend() {- if (!validation.payload || !effectiveApiKey) {+ const request: PlaygroundDecisionRequest | undefined =+ validated.endpoint === "/v1/decisions"+ ? validated.validation.payload && { endpoint: validated.endpoint, payload: validated.validation.payload }+ : validated.validation.payload && { endpoint: validated.endpoint, payload: validated.validation.payload };+ if (!request || !effectiveApiKey) {return;}clearRequestState();- setChosenEndpoint(endpoint);+ setDrafts((current) => ({ ...current, [endpoint]: rawPayload }));const controller = new AbortController();activeController.current = controller;- const variables = { payload: validation.payload, apiKey: effectiveApiKey, signal: controller.signal, endpoint };+ const variables = { request, apiKey: effectiveApiKey, signal: controller.signal };systemOne.mutate(variables);}@@ -134,43 +137,37 @@ export default function SystemOneUI({ accessToken, disabledPersonalKeyCreation =<Selectvalue={endpoint}onValueChange={(value) => {- if (value === "/v1/systemone" || value === "/typesafe/v1/systemone") {+ if (value === "/v1/decisions" || value === "/v1/systemone") {clearRequestState();- setChosenEndpoint(value);+ setEndpoint(value);}}}><SelectTrigger className="w-80" aria-label="Decision endpoint">- <SelectValue>- {endpoint === "/v1/systemone" ? "Decisions · /v1/systemone" : "TypeSafe · /typesafe/v1/systemone"}- </SelectValue>+ <SelectValue>{endpoint}</SelectValue></SelectTrigger><SelectContent>- <SelectItem value="/v1/systemone">Decisions · /v1/systemone</SelectItem>- <SelectItem value="/typesafe/v1/systemone">TypeSafe · /typesafe/v1/systemone</SelectItem>+ <SelectItem value="/v1/decisions">/v1/decisions</SelectItem>+ <SelectItem value="/v1/systemone">/v1/systemone</SelectItem></SelectContent></Select>- {endpoint === "/v1/systemone" && (- <>- <span className="ml-2 text-sm font-medium text-muted-foreground">Model</span>- <div className="w-80">- <SearchSelect- aria-label="Decision model"- options={decisionModels.map((model) => ({ label: model, value: model }))}- value={payloadModel(rawPayload) ?? null}- onValueChange={handleModelPick}- placeholder={decisionModels.length > 0 ? "Pick a decision model" : "No decision models yet"}- emptyText="No decision models found"- disabled={hasSyntaxError}- allowClear={false}- />- </div>- {decisionModelsLoaded && decisionModels.length === 0 && (- <a href={uiHref("models-and-endpoints")} className="text-sm text-primary underline">- Add a decision model- </a>- )}- </>+ <span className="ml-2 text-sm font-medium text-muted-foreground">Model</span>+ <div className="w-80">+ <SearchSelect+ aria-label="Decision model"+ options={decisionModels.map((model) => ({ label: model, value: model }))}+ value={payloadModel(rawPayload) ?? null}+ onValueChange={handleModelPick}+ placeholder={decisionModels.length > 0 ? "Pick a decision model" : "No decision models yet"}+ emptyText="No decision models found"+ disabled={hasSyntaxError}+ allowClear={false}+ />+ </div>+ {decisionModelsLoaded && decisionModels.length === 0 && (+ <a href={uiHref("models-and-endpoints")} className="text-sm text-primary underline">+ Add a decision model+ </a>)}</div><div className="flex flex-wrap items-center gap-3">@@ -230,13 +227,12 @@ export default function SystemOneUI({ accessToken, disabledPersonalKeyCreation =</div><Alert role="note" aria-label="Decision endpoint notice"><Info />- <AlertTitle>- {endpoint === "/v1/systemone" ? "Decision models · /v1/systemone" : "TypeSafe Jev · /typesafe/v1/systemone"}- </AlertTitle>+ <AlertTitle>{endpoint}</AlertTitle><AlertDescription>- {endpoint === "/v1/systemone"- ? "Sends choice, noul, and score questions through /v1/systemone to a decision model on your proxy. Pick one under Model, or omit model to use the proxy's configured default."- : "Sends requests through /typesafe/v1/systemone and requires TYPESAFE_API_KEY on the proxy."}{" "}+ {endpoint === "/v1/decisions"+ ? "Uses input and a questions array with predicate, choice, and score questions. Edit the form or JSON and inspect the response JSON in the OpenAI Decisions format."+ : "Uses state and a questions object with noul, choice, and score questions in the System One format."}{" "}+ Pick a decision model under Model, or omit model to use the proxy's configured default.{" "}<a href={DECISIONS_DOCS_URL} target="_blank" rel="noopener noreferrer" className="underline">How to call /v1/decisions and /v1/systemone</a>@@ -260,27 +256,45 @@ export default function SystemOneUI({ accessToken, disabledPersonalKeyCreation =<TabsTrigger value="json">JSON</TabsTrigger></TabsList><TabsContent value="form" className="flex min-h-0 flex-col">- <SystemOneForm+ {validated.endpoint === "/v1/decisions" ? (+ <OpenAIDecisionsForm+ value={rawPayload}+ onChange={handlePayloadChange}+ validation={validated.validation}+ onOpenJson={() => setView("json")}+ />+ ) : (+ <SystemOneForm+ value={rawPayload}+ onChange={handlePayloadChange}+ validation={validated.validation}+ onOpenJson={() => setView("json")}+ />+ )}+ </TabsContent>+ <TabsContent value="json" className="flex min-h-0 flex-col">+ <JsonEditorvalue={rawPayload}onChange={handlePayloadChange}validation={validation}- onOpenJson={() => setView("json")}+ label={endpoint === "/v1/decisions" ? "Decisions JSON payload" : "System One JSON payload"}+ placeholder={`Paste or write a ${endpoint} request`}/></TabsContent>- <TabsContent value="json" className="flex min-h-0 flex-col">- <JsonEditor value={rawPayload} onChange={handlePayloadChange} validation={validation} />- </TabsContent></Tabs></section><section className="grid content-start gap-4 xl:min-h-0 xl:overflow-auto" aria-label="Decisions results"><ResponseViewresponse={systemOne.data?.response}+ view={view}fallbackModel={validation.payload?.model}latencyMs={systemOne.data?.latencyMs}error={systemOne.error?.message}isLoading={isLoading}/>- <QuestionBreakdown payload={validation.payload} />+ {view === "form" && validated.endpoint === "/v1/systemone" && (+ <QuestionBreakdown payload={validated.validation.payload} />+ )}</section></div></div>diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/decisions.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/decisions.test.tsindex 90f1b63b09f..302eab1e21d 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/decisions.test.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/decisions.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from "vitest";-import { validateSystemOnePayload } from "./validatePayload";+import { validateSystemOnePayload, validateOpenAIDecisionsPayload } from "./validatePayload";import { systemOneResponseSchema } from "./schemas";+import { openAIDecisionsExample } from "./example";const request = {model: "configured-decision-model",@@ -81,3 +82,53 @@ describe("native decisions validation", () => {expect(systemOneResponseSchema.parse(response)).toEqual(response);});});++describe("/v1/decisions validation", () => {+ const example = openAIDecisionsExample("jev-latest");+ const validateOpenAI = (value: unknown) => validateOpenAIDecisionsPayload(JSON.stringify(value));++ it("keeps input, question arrays, provider extensions and optional model omission intact", () => {+ const payload = { input: example.input, questions: example.questions, provider_option: { enabled: true } };+ expect(validateOpenAI(payload)).toEqual({ isValid: true, payload, issues: [] });+ expect(validateOpenAI(example).isValid).toBe(true);+ });++ it("accepts multimodal messages and boolean choices without converting them to strings", () => {+ const payload = {+ input: [+ {+ role: "user",+ content: [+ { type: "input_text", text: "Does this show an error?" },+ { type: "input_image", image_url: "data:image/png;base64,example" },+ ],+ },+ ],+ questions: [{ type: "choice", instructions: "Is this an error?", choices: [{ value: true }, { value: false }] }],+ };+ expect(validateOpenAI(payload)).toEqual({ isValid: true, payload, issues: [] });+ });++ it.each([+ request,+ { ...example, questions: [] },+ { ...example, questions: request.questions },+ { ...example, input: {} },+ { ...example, questions: [{ type: "noul", instructions: "Test" }] },+ { ...example, questions: [{ type: "predicate" }] },+ { ...example, questions: [{ type: "predicate", instructions: "Test", criteria: {} }] },+ { ...example, questions: [{ type: "choice", instructions: "Test", choices: [{ value: true }] }] },+ {+ ...example,+ questions: [{ type: "choice", instructions: "Test", choices: [{ value: true }, { value: "true" }] }],+ },+ { ...example, questions: [{ type: "score", instructions: "Test", levels: [{ label: "Low" }] }] },+ ])("rejects the wrong endpoint's shape and invalid question definitions %#", (payload) => {+ expect(validateOpenAI(payload).isValid).toBe(false);+ });++ it("rejects blank and malformed JSON without throwing", () => {+ expect(validateOpenAIDecisionsPayload(" ").issues[0]?.path).toBe("root");+ expect(validateOpenAIDecisionsPayload("{").issues[0]?.path).toBe("syntax");+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/example.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/example.tsindex 796275212a1..6d751e6bfce 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/example.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/example.ts@@ -1,4 +1,5 @@import type { DecisionRequest, SystemOneRequest } from "./schemas";+import type { OpenAIDecisionsRequest } from "./openAIDecisions";export const SYSTEM_ONE_EXAMPLE = {model: "jev-latest",@@ -37,6 +38,34 @@ export const SYSTEM_ONE_EXAMPLE = {},} satisfies SystemOneRequest;-export const PLACEHOLDER_DECISION_MODEL = "your-decision-model";+export const decisionsExample = (model?: string): DecisionRequest => ({ ...SYSTEM_ONE_EXAMPLE, model });-export const decisionsExample = (model: string): DecisionRequest => ({ ...SYSTEM_ONE_EXAMPLE, model });+export const openAIDecisionsExample = (model?: string): OpenAIDecisionsRequest => ({+ model,+ input: SYSTEM_ONE_EXAMPLE.state,+ questions: [+ {+ type: "choice",+ name: "area",+ instructions: SYSTEM_ONE_EXAMPLE.questions.area.instructions,+ choices: Object.entries(SYSTEM_ONE_EXAMPLE.questions.area.criteria).map(([value, description]) => ({+ value,+ description,+ })),+ },+ {+ type: "predicate",+ name: "has_repro_steps",+ instructions: SYSTEM_ONE_EXAMPLE.questions.has_repro_steps.instructions,+ },+ {+ type: "score",+ name: "severity",+ instructions: SYSTEM_ONE_EXAMPLE.questions.severity.instructions,+ levels: SYSTEM_ONE_EXAMPLE.questions.severity.criteria.map((description, index) => ({+ label: String(index),+ description,+ })),+ },+ ],+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisions.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisions.tsnew file mode 100644index 00000000000..0e06d733ea3--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisions.ts@@ -0,0 +1,98 @@+import { z } from "zod";++const contentPart = z.discriminatedUnion("type", [+ z.strictObject({ type: z.literal("input_text"), text: z.string() }),+ z.strictObject({ type: z.literal("input_image"), image_url: z.string(), detail: z.string().nullish() }),+]);+const inputMessage = z.strictObject({+ role: z.literal("user").optional(),+ type: z.literal("message").optional(),+ content: z.union([z.string(), z.array(contentPart)]),+});+const questionFields = { name: z.string().nullish(), instructions: z.string() };+const choiceValue = z.union([z.string(), z.boolean()]);+const choiceQuestion = z+ .strictObject({+ ...questionFields,+ type: z.literal("choice"),+ choices: z+ .array(z.strictObject({ value: choiceValue, description: z.string().nullish() }))+ .min(2)+ .max(255),+ })+ .refine(+ (question) => new Set(question.choices.map((choice) => String(choice.value))).size === question.choices.length,+ {+ message: "Choice values must be unique, including their string representations.",+ path: ["choices"],+ },+ );++const requestFields = {+ model: z+ .string()+ .refine((value) => value.trim().length > 0, "Model must be a non-empty string.")+ .optional(),+ input: z.union([z.string(), z.array(inputMessage)]),+ questions: z+ .array(+ z.discriminatedUnion("type", [+ z.strictObject({ ...questionFields, type: z.literal("predicate") }),+ choiceQuestion,+ z.strictObject({+ ...questionFields,+ type: z.literal("score"),+ levels: z+ .array(z.strictObject({ label: z.string(), description: z.string().nullish() }))+ .min(2)+ .max(10),+ }),+ ]),+ )+ .min(1)+ .max(128),+ safety_identifier: z.string().nullish(),+};+export const openAIDecisionsRequestSchema = z.looseObject(requestFields);++const probability = z.number().finite().min(0).max(1);+const answerFields = { name: z.string().nullable() };+const tokenCount = z.number().int().nonnegative();+const choiceAnswerFields = {+ ...answerFields,+ type: z.literal("choice"),+ choice: choiceValue,+ confidence: probability,+ probabilities: z.array(z.looseObject({ value: choiceValue, probability })),+};+const scoreAnswerFields = {+ ...answerFields,+ type: z.literal("score"),+ score: z.number().finite(),+ confidence: probability,+ probabilities: z.array(z.looseObject({ value: z.number().int(), label: z.string(), probability })),+};+const usageFields = {+ input_tokens: tokenCount,+ output_tokens: tokenCount,+ total_tokens: tokenCount,+ input_tokens_details: z+ .looseObject({ cached_tokens: tokenCount.optional(), cache_write_tokens: tokenCount.optional() })+ .optional(),+ output_tokens_details: z.looseObject({ reasoning_tokens: tokenCount.optional() }).optional(),+};+export const openAIDecisionsResponseSchema = z.looseObject({+ model: z.string(),+ answers: z.array(+ z.discriminatedUnion("type", [+ z.looseObject({ ...answerFields, type: z.literal("predicate"), probability }),+ z.looseObject(choiceAnswerFields),+ z.looseObject(scoreAnswerFields),+ z.looseObject({ ...answerFields, type: z.literal("refusal") }),+ ]),+ ),+ usage: z.looseObject(usageFields),+});++export type OpenAIDecisionsRequest = z.infer<typeof openAIDecisionsRequestSchema>;+export type OpenAIDecisionsResponse = z.infer<typeof openAIDecisionsResponseSchema>;diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisionsForm.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisionsForm.test.tsnew file mode 100644index 00000000000..29ef30558b6--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisionsForm.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from "vitest";+import { openAIDecisionsExample } from "./example";+import { readDecisionsForm, retypeDecisionQuestion, type DecisionsFormQuestion } from "./openAIDecisionsForm";+import { validateOpenAIDecisionsPayload } from "./validatePayload";++describe("readDecisionsForm", () => {+ it("round-trips examples and preserves input order, extension fields, false choices and null names", () => {+ const example = openAIDecisionsExample();+ expect(readDecisionsForm(JSON.stringify(example))).toEqual(JSON.parse(JSON.stringify(example)));+ const payload = {+ metadata: { source: "playground" },+ input: [{ role: "user", content: [{ type: "input_image", image_url: "https://example.com/image.png" }] }],+ safety_identifier: null,+ questions: [{ type: "choice", name: null, instructions: "Choose", choices: [{ value: false }, { value: true }] }],+ };+ expect(JSON.stringify(readDecisionsForm(JSON.stringify(payload)))).toEqual(JSON.stringify(payload));+ });++ it.each([+ {},+ { input: "", questions: [] },+ { input: "text", questions: [{ type: "choice", choices: [] }] },+ { input: "text", questions: [{ type: "score", instructions: "Score", levels: [{ label: "0" }] }] },+ {+ input: "text",+ questions: [{ type: "choice", instructions: "Choose", choices: [{ value: "same" }, { value: "same" }] }],+ },+ ])("keeps incomplete requests editable without marking them valid for Send: %j", (payload) => {+ const raw = JSON.stringify(payload);+ expect(readDecisionsForm(raw)).toEqual(payload);+ expect(validateOpenAIDecisionsPayload(raw).isValid).toBe(false);+ });++ it.each(["{", "", "null", "[]", '{"input":42}', '{"questions":{}}', '{"questions":[{"type":"noul"}]}'])(+ "rejects unsupported form shapes without replacing the JSON: %s",+ (raw) => {+ expect(readDecisionsForm(raw)).toBeUndefined();+ },+ );+});++describe("retypeDecisionQuestion", () => {+ const choice: DecisionsFormQuestion = {+ type: "choice",+ name: "route",+ instructions: "Where should it go?",+ choices: [{ value: false }, { value: "other" }],+ };++ it("keeps choices unchanged when the type does not change", () => {+ expect(retypeDecisionQuestion(choice, "choice")).toEqual(choice);+ });++ it("removes type-specific fields while preserving names, instructions and extras", () => {+ const score = retypeDecisionQuestion({ ...choice, custom: "keep" }, "score");+ const expectedScore = {+ type: "score",+ name: "route",+ instructions: "Where should it go?",+ custom: "keep",+ levels: [{ label: "0" }, { label: "1" }],+ };+ expect(score).toEqual(expectedScore);+ const predicate = retypeDecisionQuestion(score, "predicate");+ const expectedPredicate = {+ type: "predicate",+ name: "route",+ instructions: "Where should it go?",+ custom: "keep",+ };+ expect(predicate).toEqual(expectedPredicate);+ expect(retypeDecisionQuestion(predicate, "choice")).toEqual({+ ...predicate,+ type: "choice",+ choices: [{ value: "option_1" }, { value: "option_2" }],+ });+ expect(choice.choices).toEqual([{ value: false }, { value: "other" }]);+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisionsForm.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisionsForm.tsnew file mode 100644index 00000000000..556b68f8f43--- /dev/null+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/openAIDecisionsForm.ts@@ -0,0 +1,54 @@+import { z } from "zod";+import { openAIDecisionsRequestSchema } from "./openAIDecisions";+import { parseJson } from "./validatePayload";++const questionFields = { name: z.string().nullish(), instructions: z.string().optional() };+const choiceFields = { value: z.union([z.string(), z.boolean()]), description: z.string().nullish() };+const levelFields = { label: z.string(), description: z.string().nullish() };+const formQuestion = z.discriminatedUnion("type", [+ z.looseObject({ ...questionFields, type: z.literal("predicate") }),+ z.looseObject({+ ...questionFields,+ type: z.literal("choice"),+ choices: z.array(z.looseObject(choiceFields)).optional(),+ }),+ z.looseObject({+ ...questionFields,+ type: z.literal("score"),+ levels: z.array(z.looseObject(levelFields)).optional(),+ }),+]);+const formPayload = z.looseObject({+ input: openAIDecisionsRequestSchema.shape.input.optional(),+ questions: z.array(formQuestion).optional(),+ safety_identifier: z.string().nullish(),+});++export type DecisionsFormPayload = z.infer<typeof formPayload>;+export type DecisionsFormQuestion = z.infer<typeof formQuestion>;+export type DecisionsQuestionType = DecisionsFormQuestion["type"];++const formPayloadInInputOrder = z.custom<DecisionsFormPayload>((value) => formPayload.safeParse(value).success);++export function readDecisionsForm(raw: string): DecisionsFormPayload | undefined {+ const json = parseJson(raw);+ return json.ok ? formPayloadInInputOrder.safeParse(json.value).data : undefined;+}++export function retypeDecisionQuestion(+ question: DecisionsFormQuestion,+ type: DecisionsQuestionType,+): DecisionsFormQuestion {+ if (question.type === type) {+ return question;+ }+ const { type: _type, choices: _choices, levels: _levels, ...rest } = question;+ switch (type) {+ case "predicate":+ return { ...rest, type };+ case "choice":+ return { ...rest, type, choices: [{ value: "option_1" }, { value: "option_2" }] };+ case "score":+ return { ...rest, type, levels: [{ label: "0" }, { label: "1" }] };+ }+}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/validatePayload.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/validatePayload.tsindex 9bed8e9924b..316c98e6c92 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/validatePayload.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/components/systemOneUI/lib/validatePayload.ts@@ -1,3 +1,5 @@+import { z } from "zod";+import { openAIDecisionsRequestSchema, type OpenAIDecisionsRequest } from "./openAIDecisions";import {decisionsRequestSchema,systemOneRequestSchema,@@ -13,15 +15,17 @@ export interface SystemOnePayloadIssue {severity: "error" | "warning";}-export interface SystemOnePayloadValidation {+export interface PayloadValidation<T> {isValid: boolean;- payload?: PlaygroundRequest;+ payload?: T;issues: SystemOnePayloadIssue[];}-const invalid = (path: string, message: string): SystemOnePayloadValidation => ({+export type SystemOnePayloadValidation = PayloadValidation<PlaygroundRequest>;++const invalid = (path: string, message: string) => ({isValid: false,- issues: [{ path, message, severity: "error" }],+ issues: [{ path, message, severity: "error" as const }],});export function parseJson(raw: string): { ok: true; value: unknown } | { ok: false; message: string } {@@ -41,10 +45,7 @@ const scoreLevelWarnings = (payload: PlaygroundRequest): SystemOnePayloadIssue[]severity: "warning",}));-export function validateSystemOnePayload(- raw: string,- endpoint: DecisionEndpoint = "/typesafe/v1/systemone",-): SystemOnePayloadValidation {+function validatePayload<T>(raw: string, schema: z.ZodType<T>): PayloadValidation<T> {if (!raw.trim()) {return invalid("root", "Payload cannot be empty.");}@@ -54,7 +55,6 @@ export function validateSystemOnePayload(return invalid("syntax", `Invalid JSON syntax: ${json.message}`);}- const schema = endpoint === "/v1/systemone" ? decisionsRequestSchema : systemOneRequestSchema;const result = schema.safeParse(json.value);if (!result.success) {return {@@ -67,5 +67,18 @@ export function validateSystemOnePayload(};}- return { isValid: true, payload: result.data, issues: scoreLevelWarnings(result.data) };+ return { isValid: true, payload: result.data, issues: [] };+}++export function validateSystemOnePayload(+ raw: string,+ endpoint: DecisionEndpoint = "/typesafe/v1/systemone",+): SystemOnePayloadValidation {+ const schema = endpoint === "/v1/systemone" ? decisionsRequestSchema : systemOneRequestSchema;+ const result = validatePayload<PlaygroundRequest>(raw, schema);+ return result.payload ? { ...result, issues: scoreLevelWarnings(result.payload) } : result;+}++export function validateOpenAIDecisionsPayload(raw: string): PayloadValidation<OpenAIDecisionsRequest> {+ return validatePayload(raw, openAIDecisionsRequestSchema);}diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/system_one.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/system_one.test.tsindex e097f2d3d26..720152d3143 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/system_one.test.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/system_one.test.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { fetchDecisionModels, makeSystemOneRequest } from "./system_one";+import { fetchDecisionModels, makeSystemOneRequest, makePlaygroundDecisionRequest } from "./system_one";+import { openAIDecisionsExample } from "../components/systemOneUI/lib/example";+import type { OpenAIDecisionsResponse } from "../components/systemOneUI/lib/openAIDecisions";import type { SystemOneRequest, SystemOneResponse } from "../components/systemOneUI/lib/schemas";vi.mock("@/components/networking", () => ({@@ -72,7 +74,7 @@ describe("makeSystemOneRequest", () => {expect(mockFetch).toHaveBeenCalledTimes(1);expect(mockFetch).toHaveBeenCalledWith(- "https://custom.example.com/typesafe/v1/systemone",+ "https://custom.example.com/v1/systemone",expect.objectContaining(expectedRequest),);expect(result.response).toEqual(responseBody);@@ -82,7 +84,7 @@ describe("makeSystemOneRequest", () => {it("uses the proxy base URL when no custom base is provided", async () => {await makeSystemOneRequest(payload, "session-key");- expect(mockFetch.mock.calls[0]?.[0]).toBe("https://proxy.example.com/typesafe/v1/systemone");+ expect(mockFetch.mock.calls[0]?.[0]).toBe("https://proxy.example.com/v1/systemone");});it("throws the upstream error text for failed requests", async () => {@@ -102,11 +104,95 @@ describe("makeSystemOneRequest", () => {} as Response);await expect(makeSystemOneRequest(payload, "session-key")).rejects.toThrow(- "System One response has an invalid shape.",+ "/v1/systemone response has an invalid shape.",);});});+describe("/v1/decisions requests", () => {+ const mockFetch = vi.fn<typeof fetch>();+ const request = { endpoint: "/v1/decisions", payload: openAIDecisionsExample("jev-latest") } as const;+ const response: OpenAIDecisionsResponse = {+ model: "jev-latest",+ answers: [+ { name: "urgent", type: "predicate", probability: 0.9 },+ {+ name: "area",+ type: "choice",+ choice: true,+ confidence: 0.8,+ probabilities: [+ { value: true, probability: 0.8 },+ { value: false, probability: 0.2 },+ ],+ },+ {+ name: "severity",+ type: "score",+ score: 0.6,+ confidence: 0.6,+ probabilities: [+ { value: 0, label: "low", probability: 0.4 },+ { value: 1, label: "high", probability: 0.6 },+ ],+ },+ { name: null, type: "refusal" },+ ],+ usage: {+ input_tokens: 10,+ output_tokens: 2,+ total_tokens: 12,+ input_tokens_details: { cached_tokens: 3 },+ output_tokens_details: { reasoning_tokens: 1 },+ },+ provider_metadata: { id: "native-result" },+ };++ beforeEach(() => {+ mockFetch.mockReset();+ vi.stubGlobal("fetch", mockFetch);+ mockFetch.mockResolvedValue({ ok: true, text: async () => JSON.stringify(response) } as Response);+ });+ afterEach(() => vi.unstubAllGlobals());++ it.each([undefined, "https://custom.example.com/"])(+ "sends the OpenAI shape unchanged and preserves all answer types (%s)",+ async (baseUrl) => {+ const controller = new AbortController();+ const result = await makePlaygroundDecisionRequest(request, "session-key", baseUrl, {+ signal: controller.signal,+ });+ const expectedRequest = {+ method: "POST",+ body: JSON.stringify(request.payload),+ signal: controller.signal,+ headers: expect.objectContaining({ Authorization: "Bearer session-key", "Content-Type": "application/json" }),+ };+ expect(mockFetch).toHaveBeenCalledWith(+ `${baseUrl?.replace(/\/$/, "") ?? "https://proxy.example.com"}/v1/decisions`,+ expect.objectContaining(expectedRequest),+ );+ expect(result.response).toEqual(response);+ },+ );++ it("rejects a System One response rather than disguising its shape", async () => {+ mockFetch.mockResolvedValueOnce({ ok: true, text: async () => JSON.stringify(responseBody) } as Response);+ await expect(makePlaygroundDecisionRequest(request, "session-key")).rejects.toThrow(+ "/v1/decisions response has an invalid shape.",+ );+ });++ it("surfaces errors from the selected endpoint", async () => {+ mockFetch.mockResolvedValueOnce({+ ok: false,+ status: 400,+ text: async () => "Unsupported decision model",+ } as Response);+ await expect(makePlaygroundDecisionRequest(request, "session-key")).rejects.toThrow("Unsupported decision model");+ });+});+describe("fetchDecisionModels", () => {const mockFetch = vi.fn<(input: RequestInfo | URL, init?: RequestInit) => Promise<Response>>();const modelGroupInfo = (data: unknown) => ({ ok: true, text: async () => JSON.stringify({ data }) }) as Response;diff --git a/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/system_one.ts b/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/system_one.tsindex 6c29d9110ac..f49874b4735 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/system_one.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/playground/llm_calls/system_one.ts@@ -5,16 +5,26 @@ import { createApiClient } from "@/lib/http/client";import { isDecisionMode } from "@/lib/decisionModels";import {systemOneResponseSchema,- type DecisionEndpoint,type PlaygroundRequest,type SystemOneResponse,} from "../components/systemOneUI/lib/schemas";+import {+ openAIDecisionsResponseSchema,+ type OpenAIDecisionsRequest,+ type OpenAIDecisionsResponse,+} from "../components/systemOneUI/lib/openAIDecisions";-export interface SystemOneResult {- response: SystemOneResponse;+export interface DecisionResult<T> {+ response: T;latencyMs: number;}+export type SystemOneResult = DecisionResult<SystemOneResponse>;+export type OpenAIDecisionsResult = DecisionResult<OpenAIDecisionsResponse>;+export type PlaygroundDecisionRequest =+ | { endpoint: "/v1/systemone"; payload: PlaygroundRequest }+ | { endpoint: "/v1/decisions"; payload: OpenAIDecisionsRequest };+const modelGroupInfoSchema = z.object({data: z.array(z.object({ model_group: z.string(), mode: z.string().nullish() })),});@@ -51,21 +61,47 @@ export async function fetchDecisionModels(.sort((a, b) => a.localeCompare(b));}-export async function makeSystemOneRequest(- payload: PlaygroundRequest,+async function sendDecisionRequest<T>(+ request: { endpoint: PlaygroundDecisionRequest["endpoint"]; payload: object; schema: z.ZodType<T> },accessToken: string,customBaseUrl?: string,- { signal, endpoint = "/typesafe/v1/systemone" }: { signal?: AbortSignal; endpoint?: DecisionEndpoint } = {},-): Promise<SystemOneResult> {+ signal?: AbortSignal,+): Promise<DecisionResult<T>> {const startedAt = performance.now();- const body = await proxyClient(customBaseUrl).post<unknown>(endpoint, {- body: payload,+ const body = await proxyClient(customBaseUrl).post<unknown>(request.endpoint, {+ body: request.payload,headers: authHeaders(accessToken),signal,});- const parsed = systemOneResponseSchema.safeParse(body);+ const parsed = request.schema.safeParse(body);if (!parsed.success) {- throw new Error("System One response has an invalid shape.");+ throw new Error(`${request.endpoint} response has an invalid shape.`);}return { response: parsed.data, latencyMs: performance.now() - startedAt };}++export function makeSystemOneRequest(+ payload: PlaygroundRequest,+ accessToken: string,+ customBaseUrl?: string,+ { signal }: { signal?: AbortSignal } = {},+): Promise<SystemOneResult> {+ return sendDecisionRequest(+ { endpoint: "/v1/systemone", payload, schema: systemOneResponseSchema },+ accessToken,+ customBaseUrl,+ signal,+ );+}++export function makePlaygroundDecisionRequest(+ request: PlaygroundDecisionRequest,+ accessToken: string,+ customBaseUrl?: string,+ { signal }: { signal?: AbortSignal } = {},+): Promise<SystemOneResult | OpenAIDecisionsResult> {+ if (request.endpoint === "/v1/systemone") {+ return makeSystemOneRequest(request.payload, accessToken, customBaseUrl, { signal });+ }+ return sendDecisionRequest({ ...request, schema: openAIDecisionsResponseSchema }, accessToken, customBaseUrl, signal);+}