🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(playground): allow non-streaming responses (#7344)
Hassieb Pakzad926c2b8e4520
diff --git a/web/src/env.mjs b/web/src/env.mjsindex e1ef24d70c..6c0b3415d3 100644--- a/web/src/env.mjs+++ b/web/src/env.mjs@@ -294,6 +294,10 @@ export const env = createEnv({NEXT_PUBLIC_PLAIN_APP_ID: z.string().optional(),NEXT_PUBLIC_BUILD_ID: z.string().optional(),NEXT_PUBLIC_BASE_PATH: z.string().optional(),+ NEXT_PUBLIC_LANGFUSE_PLAYGROUND_STREAMING_ENABLED_DEFAULT: z+ .enum(["true", "false"])+ .optional()+ .default("true"),},/**@@ -493,6 +497,9 @@ export const env = createEnv({process.env.LANGFUSE_UI_VISIBLE_PRODUCT_MODULES,LANGFUSE_UI_HIDDEN_PRODUCT_MODULES:process.env.LANGFUSE_UI_HIDDEN_PRODUCT_MODULES,+ // Playground+ NEXT_PUBLIC_LANGFUSE_PLAYGROUND_STREAMING_ENABLED_DEFAULT:+ process.env.NEXT_PUBLIC_LANGFUSE_PLAYGROUND_STREAMING_ENABLED_DEFAULT,// EE LicenseLANGFUSE_EE_LICENSE_KEY: process.env.LANGFUSE_EE_LICENSE_KEY,ADMIN_API_KEY: process.env.ADMIN_API_KEY,diff --git a/web/src/features/playground/page/components/Messages.tsx b/web/src/features/playground/page/components/Messages.tsxindex 1bd1f00b75..d7b61ca54d 100644--- a/web/src/features/playground/page/components/Messages.tsx+++ b/web/src/features/playground/page/components/Messages.tsx@@ -1,5 +1,16 @@import { Button } from "@/src/components/ui/button";import { usePlaygroundContext } from "@/src/features/playground/page/context";+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/src/components/ui/dropdown-menu";+import { Switch } from "@/src/components/ui/switch";+import { Settings } from "lucide-react";+import useLocalStorage from "@/src/components/useLocalStorage";+import { env } from "@/src/env.mjs";+import useCommandEnter from "@/src/features/playground/page/hooks/useCommandEnter";import { GenerationOutput } from "./GenerationOutput";import { ChatMessages } from "@/src/components/ChatMessages";@@ -33,16 +44,60 @@ export const Messages: React.FC<MessagesContext> = (props) => {const SubmitButton = () => {const { handleSubmit, isStreaming } = usePlaygroundContext();+ const defaultStreamingEnabled =+ env.NEXT_PUBLIC_LANGFUSE_PLAYGROUND_STREAMING_ENABLED_DEFAULT === "true";+ const [streamingEnabled, setStreamingEnabled] = useLocalStorage(+ "langfuse-playground-streaming",+ defaultStreamingEnabled,+ );++ // Handle command+enter with streaming preference+ useCommandEnter(!isStreaming, async () => {+ await handleSubmit(streamingEnabled);+ });return (- <Button- className="flex-0"- onClick={() => {- handleSubmit().catch((err) => console.error(err));- }}- loading={isStreaming}- >- <p>Submit (Ctrl + Enter)</p>- </Button>+ <div className="flex items-center gap-2">+ <Button+ className="flex-1"+ onClick={() => {+ handleSubmit(streamingEnabled).catch((err) => console.error(err));+ }}+ loading={isStreaming}+ >+ <p>Submit (Ctrl + Enter)</p>+ </Button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="h-8 w-8 focus:outline-none focus:ring-0 focus-visible:ring-0"+ disabled={isStreaming}+ >+ <Settings className="h-4 w-4" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-52">+ <DropdownMenuItem+ className="flex cursor-pointer items-center justify-between py-2.5"+ onClick={(e) => e.preventDefault()}+ >+ <div className="flex flex-col">+ <span className="font-medium">Stream responses</span>+ <span className="text-xs text-muted-foreground">+ {streamingEnabled+ ? "Real-time response streaming"+ : "Complete response at once"}+ </span>+ </div>+ <Switch+ checked={streamingEnabled}+ onCheckedChange={setStreamingEnabled}+ />+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>);};diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsxindex 50fc3f9c47..8b390179b1 100644--- a/web/src/features/playground/page/context/index.tsx+++ b/web/src/features/playground/page/context/index.tsx@@ -10,7 +10,6 @@ import React, {import { v4 as uuidv4 } from "uuid";import { createEmptyMessage } from "@/src/components/ChatMessages/utils/createEmptyMessage";-import useCommandEnter from "@/src/features/playground/page/hooks/useCommandEnter";import { useModelParams } from "@/src/features/playground/page/hooks/useModelParams";import usePlaygroundCache from "@/src/features/playground/page/hooks/usePlaygroundCache";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";@@ -52,7 +51,7 @@ type PlaygroundContextType = {outputJson: string;outputToolCalls: LLMToolCall[];- handleSubmit: () => Promise<void>;+ handleSubmit: (streaming?: boolean) => Promise<void>;isStreaming: boolean;} & ModelParamsContext &MessagesContext;@@ -257,8 +256,8 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({[],);- const handleSubmit: PlaygroundContextType["handleSubmit"] =- useCallback(async () => {+ const handleSubmit: PlaygroundContextType["handleSubmit"] = useCallback(+ async (streaming = true) => {try {setIsStreaming(true);setOutput("");@@ -291,6 +290,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({finalMessages,modelParams,tools,+ streaming,);const displayContent =@@ -310,18 +310,28 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({finalMessages,modelParams,structuredOutputSchema,+ streaming,);setOutput(response);} else {- const completionStream = getChatCompletionStream(- projectId,- finalMessages,- modelParams,- );-- for await (const token of completionStream) {- response += token;+ if (streaming) {+ const completionStream = getChatCompletionStream(+ projectId,+ finalMessages,+ modelParams,+ );++ for await (const token of completionStream) {+ response += token;+ setOutput(response);+ }+ } else {+ response = await getChatCompletionNonStreaming(+ projectId,+ finalMessages,+ modelParams,+ );setOutput(response);}}@@ -359,7 +369,8 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({} finally {setIsStreaming(false);}- }, [+ },+ [messages,modelParams,promptVariables,@@ -368,9 +379,10 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({setPlaygroundCache,structuredOutputSchema,projectId,- ]);+ ],+ );- useCommandEnter(!isStreaming, handleSubmit);+ // Command enter handling moved to Messages component to access streaming preferenceconst updatePromptVariableValue = useCallback((variable: string, value: string) => {@@ -430,6 +442,7 @@ async function getChatCompletionWithTools(messages: ChatMessageWithId[],modelParams: UIModelParams,tools: unknown[],+ streaming: boolean = false,): Promise<ToolCallResponse> {if (!projectId) throw Error("Project ID is not set");@@ -438,6 +451,7 @@ async function getChatCompletionWithTools(messages,modelParams: getFinalModelParams(modelParams),tools,+ streaming,});const result = await fetch(`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chatCompletion`,@@ -469,6 +483,7 @@ async function getChatCompletionWithStructuredOutput(messages: ChatMessageWithId[],modelParams: UIModelParams,structuredOutputSchema: PlaygroundSchema | null,+ streaming: boolean = false,): Promise<string> {if (!projectId) throw Error("Project ID is not set");@@ -477,6 +492,7 @@ async function getChatCompletionWithStructuredOutput(messages,modelParams: getFinalModelParams(modelParams),structuredOutputSchema: structuredOutputSchema?.schema,+ streaming,});const result = await fetch(@@ -517,6 +533,7 @@ async function* getChatCompletionStream(projectId,messages,modelParams: getFinalModelParams(modelParams),+ streaming: true,});const result = await fetch(`${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chatCompletion`,@@ -555,6 +572,40 @@ async function* getChatCompletionStream(}}+async function getChatCompletionNonStreaming(+ projectId: string | undefined,+ messages: ChatMessageWithId[],+ modelParams: UIModelParams,+): Promise<string> {+ if (!projectId) {+ throw new Error("Project ID is not set");+ }++ const body = JSON.stringify({+ projectId,+ messages,+ modelParams: getFinalModelParams(modelParams),+ streaming: false,+ });++ const result = await fetch(+ `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chatCompletion`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body,+ },+ );++ if (!result.ok) {+ const errorData = await result.json();+ throw new Error(`Completion failed: ${errorData.message}`);+ }++ const responseData = await result.json();+ return responseData.content || "";+}+function getFinalMessages(promptVariables: PromptVariable[],messages: ChatMessageWithId[],diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.tsindex 0b34cd07a2..2fb6a7a38a 100644--- a/web/src/features/playground/server/chatCompletionHandler.ts+++ b/web/src/features/playground/server/chatCompletionHandler.ts@@ -25,7 +25,8 @@ export default async function chatCompletionHandler(req: NextRequest) {const body = validateChatCompletionBody(await req.json());const { userId } = await authorizeRequestOrThrow(body.projectId);- const { messages, modelParams, tools, structuredOutputSchema } = body;+ const { messages, modelParams, tools, structuredOutputSchema, streaming } =+ body;const LLMApiKey = await prisma.llmApiKeys.findFirst({where: {@@ -68,12 +69,21 @@ export default async function chatCompletionHandler(req: NextRequest) {return NextResponse.json(completion);}- const { completion } = await fetchLLMCompletion({- ...fetchLLMCompletionParams,- streaming: true,- });+ if (streaming) {+ const { completion } = await fetchLLMCompletion({+ ...fetchLLMCompletionParams,+ streaming,+ });- return new StreamingTextResponse(completion);+ return new StreamingTextResponse(completion);+ } else {+ const { completion } = await fetchLLMCompletion({+ ...fetchLLMCompletionParams,+ streaming,+ });++ return NextResponse.json({ content: completion });+ }} catch (err) {logger.error("Failed to handle chat completion", err);diff --git a/web/src/features/playground/server/validateChatCompletionBody.ts b/web/src/features/playground/server/validateChatCompletionBody.tsindex 73135d6403..505d2fbe14 100644--- a/web/src/features/playground/server/validateChatCompletionBody.ts+++ b/web/src/features/playground/server/validateChatCompletionBody.ts@@ -21,6 +21,7 @@ export const ChatCompletionBodySchema = z.object({modelParams: ModelParamsSchema,tools: z.array(LLMToolDefinitionSchema).optional(),structuredOutputSchema: LLMJSONSchema.optional(),+ streaming: z.boolean().optional().default(true),});export const validateChatCompletionBody = (input: unknown) => {