Skip to content

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

feat: adds links in and out of playground (#2123)

Hassieb Pakzad9b7e0abfbc66
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 3e77594c45..1ff153f544 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -34,9 +34,9 @@ export type UIModelParams = RecordWithEnabledFlag<
export type ModelConfig = z.infer<typeof ZodModelConfig>;
export const ZodModelConfig = z.object({
- max_tokens: z.number().optional(),
- temperature: z.number().optional(),
- top_p: z.number().optional(),
+ max_tokens: z.coerce.number().optional(),
+ temperature: z.coerce.number().optional(),
+ top_p: z.coerce.number().optional(),
});
// OpenAI
diff --git a/web/src/components/ChatMessages/ChatMessageComponent.tsx b/web/src/components/ChatMessages/ChatMessageComponent.tsx
index 9bb965792b..5e82c767ff 100644
--- a/web/src/components/ChatMessages/ChatMessageComponent.tsx
+++ b/web/src/components/ChatMessages/ChatMessageComponent.tsx
@@ -63,6 +63,7 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({
<Textarea
ref={textAreaRef}
+ id={message.id}
className="height-[auto] min-h-8 w-full pt-3 font-mono text-xs focus:outline-none"
placeholder={placeholder}
value={message.content}
diff --git a/web/src/components/layouts/layout.tsx b/web/src/components/layouts/layout.tsx
index e59f9325d4..88593a203d 100644
--- a/web/src/components/layouts/layout.tsx
+++ b/web/src/components/layouts/layout.tsx
@@ -33,6 +33,15 @@ import { ProjectNavigation } from "@/src/components/projectNavigation";
import DOMPurify from "dompurify";
import { ThemeToggle } from "@/src/features/theming/ThemeToggle";
+const signOutUser = async () => {
+ localStorage.clear();
+ sessionStorage.clear();
+
+ await signOut({
+ callbackUrl: "/auth/sign-in",
+ });
+};
+
const userNavigation = [
{
name: "Theme",
@@ -41,10 +50,7 @@ const userNavigation = [
},
{
name: "Sign out",
- onClick: () =>
- signOut({
- callbackUrl: "/auth/sign-in",
- }),
+ onClick: signOutUser,
},
];
@@ -141,9 +147,8 @@ export default function Layout(props: PropsWithChildren) {
!publishablePaths.includes(router.pathname) &&
!router.pathname.startsWith("/public/")
) {
- void signOut({
- callbackUrl: "/auth/sign-in",
- });
+ signOutUser();
+
return <Spinner message="Redirecting" />;
}
diff --git a/web/src/components/trace/ObservationPreview.tsx b/web/src/components/trace/ObservationPreview.tsx
index d8abe661f5..e0996b2799 100644
--- a/web/src/components/trace/ObservationPreview.tsx
+++ b/web/src/components/trace/ObservationPreview.tsx
@@ -21,6 +21,7 @@ import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";
import { withDefault, StringParam, useQueryParam } from "use-query-params";
import ScoresTable from "@/src/components/table/use-cases/scores";
import { ScoresPreview } from "@/src/components/trace/ScoresPreview";
+import { JumpToPlaygroundButton } from "@/src/ee/features/playground/page/components/JumpToPlaygroundButton";
export const ObservationPreview = (props: {
observations: Array<ObservationReturnType>;
@@ -71,13 +72,13 @@ export const ObservationPreview = (props: {
<TabsList className="bg-background py-0">
<TabsTrigger
value="preview"
- className="data-[state=active]:border-primary-accent h-full rounded-none border-b-4 border-transparent data-[state=active]:shadow-none"
+ className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
>
Preview
</TabsTrigger>
<TabsTrigger
value="scores"
- className="data-[state=active]:border-primary-accent h-full rounded-none border-b-4 border-transparent data-[state=active]:shadow-none"
+ className="h-full rounded-none border-b-4 border-transparent data-[state=active]:border-primary-accent data-[state=active]:shadow-none"
>
Scores
</TabsTrigger>
@@ -159,6 +160,14 @@ export const ObservationPreview = (props: {
observationId={preloadedObservation.id}
scores={props.scores}
/>
+ {observationWithInputAndOutput.data?.type === "GENERATION" && (
+ <JumpToPlaygroundButton
+ source="generation"
+ generation={observationWithInputAndOutput.data}
+ analyticsEventName="trace_detail:test_in_playground_button_click"
+ fullWidth
+ />
+ )}
{observationWithInputAndOutput.data ? (
<NewDatasetItemFromTrace
traceId={preloadedObservation.traceId}
diff --git a/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx
new file mode 100644
index 0000000000..9d64ea2d7d
--- /dev/null
+++ b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -0,0 +1,170 @@
+import { Terminal } from "lucide-react";
+import Link from "next/link";
+
+import { Button } from "@/src/components/ui/button";
+import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";
+import { type PlaygroundCache } from "@/src/ee/features/playground/page/types";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import {
+ ChatMessageRole,
+ supportedModels as playgroundSupportedModels,
+ type Observation,
+ type Prompt,
+ type UIModelParams,
+ ZodModelConfig,
+} from "@langfuse/shared";
+import { useEffect, useState } from "react";
+import { PromptType } from "@/src/features/prompts/server/utils/validation";
+import { ChatMessageListSchema } from "@/src/features/prompts/components/NewPromptForm/validation";
+import { createEmptyMessage } from "@/src/components/ChatMessages/utils/createEmptyMessage";
+import { getIsCloudEnvironment } from "@/src/ee/utils/getIsCloudEnvironment";
+
+type JumpToPlaygroundButtonProps = (
+ | {
+ source: "prompt";
+ prompt: Prompt;
+ analyticsEventName: "prompt_detail:test_in_playground_button_click";
+ }
+ | {
+ source: "generation";
+ generation: Observation;
+ analyticsEventName: "trace_detail:test_in_playground_button_click";
+ }
+) & {
+ fullWidth?: boolean;
+};
+
+export const JumpToPlaygroundButton: React.FC<JumpToPlaygroundButtonProps> = (
+ props,
+) => {
+ const capture = usePostHogClientCapture();
+ const projectId = useProjectIdFromURL();
+ const { setPlaygroundCache } = usePlaygroundCache();
+ const [capturedState, setCapturedState] = useState<PlaygroundCache>(null);
+
+ useEffect(() => {
+ if (props.source === "prompt") {
+ setCapturedState(parsePrompt(props.prompt));
+ } else if (props.source === "generation") {
+ setCapturedState(parseGeneration(props.generation));
+ }
+ }, [props]);
+
+ const handleClick = () => {
+ capture(props.analyticsEventName);
+ setPlaygroundCache(capturedState);
+ };
+
+ if (!getIsCloudEnvironment()) return null;
+
+ return (
+ <Button
+ variant={props.fullWidth ? "secondary" : "outline"}
+ title="Test in LLM playground"
+ size={!props.fullWidth ? "icon" : undefined}
+ onClick={handleClick}
+ asChild
+ >
+ <Link href={`/project/${projectId}/playground`}>
+ <Terminal className="h-5 w-5" />
+ {props.fullWidth ? (
+ <span className="ml-2">Test in playground</span>
+ ) : null}
+ </Link>
+ </Button>
+ );
+};
+
+const parsePrompt = (prompt: Prompt): PlaygroundCache => {
+ if (prompt.type === PromptType.Chat) {
+ const parsedMessages = ChatMessageListSchema.safeParse(prompt.prompt);
+
+ return parsedMessages.success ? { messages: parsedMessages.data } : null;
+ } else {
+ const promptString = prompt.prompt?.valueOf();
+
+ return {
+ messages: [
+ createEmptyMessage(
+ ChatMessageRole.System,
+ typeof promptString === "string" ? promptString : "",
+ ),
+ ],
+ };
+ }
+};
+
+const parseGeneration = (generation: Observation): PlaygroundCache => {
+ if (generation.type !== "GENERATION") return null;
+
+ const modelParams = parseModelParams(generation);
+ const input = generation.input?.valueOf();
+
+ if (typeof input === "string") {
+ return {
+ messages: [createEmptyMessage(ChatMessageRole.System, input)],
+ modelParams,
+ };
+ }
+
+ if (typeof input === "object") {
+ const parsedMessages = ChatMessageListSchema.safeParse(input);
+
+ if (parsedMessages.success)
+ return { messages: parsedMessages.data, modelParams };
+ }
+
+ if (typeof input === "object" && "messages" in input) {
+ const parsedMessages = ChatMessageListSchema.safeParse(input["messages"]);
+
+ if (parsedMessages.success)
+ return { messages: parsedMessages.data, modelParams };
+ }
+
+ return null;
+};
+
+function parseModelParams(
+ generation: Observation,
+):
+ | (Partial<UIModelParams> & Pick<UIModelParams, "provider" | "model">)
+ | undefined {
+ const generationModel = generation.model?.valueOf();
+ let modelParams:
+ | (Partial<UIModelParams> & Pick<UIModelParams, "provider" | "model">)
+ | undefined = undefined;
+
+ if (generationModel) {
+ const provider = Object.entries(playgroundSupportedModels).find(
+ ([_, models]) =>
+ generationModel ? models.some((m) => m === generationModel) : false,
+ )?.[0];
+
+ if (!provider) return;
+
+ modelParams = {
+ provider: { value: provider, enabled: true },
+ model: { value: generationModel, enabled: true },
+ } as Partial<UIModelParams> & Pick<UIModelParams, "provider" | "model">;
+
+ const generationModelParams = generation.modelParameters?.valueOf();
+
+ if (generationModelParams && typeof generationModelParams === "object") {
+ const parsedParams = ZodModelConfig.safeParse(generationModelParams);
+
+ if (parsedParams.success) {
+ Object.entries(parsedParams.data).forEach(([key, value]) => {
+ if (!modelParams) return;
+
+ modelParams[key as keyof typeof parsedParams.data] = {
+ value,
+ enabled: true,
+ };
+ });
+ }
+ }
+ }
+
+ return modelParams;
+}
diff --git a/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsx b/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsx
new file mode 100644
index 0000000000..81ae74b136
--- /dev/null
+++ b/web/src/ee/features/playground/page/components/ResetPlaygroundButton.tsx
@@ -0,0 +1,28 @@
+import { ListRestartIcon } from "lucide-react";
+import { useRouter } from "next/router";
+
+import { Button } from "@/src/components/ui/button";
+import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";
+import { getIsCloudEnvironment } from "@/src/ee/utils/getIsCloudEnvironment";
+
+export const ResetPlaygroundButton: React.FC = () => {
+ const router = useRouter();
+ const { setPlaygroundCache } = usePlaygroundCache();
+
+ const handleClick = () => {
+ setPlaygroundCache(null);
+
+ router.reload();
+ };
+
+ return getIsCloudEnvironment() ? (
+ <Button
+ variant={"outline"}
+ title="Reset playground state"
+ onClick={handleClick}
+ >
+ <ListRestartIcon className="mr-1 h-5 w-5" />
+ <span>Reset playground</span>
+ </Button>
+ ) : null;
+};
diff --git a/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx b/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx
new file mode 100644
index 0000000000..4288bd7ea0
--- /dev/null
+++ b/web/src/ee/features/playground/page/components/SaveToPromptButton.tsx
@@ -0,0 +1,161 @@
+import { Check, FileInput } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/router";
+import { useState } from "react";
+
+import { Button } from "@/src/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/src/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { usePlaygroundContext } from "@/src/ee/features/playground/page/context";
+import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";
+import { getIsCloudEnvironment } from "@/src/ee/utils/getIsCloudEnvironment";
+import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import { PromptType } from "@/src/features/prompts/server/utils/validation";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { api } from "@/src/utils/api";
+import { cn } from "@/src/utils/tailwind";
+
+export const SaveToPromptButton: React.FC = () => {
+ const [open, setOpen] = useState(false);
+ const [selectedPromptId, setSelectedPromptId] = useState("");
+ const { modelParams, messages, output, promptVariables } =
+ usePlaygroundContext();
+ const capture = usePostHogClientCapture();
+ const router = useRouter();
+ const projectId = useProjectIdFromURL();
+ const { setPlaygroundCache } = usePlaygroundCache();
+
+ const allPromptNames =
+ api.prompts.all
+ .useQuery(
+ {
+ projectId: projectId as string, // Typecast as query is enabled only when projectId is present
+ filter: [],
+ orderBy: { column: "name", order: "ASC" },
+ page: 0,
+ },
+ { enabled: Boolean(projectId) },
+ )
+ .data?.prompts.filter((prompt) => prompt.type === PromptType.Chat)
+ .map((prompt) => ({
+ label:
+ prompt.name.slice(0, 20) + (prompt.name.length > 25 ? "..." : ""),
+ value: prompt.id,
+ })) ?? [];
+
+ const handleNewPrompt = async () => {
+ capture("playground:save_to_new_prompt_button_click", { projectId });
+
+ setPlaygroundCache({
+ modelParams,
+ messages,
+ output,
+ promptVariables,
+ });
+
+ await router.push(
+ `/project/${projectId}/prompts/new?loadPlaygroundCache=true`,
+ );
+ };
+
+ const handleNewPromptVersion = async () => {
+ capture("playground:save_to_prompt_version_button_click", { projectId });
+
+ setPlaygroundCache({
+ modelParams,
+ messages,
+ output,
+ promptVariables,
+ });
+
+ await router.push(
+ `/project/${projectId}/prompts/new?promptId=${selectedPromptId}&loadPlaygroundCache=true`,
+ );
+ };
+
+ if (!getIsCloudEnvironment()) return null;
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button variant={"outline"} title="Save to prompt" asChild>
+ <Link href={`/project/${projectId}/playground`}>
+ <FileInput className="mr-1 h-5 w-5" />
+ <span>Save as prompt</span>
+ </Link>
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent>
+ <Button className="mt-2 w-full" onClick={handleNewPrompt}>
+ Save as new prompt
+ </Button>
+ <Divider />
+ <Command className="min-h-[8rem]">
+ <CommandInput placeholder="Search chat prompts..." />
+ <CommandEmpty>No chat prompt found.</CommandEmpty>
+ <CommandGroup className="mt-2">
+ <CommandList>
+ {allPromptNames.map((promptName) => (
+ <CommandItem
+ key={promptName.value}
+ title={promptName.label}
+ value={promptName.value}
+ onSelect={(currentValue) => {
+ setSelectedPromptId(
+ currentValue === selectedPromptId ? "" : currentValue,
+ );
+ setOpen(false);
+ }}
+ >
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ selectedPromptId === promptName.value
+ ? "opacity-100"
+ : "opacity-0",
+ )}
+ />
+ {promptName.label}
+ </CommandItem>
+ ))}
+ </CommandList>
+ </CommandGroup>
+ </Command>
+ <Button
+ className="mt-2 w-full"
+ disabled={!Boolean(selectedPromptId)}
+ onClick={handleNewPromptVersion}
+ >
+ Save as new prompt version
+ </Button>
+ </PopoverContent>
+ </Popover>
+ );
+};
+
+export function Divider() {
+ return (
+ <div className="my-6 flex flex-row justify-center align-middle">
+ <div className="flex flex-1 flex-col">
+ <div className="flex-1 border-b-2 border-gray-200" />
+ <div className="flex-1" />
+ </div>
+ <p className="mx-2 text-sm text-gray-400">or</p>
+ <div className="flex flex-1 flex-col">
+ <div className="flex-1 border-b-2 border-gray-200" />
+ <div className="flex-1" />
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/ee/features/playground/page/context/index.tsx b/web/src/ee/features/playground/page/context/index.tsx
index 9d5bd6b843..c318360929 100644
--- a/web/src/ee/features/playground/page/context/index.tsx
+++ b/web/src/ee/features/playground/page/context/index.tsx
@@ -7,17 +7,13 @@ import React, {
useState,
} from "react";
-import { StringParam, useQueryParam } from "use-query-params";
import { v4 as uuidv4 } from "uuid";
import { createEmptyMessage } from "@/src/components/ChatMessages/utils/createEmptyMessage";
import useCommandEnter from "@/src/ee/features/playground/page/hooks/useCommandEnter";
+import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";
import { getFinalModelParams } from "@/src/ee/utils/getFinalModelParams";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { ChatMessageListSchema } from "@/src/features/prompts/components/NewPromptForm/validation";
-import { PromptType } from "@/src/features/prompts/server/utils/validation";
-import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
-import { api } from "@/src/utils/api";
import { extractVariables } from "@/src/utils/string";
import {
ChatMessageRole,
@@ -40,7 +36,6 @@ type PlaygroundContextType = {
handleSubmit: () => Promise<void>;
isStreaming: boolean;
- isInitializing: boolean;
} & ModelParamsContext &
MessagesContext;
@@ -61,9 +56,8 @@ export const usePlaygroundContext = () => {
export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
children,
}) => {
- const projectId = useProjectIdFromURL();
const capture = usePostHogClientCapture();
- const [initialPromptId] = useQueryParam("promptId", StringParam);
+ const { playgroundCache, setPlaygroundCache } = usePlaygroundCache();
const [promptVariables, setPromptVariables] = useState<PromptVariable[]>([]);
const [output, setOutput] = useState("");
const [outputJson, setOutputJson] = useState("");
@@ -76,35 +70,32 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
getDefaultModelParams(ModelProvider.OpenAI),
);
- const { data: initialPrompt, isInitialLoading } = api.prompts.byId.useQuery(
- {
- projectId: projectId as string, // Typecast as query is enabled only when projectId is present
- id: initialPromptId ?? "",
- },
- { enabled: Boolean(initialPromptId && projectId), staleTime: Infinity }, // do not refetch as this would overwrite the user's input
- );
-
+ // Load state from cache
useEffect(() => {
- if (!initialPrompt) return;
- if (initialPrompt.type === PromptType.Chat) {
- try {
- const initialMessages = ChatMessageListSchema.parse(
- initialPrompt.prompt,
- );
- setMessages(initialMessages.map((m) => ({ ...m, id: uuidv4() })));
- } catch (err) {
- console.warn("Failed to parse initial chat messages", err);
- }
- } else {
- const promptString = initialPrompt.prompt?.valueOf();
- setMessages([
- createEmptyMessage(
- ChatMessageRole.System,
- typeof promptString === "string" ? promptString : "",
- ),
- ]);
+ if (!playgroundCache) return;
+
+ const {
+ messages: cachedMessages,
+ modelParams: cachedModelParams,
+ output: cachedOutput,
+ promptVariables: cachedPromptVariables,
+ } = playgroundCache;
+
+ setMessages(cachedMessages.map((m) => ({ ...m, id: uuidv4() })));
+
+ if (cachedOutput) {
+ setOutput(cachedOutput);
+ setOutputJson("");
+ }
+
+ if (cachedModelParams) {
+ setModelParams((prev) => ({ ...prev, ...cachedModelParams }));
}
- }, [initialPrompt]);
+
+ if (cachedPromptVariables) {
+ setPromptVariables(cachedPromptVariables);
+ }
+ }, [playgroundCache]);
useEffect(() => {
setModelParams(getDefaultModelParams(modelParams.provider.value));
@@ -191,6 +182,12 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
setOutput(response);
}
setOutputJson(getOutputJson(response, finalMessages, modelParams));
+ setPlaygroundCache({
+ messages,
+ modelParams,
+ output: response,
+ promptVariables,
+ });
capture("playground:execute_button_click", {
inputLength: finalMessages.length,
modelName: modelParams.model,
@@ -258,7 +255,6 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
outputJson,
handleSubmit,
isStreaming,
- isInitializing: isInitialLoading,
}}
>
{children}
diff --git a/web/src/ee/features/playground/page/hooks/usePlaygroundCache.ts b/web/src/ee/features/playground/page/hooks/usePlaygroundCache.ts
new file mode 100644
index 0000000000..14ec16ccb5
--- /dev/null
+++ b/web/src/ee/features/playground/page/hooks/usePlaygroundCache.ts
@@ -0,0 +1,30 @@
+import { useEffect, useState } from "react";
+
+import { getIsCloudEnvironment } from "@/src/ee/utils/getIsCloudEnvironment";
+import { type PlaygroundCache } from "../types";
+
+const playgroundCacheKey = "playgroundCache";
+
+export default function usePlaygroundCache() {
+ const [cache, setCache] = useState<PlaygroundCache>(null);
+
+ const setPlaygroundCache = (cache: PlaygroundCache) => {
+ sessionStorage.setItem(playgroundCacheKey, JSON.stringify(cache));
+ };
+
+ useEffect(() => {
+ const savedCache = sessionStorage.getItem(playgroundCacheKey);
+ if (savedCache) {
+ try {
+ setCache(JSON.parse(savedCache));
+ } catch (e) {
+ console.error("Failed to parse playground cache", e);
+ }
+ }
+ }, []);
+
+ return {
+ playgroundCache: getIsCloudEnvironment() ? cache : null,
+ setPlaygroundCache: getIsCloudEnvironment() ? setPlaygroundCache : () => {},
+ };
+}
diff --git a/web/src/ee/features/playground/page/index.tsx b/web/src/ee/features/playground/page/index.tsx
index fb9f8829a7..f4051db336 100644
--- a/web/src/ee/features/playground/page/index.tsx
+++ b/web/src/ee/features/playground/page/index.tsx
@@ -1,24 +1,32 @@
import Header from "@/src/components/layouts/header";
-import Playground from "@/src/ee/features/playground/page/playground";
+import { ResetPlaygroundButton } from "@/src/ee/features/playground/page/components/ResetPlaygroundButton";
+import { SaveToPromptButton } from "@/src/ee/features/playground/page/components/SaveToPromptButton";
import { PlaygroundProvider } from "@/src/ee/features/playground/page/context";
+import Playground from "@/src/ee/features/playground/page/playground";
import { getIsCloudEnvironment } from "@/src/ee/utils/getIsCloudEnvironment";
export default function PlaygroundPage() {
return getIsCloudEnvironment() ? (
- <div className="flex h-[95vh] flex-col">
- <Header
- title="Playground"
- help={{
- description: "A sandbox to test and iterate your prompts",
- href: "https://langfuse.com/docs/playground",
- }}
- featureBetaURL="https://github.com/orgs/langfuse/discussions/1170"
- />
- <div className="flex-1 overflow-auto">
- <PlaygroundProvider>
+ <PlaygroundProvider>
+ <div className="flex h-[95vh] flex-col">
+ <Header
+ title="Playground"
+ help={{
+ description: "A sandbox to test and iterate your prompts",
+ href: "https://langfuse.com/docs/playground",
+ }}
+ featureBetaURL="https://github.com/orgs/langfuse/discussions/1170"
+ actionButtons={
+ <>
+ <SaveToPromptButton />
+ <ResetPlaygroundButton />
+ </>
+ }
+ />
+ <div className="flex-1 overflow-auto">
<Playground />
- </PlaygroundProvider>
+ </div>
</div>
- </div>
+ </PlaygroundProvider>
) : null;
}
diff --git a/web/src/ee/features/playground/page/playground.tsx b/web/src/ee/features/playground/page/playground.tsx
index fcce646570..1acd09d43e 100644
--- a/web/src/ee/features/playground/page/playground.tsx
+++ b/web/src/ee/features/playground/page/playground.tsx
@@ -6,10 +6,6 @@ import { Messages } from "./components/Messages";
export default function Playground() {
const playgroundContext = usePlaygroundContext();
- if (playgroundContext.isInitializing) {
- return <div>Loading...</div>;
- }
-
return (
<div className="flex h-full flex-row space-x-8">
<div className="h-full basis-3/4 overflow-auto">
diff --git a/web/src/ee/features/playground/page/types.ts b/web/src/ee/features/playground/page/types.ts
new file mode 100644
index 0000000000..c65b2f6f33
--- /dev/null
+++ b/web/src/ee/features/playground/page/types.ts
@@ -0,0 +1,13 @@
+import {
+ type PromptVariable,
+ type ChatMessage,
+ type UIModelParams,
+} from "@langfuse/shared";
+
+export type PlaygroundCache = {
+ messages: ChatMessage[];
+ modelParams?: Partial<UIModelParams> &
+ Pick<UIModelParams, "provider" | "model">;
+ output?: string | null;
+ promptVariables?: PromptVariable[];
+} | null;
diff --git a/web/src/ee/utils/getIsCloudEnvironment.ts b/web/src/ee/utils/getIsCloudEnvironment.ts
index 720623c263..0ccbecb556 100644
--- a/web/src/ee/utils/getIsCloudEnvironment.ts
+++ b/web/src/ee/utils/getIsCloudEnvironment.ts
@@ -1,4 +1,4 @@
import { env } from "@/src/env.mjs";
-export const getIsCloudEnvironment = () =>
- Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)
+export const getIsCloudEnvironment = () =>
+ Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
diff --git a/web/src/features/posthog-analytics/usePostHogClientCapture.ts b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
index 8e2f38e526..2273063bde 100644
--- a/web/src/features/posthog-analytics/usePostHogClientCapture.ts
+++ b/web/src/features/posthog-analytics/usePostHogClientCapture.ts
@@ -24,6 +24,7 @@ const events = {
"observation_tree_toggle_scores",
"observation_tree_toggle_metrics",
"io_mode_switch",
+ "test_in_playground_button_click",
],
generations: ["export"],
score: [
@@ -58,7 +59,11 @@ const events = {
],
integrations: ["posthog_form_submitted"],
sign_in: ["cloud_region_switch", "button_click"],
- playground: ["execute_button_click"],
+ playground: [
+ "execute_button_click",
+ "save_to_new_prompt_button_click",
+ "save_to_prompt_version_button_click",
+ ],
dashboard: ["chart_tab_switch", "date_range_changed"],
datasets: [
"delete_form_open",
diff --git a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx
index b9a77aea3b..3759593201 100644
--- a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx
@@ -1,36 +1,45 @@
import { useEffect, useState } from "react";
-import type { ControllerRenderProps } from "react-hook-form";
+import { v4 as uuidv4 } from "uuid";
+
import { ChatMessages } from "@/src/components/ChatMessages";
-import { ChatMessageRole } from "@langfuse/shared";
import { createEmptyMessage } from "@/src/components/ChatMessages/utils/createEmptyMessage";
-import type { MessagesContext } from "@/src/components/ChatMessages/types";
+import { ChatMessageRole, type ChatMessageWithId } from "@langfuse/shared";
+
import {
ChatMessageListSchema,
type NewPromptFormSchemaType,
} from "./validation";
-import { v4 as uuidv4 } from "uuid";
+
+import type { ControllerRenderProps } from "react-hook-form";
+import type { MessagesContext } from "@/src/components/ChatMessages/types";
type PromptChatMessagesProps = ControllerRenderProps<
NewPromptFormSchemaType,
"chatPrompt"
->;
+> & { initialMessages: unknown };
+
export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({
onChange,
- value,
+ initialMessages,
}) => {
- let initialMessages;
- try {
- if (value.length === 0) throw Error("Empty array");
-
- initialMessages = ChatMessageListSchema.parse(value).map((message) => ({
- ...message,
- id: uuidv4(),
- }));
- } catch (err) {
- initialMessages = [createEmptyMessage(ChatMessageRole.System)];
- }
-
- const [messages, setMessages] = useState(initialMessages);
+ const [messages, setMessages] = useState<ChatMessageWithId[]>([]);
+
+ useEffect(() => {
+ const parsedMessages = ChatMessageListSchema.safeParse(initialMessages);
+
+ if (!parsedMessages.success || !parsedMessages.data.length) {
+ setMessages([createEmptyMessage(ChatMessageRole.System)]);
+
+ return;
+ }
+
+ setMessages(
+ parsedMessages.data.map((message) => ({
+ ...message,
+ id: uuidv4(),
+ })),
+ );
+ }, [initialMessages]);
const addMessage: MessagesContext["addMessage"] = (role, content) => {
const message = createEmptyMessage(role, content);
diff --git a/web/src/features/prompts/components/NewPromptForm/index.tsx b/web/src/features/prompts/components/NewPromptForm/index.tsx
index 89f4624d35..49c5236df7 100644
--- a/web/src/features/prompts/components/NewPromptForm/index.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/index.tsx
@@ -43,6 +43,8 @@ import { PromptDescription } from "@/src/features/prompts/components/prompt-desc
import { JsonEditor } from "@/src/components/json-editor";
import { PRODUCTION_LABEL } from "@/src/features/prompts/constants";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";
+import { useQueryParam } from "use-query-params";
type NewPromptFormProps = {
initialPrompt?: Prompt | null;
@@ -52,7 +54,11 @@ type NewPromptFormProps = {
export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
const { onFormSuccess, initialPrompt } = props;
const projectId = useProjectIdFromURL();
+ const [shouldLoadPlaygroundCache] = useQueryParam("loadPlaygroundCache");
const [formError, setFormError] = useState<string | null>(null);
+ const { playgroundCache } = usePlaygroundCache();
+ const [initialMessages, setInitialMessages] = useState<unknown>([]);
+
const utils = api.useUtils();
const capture = usePostHogClientCapture();
@@ -158,6 +164,16 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
});
}
+ useEffect(() => {
+ if (shouldLoadPlaygroundCache && playgroundCache) {
+ form.setValue("type", PromptType.Chat);
+
+ setInitialMessages(playgroundCache.messages);
+ } else if (initialPrompt?.type === PromptType.Chat) {
+ setInitialMessages(initialPrompt.prompt);
+ }
+ }, [playgroundCache, initialPrompt, form, shouldLoadPlaygroundCache]);
+
useEffect(() => {
const isNewPrompt = !allPrompts
?.map((prompt) => prompt.value)
@@ -279,7 +295,10 @@ export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
name="chatPrompt"
render={({ field }) => (
<>
- <PromptChatMessages {...field} />
+ <PromptChatMessages
+ {...field}
+ initialMessages={initialMessages}
+ />
<FormMessage />
</>
)}
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index 42adb43181..9871e4f7b7 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -33,7 +33,7 @@ import {
AccordionTrigger,
} from "@/src/components/ui/accordion";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
-import { isEeAvailable } from "@langfuse/ee";
+import { JumpToPlaygroundButton } from "@/src/ee/features/playground/page/components/JumpToPlaygroundButton";
export const PromptDetail = () => {
const projectId = useProjectIdFromURL();
@@ -113,23 +113,11 @@ export const PromptDetail = () => {
<>
<SetPromptVersionLabels prompt={prompt} />
- {isEeAvailable && (
- <Button
- variant="outline"
- title="Test in prompt playground"
- size="icon"
- onClick={() =>
- capture("prompt_detail:test_in_playground_button_click")
- }
- asChild
- >
- <Link
- href={`/project/${projectId}/playground?promptId=${encodeURIComponent(prompt.id)}`}
- >
- <Terminal className="h-5 w-5" />
- </Link>
- </Button>
- )}
+ <JumpToPlaygroundButton
+ source="prompt"
+ prompt={prompt}
+ analyticsEventName="prompt_detail:test_in_playground_button_click"
+ />
<Button
variant="outline"