🪢 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): add tool call support (#6069)
Hassieb Pakzadb670abc6bc0a
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex d143193144..b9444b806d 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -401,6 +401,24 @@ export type LlmApiKeys = {config: unknown | null;project_id: string;};+export type LlmSchema = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ project_id: string;+ name: string;+ description: string;+ schema: unknown;+};+export type LlmTool = {+ id: string;+ created_at: Generated<Timestamp>;+ updated_at: Generated<Timestamp>;+ project_id: string;+ name: string;+ description: string;+ parameters: unknown;+};export type Media = {id: string;sha_256_hash: string;@@ -606,6 +624,8 @@ export type DB = {job_configurations: JobConfiguration;job_executions: JobExecution;llm_api_keys: LlmApiKeys;+ llm_schemas: LlmSchema;+ llm_tools: LlmTool;media: Media;membership_invitations: MembershipInvitation;models: Model;diff --git a/packages/shared/prisma/migrations/20250326180640_add_llm_tools_and_schemas_tables/migration.sql b/packages/shared/prisma/migrations/20250326180640_add_llm_tools_and_schemas_tables/migration.sqlnew file mode 100644index 0000000000..68c4cda393--- /dev/null+++ b/packages/shared/prisma/migrations/20250326180640_add_llm_tools_and_schemas_tables/migration.sql@@ -0,0 +1,37 @@+-- CreateTable+CREATE TABLE "llm_schemas" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT NOT NULL,+ "schema" JSON NOT NULL,++ CONSTRAINT "llm_schemas_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "llm_tools" (+ "id" TEXT NOT NULL,+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "description" TEXT NOT NULL,+ "parameters" JSON NOT NULL,++ CONSTRAINT "llm_tools_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "llm_schemas_project_id_name_key" ON "llm_schemas"("project_id", "name");++-- CreateIndex+CREATE UNIQUE INDEX "llm_tools_project_id_name_key" ON "llm_tools"("project_id", "name");++-- AddForeignKey+ALTER TABLE "llm_schemas" ADD CONSTRAINT "llm_schemas_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "llm_tools" ADD CONSTRAINT "llm_tools_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex f18907b79e..b9d2f9df94 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -142,6 +142,8 @@ model Project {LegacyObservation LegacyPrismaObservation[]LegacyScore LegacyPrismaScore[]PromptDependency PromptDependency[]+ LlmSchema LlmSchema[]+ LlmTool LlmTool[]@@index([orgId])@@map("projects")@@ -859,6 +861,7 @@ model SsoConfig {authProvider String @map("auth_provider") // e.g. "okta", ee/sso/types.tsauthConfig Json? @map("auth_config")+// e.g. { "clientId": "1234", "clientSecret": "5678" }, null if credentials from env should be used// secrets like clientSecret are encrypted on the application level@@map("sso_configs")@@ -1009,3 +1012,35 @@ model BillingMeterBackup {@@index([stripeCustomerId, meterId, startTime, endTime])@@map("billing_meter_backups")}++model LlmSchema {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)++ name String @map("name")+ description String @map("description")+ schema Json @map("schema") @db.Json++ @@unique([projectId, name])+ @@map("llm_schemas")+}++model LlmTool {+ id String @id @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")++ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)++ name String @map("name")+ description String @map("description")+ parameters Json @map("parameters") @db.Json++ @@unique([projectId, name])+ @@map("llm_tools")+}diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.tsindex a847c9eb0c..ab5a8d5bf9 100644--- a/packages/shared/prisma/seed.ts+++ b/packages/shared/prisma/seed.ts@@ -374,6 +374,46 @@ async function main() {});await createDatasets(project1, project2, observations);++ await prisma.llmSchema.createMany({+ data: [+ {+ projectId: project1.id,+ name: "get_weather",+ description: "Fetches weather in Celsius for a given location",+ schema: {+ type: "object",+ properties: {+ location: {+ type: "string",+ description: "The city and state, e.g. San Francisco, CA",+ },+ unit: {+ type: "string",+ enum: ["celsius", "fahrenheit"],+ },+ },+ required: ["location", "unit"],+ },+ },+ {+ projectId: project1.id,+ name: "calculator",+ description: "Performs basic arithmetic calculations",+ schema: {+ type: "object",+ properties: {+ expression: {+ type: "string",+ description:+ "The mathematical expression to evaluate, e.g. '2 + 2'",+ },+ },+ required: ["expression"],+ },+ },+ ],+ });}}diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex fe7146ccf6..381c8a5b51 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -1,4 +1,4 @@-import type { ZodSchema } from "zod";+import { type ZodSchema } from "zod";import { ChatAnthropic } from "@langchain/anthropic";import { ChatVertexAI } from "@langchain/google-vertexai";@@ -9,6 +9,7 @@ import {BaseMessage,HumanMessage,SystemMessage,+ ToolMessage,} from "@langchain/core/messages";import {BytesOutputParser,@@ -25,8 +26,13 @@ import { logger } from "../logger";import {ChatMessage,ChatMessageRole,+ ChatMessageType,LLMAdapter,+ LLMJSONSchema,+ LLMToolDefinition,ModelParams,+ ToolCallResponse,+ ToolCallResponseSchema,TraceParams,} from "./types";import { CallbackHandler } from "langfuse-langchain";@@ -37,7 +43,7 @@ type ProcessTracedEvents = () => Promise<void>;type LLMCompletionParams = {messages: ChatMessage[];modelParams: ModelParams;- structuredOutputSchema?: ZodSchema;+ structuredOutputSchema?: ZodSchema | LLMJSONSchema;callbacks?: BaseCallbackHandler[];baseURL?: string;apiKey: string;@@ -50,6 +56,7 @@ type LLMCompletionParams = {type FetchLLMCompletionParams = LLMCompletionParams & {streaming: boolean;+ tools?: LLMToolDefinition[];};export async function fetchLLMCompletion(@@ -65,7 +72,10 @@ export async function fetchLLMCompletion(params: LLMCompletionParams & {streaming: false;},-): Promise<{ completion: string; processTracedEvents: ProcessTracedEvents }>;+): Promise<{+ completion: string;+ processTracedEvents: ProcessTracedEvents;+}>;export async function fetchLLMCompletion(params: LLMCompletionParams & {@@ -73,19 +83,34 @@ export async function fetchLLMCompletion(structuredOutputSchema: ZodSchema;},): Promise<{- completion: unknown;+ completion: Record<string, unknown>;+ processTracedEvents: ProcessTracedEvents;+}>;++export async function fetchLLMCompletion(+ params: LLMCompletionParams & {+ tools: LLMToolDefinition[];+ streaming: false;+ },+): Promise<{+ completion: ToolCallResponse;processTracedEvents: ProcessTracedEvents;}>;export async function fetchLLMCompletion(params: FetchLLMCompletionParams,): Promise<{- completion: string | IterableReadableStream<Uint8Array> | unknown;+ completion:+ | string+ | IterableReadableStream<Uint8Array>+ | Record<string, unknown>+ | ToolCallResponse;processTracedEvents: ProcessTracedEvents;}> {// the apiKey must never be printed to the consoleconst {messages,+ tools,modelParams,streaming,callbacks,@@ -140,11 +165,25 @@ export async function fetchLLMCompletion()return new SystemMessage(message.content);- return new AIMessage(message.content);+ if (message.type === ChatMessageType.ToolResult)+ return new ToolMessage({+ content: message.content,+ tool_call_id: message.toolCallId,+ });++ return new AIMessage({+ content: message.content,+ tool_calls:+ message.type === ChatMessageType.AssistantToolCall+ ? (message.toolCalls as any)+ : undefined,+ });});}- finalMessages = finalMessages.filter((m) => m.content.length > 0);+ finalMessages = finalMessages.filter(+ (m) => m.content.length > 0 || "tool_calls" in m,+ );let chatModel:| ChatOpenAI@@ -320,6 +359,25 @@ export async function fetchLLMCompletion(};}+ if (tools && tools.length > 0) {+ const langchainTools = tools.map((tool) => ({+ type: "function",+ function: tool,+ }));++ const result = await chatModel+ .bindTools(langchainTools)+ .invoke(finalMessages, runConfig);++ const parsed = ToolCallResponseSchema.safeParse(result);+ if (!parsed.success) throw Error("Failed to parse LLM tool call result");++ return {+ completion: parsed.data,+ processTracedEvents,+ };+ }+if (streaming) {return {completion: await chatModel@@ -339,6 +397,7 @@ export async function fetchLLMCompletion(if (throwOnError) {throw error;}- return { completion: null, processTracedEvents };++ return { completion: "", processTracedEvents };}}diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.tsindex e8b09950d5..82a22ac8d1 100644--- a/packages/shared/src/server/llm/types.ts+++ b/packages/shared/src/server/llm/types.ts@@ -7,15 +7,192 @@ import { AuthHeaderValidVerificationResult } from "../auth/types";/* eslint-disable no-unused-vars */// disable lint as this is exported and used in web/worker-export type PromptVariable = { name: string; value: string; isUsed: boolean };+export const LLMJSONSchema = z.record(z.string(), z.unknown());+export type LLMJSONSchema = z.infer<typeof LLMJSONSchema>;-export type ChatMessage = {- role: ChatMessageRole | string; // Users may ingest any string as role via API/SDK- content: string;-};+export const JSONSchemaFormSchema = z+ .string()+ .transform((value, ctx) => {+ try {+ const parsed = JSON.parse(value);+ return parsed;+ } catch {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: "Parameters must be valid JSON",+ });+ return z.NEVER;+ }+ })+ .pipe(+ z+ .object({+ type: z.literal("object"),+ properties: z.record(z.any()),+ required: z.array(z.string()).optional(),+ additionalProperties: z.boolean().optional(),+ })+ .transform((data) => JSON.stringify(data, null, 2)),+ );++export const LLMToolDefinitionSchema = z.object({+ name: z.string(),+ description: z.string(),+ parameters: LLMJSONSchema,+});+export type LLMToolDefinition = z.infer<typeof LLMToolDefinitionSchema>;++const AnthropicMessageContentWithToolUse = z.union([+ z.object({+ type: z.literal("text"),+ text: z.string(),+ }),+ z.object({+ type: z.literal("tool_use"),+ id: z.string(),+ name: z.string(),+ input: z.unknown(),+ }),+]);++export const LLMToolCallSchema = z.object({+ name: z.string(),+ id: z.string(),+ args: z.record(z.string(), z.unknown()),+});+export type LLMToolCall = z.infer<typeof LLMToolCallSchema>;++export const OpenAIToolCallSchema = z.object({+ id: z.string(),+ function: z.object({+ name: z.string(),+ arguments: z.union([+ z.record(z.string(), z.unknown()),+ z+ .string()+ .transform((v) => JSON.parse(v))+ .pipe(z.record(z.string(), z.unknown())),+ ]),+ }),+ type: z.literal("function"),+});+export type OpenAIToolCallSchema = z.infer<typeof OpenAIToolCallSchema>;++export const OpenAIToolSchema = z.object({+ type: z.literal("function"),+ function: LLMToolDefinitionSchema,+});+export type OpenAIToolSchema = z.infer<typeof OpenAIToolSchema>;++export const OpenAIResponseFormatSchema = z.object({+ type: z.literal("json_schema"),+ json_schema: z.object({+ name: z.string(),+ schema: LLMJSONSchema,+ }),+});++export const ToolCallResponseSchema = z.object({+ content: z.union([z.string(), z.array(AnthropicMessageContentWithToolUse)]),+ tool_calls: z.array(LLMToolCallSchema),+});+export type ToolCallResponse = z.infer<typeof ToolCallResponseSchema>;+export enum ChatMessageRole {+ System = "system",+ Developer = "developer",+ User = "user",+ Assistant = "assistant",+ Tool = "tool",+}++export enum ChatMessageType {+ System = "system",+ Developer = "developer",+ User = "user",+ AssistantText = "assistant-text",+ AssistantToolCall = "assistant-tool-call",+ ToolResult = "tool-result",+ PublicAPICreated = "public-api-created",+}++export const SystemMessageSchema = z.object({+ type: z.literal(ChatMessageType.System),+ role: z.literal(ChatMessageRole.System),+ content: z.string(),+});+export type SystemMessage = z.infer<typeof SystemMessageSchema>;++export const DeveloperMessageSchema = z.object({+ type: z.literal(ChatMessageType.Developer),+ role: z.literal(ChatMessageRole.Developer),+ content: z.string(),+});+export type DeveloperMessage = z.infer<typeof DeveloperMessageSchema>;++export const UserMessageSchema = z.object({+ type: z.literal(ChatMessageType.User),+ role: z.literal(ChatMessageRole.User),+ content: z.string(),+});+export type UserMessage = z.infer<typeof UserMessageSchema>;++export const AssistantTextMessageSchema = z.object({+ type: z.literal(ChatMessageType.AssistantText),+ role: z.literal(ChatMessageRole.Assistant),+ content: z.string(),+});+export type AssistantTextMessage = z.infer<typeof AssistantTextMessageSchema>;++export const AssistantToolCallMessageSchema = z.object({+ type: z.literal(ChatMessageType.AssistantToolCall),+ role: z.literal(ChatMessageRole.Assistant),+ content: z.string(),+ toolCalls: z.array(LLMToolCallSchema),+});+export type AssistantToolCallMessage = z.infer<+ typeof AssistantToolCallMessageSchema+>;++export const ToolResultMessageSchema = z.object({+ type: z.literal(ChatMessageType.ToolResult),+ role: z.literal(ChatMessageRole.Tool),+ content: z.string(),+ toolCallId: z.string(),+});+export type ToolResultMessage = z.infer<typeof ToolResultMessageSchema>;++export const ChatMessageDefaultRoleSchema = z.nativeEnum(ChatMessageRole);+export const ChatMessageSchema = z.union([+ SystemMessageSchema,+ DeveloperMessageSchema,+ UserMessageSchema,+ AssistantTextMessageSchema,+ AssistantToolCallMessageSchema,+ ToolResultMessageSchema,+ z+ .object({+ role: z.union([ChatMessageDefaultRoleSchema, z.string()]), // Users may ingest any string as role via API/SDK+ content: z.string(),+ })+ .transform((msg) => {+ return {+ ...msg,+ type: ChatMessageType.PublicAPICreated as const,+ };+ }),+]);+export type ChatMessage = z.infer<typeof ChatMessageSchema>;export type ChatMessageWithId = ChatMessage & { id: string };+export const PromptChatMessageSchema = z.object({+ role: z.string(),+ content: z.string(),+});+export const PromptChatMessageListSchema = z.array(PromptChatMessageSchema);++export type PromptVariable = { name: string; value: string; isUsed: boolean };+export enum LLMAdapter {Anthropic = "anthropic",OpenAI = "openai",@@ -26,30 +203,15 @@ export enum LLMAdapter {GoogleAIStudio = "google-ai-studio",}-export enum ChatMessageRole {- System = "system",- User = "user",- Assistant = "assistant",- Developer = "developer",-}-export const SYSTEM_ROLES: string[] = [ChatMessageRole.System,ChatMessageRole.Developer,];-export const ChatMessageDefaultRoleSchema = z.nativeEnum(ChatMessageRole);--const ChatMessageSchema = z.object({- role: z.union([ChatMessageDefaultRoleSchema, z.string()]), // Users may ingest any string as role via API/SDK- content: z.string(),-});--export const ChatMessageListSchema = z.array(ChatMessageSchema);export const TextPromptSchema = z.string().min(1, "Enter a prompt");export const PromptContentSchema = z.union([- ChatMessageListSchema,+ PromptChatMessageListSchema,TextPromptSchema,]);export type PromptContent = z.infer<typeof PromptContentSchema>;diff --git a/packages/shared/src/server/services/sessions-ui-table-service.ts b/packages/shared/src/server/services/sessions-ui-table-service.tsindex 3994e36744..6a00ca0eed 100644--- a/packages/shared/src/server/services/sessions-ui-table-service.ts+++ b/packages/shared/src/server/services/sessions-ui-table-service.ts@@ -154,9 +154,10 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {session_output_usage,session_total_usage`;break;- default:+ default: {const exhaustiveCheckDefault: never = select;- throw new Error(`Unknown select type: ${select}`);+ throw new Error(`Unknown select type: ${exhaustiveCheckDefault}`);+ }}const { tracesFilter } = getProjectIdDefaultFilter(projectId, {diff --git a/web/src/components/ChatMessages/ChatMessageComponent.tsx b/web/src/components/ChatMessages/ChatMessageComponent.tsxindex 2b0942c6d5..f0d870a654 100644--- a/web/src/components/ChatMessages/ChatMessageComponent.tsx+++ b/web/src/components/ChatMessages/ChatMessageComponent.tsx@@ -2,9 +2,12 @@ import { capitalize } from "lodash";import { GripVertical, MinusCircleIcon } from "lucide-react";import { memo, useState, useCallback } from "react";import {+ type ChatMessage,ChatMessageRole,+ ChatMessageType,SYSTEM_ROLES,type ChatMessageWithId,+ type LLMToolCall,} from "@langfuse/shared";import { Button } from "@/src/components/ui/button";import { Card, CardContent } from "@/src/components/ui/card";@@ -13,18 +16,31 @@ import type { MessagesContext } from "./types";import { useSortable } from "@dnd-kit/sortable";import { cn } from "@/src/utils/tailwind";import { CSS } from "@dnd-kit/utilities";+import { ToolCallCard } from "./ToolCallCard";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/src/components/ui/select";type ChatMessageProps = Pick<MessagesContext,- "deleteMessage" | "updateMessage" | "availableRoles"+ | "deleteMessage"+ | "updateMessage"+ | "availableRoles"+ | "toolCallIds"+ | "replaceMessage"> & { message: ChatMessageWithId; index: number };-const ROLES: string[] = [+const ROLES: ChatMessageRole[] = [ChatMessageRole.User,ChatMessageRole.System,ChatMessageRole.Developer,ChatMessageRole.Assistant,-];+ ChatMessageRole.Tool,+] as const;const getRoleNamePlaceholder = (role: string) => {switch (role) {@@ -36,17 +52,33 @@ const getRoleNamePlaceholder = (role: string) => {return "an assistant";case ChatMessageRole.User:return "a user";+ case ChatMessageRole.Tool:+ return "a tool response";default:return `a ${role}`;}};+const ToolCalls: React.FC<{ toolCalls: LLMToolCall[] }> = ({ toolCalls }) => {+ if (!toolCalls || toolCalls.length === 0) return null;++ return (+ <div className="w-full space-y-2">+ {toolCalls.map((toolCall) => (+ <ToolCallCard key={toolCall.id} toolCall={toolCall} />+ ))}+ </div>+ );+};+export const ChatMessageComponent: React.FC<ChatMessageProps> = ({message,updateMessage,deleteMessage,+ replaceMessage,availableRoles,index,+ toolCallIds,}) => {const [roleIndex, setRoleIndex] = useState(1);@@ -66,31 +98,115 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({if (randomRole === message.role) {randomRole = availableRoles[(roleIndex + 1) % availableRoles.length];}- updateMessage(message.id, "role", randomRole);+ replaceMessage(message.id, {+ content: message.content,+ role: randomRole,+ type: ChatMessageType.PublicAPICreated,+ });setRoleIndex(roleIndex + 1);} else {// if user has not set custom roles, we toggle through default roles (assistant, user)if (index === 0) {- const currentIndex = ROLES.indexOf(message.role);- const nextRole = ROLES[(currentIndex + 1) % ROLES.length];- updateMessage(message.id, "role", nextRole);+ const eligibleRoles = ROLES.filter(+ (r) =>+ r !== ChatMessageRole.Tool ||+ (toolCallIds && toolCallIds.length > 0),+ );+ const currentIndex = eligibleRoles.indexOf(+ message.role as ChatMessageRole,+ );+ const nextRole =+ eligibleRoles[(currentIndex + 1) % eligibleRoles.length];++ if (nextRole === ChatMessageRole.User) {+ replaceMessage(message.id, {+ content: message.content,+ role: nextRole,+ type: ChatMessageType.User,+ });+ } else if (nextRole === ChatMessageRole.Assistant) {+ replaceMessage(message.id, {+ content: message.content,+ role: nextRole,+ type: ChatMessageType.AssistantText,+ });+ } else if (nextRole === ChatMessageRole.Tool) {+ replaceMessage(message.id, {+ content: message.content,+ role: nextRole,+ type: ChatMessageType.ToolResult,+ toolCallId: toolCallIds?.[0] ?? "",+ });+ } else if (nextRole === ChatMessageRole.Developer) {+ replaceMessage(message.id, {+ content: message.content,+ role: nextRole,+ type: ChatMessageType.Developer,+ });+ } else if (nextRole === ChatMessageRole.System) {+ replaceMessage(message.id, {+ content: message.content,+ role: nextRole,+ type: ChatMessageType.System,+ });+ } else {+ const exhaustiveCheck: never = nextRole;+ console.error(`Unhandled role: ${exhaustiveCheck}`);+ }} else {- updateMessage(- message.id,- "role",+ // Instead of directly updating the role, we need to replace the message with a new one+ // that has the appropriate type and role+ const newRole:+ | ChatMessageRole.User+ | ChatMessageRole.Assistant+ | ChatMessageRole.Tool =message.role === ChatMessageRole.User? ChatMessageRole.Assistant- : ChatMessageRole.User,- );+ : message.role === ChatMessageRole.Assistant &&+ toolCallIds &&+ toolCallIds.length > 0+ ? ChatMessageRole.Tool+ : ChatMessageRole.User;++ if (newRole === ChatMessageRole.User) {+ replaceMessage(message.id, {+ content: message.content,+ role: newRole,+ type: ChatMessageType.User,+ });+ } else if (newRole === ChatMessageRole.Assistant) {+ replaceMessage(message.id, {+ content: message.content,+ role: newRole,+ type: ChatMessageType.AssistantText,+ });+ } else if (newRole === ChatMessageRole.Tool) {+ replaceMessage(message.id, {+ content: message.content,+ role: newRole,+ type: ChatMessageType.ToolResult,+ toolCallId: toolCallIds?.[0] ?? "",+ });+ } else {+ const exhaustiveCheck: never = newRole;+ console.error(`Unhandled role: ${exhaustiveCheck}`);+ }}}};const onValueChange = useCallback(- (value: string) => updateMessage(message.id, "content", value),- [message.id, updateMessage],+ (value: string) =>+ updateMessage(message.type, message.id, "content", value),+ [message.id, message.type, updateMessage],);+ const showDragHandle = !SYSTEM_ROLES.includes(message.role);+ const showToolCallSelect =+ message.type === ChatMessageType.ToolResult &&+ toolCallIds &&+ toolCallIds.length > 0;+return (<Cardref={setNodeRef}@@ -100,50 +216,90 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({}}className={cn(isDragging ? "opacity-80" : "opacity-100",- "group relative whitespace-nowrap p-3",+ "shadow-xs group relative border p-1 transition-shadow duration-200 hover:shadow-sm",)}>- {!SYSTEM_ROLES.includes(message.role) && (- <div- {...attributes}- {...listeners}- className="absolute bottom-0 left-0 top-4 flex w-6 cursor-move justify-center"+ <div className="flex flex-row justify-center">+ {showDragHandle && (+ <div+ {...attributes}+ {...listeners}+ className="flex w-3 cursor-move items-center justify-center opacity-50 transition-opacity hover:opacity-100"+ >+ <GripVertical className="h-3 w-3" />+ </div>+ )}+ <CardContent+ className={cn(+ "flex flex-1 flex-row items-center gap-2 p-0",+ showDragHandle ? "pl-1" : "pl-4",+ )}>- <GripVertical className="h-4 w-4" />- </div>- )}- <CardContent className="ml-4 flex flex-row space-x-1 p-0">- <div className="min-w-[5rem]">+ <div className="flex w-[4rem] flex-shrink-0 flex-col gap-1">+ <Button+ onClick={toggleRole}+ type="button"+ variant="ghost"+ className="h-6 w-full px-1 py-0 text-[10px] font-semibold text-gray-500 hover:bg-gray-50"+ >+ {capitalize(message.role)}+ </Button>+ </div>+ <div className="flex flex-1 flex-col gap-1">+ <div className="flex gap-2">+ {showToolCallSelect && (+ <Select+ value={message.toolCallId}+ onValueChange={(value) =>+ updateMessage(+ ChatMessageType.ToolResult,+ message.id,+ "toolCallId",+ value,+ )+ }+ >+ <SelectTrigger className="h-[25px] w-[96px] border-0 bg-muted text-[9px]">+ <SelectValue placeholder="Tool Call ID" />+ </SelectTrigger>+ <SelectContent>+ {toolCallIds.map((id) => (+ <SelectItem key={id} value={id} className="text-[10px]">+ {id}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ <MemoizedEditor+ value={message.content}+ onChange={onValueChange}+ role={message.role}+ />+ </div>+ {message.type === ChatMessageType.AssistantToolCall && (+ <ToolCalls toolCalls={message.toolCalls as LLMToolCall[]} />+ )}+ </div><Button- onClick={toggleRole}- type="button" // prevents submitting a form if this button is inside a form- variant="outline"- className="px-2 text-xs"+ variant="ghost"+ type="button"+ size="icon"+ onClick={() => deleteMessage(message.id)}+ className="h-5 w-5 flex-shrink-0 rounded-full p-0 opacity-60 transition-all hover:opacity-100"+ aria-label="Delete message">- {capitalize(message.role)}+ <MinusCircleIcon size={14} /></Button>- </div>- <MemoizedEditor- value={message.content}- onChange={onValueChange}- role={message.role}- />- <Button- variant="ghost"- type="button" // prevents submitting a form if this button is inside a form- size="icon"- onClick={() => deleteMessage(message.id)}- >- <MinusCircleIcon size={16} />- </Button>- </CardContent>+ </CardContent>+ </div></Card>);};const MemoizedEditor = memo(function MemoizedEditor(props: {value: string;- role: (typeof ROLES)[1];+ role: ChatMessage["role"];onChange: (value: string) => void;}) {const { value, role, onChange } = props;@@ -154,8 +310,8 @@ const MemoizedEditor = memo(function MemoizedEditor(props: {value={value}onChange={onChange}mode="prompt"- minHeight={30}- className="w-full"+ minHeight="none"+ className="w-full rounded-md border-0"editable={true}lineNumbers={false}placeholder={placeholder}diff --git a/web/src/components/ChatMessages/ToolCallCard.tsx b/web/src/components/ChatMessages/ToolCallCard.tsxnew file mode 100644index 0000000000..89869297fd--- /dev/null+++ b/web/src/components/ChatMessages/ToolCallCard.tsx@@ -0,0 +1,36 @@+import { type LLMToolCall } from "@langfuse/shared";+import { JSONView } from "@/src/components/ui/CodeJsonViewer";++export const ToolCallCard: React.FC<{ toolCall: LLMToolCall }> = ({+ toolCall,+}) => {+ return (+ <div className="my-1 rounded border border-gray-200 p-2 text-sm dark:border-gray-700">+ <div className="flex flex-row gap-4">+ <div className="flex w-[15%] flex-col overflow-hidden">+ <div className="text-xs text-gray-500 dark:text-gray-400">+ Tool called+ </div>+ <div className="mt-1 overflow-hidden text-ellipsis whitespace-nowrap text-xs font-medium">+ {toolCall.name}+ </div>+ </div>+ <div className="w-[50%] flex-1 overflow-hidden">+ <div className="text-xs text-gray-500 dark:text-gray-400">+ Arguments+ </div>+ <JSONView+ json={JSON.stringify(toolCall.args, null, 2)}+ codeClassName="border-none p-1"+ />+ </div>+ <div className="flex w-[25%] flex-col overflow-hidden">+ <div className="text-xs text-gray-500 dark:text-gray-400">ID</div>+ <div className="mt-1 overflow-hidden text-ellipsis whitespace-nowrap text-xs">+ {toolCall.id}+ </div>+ </div>+ </div>+ </div>+ );+};diff --git a/web/src/components/ChatMessages/index.tsx b/web/src/components/ChatMessages/index.tsxindex d93eaa2a54..ebe448eaf0 100644--- a/web/src/components/ChatMessages/index.tsx+++ b/web/src/components/ChatMessages/index.tsx@@ -2,7 +2,11 @@ import { PlusCircleIcon } from "lucide-react";import { useEffect, useRef } from "react";import { Button } from "@/src/components/ui/button";-import { ChatMessageRole, SYSTEM_ROLES } from "@langfuse/shared";+import {+ ChatMessageRole,+ ChatMessageType,+ SYSTEM_ROLES,+} from "@langfuse/shared";import { ChatMessageComponent } from "./ChatMessageComponent";@@ -75,7 +79,7 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {><div className="flex h-full flex-col"><div className="flex-1 overflow-auto scroll-smooth" ref={scrollAreaRef}>- <div className="mb-4 flex-1 space-y-3">+ <div className="mb-4 flex-1 space-y-2"><SortableContextitems={props.messages.map((message) => message.id)}strategy={verticalListSortingStrategy}@@ -88,7 +92,9 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {index={index}deleteMessage={props.deleteMessage}updateMessage={props.updateMessage}+ replaceMessage={props.replaceMessage}availableRoles={props.availableRoles}+ toolCallIds={props.toolCallIds}/>);})}@@ -119,7 +125,21 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({type="button" // prevents submitting a form if this button is inside a formvariant="outline"className="w-full"- onClick={() => addMessage(nextMessageRole)}+ onClick={() => {+ if (nextMessageRole === ChatMessageRole.User) {+ addMessage({+ role: nextMessageRole,+ content: "",+ type: ChatMessageType.User,+ });+ } else {+ addMessage({+ role: nextMessageRole,+ content: "",+ type: ChatMessageType.AssistantText,+ });+ }+ }}><PlusCircleIcon size={14} className="mr-2" /><p>Add message</p>diff --git a/web/src/components/ChatMessages/types.ts b/web/src/components/ChatMessages/types.tsindex 047760f4cd..f819ec0002 100644--- a/web/src/components/ChatMessages/types.ts+++ b/web/src/components/ChatMessages/types.ts@@ -1,14 +1,24 @@-import type { ChatMessageRole, ChatMessageWithId } from "@langfuse/shared";+import type { ChatMessage, ChatMessageWithId } from "@langfuse/shared";export type MessagesContext = {messages: ChatMessageWithId[];- addMessage: (role: ChatMessageRole, content?: string) => ChatMessageWithId;+ addMessage: (message: ChatMessage) => ChatMessageWithId;setMessages: (messages: ChatMessageWithId[]) => void;deleteMessage: (id: string) => void;- updateMessage: <Key extends keyof ChatMessageWithId>(+ updateMessage: <+ T extends ChatMessageWithId["type"],+ Key extends keyof Omit<+ Extract<ChatMessageWithId, { type: T }>,+ "id" | "type" | "role"+ >,+ Value = Extract<ChatMessageWithId, { type: T }>[Key],+ >(+ type: T,id: string,key: Key,- value: ChatMessageWithId[Key],+ value: Value,) => void;+ replaceMessage: (id: string, message: ChatMessage) => void;availableRoles?: string[]; // Only defined if user has extended default roles (ChatMessageRole) with custom roles via SDK/API+ toolCallIds?: string[];};diff --git a/web/src/components/ChatMessages/utils/createEmptyMessage.ts b/web/src/components/ChatMessages/utils/createEmptyMessage.tsindex ffc6626353..8fb1b67beb 100644--- a/web/src/components/ChatMessages/utils/createEmptyMessage.ts+++ b/web/src/components/ChatMessages/utils/createEmptyMessage.ts@@ -1,13 +1,10 @@import { v4 as uuidv4 } from "uuid";-import type { ChatMessageRole, ChatMessageWithId } from "@langfuse/shared";+import { type ChatMessage, type ChatMessageWithId } from "@langfuse/shared";-export function createEmptyMessage(- role: ChatMessageRole,- content?: string,-): ChatMessageWithId {+export function createEmptyMessage(message: ChatMessage): ChatMessageWithId {return {- role,- content: content ?? "",+ ...message,+ content: message.content ?? "",id: uuidv4(),};}diff --git a/web/src/components/ModelParameters/index.tsx b/web/src/components/ModelParameters/index.tsxindex bb1441e327..72151c68c1 100644--- a/web/src/components/ModelParameters/index.tsx+++ b/web/src/components/ModelParameters/index.tsx@@ -1,3 +1,5 @@+import { useState, useEffect } from "react";+import { Button } from "@/src/components/ui/button";import { Input } from "@/src/components/ui/input";import {Select,@@ -17,6 +19,12 @@ import {type supportedModels,type UIModelParams,} from "@langfuse/shared";+import { Settings2 } from "lucide-react";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";import { LLMApiKeyComponent } from "./LLMApiKeyComponent";import { FormDescription } from "@/src/components/ui/form";@@ -44,19 +52,112 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({modelParamsDescription,}) => {const projectId = useProjectIdFromURL();+ const [modelSettingsOpen, setModelSettingsOpen] = useState(false);+ const [modelSettingsUsed, setModelSettingsUsed] = useState(false);++ useEffect(() => {+ const hasEnabledModelSetting = Object.keys(modelParams).some(+ (key) =>+ !["adapter", "provider", "model"].includes(key) &&+ modelParams[key as keyof typeof modelParams].enabled === true,+ );++ if (hasEnabledModelSetting) {+ setModelSettingsUsed(true);+ } else {+ setModelSettingsUsed(false);+ }+ }, [setModelSettingsUsed, modelParams]);if (!projectId) return null;+ if (availableProviders.length === 0) {+ return (+ <div className="flex flex-col space-y-4 pr-1">+ <div className="flex items-center justify-between">+ <p className="font-semibold">Model</p>+ </div>+ <p className="text-xs">No LLM API key set in project. </p>+ <CreateLLMApiKeyDialog />+ </div>+ );+ }+return (- <div className="flex flex-col space-y-4">- <p className="font-semibold">Model</p>- {availableProviders.length === 0 ? (- <>- <p className="text-xs">No LLM API key set in project. </p>- <CreateLLMApiKeyDialog />- </>- ) : (- <div className="space-y-4">+ <div className="flex flex-col space-y-2 pr-1 pt-2">+ <div className="flex items-center justify-between">+ <p className="font-semibold">Model</p>+ <Popover open={modelSettingsOpen} onOpenChange={setModelSettingsOpen}>+ <PopoverTrigger asChild>+ <Button+ variant="outline"+ size="icon"+ className="relative h-7 w-7"+ disabled={formDisabled}+ >+ <Settings2 size={14} />+ {modelSettingsUsed && (+ <div className="absolute -right-0.5 -top-0.5 h-2 w-2 rounded-full bg-primary" />+ )}+ </Button>+ </PopoverTrigger>+ <PopoverContent className="p-4" align="end" sideOffset={5}>+ <div className="mb-3">+ <h4 className="mb-1 text-sm font-medium">+ Model Advanced Settings+ </h4>+ <p className="text-xs text-muted-foreground">+ Configure advanced parameters for your model.+ </p>+ </div>+ <div className="space-y-4">+ <ModelParamsSlider+ title="Temperature"+ modelParamsKey="temperature"+ formDisabled={formDisabled}+ enabled={modelParams.temperature.enabled}+ setModelParamEnabled={setModelParamEnabled}+ value={modelParams.temperature.value}+ min={0}+ max={modelParams.maxTemperature.value}+ step={0.01}+ tooltip="The sampling temperature. Higher values will make the output more random, while lower values will make it more focused and deterministic."+ updateModelParam={updateModelParamValue}+ />+ <ModelParamsSlider+ title="Output token limit"+ modelParamsKey="max_tokens"+ formDisabled={formDisabled}+ enabled={modelParams.max_tokens.enabled}+ setModelParamEnabled={setModelParamEnabled}+ value={modelParams.max_tokens.value}+ min={1}+ max={16384}+ step={1}+ tooltip="The maximum number of tokens that can be generated in the chat completion."+ updateModelParam={updateModelParamValue}+ />+ <ModelParamsSlider+ title="Top P"+ modelParamsKey="top_p"+ formDisabled={formDisabled}+ enabled={modelParams.top_p.enabled}+ setModelParamEnabled={setModelParamEnabled}+ value={modelParams.top_p.value}+ min={0}+ max={1}+ step={0.01}+ tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."+ updateModelParam={updateModelParamValue}+ />+ <LLMApiKeyComponent {...{ projectId, modelParams }} />+ </div>+ </PopoverContent>+ </Popover>+ </div>++ <div className="space-y-4">+ <div className="space-y-3"><ModelParamsSelecttitle="Provider"modelParamsKey="provider"@@ -74,62 +175,23 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({updateModelParam={updateModelParamValue}modelParamsDescription={modelParamsDescription}/>- {modelParams.model.value?.startsWith("o1-") ? (- <p className="text-sm text-dark-yellow">- For {modelParams.model.value}, the system message and the- temperature, max_tokens and top_p setting are not supported while- it is in beta.{" "}- <a- href="https://platform.openai.com/docs/guides/reasoning/beta-limitations"- target="_blank"- rel="noreferrer noopener"- >- More info ↗- </a>- </p>- ) : null}- <ModelParamsSlider- title="Temperature"- modelParamsKey="temperature"- formDisabled={formDisabled}- enabled={modelParams.temperature.enabled}- setModelParamEnabled={setModelParamEnabled}- value={modelParams.temperature.value}- min={0}- max={modelParams.maxTemperature.value}- step={0.01}- tooltip="The sampling temperature. Higher values will make the output more random, while lower values will make it more focused and deterministic."- updateModelParam={updateModelParamValue}- />- <ModelParamsSlider- title="Output token limit"- modelParamsKey="max_tokens"- formDisabled={formDisabled}- enabled={modelParams.max_tokens.enabled}- setModelParamEnabled={setModelParamEnabled}- value={modelParams.max_tokens.value}- min={1}- max={16384}- step={1}- tooltip="The maximum number of tokens that can be generated in the chat completion."- updateModelParam={updateModelParamValue}- />- <ModelParamsSlider- title="Top P"- modelParamsKey="top_p"- formDisabled={formDisabled}- enabled={modelParams.top_p.enabled}- setModelParamEnabled={setModelParamEnabled}- value={modelParams.top_p.value}- min={0}- max={1}- step={0.01}- tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."- updateModelParam={updateModelParamValue}- />- <LLMApiKeyComponent {...{ projectId, modelParams }} /></div>- )}++ {modelParams.model.value?.startsWith("o1-") ? (+ <p className="mt-1 text-xs text-dark-yellow">+ For {modelParams.model.value}, the system message and the+ temperature, max_tokens and top_p setting are not supported while it+ is in beta.{" "}+ <a+ href="https://platform.openai.com/docs/guides/reasoning/beta-limitations"+ target="_blank"+ rel="noreferrer noopener"+ >+ More info ↗+ </a>+ </p>+ ) : null}+ </div></div>);};@@ -153,41 +215,47 @@ const ModelParamsSelect = ({modelParamsDescription,}: ModelParamsSelectProps) => {return (- <div className="space-y-2">- <p- className={cn(- "text-xs font-semibold",- disabled && "text-muted-foreground",- )}- >- {title}- </p>- <Select- disabled={disabled}- onValueChange={(value) =>- updateModelParam(- modelParamsKey,- value as (typeof supportedModels)[LLMAdapter][number],- )- }- value={value}- >- <SelectTrigger>- <SelectValue />- </SelectTrigger>- <SelectContent>- {options.map((option) => (- <SelectItem value={option} key={option}>- {option}- </SelectItem>- ))}- <SelectSeparator />- <CreateLLMApiKeyDialog />- </SelectContent>- </Select>- {modelParamsDescription ? (- <FormDescription>{modelParamsDescription}</FormDescription>- ) : undefined}+ <div className="flex items-center gap-4">+ <div className="w-24 flex-shrink-0">+ <p+ className={cn(+ "text-xs font-semibold",+ disabled && "text-muted-foreground",+ )}+ >+ {title}+ </p>+ </div>+ <div className="flex-1">+ <Select+ disabled={disabled}+ onValueChange={(value) =>+ updateModelParam(+ modelParamsKey,+ value as (typeof supportedModels)[LLMAdapter][number],+ )+ }+ value={value}+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {options.map((option) => (+ <SelectItem value={option} key={option}>+ {option}+ </SelectItem>+ ))}+ <SelectSeparator />+ <CreateLLMApiKeyDialog />+ </SelectContent>+ </Select>+ {modelParamsDescription ? (+ <FormDescription className="mt-1 text-xs">+ {modelParamsDescription}+ </FormDescription>+ ) : undefined}+ </div></div>);};diff --git a/web/src/components/editor/CodeMirrorEditor.tsx b/web/src/components/editor/CodeMirrorEditor.tsxindex 2c4e208a85..7e2e48ae47 100644--- a/web/src/components/editor/CodeMirrorEditor.tsx+++ b/web/src/components/editor/CodeMirrorEditor.tsx@@ -167,6 +167,12 @@ export function CodeMirrorEditor({}}lang={mode === "json" ? "json" : undefined}extensions={[+ // Remove outline if field is focussed+ EditorView.theme({+ "&.cm-focused": {+ outline: "none",+ },+ }),// Hide gutter when lineNumbers is false// Fix missing gutter border...(!lineNumbersdiff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsxindex 49ff0faa85..371216edf3 100644--- a/web/src/components/ui/CodeJsonViewer.tsx+++ b/web/src/components/ui/CodeJsonViewer.tsx@@ -55,7 +55,6 @@ export function JSONView(props: {<divclassName={cn("flex gap-2 whitespace-pre-wrap break-words p-3 text-xs",- props.codeClassName,props.title === "assistant" || props.title === "Output"? "bg-accent-light-green dark:border-accent-dark-green": "",@@ -63,6 +62,7 @@ export function JSONView(props: {? "bg-primary-foreground": "",props.scrollable ? "" : "rounded-sm border",+ props.codeClassName,)}>{props.isLoading ? (diff --git a/web/src/components/ui/dialog.tsx b/web/src/components/ui/dialog.tsxindex 286aa6ade9..69b87b8358 100644--- a/web/src/components/ui/dialog.tsx+++ b/web/src/components/ui/dialog.tsx@@ -44,7 +44,7 @@ const DialogContent = React.forwardRef<<DialogPrimitive.Contentref={ref}className={cn(- "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",+ "fixed left-[50%] top-[50%] z-50 grid max-h-[85vh] w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 overflow-y-auto border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",className,)}aria-describedby={undefined}diff --git a/web/src/ee/features/evals/server/router.ts b/web/src/ee/features/evals/server/router.tsindex 93b7dd9591..e275ac8c1a 100644--- a/web/src/ee/features/evals/server/router.ts+++ b/web/src/ee/features/evals/server/router.ts@@ -29,6 +29,7 @@ import {QueueName,QueueJobs,LLMApiKeySchema,+ ChatMessageType,} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";import { EvalReferencedEvaluators } from "@/src/ee/features/evals/types";@@ -735,7 +736,13 @@ export const evalRouter = createTRPCRouter({parsedKey.data.extraHeaders,),baseURL: parsedKey.data.baseURL ?? undefined,- messages: [{ role: ChatMessageRole.User, content: input.prompt }],+ messages: [+ {+ role: ChatMessageRole.User,+ content: input.prompt,+ type: ChatMessageType.User,+ },+ ],modelParams: {provider: input.provider,model: input.model,diff --git a/web/src/ee/features/playground/page/components/CreateOrEditLLMSchemaDialog.tsx b/web/src/ee/features/playground/page/components/CreateOrEditLLMSchemaDialog.tsxnew file mode 100644index 0000000000..684459d279--- /dev/null+++ b/web/src/ee/features/playground/page/components/CreateOrEditLLMSchemaDialog.tsx@@ -0,0 +1,283 @@+import React, { useEffect, useState } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import * as z from "zod";++import { Button } from "@/src/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/src/components/ui/dialog";+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+ FormDescription,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import { Textarea } from "@/src/components/ui/textarea";+import { api } from "@/src/utils/api";++import { JSONSchemaFormSchema, type LlmSchema } from "@langfuse/shared";+import { CodeMirrorEditor } from "@/src/components/editor";+import { ArrowUpRight } from "lucide-react";++const formSchema = z.object({+ name: z+ .string()+ .regex(+ /^[a-z0-9_-]+$/,+ "Name must contain only lowercase letters, numbers, hyphens and underscores",+ )+ .min(1, "Name is required"),+ description: z.string().min(1, "Description is required"),+ schema: JSONSchemaFormSchema,+});++type FormValues = z.infer<typeof formSchema>;++type CreateOrEditLLMSchemaDialog = {+ children: React.ReactNode;+ projectId: string;+ onSave: (llmSchema: LlmSchema) => void;+ onDelete?: (llmSchema: LlmSchema) => void;+ existingLlmSchema?: LlmSchema;+ defaultValues?: {+ name: string;+ description: string;+ schema: string;+ };+};++export const CreateOrEditLLMSchemaDialog: React.FC<+ CreateOrEditLLMSchemaDialog+> = (props) => {+ const { children, projectId, onSave, existingLlmSchema } = props;++ const utils = api.useUtils();+ const createLlmSchema = api.llmSchemas.create.useMutation();+ const updateLlmSchema = api.llmSchemas.update.useMutation();+ const deleteLlmSchema = api.llmSchemas.delete.useMutation();++ const [open, setOpen] = useState(false);++ const form = useForm<FormValues>({+ resolver: zodResolver(formSchema),+ defaultValues: props.defaultValues ?? {+ name: "",+ description: "",+ schema: JSON.stringify(+ {+ type: "object",+ properties: {},+ required: [],+ additionalProperties: false,+ },+ null,+ 2,+ ),+ },+ });++ // Populate form when in edit mode+ useEffect(() => {+ if (existingLlmSchema) {+ form.reset({+ name: existingLlmSchema.name,+ description: existingLlmSchema.description,+ schema: JSON.stringify(existingLlmSchema.schema, null, 2),+ });+ }+ }, [existingLlmSchema, form]);++ async function onSubmit(values: FormValues) {+ let result;+ if (existingLlmSchema) {+ result = await updateLlmSchema.mutateAsync({+ id: existingLlmSchema.id,+ projectId,+ name: values.name,+ description: values.description,+ schema: JSON.parse(values.schema),+ });+ } else {+ result = await createLlmSchema.mutateAsync({+ projectId,+ name: values.name,+ description: values.description,+ schema: JSON.parse(values.schema),+ });+ }++ await utils.llmSchemas.getAll.invalidate({ projectId });++ onSave(result);+ setOpen(false);+ }++ async function handleDelete() {+ if (!existingLlmSchema) return;++ await deleteLlmSchema.mutateAsync({+ id: existingLlmSchema.id,+ projectId,+ });++ props.onDelete?.(existingLlmSchema);++ await utils.llmSchemas.getAll.invalidate({ projectId });+ setOpen(false);+ }++ const prettifyJson = () => {+ try {+ const currentValue = form.getValues("schema");+ const parsedJson = JSON.parse(currentValue);+ const prettified = JSON.stringify(parsedJson, null, 2);+ form.setValue("schema", prettified);+ } catch (error) {+ console.error("Failed to prettify JSON:", error);+ }+ };++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild>{children}</DialogTrigger>+ <DialogContent className="flex flex-col sm:min-w-[32rem] md:min-w-[40rem]">+ <DialogHeader>+ <DialogTitle>+ {existingLlmSchema ? "Edit LLM Schema" : "Create LLM Schema"}+ </DialogTitle>+ <DialogDescription>+ Define a JSON Schema for structured outputs+ </DialogDescription>+ </DialogHeader>++ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(onSubmit)}+ className="flex flex-1 flex-col"+ >+ <div className="flex-1 space-y-4 overflow-y-auto">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Name</FormLabel>+ <FormControl>+ <Input placeholder="e.g., get_weather" {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Description</FormLabel>+ <FormControl>+ <Textarea+ placeholder="Describe the schema"+ className="max-h-[120px] focus:ring-0 focus:ring-offset-0 focus-visible:ring-0 focus-visible:ring-offset-0"+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="schema"+ render={({ field }) => (+ <FormItem>+ <FormLabel>JSON Schema</FormLabel>+ <FormDescription>+ Define the structure of your schema using JSON Schema+ format.{" "}+ <a+ href="https://json-schema.org/learn/miscellaneous-examples"+ target="_blank"+ rel="noopener noreferrer"+ className="flex items-center"+ >+ See JSON Schema examples here+ <ArrowUpRight className="h-3 w-3" />+ </a>+ </FormDescription>+ <FormControl>+ <div className="relative flex flex-col gap-1">+ <CodeMirrorEditor+ value={field.value}+ onChange={field.onChange}+ mode="json"+ minHeight={200}+ className="max-h-[25vh]"+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={prettifyJson}+ className="absolute right-3 top-3 text-xs"+ >+ Prettify+ </Button>+ </div>+ </FormControl>+ <p className="text-xs text-muted-foreground">+ Parameters must be a valid JSON Schema object+ </p>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ <DialogFooter className="sticky bottom-0 mt-4 flex flex-col gap-2 border-t bg-background pt-4">+ <div className="flex w-full flex-col gap-2">+ <p className="text-xs text-muted-foreground">+ Note: Changes to schemas are reflected to all members of this+ project.+ </p>+ <div className="flex items-center justify-between gap-2">+ {existingLlmSchema && (+ <Button+ type="button"+ variant="destructive"+ onClick={handleDelete}+ className="mr-auto"+ >+ Delete+ </Button>+ )}+ <Button+ type="button"+ variant="outline"+ onClick={() => setOpen(false)}+ >+ Cancel+ </Button>+ <Button type="submit">Save</Button>+ </div>+ </div>+ </DialogFooter>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+};diff --git a/web/src/ee/features/playground/page/components/CreateOrEditLLMToolDialog.tsx b/web/src/ee/features/playground/page/components/CreateOrEditLLMToolDialog.tsxnew file mode 100644index 0000000000..3ebda40fbb--- /dev/null+++ b/web/src/ee/features/playground/page/components/CreateOrEditLLMToolDialog.tsx@@ -0,0 +1,292 @@+import React, { useEffect, useState } from "react";+import { useForm } from "react-hook-form";+import { zodResolver } from "@hookform/resolvers/zod";+import * as z from "zod";++import { Button } from "@/src/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/src/components/ui/dialog";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import { Textarea } from "@/src/components/ui/textarea";+import { api } from "@/src/utils/api";++import { CodeMirrorEditor } from "@/src/components/editor";+import { JSONSchemaFormSchema, type LlmTool } from "@langfuse/shared";+import { ArrowUpRight } from "lucide-react";++const formSchema = z.object({+ name: z+ .string()+ .regex(+ /^[a-z0-9_-]+$/,+ "Name must contain only lowercase letters, numbers, hyphens and underscores",+ )+ .min(1, "Name is required"),+ description: z.string().min(1, "Description is required"),+ parameters: JSONSchemaFormSchema,+});++type FormValues = z.infer<typeof formSchema>;++type CreateOrEditLLMToolDialog = {+ children: React.ReactNode;+ projectId: string;+ onSave: (llmTool: LlmTool) => void;+ onDelete?: (llmTool: LlmTool) => void;+ existingLlmTool?: LlmTool;+ defaultValues?: {+ name: string;+ description: string;+ parameters: string;+ };+};++export const CreateOrEditLLMToolDialog: React.FC<CreateOrEditLLMToolDialog> = (+ props,+) => {+ const { children, projectId, onSave, existingLlmTool } = props;++ const utils = api.useUtils();+ const createLlmTool = api.llmTools.create.useMutation();+ const updateLlmTool = api.llmTools.update.useMutation();+ const deleteLlmTool = api.llmTools.delete.useMutation();++ const [open, setOpen] = useState(false);++ const form = useForm<FormValues>({+ resolver: zodResolver(formSchema),+ defaultValues: props.defaultValues ?? {+ name: "",+ description: "",+ parameters: JSON.stringify(+ {+ type: "object",+ properties: {},+ required: [],+ additionalProperties: false,+ },+ null,+ 2,+ ),+ },+ });++ // Populate form when in edit mode+ useEffect(() => {+ if (existingLlmTool) {+ form.reset({+ name: existingLlmTool.name,+ description: existingLlmTool.description,+ parameters: JSON.stringify(existingLlmTool.parameters, null, 2),+ });+ }+ }, [existingLlmTool, form]);++ async function onSubmit(values: FormValues) {+ let result;+ if (existingLlmTool) {+ result = await updateLlmTool.mutateAsync({+ id: existingLlmTool.id,+ projectId,+ name: values.name,+ description: values.description,+ parameters: JSON.parse(values.parameters),+ });+ } else {+ result = await createLlmTool.mutateAsync({+ projectId,+ name: values.name,+ description: values.description,+ parameters: JSON.parse(values.parameters),+ });+ }++ await utils.llmTools.getAll.invalidate({ projectId });++ onSave(result);+ setOpen(false);+ }++ async function handleDelete() {+ if (!existingLlmTool) return;++ await deleteLlmTool.mutateAsync({+ id: existingLlmTool.id,+ projectId,+ });++ props.onDelete?.(existingLlmTool);++ await utils.llmTools.getAll.invalidate({ projectId });+ setOpen(false);+ }++ const prettifyJson = () => {+ try {+ const currentValue = form.getValues("parameters");+ const parsedJson = JSON.parse(currentValue);+ const prettified = JSON.stringify(parsedJson, null, 2);+ form.setValue("parameters", prettified);+ } catch (error) {+ console.error("Failed to prettify JSON:", error);+ }+ };++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger asChild onClick={(e) => e.stopPropagation()}>+ {children}+ </DialogTrigger>+ <DialogContent+ className="flex flex-col sm:min-w-[32rem] md:min-w-[40rem]"+ onClick={(e) => e.stopPropagation()}+ >+ <DialogHeader>+ <DialogTitle>+ {existingLlmTool ? "Edit LLM Tool" : "Create LLM Tool"}+ </DialogTitle>+ <DialogDescription>+ Define a tool for LLM function calling+ </DialogDescription>+ </DialogHeader>++ <Form {...form}>+ <form+ onSubmit={form.handleSubmit(onSubmit)}+ className="flex flex-1 flex-col"+ >+ <div className="flex-1 space-y-4 overflow-y-auto">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Name</FormLabel>+ <FormControl>+ <Input placeholder="e.g., get_weather" {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="description"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Description</FormLabel>+ <FormDescription>+ This description will be sent to the LLM to help it+ understand the tool's purpose and functionality.+ </FormDescription>+ <FormControl>+ <Textarea+ placeholder="Describe the tool's purpose and usage"+ className="max-h-[120px] focus:ring-0 focus:ring-offset-0 focus-visible:ring-0 focus-visible:ring-offset-0"+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />++ <FormField+ control={form.control}+ name="parameters"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Parameters (JSON Schema)</FormLabel>+ <FormDescription>+ Define the structure of your tool parameters using JSON+ Schema format.{" "}+ <a+ href="https://json-schema.org/learn/miscellaneous-examples"+ target="_blank"+ rel="noopener noreferrer"+ className="flex items-center"+ >+ See JSON Schema examples here+ <ArrowUpRight className="h-3 w-3" />+ </a>+ </FormDescription>+ <FormControl>+ <div className="relative flex flex-col gap-1">+ <CodeMirrorEditor+ value={field.value}+ onChange={field.onChange}+ mode="json"+ minHeight={200}+ className="max-h-[25vh]"+ />+ <Button+ type="button"+ variant="outline"+ size="sm"+ onClick={prettifyJson}+ className="absolute right-3 top-3 text-xs"+ >+ Prettify+ </Button>+ </div>+ </FormControl>+ <p className="text-xs text-muted-foreground">+ Parameters must be a valid JSON Schema object+ </p>+ <FormMessage />+ </FormItem>+ )}+ />+ </div>++ <DialogFooter className="sticky bottom-0 mt-4 flex flex-col gap-2 border-t bg-background pt-4">+ <div className="flex w-full flex-col gap-2">+ <p className="text-xs text-muted-foreground">+ Note: Changes to tools are reflected to all members of this+ project.+ </p>+ <div className="flex items-center justify-between gap-2">+ {existingLlmTool && (+ <Button+ type="button"+ variant="destructive"+ onClick={handleDelete}+ className="mr-auto"+ >+ Delete+ </Button>+ )}+ <Button+ type="button"+ variant="outline"+ onClick={() => setOpen(false)}+ >+ Cancel+ </Button>+ <Button type="submit">Save</Button>+ </div>+ </div>+ </DialogFooter>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+};diff --git a/web/src/ee/features/playground/page/components/GenerationOutput.tsx b/web/src/ee/features/playground/page/components/GenerationOutput.tsxindex 2553cb6c7d..27d23647a9 100644--- a/web/src/ee/features/playground/page/components/GenerationOutput.tsx+++ b/web/src/ee/features/playground/page/components/GenerationOutput.tsx@@ -2,15 +2,17 @@ import { useEffect, useRef, useState } from "react";import { Button } from "@/src/components/ui/button";import { usePlaygroundContext } from "../context";import { CheckIcon, CopyIcon, PlusIcon } from "@radix-ui/react-icons";-import { ChatMessageRole } from "@langfuse/shared";+import { ChatMessageRole, ChatMessageType } from "@langfuse/shared";import { BracesIcon } from "lucide-react";+import { ToolCallCard } from "@/src/components/ChatMessages/ToolCallCard";export const GenerationOutput = () => {const [isCopied, setIsCopied] = useState(false);const [isAdded, setIsAdded] = useState(false);const [isJson, setIsJson] = useState(false);const scrollAreaRef = useRef<HTMLDivElement | null>(null);- const { output, outputJson, addMessage } = usePlaygroundContext();+ const { output, outputJson, addMessage, outputToolCalls } =+ usePlaygroundContext();const handleCopy = () => {setIsCopied(true);@@ -20,7 +22,20 @@ export const GenerationOutput = () => {const handleAddAssistantMessage = () => {setIsAdded(true);- addMessage(ChatMessageRole.Assistant, output);+ if (outputToolCalls.length > 0) {+ addMessage({+ type: ChatMessageType.AssistantToolCall,+ role: ChatMessageRole.Assistant,+ content: output,+ toolCalls: outputToolCalls,+ });+ } else {+ addMessage({+ type: ChatMessageType.AssistantText,+ role: ChatMessageRole.Assistant,+ content: output,+ });+ }setTimeout(() => setIsAdded(false), 1000);};@@ -31,38 +46,41 @@ export const GenerationOutput = () => {}}, [output]);- const copyButton = output ? (- <div className="absolute right-3 top-2 space-x-1 opacity-50">- <Button- size="icon"- variant={isJson ? "default" : "secondary"}- onClick={() => {- setIsJson((prev) => !prev);- }}- title="Toggle Input/Output JSON"- >- <BracesIcon size={15} />- </Button>+ const copyButton =+ output || outputToolCalls.length ? (+ <div className="absolute right-3 top-2 flex space-x-1 opacity-50">+ <Button+ size="icon"+ variant={isJson ? "default" : "secondary"}+ onClick={() => {+ setIsJson((prev) => !prev);+ }}+ title="Toggle Input/Output JSON"+ >+ <BracesIcon size={15} />+ </Button>- <Button- size="icon"- variant="secondary"- onClick={!isCopied ? handleCopy : undefined}- title="Copy output"- >- {isCopied ? <CheckIcon /> : <CopyIcon />}- </Button>+ <Button+ size="icon"+ variant="secondary"+ onClick={!isCopied ? handleCopy : undefined}+ title="Copy output"+ >+ {isCopied ? <CheckIcon /> : <CopyIcon />}+ </Button>- <Button- size="icon"- variant="secondary"- onClick={!isAdded ? handleAddAssistantMessage : undefined}- title="Add as assistant message"- >- {isAdded ? <CheckIcon /> : <PlusIcon />}- </Button>- </div>- ) : null;+ <Button+ className="flex items-center gap-1 whitespace-nowrap p-0 px-1"+ variant="secondary"+ onClick={!isAdded ? handleAddAssistantMessage : undefined}+ title="Add as assistant message"+ disabled={isAdded}+ >+ {isAdded ? <CheckIcon /> : <PlusIcon />}+ <span className="text-xs">Add to messages</span>+ </Button>+ </div>+ ) : null;return (<div className="relative h-full overflow-auto">@@ -77,6 +95,13 @@ export const GenerationOutput = () => {<pre className="whitespace-break-spaces break-words text-xs">{isJson ? outputJson : output}</pre>+ {outputToolCalls.length > 0+ ? outputToolCalls.map((toolCall) => (+ <div className="mt-4" key={toolCall.id}>+ <ToolCallCard toolCall={toolCall} />+ </div>+ ))+ : null}</div></div>);diff --git a/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsxindex d8efc5ac20..86290b9aa7 100644--- a/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx+++ b/web/src/ee/features/playground/page/components/JumpToPlaygroundButton.tsx@@ -6,7 +6,11 @@ import { z } from "zod";import { createEmptyMessage } from "@/src/components/ChatMessages/utils/createEmptyMessage";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 {+ type PlaygroundTool,+ type PlaygroundCache,+ type PlaygroundSchema,+} from "@/src/ee/features/playground/page/types";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { PromptType } from "@/src/features/prompts/server/utils/validation";import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";@@ -17,6 +21,12 @@ import {supportedModels as playgroundSupportedModels,type UIModelParams,ZodModelConfig,+ ChatMessageType,+ LLMToolCallSchema,+ OpenAIToolCallSchema,+ OpenAIToolSchema,+ type ChatMessage,+ OpenAIResponseFormatSchema,} from "@langfuse/shared";import { useHasEntitlement } from "@/src/features/entitlements/hooks";import { cn } from "@/src/utils/tailwind";@@ -106,7 +116,6 @@ const ParsedChatMessageListSchema = z.array(role: z.nativeEnum(ChatMessageRole),content: z.union([z.string(),- // If system message is cached, the message is an array of objects with a text propertyz.array(z@@ -116,25 +125,75 @@ const ParsedChatMessageListSchema = z.array(.transform((v) => v.text),).transform((v) => v.join("")),+ z.null().transform((_) => ""),z.any().transform((v) => JSON.stringify(v, null, 2)),]),+ tool_calls: z+ .union([z.array(LLMToolCallSchema), z.array(OpenAIToolCallSchema)])+ .optional(),+ tool_call_id: z.string().optional(),}),);+const transformToPlaygroundMessage = (+ message: z.infer<typeof ParsedChatMessageListSchema>[0],+): ChatMessage => {+ const { role, content } = message;++ if (message.role === "assistant" && message.tool_calls) {+ const playgroundMessage: ChatMessage = {+ role: ChatMessageRole.Assistant,+ content,+ type: ChatMessageType.AssistantToolCall,+ toolCalls: message.tool_calls.map((tc) => {+ if ("function" in tc) {+ return {+ name: tc.function.name,+ id: tc.id,+ args: tc.function.arguments,+ };+ }++ return tc;+ }),+ };++ return playgroundMessage;+ } else if (message.role === "tool" && message.tool_call_id) {+ const playgroundMessage: ChatMessage = {+ role: ChatMessageRole.Tool,+ content,+ type: ChatMessageType.ToolResult,+ toolCallId: message.tool_call_id,+ };++ return playgroundMessage;+ } else {+ return {+ role,+ content,+ type: ChatMessageType.PublicAPICreated,+ };+ }+};+const parsePrompt = (prompt: Prompt): PlaygroundCache => {if (prompt.type === PromptType.Chat) {const parsedMessages = ParsedChatMessageListSchema.safeParse(prompt.prompt);- return parsedMessages.success ? { messages: parsedMessages.data } : null;+ return parsedMessages.success+ ? { messages: parsedMessages.data.map(transformToPlaygroundMessage) }+ : null;} else {const promptString = prompt.prompt?.valueOf();return {messages: [- createEmptyMessage(- ChatMessageRole.System,- typeof promptString === "string" ? promptString : "",- ),+ createEmptyMessage({+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: typeof promptString === "string" ? promptString : "",+ }),],};}@@ -149,6 +208,9 @@ const parseGeneration = (if (generation.type !== "GENERATION") return null;const modelParams = parseModelParams(generation);+ const tools = parseTools(generation);+ const structuredOutputSchema = parseStructuredOutputSchema(generation);+let input = generation.input?.valueOf();if (typeof input === "string") {@@ -157,25 +219,48 @@ const parseGeneration = (if (typeof input === "string") {return {- messages: [createEmptyMessage(ChatMessageRole.System, input)],+ messages: [+ createEmptyMessage({+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: input,+ }),+ ],modelParams,+ tools,+ structuredOutputSchema,};}} catch (err) {return {messages: [- createEmptyMessage(ChatMessageRole.System, input?.toString()),+ createEmptyMessage({+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: input?.toString() ?? "",+ }),],modelParams,+ tools,+ structuredOutputSchema,};}}if (typeof input === "object") {- const parsedMessages = ParsedChatMessageListSchema.safeParse(input);+ const parsedMessages = ParsedChatMessageListSchema.safeParse(+ "messages" in input ? input["messages"] : input,+ );++ console.log(parsedMessages);if (parsedMessages.success)- return { messages: parsedMessages.data, modelParams };+ return {+ messages: parsedMessages.data.map(transformToPlaygroundMessage),+ modelParams,+ tools,+ structuredOutputSchema,+ };}if (typeof input === "object" && "messages" in input) {@@ -184,7 +269,12 @@ const parseGeneration = ();if (parsedMessages.success)- return { messages: parsedMessages.data, modelParams };+ return {+ messages: parsedMessages.data.map(transformToPlaygroundMessage),+ modelParams,+ tools,+ structuredOutputSchema,+ };}return null;@@ -233,3 +323,47 @@ function parseModelParams(return modelParams;}++function parseTools(generation: Observation): PlaygroundTool[] {+ try {+ const input = JSON.parse(generation.input as string);+ if (typeof input === "object" && input !== null && "tools" in input) {+ const parsedTools = z.array(OpenAIToolSchema).safeParse(input["tools"]);++ if (parsedTools.success)+ return parsedTools.data.map((tool) => ({+ id: Math.random().toString(36).substring(2),+ ...tool.function,+ }));+ }+ } catch {}++ return [];+}++function parseStructuredOutputSchema(+ generation: Observation,+): PlaygroundSchema | null {+ try {+ const metadata = generation.metadata;++ if (+ typeof metadata === "object" &&+ metadata !== null &&+ "response_format" in metadata+ ) {+ const parseStructuredOutputSchema = OpenAIResponseFormatSchema.safeParse(+ metadata["response_format"],+ );++ if (parseStructuredOutputSchema.success)+ return {+ id: Math.random().toString(36).substring(2),+ name: parseStructuredOutputSchema.data.json_schema.name,+ description: "Schema parsed from generation",+ schema: parseStructuredOutputSchema.data.json_schema.schema,+ };+ }+ } catch {}+ return null;+}diff --git a/web/src/ee/features/playground/page/components/Messages.tsx b/web/src/ee/features/playground/page/components/Messages.tsxindex fa87f4a2e8..ee170d4156 100644--- a/web/src/ee/features/playground/page/components/Messages.tsx+++ b/web/src/ee/features/playground/page/components/Messages.tsx@@ -12,7 +12,7 @@ import {export const Messages: React.FC<MessagesContext> = (props) => {return (- <div className="flex h-full flex-col space-y-4 pr-4">+ <div className="flex h-full flex-col space-y-4 pr-4 pt-2"><ResizablePanelGroup direction="vertical"><ResizablePanel minSize={10}><ChatMessages {...props} />@@ -42,7 +42,7 @@ const SubmitButton = () => {}}loading={isStreaming}>- <p>Submit ({"\u2318"} + Enter)</p>+ <p>Submit (Ctrl + Enter)</p></Button>);};diff --git a/web/src/ee/features/playground/page/components/PlaygroundTools/index.tsx b/web/src/ee/features/playground/page/components/PlaygroundTools/index.tsxnew file mode 100644index 0000000000..d063a128da--- /dev/null+++ b/web/src/ee/features/playground/page/components/PlaygroundTools/index.tsx@@ -0,0 +1,272 @@+import React, { useCallback, useEffect, useState } from "react";++import { usePlaygroundContext } from "@/src/ee/features/playground/page/context";+import { Button } from "@/src/components/ui/button";+import { ScrollArea } from "@/src/components/ui/scroll-area";+import { PlusIcon, PencilIcon, MinusCircle, WrenchIcon } from "lucide-react";+import { type LlmTool } from "@prisma/client";+import { api } from "@/src/utils/api";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { CreateOrEditLLMToolDialog } from "@/src/ee/features/playground/page/components/CreateOrEditLLMToolDialog";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandSeparator,+} from "@/src/components/ui/command";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";++import { type PlaygroundTool } from "@/src/ee/features/playground/page/types";++export const PlaygroundTools = () => {+ const { tools, setTools } = usePlaygroundContext();+ const projectId = useProjectIdFromURL();+ const [isSearchOpen, setIsSearchOpen] = useState(false);++ const { data: savedTools = [] } = api.llmTools.getAll.useQuery(+ {+ projectId: projectId as string,+ },+ {+ enabled: Boolean(projectId),+ staleTime: 1000 * 60 * 5, // 5 minutes+ },+ );++ const isToolSaved = useCallback(+ (tool: PlaygroundTool) => {+ return savedTools.some((savedTool) => savedTool.id === tool.id);+ },+ [savedTools],+ );++ useEffect(() => {+ tools.forEach((tool, index) => {+ if (!tool.existingLlmTool) {+ const matchingSavedTool = savedTools.find(+ (savedTool) =>+ savedTool.name === tool.name &&+ savedTool.description === tool.description &&+ JSON.stringify(savedTool.parameters) ===+ JSON.stringify(tool.parameters),+ );++ if (matchingSavedTool) {+ const newTools = [...tools];+ newTools[index] = {+ ...tool,+ id: matchingSavedTool.id,+ existingLlmTool: matchingSavedTool,+ };+ setTools(newTools);+ }+ }+ });+ }, [savedTools, tools, setTools]);++ const handleSelectTool = (selectedLLMTool: LlmTool) => {+ setTools((prev: PlaygroundTool[]) => {+ let existingToolIndex = -1;+ existingToolIndex = prev.findIndex((t) => t.id === selectedLLMTool.id);++ if (existingToolIndex === -1) {+ const unsavedToolIndexWithSameName = prev.findIndex(+ (t) => t.name === selectedLLMTool.name,+ );++ if (unsavedToolIndexWithSameName !== -1) {+ existingToolIndex = unsavedToolIndexWithSameName;+ }+ }++ const newTool: PlaygroundTool = {+ id: selectedLLMTool.id,+ name: selectedLLMTool.name,+ description: selectedLLMTool.description,+ parameters: selectedLLMTool.parameters as Record<string, unknown>,+ existingLlmTool: selectedLLMTool,+ };++ if (existingToolIndex !== -1) {+ const newTools = [...prev];+ newTools[existingToolIndex] = newTool;++ return newTools;+ }++ return [...prev, newTool];+ });+ setIsSearchOpen(false);+ };++ const handleRemoveTool = (toolId: string) => {+ setTools(+ (prev: PlaygroundTool[]) =>+ prev.filter((t) => !(t.id === toolId)) as PlaygroundTool[],+ );+ };++ return (+ <div className="flex h-full flex-col pr-1">+ <div className="mb-2 flex items-center justify-between">+ <div className="flex items-center gap-2">+ <p className="font-semibold">Tools</p>+ <a+ href="https://github.com/orgs/langfuse/discussions/3166"+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center"+ title="Tool calling is currently in beta. Click here to learn more and provide feedback!"+ >+ <span className="rounded bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">+ Beta+ </span>+ </a>+ </div>+ <Popover open={isSearchOpen} onOpenChange={setIsSearchOpen}>+ <PopoverTrigger asChild>+ <Button className="h-7 w-7" variant="outline" size="icon">+ <PlusIcon size={14} />+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="p-1">+ <Command className="flex flex-col">+ <CommandInput+ placeholder="Search tools..."+ className="h-8 border-none p-1 focus:ring-0 focus:ring-offset-0"+ />+ <CommandList className="max-h-[300px] overflow-y-auto">+ <CommandEmpty>No tools found.</CommandEmpty>+ <CommandGroup>+ {savedTools.map((tool) => (+ <CommandItem+ key={tool.id}+ value={tool.name}+ onSelect={() => handleSelectTool(tool)}+ className="flex items-center justify-between px-1 py-2"+ >+ <div className="flex items-center gap-2">+ <WrenchIcon+ size={12}+ className="text-muted-foreground"+ />+ <div className="flex-1 overflow-hidden">+ <div className="truncate font-medium">+ {tool.name}+ </div>+ <div className="line-clamp-1 text-xs text-muted-foreground">+ {tool.description}+ </div>+ </div>+ </div>+ <CreateOrEditLLMToolDialog+ projectId={projectId as string}+ onSave={handleSelectTool}+ onDelete={() => handleRemoveTool(tool.id)}+ existingLlmTool={tool}+ >+ <Button+ variant="ghost"+ size="icon"+ className="ml-2 h-7 w-7 shrink-0"+ >+ <PencilIcon className="h-3.5 w-3.5" />+ </Button>+ </CreateOrEditLLMToolDialog>+ </CommandItem>+ ))}+ </CommandGroup>+ <CommandSeparator />+ </CommandList>+ <div className="mt-auto p-1">+ <CreateOrEditLLMToolDialog+ projectId={projectId as string}+ onSave={handleSelectTool}+ >+ <Button variant="outline" size="default" className="w-full">+ <PlusIcon className="mr-2 h-4 w-4" />+ Create new tool+ </Button>+ </CreateOrEditLLMToolDialog>+ </div>+ </Command>+ </PopoverContent>+ </Popover>+ </div>++ <ScrollArea className="h-[calc(100%-2rem)]">+ {tools.length === 0 ? (+ <div className="flex h-16 flex-col items-center justify-center p-4 text-center">+ <p className="text-xs text-muted-foreground">No tools attached.</p>+ </div>+ ) : (+ <div className="space-y-1">+ {tools.map((tool) => (+ <CreateOrEditLLMToolDialog+ key={tool.id}+ projectId={projectId as string}+ onSave={handleSelectTool}+ onDelete={() => handleRemoveTool(tool.id)}+ existingLlmTool={tool.existingLlmTool}+ defaultValues={+ !isToolSaved(tool)+ ? {+ name: tool.name,+ description: tool.description,+ parameters: JSON.stringify(tool.parameters, null, 2),+ }+ : undefined+ }+ >+ <div className="cursor-pointer rounded-md border bg-background p-2 transition-colors duration-200 hover:bg-accent/50">+ <div className="mb-1 flex items-center justify-between">+ <div className="flex items-center gap-1">+ <WrenchIcon className="h-4 w-4 text-muted-foreground" />+ <h3+ className="max-w-[200px] truncate text-ellipsis text-sm font-medium"+ title={tool.name}+ >+ {tool.name}+ </h3>+ {!isToolSaved(tool) ? (+ <span className="rounded bg-muted px-1 py-0.5 text-xs text-muted-foreground">+ Unsaved+ </span>+ ) : null}+ </div>+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="sm"+ className="h-6 w-6 p-0"+ onClick={(e) => {+ e.stopPropagation();+ handleRemoveTool(tool.id);+ }}+ >+ <MinusCircle className="h-4 w-4" />+ </Button>+ </div>+ </div>+ <p+ className="line-clamp-2 text-xs text-muted-foreground"+ title={tool.description}+ >+ {tool.description}+ </p>+ </div>+ </CreateOrEditLLMToolDialog>+ ))}+ </div>+ )}+ </ScrollArea>+ </div>+ );+};diff --git a/web/src/ee/features/playground/page/components/PromptVariableComponent.tsx b/web/src/ee/features/playground/page/components/PromptVariableComponent.tsxindex d21867edaa..b357b157b4 100644--- a/web/src/ee/features/playground/page/components/PromptVariableComponent.tsx+++ b/web/src/ee/features/playground/page/components/PromptVariableComponent.tsx@@ -1,8 +1,7 @@-import { type ChangeEvent } from "react";import { CheckCircle2, Circle, TrashIcon } from "lucide-react";import { Button } from "@/src/components/ui/button";-import { Textarea } from "@/src/components/ui/textarea";import { type PromptVariable } from "@langfuse/shared";+import { CodeMirrorEditor } from "@/src/components/editor";import { usePlaygroundContext } from "../context";@@ -13,13 +12,12 @@ export const PromptVariableComponent: React.FC<{usePlaygroundContext();const { name, value, isUsed } = promptVariable;- const handleInputChange = (event: ChangeEvent<HTMLTextAreaElement>) => {- updatePromptVariableValue(name, event.target.value);+ const handleInputChange = (value: string) => {+ updatePromptVariableValue(name, value);};const handleDeleteVariable = () => {deletePromptVariable(name);};- const displayName = name.slice(0, 10) + (name.length > 10 ? "..." : "");const isUsedIcon = isUsed ? (<CheckCircle2 size={16} color="green" />) : (@@ -34,8 +32,8 @@ export const PromptVariableComponent: React.FC<{<div className="mb-1 flex flex-row items-center"><span className="flex flex-1 flex-row space-x-2 text-xs"><p title={isUsedTooltip}>{isUsedIcon}</p>- <p className="min-w-[90px] font-mono" title={name}>- {displayName}+ <p className="min-w-[90px] truncate font-mono" title={name}>+ {name}</p></span><Button@@ -49,10 +47,15 @@ export const PromptVariableComponent: React.FC<{{!isUsed && <TrashIcon size={16} />}</Button></div>- <Textarea- className="max-h-[10rem] min-h-[3rem] w-full resize-y pt-3 font-mono text-xs focus:outline-none"++ <CodeMirrorEditorvalue={value}- onChange={handleInputChange}+ onChange={(e) => handleInputChange(e)}+ mode="prompt"+ minHeight="none"+ className="max-h-[10rem] w-full resize-y p-1 font-mono text-xs focus:outline-none"+ editable={true}+ lineNumbers={false}placeholder={name}/></div>diff --git a/web/src/ee/features/playground/page/components/StructuredOutputSchemaSection.tsx b/web/src/ee/features/playground/page/components/StructuredOutputSchemaSection.tsxnew file mode 100644index 0000000000..df4cae4ac2--- /dev/null+++ b/web/src/ee/features/playground/page/components/StructuredOutputSchemaSection.tsx@@ -0,0 +1,269 @@+import React, { useState, useCallback, useEffect } from "react";++import { usePlaygroundContext } from "@/src/ee/features/playground/page/context";+import { Button } from "@/src/components/ui/button";+import { ScrollArea } from "@/src/components/ui/scroll-area";+import { PlusIcon, PencilIcon, MinusCircle, BoxIcon } from "lucide-react";+import { type LlmSchema } from "@langfuse/shared";+import { api } from "@/src/utils/api";+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";+import { CreateOrEditLLMSchemaDialog } from "@/src/ee/features/playground/page/components/CreateOrEditLLMSchemaDialog";+import {+ Command,+ CommandEmpty,+ CommandGroup,+ CommandInput,+ CommandItem,+ CommandList,+ CommandSeparator,+} from "@/src/components/ui/command";+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from "@/src/components/ui/popover";+import { type PlaygroundSchema } from "@/src/ee/features/playground/page/types";++export const StructuredOutputSchemaSection = () => {+ const { structuredOutputSchema, setStructuredOutputSchema } =+ usePlaygroundContext();+ const projectId = useProjectIdFromURL();+ const [isSearchOpen, setIsSearchOpen] = useState(false);++ const { data: savedSchemas = [] } = api.llmSchemas.getAll.useQuery(+ {+ projectId: projectId as string,+ },+ {+ enabled: Boolean(projectId),+ staleTime: 1000 * 60 * 5, // 5 minutes+ },+ );++ const isSchemaSaved = useCallback(+ (schema: PlaygroundSchema) => {+ return savedSchemas.some((savedSchema) => savedSchema.id === schema.id);+ },+ [savedSchemas],+ );++ useEffect(() => {+ if (structuredOutputSchema && !structuredOutputSchema.existingLlmSchema) {+ const matchingSavedSchema = savedSchemas.find(+ (savedSchema) =>+ savedSchema.name === structuredOutputSchema.name &&+ savedSchema.description === structuredOutputSchema.description &&+ JSON.stringify(savedSchema.schema) ===+ JSON.stringify(structuredOutputSchema.schema),+ );++ if (matchingSavedSchema) {+ setStructuredOutputSchema({+ ...structuredOutputSchema,+ id: matchingSavedSchema.id,+ existingLlmSchema: matchingSavedSchema,+ });+ }+ }+ }, [savedSchemas, structuredOutputSchema, setStructuredOutputSchema]);++ const handleSelectSchema = (selectedLLMSchema: LlmSchema) => {+ if (+ structuredOutputSchema &&+ structuredOutputSchema.id === selectedLLMSchema.id+ ) {+ // Schema already selected, just update it+ setStructuredOutputSchema({+ ...structuredOutputSchema,+ name: selectedLLMSchema.name,+ description: selectedLLMSchema.description,+ schema: selectedLLMSchema.schema as Record<string, unknown>,+ existingLlmSchema: selectedLLMSchema,+ });+ } else if (+ structuredOutputSchema &&+ structuredOutputSchema.name === selectedLLMSchema.name &&+ !isSchemaSaved(structuredOutputSchema)+ ) {+ // Replace unsaved schema with same name+ setStructuredOutputSchema({+ id: selectedLLMSchema.id,+ name: selectedLLMSchema.name,+ description: selectedLLMSchema.description,+ schema: selectedLLMSchema.schema as Record<string, unknown>,+ existingLlmSchema: selectedLLMSchema,+ });+ } else {+ // New schema+ const newPlaygroundSchema: PlaygroundSchema = {+ id: selectedLLMSchema.id,+ name: selectedLLMSchema.name,+ description: selectedLLMSchema.description,+ schema: selectedLLMSchema.schema as Record<string, unknown>,+ existingLlmSchema: selectedLLMSchema,+ };+ setStructuredOutputSchema(newPlaygroundSchema);+ }+ setIsSearchOpen(false);+ };++ const handleRemoveSchema = () => {+ setStructuredOutputSchema(null);+ };++ return (+ <div className="flex h-full flex-col pr-1">+ <div className="mb-2 flex items-center justify-between">+ <div className="flex items-center gap-2">+ <p className="font-semibold">Structured Output</p>+ <a+ href="https://github.com/orgs/langfuse/discussions/3166"+ target="_blank"+ rel="noopener noreferrer"+ className="inline-flex items-center"+ title="Structured output is currently in beta. Click here to learn more and provide feedback!"+ >+ <span className="rounded bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground">+ Beta+ </span>+ </a>+ </div>+ <Popover open={isSearchOpen} onOpenChange={setIsSearchOpen}>+ <PopoverTrigger asChild>+ <Button className="h-7 w-7" variant="outline" size="icon">+ <PlusIcon size={14} />+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="p-1">+ <Command className="flex flex-col">+ <CommandInput+ placeholder="Search schemas..."+ className="h-8 border-none p-1 focus:ring-0 focus:ring-offset-0"+ />+ <CommandList className="max-h-[300px] overflow-y-auto">+ <CommandEmpty>No schemas found.</CommandEmpty>+ <CommandGroup>+ {savedSchemas.map((schema) => (+ <CommandItem+ key={schema.id}+ value={schema.name}+ onSelect={() => handleSelectSchema(schema)}+ className="flex items-center justify-between px-1 py-2"+ >+ <div className="flex items-center gap-2">+ <BoxIcon className="h-4 w-4 text-muted-foreground" />+ <div className="flex-1 overflow-hidden">+ <div className="truncate font-medium">+ {schema.name}+ </div>+ <div className="line-clamp-1 text-xs text-muted-foreground">+ {schema.description}+ </div>+ </div>+ </div>+ <CreateOrEditLLMSchemaDialog+ projectId={projectId as string}+ onSave={handleSelectSchema}+ onDelete={() => handleRemoveSchema()}+ existingLlmSchema={schema}+ >+ <Button+ variant="ghost"+ size="icon"+ className="ml-2 h-7 w-7 shrink-0"+ onClick={(e) => e.stopPropagation()}+ >+ <PencilIcon className="h-3.5 w-3.5" />+ </Button>+ </CreateOrEditLLMSchemaDialog>+ </CommandItem>+ ))}+ </CommandGroup>+ <CommandSeparator />+ </CommandList>+ <div className="mt-auto p-1">+ <CreateOrEditLLMSchemaDialog+ projectId={projectId as string}+ onSave={handleSelectSchema}+ >+ <Button variant="outline" size="default" className="w-full">+ <PlusIcon className="mr-2 h-4 w-4" />+ Create new schema+ </Button>+ </CreateOrEditLLMSchemaDialog>+ </div>+ </Command>+ </PopoverContent>+ </Popover>+ </div>++ <ScrollArea className="h-[calc(100%-2rem)]">+ {!structuredOutputSchema ? (+ <div className="flex h-16 flex-col items-center justify-center p-4 text-center">+ <p className="text-xs text-muted-foreground">No schema provided.</p>+ </div>+ ) : (+ <div className="space-y-1">+ <CreateOrEditLLMSchemaDialog+ projectId={projectId as string}+ onSave={handleSelectSchema}+ onDelete={() => handleRemoveSchema()}+ existingLlmSchema={structuredOutputSchema.existingLlmSchema}+ defaultValues={+ !isSchemaSaved(structuredOutputSchema)+ ? {+ name: structuredOutputSchema.name,+ description: structuredOutputSchema.description,+ schema: JSON.stringify(+ structuredOutputSchema.schema,+ null,+ 2,+ ),+ }+ : undefined+ }+ >+ <div className="cursor-pointer rounded-md border bg-background p-2 transition-colors duration-200 hover:bg-accent/50">+ <div className="mb-1 flex items-center justify-between">+ <div className="flex items-center gap-1">+ <BoxIcon className="h-4 w-4 text-muted-foreground" />+ <h3+ className="max-w-[200px] truncate text-ellipsis text-sm font-medium"+ title={structuredOutputSchema.name}+ >+ {structuredOutputSchema.name}+ </h3>+ {!isSchemaSaved(structuredOutputSchema) ? (+ <span className="rounded bg-muted px-1 py-0.5 text-xs text-muted-foreground">+ Unsaved+ </span>+ ) : null}+ </div>+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="sm"+ className="h-6 w-6 p-0"+ onClick={(e) => {+ e.stopPropagation();+ handleRemoveSchema();+ }}+ >+ <MinusCircle className="h-4 w-4" />+ </Button>+ </div>+ </div>+ <p+ className="line-clamp-2 text-xs text-muted-foreground"+ title={structuredOutputSchema.description}+ >+ {structuredOutputSchema.description}+ </p>+ </div>+ </CreateOrEditLLMSchemaDialog>+ </div>+ )}+ </ScrollArea>+ </div>+ );+};diff --git a/web/src/ee/features/playground/page/components/Variables.tsx b/web/src/ee/features/playground/page/components/Variables.tsxindex d489072eec..e2f3de4374 100644--- a/web/src/ee/features/playground/page/components/Variables.tsx+++ b/web/src/ee/features/playground/page/components/Variables.tsx@@ -15,7 +15,7 @@ export const Variables = () => {</div>);const renderVariables = () => (- <div className="h-full overflow-auto pr-4">+ <div className="h-full overflow-auto">{promptVariables.sort((a, b) => {if (a.isUsed && !b.isUsed) return -1;diff --git a/web/src/ee/features/playground/page/context/index.tsx b/web/src/ee/features/playground/page/context/index.tsxindex 7fd2afa37b..02b17f3277 100644--- a/web/src/ee/features/playground/page/context/index.tsx+++ b/web/src/ee/features/playground/page/context/index.tsx@@ -21,20 +21,36 @@ import {extractVariables,type ChatMessageWithId,type PromptVariable,+ ToolCallResponseSchema,type UIModelParams,+ type ToolCallResponse,+ type LLMToolDefinition,+ type LLMToolCall,+ ChatMessageType,} from "@langfuse/shared";import type { MessagesContext } from "@/src/components/ChatMessages/types";import type { ModelParamsContext } from "@/src/components/ModelParameters";import { env } from "@/src/env.mjs";+import {+ type PlaygroundSchema,+ type PlaygroundTool,+} from "@/src/ee/features/playground/page/types";type PlaygroundContextType = {promptVariables: PromptVariable[];updatePromptVariableValue: (variable: string, value: string) => void;deletePromptVariable: (variable: string) => void;+ tools: PlaygroundTool[];+ setTools: React.Dispatch<React.SetStateAction<PlaygroundTool[]>>;++ structuredOutputSchema: PlaygroundSchema | null;+ setStructuredOutputSchema: (schema: PlaygroundSchema | null) => void;+output: string;outputJson: string;+ outputToolCalls: LLMToolCall[];handleSubmit: () => Promise<void>;isStreaming: boolean;@@ -63,12 +79,25 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({const { playgroundCache, setPlaygroundCache } = usePlaygroundCache();const [promptVariables, setPromptVariables] = useState<PromptVariable[]>([]);const [output, setOutput] = useState("");+ const [outputToolCalls, setOutputToolCalls] = useState<LLMToolCall[]>([]);const [outputJson, setOutputJson] = useState("");const [isStreaming, setIsStreaming] = useState(false);+ const [tools, setTools] = useState<PlaygroundTool[]>([]);+ const [structuredOutputSchema, setStructuredOutputSchema] =+ useState<PlaygroundSchema | null>(null);const [messages, setMessages] = useState<ChatMessageWithId[]>([- createEmptyMessage(ChatMessageRole.System),- createEmptyMessage(ChatMessageRole.User),+ createEmptyMessage({+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "",+ }),+ createEmptyMessage({+ type: ChatMessageType.User,+ role: ChatMessageRole.User,+ content: "",+ }),]);+const {modelParams,setModelParams,@@ -78,6 +107,13 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({setModelParamEnabled,} = useModelParams();+ const toolCallIds = messages.reduce((acc, m) => {+ if (m.type === ChatMessageType.AssistantToolCall) {+ acc.push(...m.toolCalls.map((tc) => tc.id));+ }+ return acc;+ }, [] as string[]);+// Load state from cacheuseEffect(() => {if (!playgroundCache) return;@@ -87,13 +123,24 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({modelParams: cachedModelParams,output: cachedOutput,promptVariables: cachedPromptVariables,+ tools: cachedTools,+ structuredOutputSchema: cachedStructuredOutputSchema,} = playgroundCache;setMessages(cachedMessages.map((m) => ({ ...m, id: uuidv4() })));if (cachedOutput) {- setOutput(cachedOutput);- setOutputJson("");+ // Try parsing a previous output with tool calls+ try {+ const completion = JSON.parse(cachedOutput);+ const parsed = ToolCallResponseSchema.parse(completion);++ setOutput(String(parsed.content));+ setOutputToolCalls(parsed.tool_calls);+ } catch {+ setOutput(cachedOutput);+ setOutputJson("");+ }}if (cachedModelParams) {@@ -103,6 +150,14 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({if (cachedPromptVariables) {setPromptVariables(cachedPromptVariables);}++ if (cachedTools) {+ setTools(cachedTools);+ }++ if (cachedStructuredOutputSchema) {+ setStructuredOutputSchema(cachedStructuredOutputSchema);+ }}, [playgroundCache, setModelParams]);const updatePromptVariables = useCallback(() => {@@ -137,17 +192,46 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({useEffect(updatePromptVariables, [messages, updatePromptVariables]);const addMessage: PlaygroundContextType["addMessage"] = useCallback(- (role, content) => {- const message = createEmptyMessage(role, content);- setMessages((prev) => [...prev, message]);+ (message) => {+ if (message.type === ChatMessageType.AssistantToolCall) {+ const toolCallMessage = createEmptyMessage({+ type: ChatMessageType.AssistantToolCall,+ role: ChatMessageRole.Assistant,+ content: message.content ?? "",+ toolCalls: message.toolCalls,+ });+ const toolResultMessages: ChatMessageWithId[] = [];++ for (const toolCall of message.toolCalls) {+ const toolResultMessage = createEmptyMessage({+ type: ChatMessageType.ToolResult,+ role: ChatMessageRole.Tool,+ content: "",+ toolCallId: toolCall.id,+ });- return message;+ toolResultMessages.push(toolResultMessage);+ }++ setMessages((prev) => [+ ...prev,+ ...[toolCallMessage],+ ...toolResultMessages,+ ]);++ return toolCallMessage;+ } else {+ const newMessage = createEmptyMessage(message);+ setMessages((prev) => [...prev, newMessage]);++ return newMessage;+ }},[],);const updateMessage: PlaygroundContextType["updateMessage"] = useCallback(- (id, key, value) => {+ (_, id, key, value) => {setMessages((prev) =>prev.map((message) =>message.id === id ? { ...message, [key]: value } : message,@@ -157,6 +241,15 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({[],);+ const replaceMessage: PlaygroundContextType["replaceMessage"] = useCallback(+ (id, message) => {+ setMessages((prev) =>+ prev.map((m) => (m.id === id ? { id, ...message } : m)),+ );+ },+ [],+ );+const deleteMessage: PlaygroundContextType["deleteMessage"] = useCallback((id) => {setMessages((prev) => prev.filter((message) => message.id !== id));@@ -170,6 +263,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({setIsStreaming(true);setOutput("");setOutputJson("");+ setOutputToolCalls([]);const finalMessages = getFinalMessages(promptVariables, messages);const leftOverVariables = extractVariables(@@ -184,29 +278,78 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({throw Error("Error replacing variables. Please check your inputs.");}- const completionStream = getChatCompletionStream(- projectId,- finalMessages,- modelParams,- );+ if (tools.length > 0 && structuredOutputSchema) {+ throw new Error(+ "Cannot use both tools and structured output at the same time",+ );+ }let response = "";- for await (const token of completionStream) {- response += token;+ if (tools.length > 0) {+ const completion = await getChatCompletionWithTools(+ projectId,+ finalMessages,+ modelParams,+ tools,+ );++ const displayContent =+ typeof completion.content === "string"+ ? completion.content+ : (completion.content.find(+ (m): m is { type: "text"; text: string } => m.type === "text",+ )?.text as string);++ setOutput(displayContent);+ setOutputToolCalls(completion.tool_calls);++ response = JSON.stringify(completion, null, 2);+ } else if (structuredOutputSchema) {+ response = await getChatCompletionWithStructuredOutput(+ projectId,+ finalMessages,+ modelParams,+ structuredOutputSchema,+ );+setOutput(response);+ } else {+ const completionStream = getChatCompletionStream(+ projectId,+ finalMessages,+ modelParams,+ );++ for await (const token of completionStream) {+ response += token;+ setOutput(response);+ }}- setOutputJson(getOutputJson(response, finalMessages, modelParams));++ setOutputJson(+ getOutputJson(+ response,+ finalMessages,+ modelParams,+ tools,+ structuredOutputSchema,+ ),+ );setPlaygroundCache({messages,modelParams,output: response,promptVariables,+ tools,+ structuredOutputSchema,});capture("playground:execute_button_click", {inputLength: finalMessages.length,modelName: modelParams.model,modelProvider: modelParams.provider,outputLength: response.length,+ toolCount: tools.length,+ isStructuredOutput: Boolean(structuredOutputSchema),});} catch (err) {console.error(err);@@ -216,8 +359,16 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({} finally {setIsStreaming(false);}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [messages, modelParams, promptVariables]);+ }, [+ messages,+ modelParams,+ promptVariables,+ tools,+ capture,+ setPlaygroundCache,+ structuredOutputSchema,+ projectId,+ ]);useCommandEnter(!isStreaming, handleSubmit);@@ -241,11 +392,19 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({updatePromptVariableValue,deletePromptVariable,+ tools,+ setTools,++ structuredOutputSchema,+ setStructuredOutputSchema,+messages,addMessage,setMessages,updateMessage,+ replaceMessage,deleteMessage,+ toolCallIds,modelParams,updateModelParamValue,@@ -253,6 +412,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({output,outputJson,+ outputToolCalls,handleSubmit,isStreaming,@@ -265,6 +425,84 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({);};+async function getChatCompletionWithTools(+ projectId: string | undefined,+ messages: ChatMessageWithId[],+ modelParams: UIModelParams,+ tools: unknown[],+): Promise<ToolCallResponse> {+ if (!projectId) throw Error("Project ID is not set");++ const body = JSON.stringify({+ projectId,+ messages,+ modelParams: getFinalModelParams(modelParams),+ tools,+ });+ const result = await fetch(+ `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chatCompletion`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body,+ },+ );++ const responseData = await result.json();++ if (!result.ok) {+ throw new Error(`Completion failed: ${responseData.message}`);+ }++ const parsed = ToolCallResponseSchema.safeParse(responseData);+ if (!parsed.success)+ throw Error(+ "Failed to parse tool call response client-side:\n" ++ JSON.stringify(responseData, null, 2),+ );++ return parsed.data;+}++async function getChatCompletionWithStructuredOutput(+ projectId: string | undefined,+ messages: ChatMessageWithId[],+ modelParams: UIModelParams,+ structuredOutputSchema: PlaygroundSchema | null,+): Promise<string> {+ if (!projectId) throw Error("Project ID is not set");++ const body = JSON.stringify({+ projectId,+ messages,+ modelParams: getFinalModelParams(modelParams),+ structuredOutputSchema: structuredOutputSchema?.schema,+ });++ const result = await fetch(+ `${env.NEXT_PUBLIC_BASE_PATH ?? ""}/api/chatCompletion`,+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body,+ },+ );++ if (!result.ok) {+ const responseData = await result.json();+ throw new Error(`Completion failed: ${responseData.message}`);+ }++ const responseData = await result.text();++ try {+ const parsed = JSON.parse(responseData);+ return JSON.stringify(parsed, null, 2);+ } catch {+ return responseData;+ }+}+async function* getChatCompletionStream(projectId: string | undefined,messages: ChatMessageWithId[],@@ -332,7 +570,10 @@ function getFinalMessages(// Dynamically replace variables in the promptconst finalMessages = messages- .filter((m) => m.content.length > 0)+ .filter(+ (m) =>+ m.content.length > 0 || ("toolCalls" in m && m.toolCalls.length > 0),+ ).map((m) => {let content = m.content;for (const variable of promptVariables) {@@ -351,12 +592,16 @@ function getOutputJson(output: string,messages: ChatMessageWithId[],modelParams: UIModelParams,+ tools: LLMToolDefinition[],+ structuredOutputSchema: PlaygroundSchema | null,) {return JSON.stringify({input: messages.map((obj) => filterKeyFromObject(obj, "id")),output,model: getFinalModelParams(modelParams),+ tools,+ structuredOutputSchema,},null,2,diff --git a/web/src/ee/features/playground/page/hooks/useModelParams.ts b/web/src/ee/features/playground/page/hooks/useModelParams.tsindex 00ad69c1b9..4870da2162 100644--- a/web/src/ee/features/playground/page/hooks/useModelParams.ts+++ b/web/src/ee/features/playground/page/hooks/useModelParams.ts@@ -145,10 +145,10 @@ function getDefaultAdapterParams(value: adapter,enabled: true,},- temperature: { value: 0, enabled: true },- maxTemperature: { value: 2, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },+ temperature: { value: 0, enabled: false },+ maxTemperature: { value: 2, enabled: false },+ max_tokens: { value: 256, enabled: false },+ top_p: { value: 1, enabled: false },};case LLMAdapter.Azure:@@ -157,10 +157,10 @@ function getDefaultAdapterParams(value: adapter,enabled: true,},- temperature: { value: 0, enabled: true },- maxTemperature: { value: 2, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },+ temperature: { value: 0, enabled: false },+ maxTemperature: { value: 2, enabled: false },+ max_tokens: { value: 256, enabled: false },+ top_p: { value: 1, enabled: false },};// Docs: https://docs.anthropic.com/claude/reference/messages_post@@ -170,10 +170,10 @@ function getDefaultAdapterParams(value: adapter,enabled: true,},- temperature: { value: 0, enabled: true },- maxTemperature: { value: 1, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },+ temperature: { value: 0, enabled: false },+ maxTemperature: { value: 1, enabled: false },+ max_tokens: { value: 256, enabled: false },+ top_p: { value: 1, enabled: false },};case LLMAdapter.Bedrock:@@ -182,10 +182,10 @@ function getDefaultAdapterParams(value: adapter,enabled: true,},- temperature: { value: 0, enabled: true },- maxTemperature: { value: 1, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },+ temperature: { value: 0, enabled: false },+ maxTemperature: { value: 1, enabled: false },+ max_tokens: { value: 256, enabled: false },+ top_p: { value: 1, enabled: false },};case LLMAdapter.VertexAI:@@ -194,10 +194,10 @@ function getDefaultAdapterParams(value: adapter,enabled: true,},- temperature: { value: 1, enabled: true },- maxTemperature: { value: 2, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },+ temperature: { value: 1, enabled: false },+ maxTemperature: { value: 2, enabled: false },+ max_tokens: { value: 256, enabled: false },+ top_p: { value: 1, enabled: false },};case LLMAdapter.GoogleAIStudio:@@ -206,10 +206,10 @@ function getDefaultAdapterParams(value: adapter,enabled: true,},- temperature: { value: 1, enabled: true },- maxTemperature: { value: 2, enabled: true },- max_tokens: { value: 256, enabled: true },- top_p: { value: 1, enabled: true },+ temperature: { value: 1, enabled: false },+ maxTemperature: { value: 2, enabled: false },+ max_tokens: { value: 256, enabled: false },+ top_p: { value: 1, enabled: false },};case LLMAdapter.Atla:return {diff --git a/web/src/ee/features/playground/page/playground.tsx b/web/src/ee/features/playground/page/playground.tsxindex 55177ad3cc..6f62afec30 100644--- a/web/src/ee/features/playground/page/playground.tsx+++ b/web/src/ee/features/playground/page/playground.tsx@@ -2,6 +2,8 @@ import { ModelParameters } from "@/src/components/ModelParameters";import { usePlaygroundContext } from "./context";import { Variables } from "./components/Variables";import { Messages } from "./components/Messages";+import { PlaygroundTools } from "./components/PlaygroundTools";+import { StructuredOutputSchemaSection } from "./components/StructuredOutputSchemaSection";export default function Playground() {const playgroundContext = usePlaygroundContext();@@ -12,11 +14,17 @@ export default function Playground() {<Messages {...playgroundContext} /></div><div className="max-h-full min-h-0 basis-1/4 pr-2">- <div className="grid h-full grid-rows-[minmax(20dvh,max-content),minmax(20dvh,auto)] overflow-auto">- <div className="mb-4 max-h-[80dvh] min-h-[20dvh] overflow-y-auto">+ <div className="flex h-full flex-col gap-4 overflow-auto">+ <div className="mb-4 flex-shrink-0 overflow-y-auto"><ModelParameters {...playgroundContext} /></div>- <div className="min-h-[20dvh]">+ <div className="mb-4 max-h-[25vh] flex-shrink-0 overflow-y-auto">+ <PlaygroundTools />+ </div>+ <div className="mb-4 flex-shrink-0">+ <StructuredOutputSchemaSection />+ </div>+ <div className="flex-grow overflow-y-auto"><Variables /></div></div>diff --git a/web/src/ee/features/playground/page/types.ts b/web/src/ee/features/playground/page/types.tsindex c65b2f6f33..23671a2d60 100644--- a/web/src/ee/features/playground/page/types.ts+++ b/web/src/ee/features/playground/page/types.ts@@ -2,12 +2,31 @@ import {type PromptVariable,type ChatMessage,type UIModelParams,+ type LlmSchema,+ type LLMToolDefinition,+ type LlmTool,+ type LLMJSONSchema,} from "@langfuse/shared";+export type PlaygroundTool = LLMToolDefinition & {+ id: string;+ existingLlmTool?: LlmTool;+};++export type PlaygroundSchema = {+ id: string;+ name: string;+ description: string;+ schema: LLMJSONSchema;+ existingLlmSchema?: LlmSchema;+};+export type PlaygroundCache = {messages: ChatMessage[];modelParams?: Partial<UIModelParams> &Pick<UIModelParams, "provider" | "model">;output?: string | null;promptVariables?: PromptVariable[];+ tools?: PlaygroundTool[];+ structuredOutputSchema?: PlaygroundSchema | null;} | null;diff --git a/web/src/ee/features/playground/server/chatCompletionHandler.ts b/web/src/ee/features/playground/server/chatCompletionHandler.tsindex 5864014409..0b34cd07a2 100644--- a/web/src/ee/features/playground/server/chatCompletionHandler.ts+++ b/web/src/ee/features/playground/server/chatCompletionHandler.ts@@ -25,7 +25,7 @@ export default async function chatCompletionHandler(req: NextRequest) {const body = validateChatCompletionBody(await req.json());const { userId } = await authorizeRequestOrThrow(body.projectId);- const { messages, modelParams } = body;+ const { messages, modelParams, tools, structuredOutputSchema } = body;const LLMApiKey = await prisma.llmApiKeys.findFirst({where: {@@ -46,15 +46,31 @@ export default async function chatCompletionHandler(req: NextRequest) {);}- const { completion } = await fetchLLMCompletion({+ const fetchLLMCompletionParams = {messages,modelParams,- streaming: true,+ structuredOutputSchema,callbacks: [new PosthogCallbackHandler("playground", body, userId)],apiKey: decrypt(parsedKey.data.secretKey),extraHeaders: decryptAndParseExtraHeaders(parsedKey.data.extraHeaders),baseURL: parsedKey.data.baseURL || undefined,config: parsedKey.data.config,+ };++ if ((tools && tools.length > 0) || structuredOutputSchema) {+ const { completion } = await fetchLLMCompletion({+ ...fetchLLMCompletionParams,+ streaming: false,+ tools: tools ?? [],+ structuredOutputSchema,+ });++ return NextResponse.json(completion);+ }++ const { completion } = await fetchLLMCompletion({+ ...fetchLLMCompletionParams,+ streaming: true,});return new StreamingTextResponse(completion);diff --git a/web/src/ee/features/playground/server/validateChatCompletionBody.ts b/web/src/ee/features/playground/server/validateChatCompletionBody.tsindex d562ed0654..7813aa7504 100644--- a/web/src/ee/features/playground/server/validateChatCompletionBody.ts+++ b/web/src/ee/features/playground/server/validateChatCompletionBody.ts@@ -1,5 +1,10 @@import { z } from "zod";-import { ChatMessageRole, LLMAdapter } from "@langfuse/shared";+import {+ LLMAdapter,+ LLMJSONSchema,+ LLMToolDefinitionSchema,+ ChatMessageSchema,+} from "@langfuse/shared";const ModelParamsSchema = z.object({provider: z.string(),@@ -9,15 +14,13 @@ const ModelParamsSchema = z.object({max_tokens: z.number().optional(),top_p: z.number().optional(),});-const MessageSchema = z.object({- role: z.nativeEnum(ChatMessageRole),- content: z.string(),- id: z.string().optional(),-});+export const ChatCompletionBodySchema = z.object({projectId: z.string(),- messages: z.array(MessageSchema),+ messages: z.array(ChatMessageSchema),modelParams: ModelParamsSchema,+ tools: z.array(LLMToolDefinitionSchema).optional(),+ structuredOutputSchema: LLMJSONSchema.optional(),});export const validateChatCompletionBody = (input: unknown) => {diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.tsindex d5e31f5c25..5fddf46fd5 100644--- a/web/src/features/llm-api-key/server/router.ts+++ b/web/src/features/llm-api-key/server/router.ts@@ -16,6 +16,7 @@ import {} from "@langfuse/shared";import { encrypt } from "@langfuse/shared/encryption";import {+ ChatMessageType,fetchLLMCompletion,LLMAdapter,logger,@@ -170,8 +171,16 @@ export const llmApiKeyRouter = createTRPCRouter({}const testMessages: ChatMessage[] = [- { role: ChatMessageRole.System, content: "You are a bot" },- { role: ChatMessageRole.User, content: "How are you?" },+ {+ role: ChatMessageRole.System,+ content: "You are a bot",+ type: ChatMessageType.System,+ },+ {+ role: ChatMessageRole.User,+ content: "How are you?",+ type: ChatMessageType.User,+ },];await fetchLLMCompletion({diff --git a/web/src/features/llm-schemas/server/router.ts b/web/src/features/llm-schemas/server/router.tsnew file mode 100644index 0000000000..2c5fce69f7--- /dev/null+++ b/web/src/features/llm-schemas/server/router.ts@@ -0,0 +1,238 @@+import { type Prisma } from "@langfuse/shared";+import { z } from "zod";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { TRPCError } from "@trpc/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { logger } from "@langfuse/shared/src/server";+import {+ CreateLlmSchemaInput,+ DeleteLlmSchemaInput,+ UpdateLlmSchemaInput,+} from "../validation";++export const llmSchemaRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(CreateLlmSchemaInput)+ .mutation(async ({ input, ctx }) => {+ try {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "llmSchemas:CUD",+ });++ const existingSchema = await ctx.prisma.llmSchema.findUnique({+ where: {+ projectId_name: {+ projectId: input.projectId,+ name: input.name,+ },+ },+ });++ if (existingSchema) {+ throw new TRPCError({+ code: "CONFLICT",+ message:+ "An LLM Schema with this name already exists in this project",+ });+ }++ const llmSchema = await ctx.prisma.llmSchema.create({+ data: {+ projectId: input.projectId,+ name: input.name,+ description: input.description,+ schema: input.schema as Prisma.InputJsonValue,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "project",+ resourceId: llmSchema.id,+ action: "create",+ after: llmSchema,+ });++ return llmSchema;+ } catch (error) {+ logger.error("Failed to create LLM Schema", error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Creating LLM Schema failed",+ });+ }+ }),++ getAll: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ }),+ )+ .query(async ({ input, ctx }) => {+ try {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "llmSchemas:read",+ });++ const llmSchemas = await ctx.prisma.llmSchema.findMany({+ where: {+ projectId: input.projectId,+ },+ orderBy: {+ updatedAt: "desc",+ },+ });++ return llmSchemas;+ } catch (error) {+ logger.error("Failed to get LLM Schemas", error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Fetching LLM Schemas failed",+ });+ }+ }),++ update: protectedProjectProcedure+ .input(UpdateLlmSchemaInput)+ .mutation(async ({ input, ctx }) => {+ try {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "llmSchemas:CUD",+ });++ const existingSchema = await ctx.prisma.llmSchema.findUnique({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ });++ if (!existingSchema) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "LLM Schema not found",+ });+ }++ const duplicateNameCheck = await ctx.prisma.llmSchema.findFirst({+ where: {+ projectId: input.projectId,+ name: input.name,+ id: {+ not: input.id,+ },+ },+ });++ if (duplicateNameCheck) {+ throw new TRPCError({+ code: "CONFLICT",+ message:+ "Another LLM Schema with this name already exists in this project",+ });+ }++ const updatedSchema = await ctx.prisma.llmSchema.update({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ data: {+ name: input.name,+ description: input.description,+ schema: input.schema as Prisma.InputJsonValue,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "project",+ resourceId: updatedSchema.id,+ action: "update",+ before: existingSchema,+ after: updatedSchema,+ });++ return updatedSchema;+ } catch (error) {+ logger.error("Failed to update LLM Schema", error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Updating LLM Schema failed",+ });+ }+ }),++ delete: protectedProjectProcedure+ .input(DeleteLlmSchemaInput)+ .mutation(async ({ input, ctx }) => {+ try {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "llmSchemas:CUD",+ });++ const existingSchema = await ctx.prisma.llmSchema.findUnique({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ });++ if (!existingSchema) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "LLM Schema not found",+ });+ }++ await ctx.prisma.llmSchema.delete({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "project",+ resourceId: input.id,+ action: "delete",+ before: existingSchema,+ });++ return { success: true };+ } catch (error) {+ logger.error("Failed to delete LLM Schema", error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Deleting LLM Schema failed",+ });+ }+ }),+});diff --git a/web/src/features/llm-schemas/validation.ts b/web/src/features/llm-schemas/validation.tsnew file mode 100644index 0000000000..6326d647e2--- /dev/null+++ b/web/src/features/llm-schemas/validation.ts@@ -0,0 +1,28 @@+import { z } from "zod";+import { LLMJSONSchema } from "@langfuse/shared";++export const LLMSchemaInput = z.object({+ name: z+ .string()+ .regex(+ /^[a-z0-9_-]+$/,+ "Name must contain only lowercase letters, numbers, hyphens and underscores",+ )+ .min(1, "Name is required"),+ description: z.string(),+ schema: LLMJSONSchema,+});++export const CreateLlmSchemaInput = LLMSchemaInput.extend({+ projectId: z.string(),+});++export const UpdateLlmSchemaInput = LLMSchemaInput.extend({+ id: z.string(),+ projectId: z.string(),+});++export const DeleteLlmSchemaInput = z.object({+ id: z.string(),+ projectId: z.string(),+});diff --git a/web/src/features/llm-tools/server/router.ts b/web/src/features/llm-tools/server/router.tsnew file mode 100644index 0000000000..0e48bd9035--- /dev/null+++ b/web/src/features/llm-tools/server/router.ts@@ -0,0 +1,238 @@+import { type Prisma } from "@langfuse/shared";+import { z } from "zod";+import {+ createTRPCRouter,+ protectedProjectProcedure,+} from "@/src/server/api/trpc";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import { TRPCError } from "@trpc/server";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { logger } from "@langfuse/shared/src/server";+import {+ CreateLlmToolInput,+ DeleteLlmToolInput,+ UpdateLlmToolInput,+} from "../validation";++export const llmToolRouter = createTRPCRouter({+ create: protectedProjectProcedure+ .input(CreateLlmToolInput)+ .mutation(async ({ input, ctx }) => {+ try {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "llmTools:CUD",+ });++ const existingTool = await ctx.prisma.llmTool.findUnique({+ where: {+ projectId_name: {+ projectId: input.projectId,+ name: input.name,+ },+ },+ });++ if (existingTool) {+ throw new TRPCError({+ code: "CONFLICT",+ message:+ "An LLM Tool with this name already exists in this project",+ });+ }++ const llmTool = await ctx.prisma.llmTool.create({+ data: {+ projectId: input.projectId,+ name: input.name,+ description: input.description,+ parameters: input.parameters as Prisma.InputJsonValue,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "project",+ resourceId: llmTool.id,+ action: "create",+ after: llmTool,+ });++ return llmTool;+ } catch (error) {+ logger.error("Failed to create LLM Tool", error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Creating LLM Tool failed",+ });+ }+ }),++ getAll: protectedProjectProcedure+ .input(+ z.object({+ projectId: z.string(),+ }),+ )+ .query(async ({ input, ctx }) => {+ try {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "llmTools:read",+ });++ const llmTools = await ctx.prisma.llmTool.findMany({+ where: {+ projectId: input.projectId,+ },+ orderBy: {+ updatedAt: "desc",+ },+ });++ return llmTools;+ } catch (error) {+ logger.error("Failed to get LLM Tools", error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Fetching LLM Tools failed",+ });+ }+ }),++ update: protectedProjectProcedure+ .input(UpdateLlmToolInput)+ .mutation(async ({ input, ctx }) => {+ try {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "llmTools:CUD",+ });++ const existingTool = await ctx.prisma.llmTool.findUnique({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ });++ if (!existingTool) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "LLM Tool not found",+ });+ }++ const duplicateNameCheck = await ctx.prisma.llmTool.findFirst({+ where: {+ projectId: input.projectId,+ name: input.name,+ id: {+ not: input.id,+ },+ },+ });++ if (duplicateNameCheck) {+ throw new TRPCError({+ code: "CONFLICT",+ message:+ "Another LLM Tool with this name already exists in this project",+ });+ }++ const updatedTool = await ctx.prisma.llmTool.update({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ data: {+ name: input.name,+ description: input.description,+ parameters: input.parameters as Prisma.InputJsonValue,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "project",+ resourceId: updatedTool.id,+ action: "update",+ before: existingTool,+ after: updatedTool,+ });++ return updatedTool;+ } catch (error) {+ logger.error("Failed to update LLM Tool", error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Updating LLM Tool failed",+ });+ }+ }),++ delete: protectedProjectProcedure+ .input(DeleteLlmToolInput)+ .mutation(async ({ input, ctx }) => {+ try {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "llmTools:CUD",+ });++ const existingTool = await ctx.prisma.llmTool.findUnique({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ });++ if (!existingTool) {+ throw new TRPCError({+ code: "NOT_FOUND",+ message: "LLM Tool not found",+ });+ }++ await ctx.prisma.llmTool.delete({+ where: {+ id: input.id,+ projectId: input.projectId,+ },+ });++ await auditLog({+ session: ctx.session,+ resourceType: "project",+ resourceId: input.id,+ action: "delete",+ before: existingTool,+ });++ return { success: true };+ } catch (error) {+ logger.error("Failed to delete LLM Tool", error);+ if (error instanceof TRPCError) {+ throw error;+ }+ throw new TRPCError({+ code: "INTERNAL_SERVER_ERROR",+ message: "Deleting LLM Tool failed",+ });+ }+ }),+});diff --git a/web/src/features/llm-tools/validation.ts b/web/src/features/llm-tools/validation.tsnew file mode 100644index 0000000000..1e59135378--- /dev/null+++ b/web/src/features/llm-tools/validation.ts@@ -0,0 +1,28 @@+import { z } from "zod";+import { LLMJSONSchema } from "@langfuse/shared";++export const LLMToolInput = z.object({+ name: z+ .string()+ .regex(+ /^[a-z0-9_-]+$/,+ "Name must contain only lowercase letters, numbers, hyphens and underscores",+ )+ .min(1, "Name is required"),+ description: z.string(),+ parameters: LLMJSONSchema,+});++export const CreateLlmToolInput = LLMToolInput.extend({+ projectId: z.string(),+});++export const UpdateLlmToolInput = LLMToolInput.extend({+ id: z.string(),+ projectId: z.string(),+});++export const DeleteLlmToolInput = z.object({+ id: z.string(),+ projectId: z.string(),+});diff --git a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsxindex 7e0ed1d882..b101c1ccbe 100644--- a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx+++ b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx@@ -9,7 +9,8 @@ import {ChatMessageRole,ChatMessageDefaultRoleSchema,type ChatMessageWithId,- ChatMessageListSchema,+ PromptChatMessageListSchema,+ ChatMessageType,} from "@langfuse/shared";import { type NewPromptFormSchemaType } from "./validation";@@ -33,10 +34,17 @@ export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({const [isDialogOpen, setIsDialogOpen] = useState(false);useEffect(() => {- const parsedMessages = ChatMessageListSchema.safeParse(initialMessages);+ const parsedMessages =+ PromptChatMessageListSchema.safeParse(initialMessages);if (!parsedMessages.success || !parsedMessages.data.length) {- setMessages([createEmptyMessage(ChatMessageRole.System)]);+ setMessages([+ createEmptyMessage({+ type: ChatMessageType.System,+ role: ChatMessageRole.System,+ content: "",+ }),+ ]);return;}@@ -45,6 +53,7 @@ export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({parsedMessages.data.map((message) => ({...message,id: uuidv4(),+ type: ChatMessageType.PublicAPICreated,})),);@@ -64,18 +73,15 @@ export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({}}, [initialMessages]);- const addMessage: MessagesContext["addMessage"] = useCallback(- (role, content) => {- const message = createEmptyMessage(role, content);- setMessages((prev) => [...prev, message]);+ const addMessage: MessagesContext["addMessage"] = useCallback((message) => {+ const newMessage = { ...message, id: uuidv4() };+ setMessages((prev) => [...prev, newMessage]);- return message;- },- [],- );+ return newMessage;+ }, []);const updateMessage: MessagesContext["updateMessage"] = useCallback(- (id, key, value) => {+ (type, id, key, value) => {setMessages((prev) =>prev.map((message) =>message.id === id ? { ...message, [key]: value } : message,@@ -89,6 +95,15 @@ export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({setMessages((prev) => prev.filter((message) => message.id !== id));}, []);+ const replaceMessage: MessagesContext["replaceMessage"] = useCallback(+ (id, message) => {+ setMessages((prev) =>+ prev.map((m) => (m.id === id ? { id, ...message } : m)),+ );+ },+ [],+ );+useEffect(() => {onChange(messages);}, [messages, onChange]);@@ -122,6 +137,7 @@ export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({setMessages,deleteMessage,updateMessage,+ replaceMessage,availableRoles,}}/>diff --git a/web/src/features/prompts/components/NewPromptForm/validation.ts b/web/src/features/prompts/components/NewPromptForm/validation.tsindex d471db599c..4067195f31 100644--- a/web/src/features/prompts/components/NewPromptForm/validation.ts+++ b/web/src/features/prompts/components/NewPromptForm/validation.ts@@ -1,6 +1,9 @@import { z } from "zod";import { PromptType } from "@/src/features/prompts/server/utils/validation";-import { ChatMessageListSchema, TextPromptSchema } from "@langfuse/shared";+import {+ PromptChatMessageListSchema,+ TextPromptSchema,+} from "@langfuse/shared";import { COMMIT_MESSAGE_MAX_LENGTH } from "@/src/features/prompts/constants";const NewPromptBaseSchema = z.object({@@ -22,7 +25,7 @@ const NewPromptBaseSchema = z.object({const NewChatPromptSchema = NewPromptBaseSchema.extend({type: z.literal(PromptType.Chat),- chatPrompt: ChatMessageListSchema.refine(+ chatPrompt: PromptChatMessageListSchema.refine((messages) => messages.every((message) => message.content.length > 0),"Enter a chat message or remove the empty message",),@@ -44,7 +47,7 @@ export type NewPromptFormSchemaType = z.infer<typeof NewPromptFormSchema>;export const PromptVariantSchema = z.union([z.object({type: z.literal(PromptType.Chat),- prompt: ChatMessageListSchema,+ prompt: PromptChatMessageListSchema,}),z.object({type: z.literal(PromptType.Text),diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.tsindex 5a01086a73..cdcead2111 100644--- a/web/src/features/rbac/constants/projectAccessRights.ts+++ b/web/src/features/rbac/constants/projectAccessRights.ts@@ -47,6 +47,12 @@ const projectScopes = ["llmApiKeys:create","llmApiKeys:delete",+ "llmSchemas:CUD",+ "llmSchemas:read",++ "llmTools:CUD",+ "llmTools:read",+"comments:CUD","comments:read",@@ -88,6 +94,10 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"llmApiKeys:read","llmApiKeys:create","llmApiKeys:delete",+ "llmSchemas:CUD",+ "llmSchemas:read",+ "llmTools:CUD",+ "llmTools:read","batchExports:create","batchExports:read","comments:CUD",@@ -125,6 +135,10 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"llmApiKeys:read","llmApiKeys:create","llmApiKeys:delete",+ "llmSchemas:CUD",+ "llmSchemas:read",+ "llmTools:CUD",+ "llmTools:read","batchExports:create","batchExports:read","comments:CUD",@@ -154,6 +168,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"evalJob:CUD","evalJobExecution:read","llmApiKeys:read",+ "llmSchemas:read",+ "llmTools:read","batchExports:create","batchExports:read","comments:CUD",@@ -171,6 +187,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"evalJob:read","evalJobExecution:read","llmApiKeys:read",+ "llmSchemas:read",+ "llmTools:read","comments:read","annotationQueues:read","promptExperiments:read",diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex 41525c376c..0838652edb 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -17,6 +17,8 @@ import { evalRouter } from "@/src/ee/features/evals/server/router";import { posthogIntegrationRouter } from "@/src/features/posthog-integration/posthog-integration-router";import { blobStorageIntegrationRouter } from "@/src/features/blobstorage-integration/blobstorage-integration-router";import { llmApiKeyRouter } from "@/src/features/llm-api-key/server/router";+import { llmSchemaRouter } from "@/src/features/llm-schemas/server/router";+import { llmToolRouter } from "@/src/features/llm-tools/server/router";import { organizationsRouter } from "@/src/features/organizations/server/organizationRouter";import { scoreConfigsRouter } from "@/src/server/api/routers/scoreConfigs";import { publicRouter } from "@/src/server/api/routers/public";@@ -64,6 +66,8 @@ export const appRouter = createTRPCRouter({posthogIntegration: posthogIntegrationRouter,blobStorageIntegration: blobStorageIntegrationRouter,llmApiKey: llmApiKeyRouter,+ llmSchemas: llmSchemaRouter,+ llmTools: llmToolRouter,public: publicRouter,credentials: credentialsRouter,utilities: utilsRouter,diff --git a/worker/src/ee/evaluation/evalService.ts b/worker/src/ee/evaluation/evalService.tsindex dd73c4ccb7..2001049267 100644--- a/worker/src/ee/evaluation/evalService.ts+++ b/worker/src/ee/evaluation/evalService.ts@@ -23,6 +23,7 @@ import {StorageService,StorageServiceFactory,CreateEvalQueueEventType,+ ChatMessageType,} from "@langfuse/shared/src/server";import {availableTraceEvalVariables,@@ -430,7 +431,13 @@ export const evaluate = async ({);}- const messages = [{ role: ChatMessageRole.User, content: prompt }];+ const messages = [+ {+ type: ChatMessageType.User,+ role: ChatMessageRole.User,+ content: prompt,+ } as const,+ ];const parsedLLMOutput = await backOff(async () =>diff --git a/worker/src/ee/experiments/experimentService.ts b/worker/src/ee/experiments/experimentService.tsindex 48b056f9f8..cc3302a3c2 100644--- a/worker/src/ee/experiments/experimentService.ts+++ b/worker/src/ee/experiments/experimentService.ts@@ -7,6 +7,8 @@ import {ExperimentMetadataSchema,PromptContentSchema,DatasetRunItemUpsertQueue,+ ChatMessageType,+ ChatMessage,} from "@langfuse/shared/src/server";import { kyselyPrisma, prisma } from "@langfuse/shared/src/db";import { ExperimentCreateEventSchema } from "@langfuse/shared/src/server";@@ -38,7 +40,7 @@ const replaceVariablesInPrompt = (prompt: PromptContent,itemInput: Record<string, any>,variables: string[],-): { role: string; content: string }[] => {+): ChatMessage[] => {const processContent = (content: string) => {// Extract only relevant variables from itemInputconst filteredContext = Object.fromEntries(@@ -54,11 +56,18 @@ const replaceVariablesInPrompt = (};if (typeof prompt === "string") {- return [{ role: ChatMessageRole.System, content: processContent(prompt) }];+ return [+ {+ role: ChatMessageRole.System,+ content: processContent(prompt),+ type: ChatMessageType.System as const,+ },+ ];} else {return prompt.map((message) => ({...message,content: processContent(message.content),+ type: ChatMessageType.PublicAPICreated as const,}));}};@@ -230,7 +239,7 @@ export const createExperimentJob = async ({* VARIABLE EXTRACTION *********************/- let messages: { role: string; content: string }[] = [];+ let messages: ChatMessage[] = [];try {messages = replaceVariablesInPrompt(validatedPrompt.data,