Skip to content

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

feat: pretty view of generation I/O (#484)

Marc Klingen0574fe538be7
diff --git a/src/components/trace/ObservationPreview.tsx b/src/components/trace/ObservationPreview.tsx
index 20286a2540..17aa001eb0 100644
--- a/src/components/trace/ObservationPreview.tsx
+++ b/src/components/trace/ObservationPreview.tsx
@@ -20,6 +20,12 @@ import { ManualScoreButton } from "@/src/features/manual-scoring/components";
import { NewDatasetItemFromObservationButton } from "@/src/features/datasets/components/NewDatasetItemFromObservationButton";
import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
+import { z } from "zod";
+import { deepParseJson } from "@/src/utils/json";
+import { cn } from "@/src/utils/tailwind";
+import { useState } from "react";
+import { Button } from "@/src/components/ui/button";
+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
export const ObservationPreview = (props: {
observations: Array<ObservationReturnType>;
@@ -106,39 +112,33 @@ export const ObservationPreview = (props: {
observationOutput={observationWithInputAndOutput.data.output}
key={preloadedObservation.id}
/>
- ) : (
- <div>Loading ...</div>
- )}
+ ) : null}
</div>
</CardHeader>
<CardContent className="flex flex-col gap-4">
- <JSONView
+ <ObservationIO
key={preloadedObservation.id + "-input"}
- title={
- preloadedObservation.type === "GENERATION" ? "Prompt" : "Input"
- }
- json={observationWithInputAndOutput.data?.input ?? undefined}
- isLoading={observationWithInputAndOutput.isLoading}
- />
- <JSONView
- key={preloadedObservation.id + "-output"}
- title={
- preloadedObservation.type === "GENERATION" ? "Completion" : "Output"
- }
- json={observationWithInputAndOutput.data?.output ?? undefined}
+ observationType={preloadedObservation.type}
+ input={observationWithInputAndOutput.data?.input ?? undefined}
+ output={observationWithInputAndOutput.data?.output ?? undefined}
isLoading={observationWithInputAndOutput.isLoading}
/>
- <JSONView
- key={preloadedObservation.id + "-status"}
- title="Status Message"
- json={preloadedObservation.statusMessage}
- />
- <JSONView
- key={preloadedObservation.id + "-metadata"}
- title="Metadata"
- json={preloadedObservation.metadata}
- />
+ {preloadedObservation.statusMessage ? (
+ <JSONView
+ key={preloadedObservation.id + "-status"}
+ title="Status Message"
+ json={preloadedObservation.statusMessage}
+ />
+ ) : null}
+
+ {preloadedObservation.metadata ? (
+ <JSONView
+ key={preloadedObservation.id + "-metadata"}
+ title="Metadata"
+ json={preloadedObservation.metadata}
+ />
+ ) : null}
{props.scores.find(
(s) => s.observationId === preloadedObservation.id,
@@ -177,3 +177,147 @@ export const ObservationPreview = (props: {
</Card>
);
};
+
+const ObservationIO: React.FC<{
+ observationType: string;
+ input?: unknown;
+ output?: unknown;
+ isLoading: boolean;
+}> = ({ isLoading, ...props }) => {
+ const [currentView, setCurrentView] = useState<"pretty" | "json">("pretty");
+
+ const input = deepParseJson(props.input);
+ const output = deepParseJson(props.output);
+
+ // parse old completions: { completion: string } -> string
+ const outLegacyCompletionSchema = z
+ .object({
+ completion: z.string(),
+ })
+ .refine((value) => Object.keys(value).length === 1);
+ const outLegacyCompletionSchemaParsed =
+ outLegacyCompletionSchema.safeParse(output);
+ const outputClean = outLegacyCompletionSchemaParsed.success
+ ? outLegacyCompletionSchemaParsed.data
+ : props.output ?? null;
+
+ // OpenAI messages
+ let inOpenAiMessageArray = OpenAiMessageArraySchema.safeParse(input);
+ if (!inOpenAiMessageArray.success) {
+ // check if input is an array of length 1 including an array of OpenAiMessageSchema
+ // this is the case for some integrations
+ const inputArray = z.array(OpenAiMessageArraySchema).safeParse(input);
+ if (inputArray.success && inputArray.data.length === 1) {
+ inOpenAiMessageArray = OpenAiMessageArraySchema.safeParse(
+ inputArray.data[0],
+ );
+ }
+ }
+ const outOpenAiMessage = OpenAiMessageSchema.safeParse(output);
+
+ // Pretty view available
+ const isPrettyViewAvailable = inOpenAiMessageArray.success;
+
+ // default I/O
+ return (
+ <>
+ {isPrettyViewAvailable ? (
+ <Tabs
+ value={currentView}
+ onValueChange={(v) => setCurrentView(v as "pretty" | "json")}
+ >
+ <TabsList>
+ <TabsTrigger value="pretty">Pretty ✨</TabsTrigger>
+ <TabsTrigger value="json">JSON</TabsTrigger>
+ </TabsList>
+ </Tabs>
+ ) : null}
+ {isPrettyViewAvailable && currentView === "pretty" ? (
+ inOpenAiMessageArray.success ? (
+ <OpenAiMessageView
+ messages={inOpenAiMessageArray.data.concat(
+ outOpenAiMessage.success
+ ? {
+ ...outOpenAiMessage.data,
+ role: outOpenAiMessage.data.role ?? "assistant",
+ }
+ : {
+ role: "assistant",
+ content: JSON.stringify(outputClean) ?? null,
+ },
+ )}
+ />
+ ) : null
+ ) : null}
+ {currentView === "json" || !isPrettyViewAvailable ? (
+ <>
+ <JSONView
+ title="Input"
+ json={input ?? null}
+ isLoading={isLoading}
+ className="flex-1"
+ />
+ <JSONView
+ title="Output"
+ json={outputClean}
+ isLoading={isLoading}
+ className="flex-1"
+ />
+ </>
+ ) : null}
+ </>
+ );
+};
+
+const OpenAiMessageSchema = z
+ .object({
+ role: z.enum(["system", "user", "assistant"]).optional(),
+ content: z.string().nullable(),
+ })
+ .refine((value) => value.content !== null || value.role !== undefined);
+
+const OpenAiMessageArraySchema = z.array(OpenAiMessageSchema).min(1);
+
+const OpenAiMessageView: React.FC<{
+ messages: z.infer<typeof OpenAiMessageArraySchema>;
+}> = ({ messages }) => {
+ const COLLAPSE_THRESHOLD = 3;
+ const [isCollapsed, setCollapsed] = useState(
+ messages.length > COLLAPSE_THRESHOLD ? true : null,
+ );
+
+ return (
+ <div className="flex flex-col gap-2 rounded-md border p-3">
+ {messages
+ .filter(
+ (_, i) =>
+ // show all if not collapsed or null; show first and last n if collapsed
+ !isCollapsed || i == 0 || i > messages.length - COLLAPSE_THRESHOLD,
+ )
+ .map((message, index) => (
+ <>
+ <JSONView
+ title={message.role}
+ json={message.content}
+ key={index}
+ className={cn(
+ message.role === "system" && "bg-gray-100",
+ message.role === "assistant" && "bg-green-50",
+ )}
+ />
+ {isCollapsed !== null && index === 0 ? (
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => setCollapsed((v) => !v)}
+ >
+ {isCollapsed
+ ? `Show ${messages.length - COLLAPSE_THRESHOLD} more ...`
+ : "Hide history"}
+ </Button>
+ ) : null}
+ </>
+ ))}
+ </div>
+ );
+};
diff --git a/src/components/ui/code.tsx b/src/components/ui/code.tsx
index a40b4c84ed..c1b6ee34c7 100644
--- a/src/components/ui/code.tsx
+++ b/src/components/ui/code.tsx
@@ -3,6 +3,8 @@ import { Button } from "@/src/components/ui/button";
import { Check, ChevronsDownUp, ChevronsUpDown, Copy } from "lucide-react";
import { cn } from "@/src/utils/tailwind";
import { default as React18JsonView } from "react18-json-view";
+import { deepParseJson } from "@/src/utils/json";
+import { Skeleton } from "@/src/components/ui/skeleton";
export function JSONView(props: {
json?: unknown;
@@ -10,31 +12,19 @@ export function JSONView(props: {
className?: string;
isLoading?: boolean;
}) {
- const isCompletion =
- props.json &&
- typeof props.json === "object" &&
- Object.keys(props.json).length === 1 &&
- "completion" in props.json &&
- typeof props.json.completion === "string";
-
- // some users ingest stringified json, parse it
- const json = isCompletion
- ? parseJson((props.json as { completion: string }).completion)
- : props.json;
-
// some users ingest stringified json nested in json, parse it
- const parsedJson = deepParseJson(json);
+ const parsedJson = deepParseJson(props.json);
return (
<div className={cn("max-w-full rounded-md border ", props.className)}>
{props.title ? (
- <div className="border-b px-4 py-1 text-xs font-medium">
+ <div className="border-b px-3 py-1 text-xs font-medium">
{props.title}
</div>
) : undefined}
<div className="flex gap-2 whitespace-pre-wrap p-3 text-xs">
{props.isLoading ? (
- <div>Loading ...</div>
+ <Skeleton className="h-3 w-3/4" />
) : (
<React18JsonView
src={parsedJson}
@@ -71,7 +61,7 @@ export function CodeView(props: {
return (
<div className={cn("max-w-full rounded-md border ", props.className)}>
{props.title ? (
- <div className="border-b px-4 py-1 text-xs font-medium">
+ <div className="border-b px-3 py-1 text-xs font-medium">
{props.title}
</div>
) : undefined}
@@ -107,48 +97,3 @@ export function CodeView(props: {
</div>
);
}
-
-const parseJson = (input: string) => {
- try {
- return JSON.parse(input) as unknown;
- } catch {
- return input;
- }
-};
-
-/**
- * Deeply parses a JSON string or object for nested stringified JSON
- * @param json JSON string or object to parse
- * @returns Parsed JSON object
- */
-function deepParseJson(json: unknown): unknown {
- if (typeof json === "string") {
- try {
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
- const parsed = JSON.parse(json);
- return deepParseJson(parsed); // Recursively parse parsed value
- } catch (e) {
- return json; // If it's not a valid JSON string, just return the original string
- }
- } else if (typeof json === "object" && json !== null) {
- // Handle arrays
- if (Array.isArray(json)) {
- for (let i = 0; i < json.length; i++) {
- json[i] = deepParseJson(json[i]);
- }
- } else {
- // Handle nested objects
- for (const key in json) {
- // Ensure we only iterate over the object's own properties
- if (Object.prototype.hasOwnProperty.call(json, key)) {
- (json as Record<string, unknown>)[key] = deepParseJson(
- (json as Record<string, unknown>)[key],
- );
- }
- }
- }
- return json;
- }
-
- return json;
-}
diff --git a/src/components/ui/skeleton.tsx b/src/components/ui/skeleton.tsx
new file mode 100644
index 0000000000..836f0d2ea4
--- /dev/null
+++ b/src/components/ui/skeleton.tsx
@@ -0,0 +1,15 @@
+import { cn } from "@/src/utils/tailwind";
+
+function Skeleton({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) {
+ return (
+ <div
+ className={cn("animate-pulse rounded-md bg-muted", className)}
+ {...props}
+ />
+ );
+}
+
+export { Skeleton };
diff --git a/src/utils/json.ts b/src/utils/json.ts
index a2cec8ddbf..27caf97eb9 100644
--- a/src/utils/json.ts
+++ b/src/utils/json.ts
@@ -2,6 +2,51 @@ import { type jsonSchema } from "@/src/utils/zod";
import { type z } from "zod";
import lodash from "lodash";
+export const parseJson = (input: string) => {
+ try {
+ return JSON.parse(input) as unknown;
+ } catch {
+ return input;
+ }
+};
+
+/**
+ * Deeply parses a JSON string or object for nested stringified JSON
+ * @param json JSON string or object to parse
+ * @returns Parsed JSON object
+ */
+export function deepParseJson(json: unknown): unknown {
+ if (typeof json === "string") {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
+ const parsed = JSON.parse(json);
+ return deepParseJson(parsed); // Recursively parse parsed value
+ } catch (e) {
+ return json; // If it's not a valid JSON string, just return the original string
+ }
+ } else if (typeof json === "object" && json !== null) {
+ // Handle arrays
+ if (Array.isArray(json)) {
+ for (let i = 0; i < json.length; i++) {
+ json[i] = deepParseJson(json[i]);
+ }
+ } else {
+ // Handle nested objects
+ for (const key in json) {
+ // Ensure we only iterate over the object's own properties
+ if (Object.prototype.hasOwnProperty.call(json, key)) {
+ (json as Record<string, unknown>)[key] = deepParseJson(
+ (json as Record<string, unknown>)[key],
+ );
+ }
+ }
+ }
+ return json;
+ }
+
+ return json;
+}
+
export const mergeJson = (
json1?: z.infer<typeof jsonSchema>,
json2?: z.infer<typeof jsonSchema>,