Skip to content

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

feat: adds chat prompts (#1508)

Hassieb Pakzadc92e9984f17d
diff --git a/fern/apis/server/definition/prompts.yml b/fern/apis/server/definition/prompts.yml
index ea03a8688f..aad2090bf7 100644
--- a/fern/apis/server/definition/prompts.yml
+++ b/fern/apis/server/definition/prompts.yml
@@ -25,6 +25,20 @@ service:
types:
CreatePromptRequest:
+ union:
+ chat: CreateChatPromptRequest
+ text: CreateTextPromptRequest
+
+ CreateChatPromptRequest:
+ properties:
+ name: string
+ isActive:
+ docs: Should the prompt be promoted to production immediately?
+ type: boolean
+ prompt: list<ChatMessage>
+ config: optional<unknown>
+
+ CreateTextPromptRequest:
properties:
name: string
isActive:
@@ -34,8 +48,29 @@ types:
config: optional<unknown>
Prompt:
+ union:
+ chat: ChatPrompt
+ text: TextPrompt
+
+ BasePrompt:
properties:
name: string
version: integer
- prompt: string
config: unknown
+
+ ChatMessage:
+ properties:
+ role:
+ type: string
+ content:
+ type: string
+
+ TextPrompt:
+ extends: BasePrompt
+ properties:
+ prompt: string
+
+ ChatPrompt:
+ extends: BasePrompt
+ properties:
+ prompt: list<ChatMessage>
diff --git a/generated/postman/collection.json b/generated/postman/collection.json
index 6dfe0fdec5..8702aaadb8 100644
--- a/generated/postman/collection.json
+++ b/generated/postman/collection.json
@@ -628,7 +628,7 @@
"auth": null,
"body": {
"mode": "raw",
- "raw": "{\n \"name\": \"example\",\n \"isActive\": true,\n \"prompt\": \"example\",\n \"config\": \"UNKNOWN\"\n}",
+ "raw": "{\n \"type\": \"chat\",\n \"name\": \"example\",\n \"isActive\": true,\n \"prompt\": [\n {\n \"role\": \"example\",\n \"content\": \"example\"\n }\n ],\n \"config\": \"UNKNOWN\"\n}",
"options": {
"raw": {
"language": "json"
diff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.ts
index 2ce2045e9b..1562e26718 100644
--- a/packages/shared/prisma/generated/types.ts
+++ b/packages/shared/prisma/generated/types.ts
@@ -253,9 +253,10 @@ export type Prompt = {
updated_at: Generated<Timestamp>;
project_id: string;
created_by: string;
- prompt: string;
+ prompt: unknown;
name: string;
version: number;
+ type: Generated<string>;
is_active: boolean;
config: Generated<unknown>;
};
diff --git a/packages/shared/prisma/migrations/20240405124810_prompt_to_json/migration.sql b/packages/shared/prisma/migrations/20240405124810_prompt_to_json/migration.sql
new file mode 100644
index 0000000000..2f4d8e3993
--- /dev/null
+++ b/packages/shared/prisma/migrations/20240405124810_prompt_to_json/migration.sql
@@ -0,0 +1,21 @@
+BEGIN;
+
+ALTER TABLE prompts
+ADD COLUMN json_prompt JSONB;
+
+UPDATE prompts
+SET json_prompt = to_json(prompt::text)::json;
+
+ALTER TABLE prompts
+DROP COLUMN prompt;
+
+ALTER TABLE prompts
+RENAME COLUMN json_prompt TO prompt;
+
+ALTER TABLE prompts
+ALTER COLUMN prompt SET NOT NULL;
+
+ALTER TABLE prompts
+ADD COLUMN type TEXT NOT NULL DEFAULT 'text';
+
+COMMIT;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index ff639b19e6..5d767cd8a1 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -521,9 +521,10 @@ model Prompt {
createdBy String @map("created_by")
- prompt String
+ prompt Json
name String
version Int
+ type String @default("text")
isActive Boolean @map("is_active")
config Json @default("{}")
Observation Observation[]
diff --git a/web/generated/openapi-server/openapi.yml b/web/generated/openapi-server/openapi.yml
index 86a8671861..a8ac42047a 100644
--- a/web/generated/openapi-server/openapi.yml
+++ b/web/generated/openapi-server/openapi.yml
@@ -2412,6 +2412,50 @@ components:
- name
CreatePromptRequest:
title: CreatePromptRequest
+ oneOf:
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - chat
+ - $ref: '#/components/schemas/CreateChatPromptRequest'
+ required:
+ - type
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - text
+ - $ref: '#/components/schemas/CreateTextPromptRequest'
+ required:
+ - type
+ CreateChatPromptRequest:
+ title: CreateChatPromptRequest
+ type: object
+ properties:
+ name:
+ type: string
+ isActive:
+ type: boolean
+ description: Should the prompt be promoted to production immediately?
+ prompt:
+ type: array
+ items:
+ $ref: '#/components/schemas/ChatMessage'
+ config:
+ nullable: true
+ required:
+ - name
+ - isActive
+ - prompt
+ CreateTextPromptRequest:
+ title: CreateTextPromptRequest
type: object
properties:
name:
@@ -2429,20 +2473,75 @@ components:
- prompt
Prompt:
title: Prompt
+ oneOf:
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - chat
+ - $ref: '#/components/schemas/ChatPrompt'
+ required:
+ - type
+ - type: object
+ allOf:
+ - type: object
+ properties:
+ type:
+ type: string
+ enum:
+ - text
+ - $ref: '#/components/schemas/TextPrompt'
+ required:
+ - type
+ BasePrompt:
+ title: BasePrompt
type: object
properties:
name:
type: string
version:
type: integer
- prompt:
- type: string
config: {}
required:
- name
- version
- - prompt
- config
+ ChatMessage:
+ title: ChatMessage
+ type: object
+ properties:
+ role:
+ type: string
+ content:
+ type: string
+ required:
+ - role
+ - content
+ TextPrompt:
+ title: TextPrompt
+ type: object
+ properties:
+ prompt:
+ type: string
+ required:
+ - prompt
+ allOf:
+ - $ref: '#/components/schemas/BasePrompt'
+ ChatPrompt:
+ title: ChatPrompt
+ type: object
+ properties:
+ prompt:
+ type: array
+ items:
+ $ref: '#/components/schemas/ChatMessage'
+ required:
+ - prompt
+ allOf:
+ - $ref: '#/components/schemas/BasePrompt'
CreateScoreRequest:
title: CreateScoreRequest
type: object
diff --git a/web/src/__tests__/prompts.servertest.ts b/web/src/__tests__/prompts.servertest.ts
index 466545a3be..3c70a5c94b 100644
--- a/web/src/__tests__/prompts.servertest.ts
+++ b/web/src/__tests__/prompts.servertest.ts
@@ -4,6 +4,11 @@ import { prisma } from "@langfuse/shared/src/db";
import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
import { v4 as uuidv4, v4 } from "uuid";
import { type Prompt } from "@langfuse/shared/src/db";
+import {
+ PromptSchema,
+ PromptType,
+ type ValidatedPrompt,
+} from "@/src/features/prompts/server/validation";
describe("/api/public/prompts API Endpoint", () => {
beforeEach(async () => await pruneDatabase());
@@ -43,6 +48,7 @@ describe("/api/public/prompts API Endpoint", () => {
expect(fetchedObservations.body.id).toBe(promptId);
expect(fetchedObservations.body.name).toBe("prompt-name");
expect(fetchedObservations.body.prompt).toBe("prompt");
+ expect(fetchedObservations.body.type).toBe("text");
expect(fetchedObservations.body.version).toBe(1);
expect(fetchedObservations.body.isActive).toBe(true);
expect(fetchedObservations.body.createdBy).toBe("user-1");
@@ -190,6 +196,7 @@ describe("/api/public/prompts API Endpoint", () => {
expect(fetchedObservations.body.id).toBe(promptIdTwo);
expect(fetchedObservations.body.name).toBe("prompt-name");
expect(fetchedObservations.body.prompt).toBe("prompt");
+ expect(fetchedObservations.body.type).toBe("text");
expect(fetchedObservations.body.version).toBe(2);
expect(fetchedObservations.body.isActive).toBe(true);
expect(fetchedObservations.body.createdBy).toBe("user-1");
@@ -221,6 +228,7 @@ describe("/api/public/prompts API Endpoint", () => {
expect(fetchedObservations.body.name).toBe("prompt-name");
expect(fetchedObservations.body.prompt).toBe("prompt");
+ expect(fetchedObservations.body.type).toBe("text");
expect(fetchedObservations.body.version).toBe(1);
expect(fetchedObservations.body.isActive).toBe(true);
expect(fetchedObservations.body.createdBy).toBe("API");
@@ -342,8 +350,6 @@ describe("/api/public/prompts API Endpoint", () => {
expect(response.status).toBe(207);
- console.log("response body", response.body);
-
const dbGeneration = await prisma.observation.findUnique({
where: {
id: generationId,
@@ -375,11 +381,185 @@ describe("/api/public/prompts API Endpoint", () => {
expect(fetchedObservations.body.name).toBe("prompt-name");
expect(fetchedObservations.body.prompt).toBe("prompt");
+ expect(fetchedObservations.body.type).toBe("text");
expect(fetchedObservations.body.version).toBe(1);
expect(fetchedObservations.body.isActive).toBe(true);
expect(fetchedObservations.body.createdBy).toBe("API");
expect(fetchedObservations.body.config).toEqual({});
});
+
+ it("should create and fetch a chat prompt", async () => {
+ const promptName = "prompt-name";
+ const chatMessages = [
+ { role: "system", content: "You are a bot" },
+ { role: "user", content: "What's up?" },
+ ];
+ const response = await makeAPICall("POST", "/api/public/prompts", {
+ name: promptName,
+ prompt: chatMessages,
+ type: "chat",
+ isActive: true,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+
+ expect(response.status).toBe(201);
+
+ const { body: fetchedPrompt } = await makeAPICall(
+ "GET",
+ `/api/public/prompts?name=${promptName}`,
+ undefined,
+ );
+
+ const validatedPrompt = validatePrompt(fetchedPrompt);
+
+ expect(validatedPrompt.name).toBe("prompt-name");
+ expect(validatedPrompt.prompt).toEqual(chatMessages);
+ expect(validatedPrompt.type).toBe("chat");
+ expect(validatedPrompt.version).toBe(1);
+ expect(validatedPrompt.isActive).toBe(true);
+ expect(validatedPrompt.createdBy).toBe("API");
+ expect(validatedPrompt.config).toEqual({});
+ });
+
+ it("should fail if chat prompt has string prompt", async () => {
+ const promptName = "prompt-name";
+ const response = await makeAPICall("POST", "/api/public/prompts", {
+ name: promptName,
+ prompt: "prompt",
+ type: "chat",
+ isActive: true,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+
+ expect(response.status).toBe(400);
+
+ const { body, status } = await makeAPICall(
+ "GET",
+ `/api/public/prompts?name=${promptName}`,
+ undefined,
+ );
+ expect(status).toBe(404);
+ expect(body).toEqual({
+ error: "NotFoundError",
+ message: "Prompt not found",
+ });
+ });
+
+ it("should fail if chat prompt has incorrect messages format", async () => {
+ const promptName = "prompt-name";
+ const incorrectChatMessages = [
+ { role: "system", content: "You are a bot" },
+ { role: "user", message: "What's up?" },
+ ];
+ const response = await makeAPICall("POST", "/api/public/prompts", {
+ name: promptName,
+ prompt: incorrectChatMessages,
+ type: "chat",
+ isActive: true,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+
+ expect(response.status).toBe(400);
+
+ const { body, status } = await makeAPICall(
+ "GET",
+ `/api/public/prompts?name=${promptName}`,
+ undefined,
+ );
+ expect(status).toBe(404);
+ expect(body).toEqual({
+ error: "NotFoundError",
+ message: "Prompt not found",
+ });
+ });
+ it("should fail if text prompt has message format", async () => {
+ const promptName = "prompt-name";
+ const response = await makeAPICall("POST", "/api/public/prompts", {
+ name: promptName,
+ prompt: [{ role: "system", content: "You are a bot" }],
+ type: "text",
+ isActive: true,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+
+ expect(response.status).toBe(400);
+
+ const { body, status } = await makeAPICall(
+ "GET",
+ `/api/public/prompts?name=${promptName}`,
+ undefined,
+ );
+ expect(status).toBe(404);
+ expect(body).toEqual({
+ error: "NotFoundError",
+ message: "Prompt not found",
+ });
+ });
+
+ it("should fail if previous versions have different prompt type", async () => {
+ // Create a chat prompt
+ const promptName = "prompt-name";
+ const chatMessages = [
+ { role: "system", content: "You are a bot" },
+ { role: "user", content: "What's up?" },
+ ];
+ const postResponse1 = await makeAPICall("POST", "/api/public/prompts", {
+ name: promptName,
+ prompt: chatMessages,
+ type: "chat",
+ isActive: true,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+
+ expect(postResponse1.status).toBe(201);
+
+ // Try creating a text prompt with the same name
+ const postResponse2 = await makeAPICall("POST", "/api/public/prompts", {
+ name: promptName,
+ prompt: "prompt",
+ type: "text",
+ isActive: true,
+ version: 2,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+
+ expect(postResponse2.status).toBe(400);
+ expect(postResponse2.body).toEqual({
+ error: "ValidationError",
+ message:
+ "Previous versions have different prompt type. Create a new prompt with a different name.",
+ });
+
+ // Check if the prompt is still the chat prompt
+ const getResponse1 = await makeAPICall(
+ "GET",
+ `/api/public/prompts?name=${promptName}`,
+ undefined,
+ );
+ expect(getResponse1.status).toBe(200);
+
+ const validatedPrompt = validatePrompt(getResponse1.body);
+
+ expect(validatedPrompt.name).toBe("prompt-name");
+ expect(validatedPrompt.prompt).toEqual(chatMessages);
+ expect(validatedPrompt.type).toBe("chat");
+ expect(validatedPrompt.version).toBe(1);
+ expect(validatedPrompt.isActive).toBe(true);
+ expect(validatedPrompt.createdBy).toBe("API");
+ expect(validatedPrompt.config).toEqual({});
+
+ // Check that the text prompt has not been created
+ const getResponse2 = await makeAPICall(
+ "GET",
+ `/api/public/prompts?name=${promptName}&version=2`,
+ undefined,
+ );
+ expect(getResponse2.status).toBe(404);
+ expect(getResponse2.body).toEqual({
+ error: "NotFoundError",
+ message: "Prompt not found",
+ });
+ });
});
const isPrompt = (x: unknown): x is Prompt => {
@@ -393,6 +573,18 @@ const isPrompt = (x: unknown): x is Prompt => {
typeof prompt.isActive === "boolean" &&
typeof prompt.projectId === "string" &&
typeof prompt.createdBy === "string" &&
- typeof prompt.config === "object"
+ typeof prompt.config === "object" &&
+ Object.values(PromptType).includes(prompt.type as PromptType)
);
};
+
+const validatePrompt = (obj: Record<string, unknown>): ValidatedPrompt => {
+ Object.keys(obj).forEach((key) => {
+ obj[key] =
+ key === "createdAt" || key === "updatedAt"
+ ? new Date(obj[key] as string)
+ : obj[key];
+ });
+
+ return PromptSchema.parse(obj);
+};
diff --git a/web/src/components/projectNavigation.tsx b/web/src/components/projectNavigation.tsx
index 6daed18079..d06fa59ff8 100644
--- a/web/src/components/projectNavigation.tsx
+++ b/web/src/components/projectNavigation.tsx
@@ -7,7 +7,6 @@ import {
SelectValue,
} from "@/src/components/ui/select";
import { cn } from "@/src/utils/tailwind";
-import { Code } from "lucide-react";
import { useRouter } from "next/router";
interface Project {
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index aa491a539b..3fd35f290a 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -6,11 +6,11 @@ import useColumnVisibility from "@/src/features/column-visibility/hooks/useColum
import { useQueryFilterState } from "@/src/features/filters/hooks/useFilterState";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import {
- ScoreOptions,
+ type ScoreOptions,
scoresTableColsWithOptions,
} from "@/src/server/api/definitions/scoresTable";
import { api } from "@/src/utils/api";
-import { RouterOutput, type RouterInput } from "@/src/utils/types";
+import type { RouterOutput, RouterInput } from "@/src/utils/types";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
export type ScoresTableRow = {
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index c41e507ae3..156a40166c 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -14,7 +14,7 @@ import { type FilterState } from "@/src/features/filters/types";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
import { useOrderByState } from "@/src/features/orderBy/hooks/useOrderByState";
import {
- TraceOptions,
+ type TraceOptions,
tracesTableColsWithOptions,
} from "@/src/server/api/definitions/tracesTable";
import { api } from "@/src/utils/api";
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index db7dfcaae6..a7d4982009 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -136,11 +136,12 @@ const ChatMlMessageSchema = z
content,
json: Object.keys(other).length === 0 ? undefined : other,
}));
-const ChatMlArraySchema = z.array(ChatMlMessageSchema).min(1);
+export const ChatMlArraySchema = z.array(ChatMlMessageSchema).min(1);
-const OpenAiMessageView: React.FC<{
+export const OpenAiMessageView: React.FC<{
+ title?: string;
messages: z.infer<typeof ChatMlArraySchema>;
-}> = ({ messages }) => {
+}> = ({ title, messages }) => {
const COLLAPSE_THRESHOLD = 3;
const [isCollapsed, setCollapsed] = useState(
messages.length > COLLAPSE_THRESHOLD ? true : null,
@@ -158,58 +159,65 @@ const OpenAiMessageView: React.FC<{
// );
return (
- <div className="flex flex-col gap-2 rounded-md border p-3">
- {transformedMessages
- .filter(
- (_, i) =>
- // show all if not collapsed or null; show first and last n if collapsed
- !isCollapsed || i == 0 || i > messages.length - COLLAPSE_THRESHOLD,
- )
- .map((message, index) => (
- <Fragment key={index}>
- <div>
- {!!message.content && (
- <JSONView
- title={message.name ?? message.role}
- json={message.content}
- className={cn(
- "bg-gray-100",
- message.role === "system" && "bg-gray-100",
- message.role === "assistant" && "bg-green-50",
- message.role === "user" && "bg-white",
- !!message.json && "rounded-b-none",
- )}
- />
- )}
- {!!message.json && (
- <JSONView
- title={
- message.content ? undefined : message.name ?? message.role
- }
- json={message.json}
- className={cn(
- "bg-gray-100",
- message.role === "system" && "bg-gray-100",
- message.role === "assistant" && "bg-green-50",
- message.role === "user" && "bg-white",
- !!message.content && "rounded-t-none border-t-0",
- )}
- />
- )}
- </div>
- {isCollapsed !== null && index === 0 ? (
- <Button
- variant="ghost"
- size="xs"
- onClick={() => setCollapsed((v) => !v)}
- >
- {isCollapsed
- ? `Show ${messages.length - COLLAPSE_THRESHOLD} more ...`
- : "Hide history"}
- </Button>
- ) : null}
- </Fragment>
- ))}
+ <div className="rounded-md border">
+ {title && (
+ <div className="border-b px-3 py-1 text-xs font-medium">{title}</div>
+ )}
+ <div className="flex flex-col gap-2 p-3">
+ {transformedMessages
+ .filter(
+ (_, i) =>
+ // show all if not collapsed or null; show first and last n if collapsed
+ !isCollapsed ||
+ i == 0 ||
+ i > messages.length - COLLAPSE_THRESHOLD,
+ )
+ .map((message, index) => (
+ <Fragment key={index}>
+ <div>
+ {!!message.content && (
+ <JSONView
+ title={message.name ?? message.role}
+ json={message.content}
+ className={cn(
+ "bg-gray-100",
+ message.role === "system" && "bg-gray-100",
+ message.role === "assistant" && "bg-green-50",
+ message.role === "user" && "bg-white",
+ !!message.json && "rounded-b-none",
+ )}
+ />
+ )}
+ {!!message.json && (
+ <JSONView
+ title={
+ message.content ? undefined : message.name ?? message.role
+ }
+ json={message.json}
+ className={cn(
+ "bg-gray-100",
+ message.role === "system" && "bg-gray-100",
+ message.role === "assistant" && "bg-green-50",
+ message.role === "user" && "bg-white",
+ !!message.content && "rounded-t-none border-t-0",
+ )}
+ />
+ )}
+ </div>
+ {isCollapsed !== null && index === 0 ? (
+ <Button
+ variant="ghost"
+ size="xs"
+ onClick={() => setCollapsed((v) => !v)}
+ >
+ {isCollapsed
+ ? `Show ${messages.length - COLLAPSE_THRESHOLD} more ...`
+ : "Hide history"}
+ </Button>
+ ) : null}
+ </Fragment>
+ ))}
+ </div>
</div>
);
};
diff --git a/web/src/features/column-visibility/hooks/setSmallPaginationIfColumnsVisible.tsx b/web/src/features/column-visibility/hooks/setSmallPaginationIfColumnsVisible.tsx
index e07fd8d37e..2d24a27b28 100644
--- a/web/src/features/column-visibility/hooks/setSmallPaginationIfColumnsVisible.tsx
+++ b/web/src/features/column-visibility/hooks/setSmallPaginationIfColumnsVisible.tsx
@@ -1,7 +1,6 @@
-import { type LangfuseColumnDef } from "@/src/components/table/types";
-import React from "react";
-import { TracesTableRow } from "@/src/components/table/use-cases/traces";
-import { GenerationsTableRow } from "../../../components/table/use-cases/generations";
+import type React from "react";
+import type { TracesTableRow } from "@/src/components/table/use-cases/traces";
+import type { GenerationsTableRow } from "../../../components/table/use-cases/generations";
export type TableColumn =
| (keyof GenerationsTableRow)[]
diff --git a/web/src/features/datasets/components/DatasetRunItemsTable.tsx b/web/src/features/datasets/components/DatasetRunItemsTable.tsx
index aba82cab2f..aaa597ab26 100644
--- a/web/src/features/datasets/components/DatasetRunItemsTable.tsx
+++ b/web/src/features/datasets/components/DatasetRunItemsTable.tsx
@@ -3,7 +3,7 @@ import { DataTable } from "@/src/components/table/data-table";
import TableLink from "@/src/components/table/table-link";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { api } from "@/src/utils/api";
-import { formatIntervalSeconds, intervalInSeconds } from "@/src/utils/dates";
+import { formatIntervalSeconds } from "@/src/utils/dates";
import { type RouterOutput } from "@/src/utils/types";
import { useQueryParams, withDefault, NumberParam } from "use-query-params";
diff --git a/web/src/features/feature-flags/hooks/useIsFeatureEnabled.ts b/web/src/features/feature-flags/hooks/useIsFeatureEnabled.ts
new file mode 100644
index 0000000000..b8cdf3544e
--- /dev/null
+++ b/web/src/features/feature-flags/hooks/useIsFeatureEnabled.ts
@@ -0,0 +1,15 @@
+import { useSession } from "next-auth/react";
+
+import { api } from "@/src/utils/api";
+
+import type { Flag } from "../types";
+
+export default function useIsFeatureEnabled(feature: Flag): boolean {
+ const session = useSession();
+ const isExperimentalFeaturesEnabled =
+ api.environment.enableExperimentalFeatures.useQuery().data ?? false;
+ const isFeatureEnabledOnUser =
+ session.data?.user?.featureFlags[feature] ?? false;
+
+ return isExperimentalFeaturesEnabled || isFeatureEnabledOnUser;
+}
diff --git a/web/src/features/playground/client/components/ChatMessageComponent.tsx b/web/src/features/playground/client/components/ChatMessageComponent.tsx
index 48909bc1a1..a8b27248c7 100644
--- a/web/src/features/playground/client/components/ChatMessageComponent.tsx
+++ b/web/src/features/playground/client/components/ChatMessageComponent.tsx
@@ -5,17 +5,16 @@ import { ChatMessageRole, type ChatMessageWithId } from "@langfuse/shared";
import { Button } from "@/src/components/ui/button";
import { Card, CardContent } from "@/src/components/ui/card";
import { Textarea } from "@/src/components/ui/textarea";
-import { MessagesContext } from "@/src/features/playground/client/components/Messages";
+import type { MessagesContext } from "@/src/features/playground/client/components/Messages";
type ChatMessageProps = Pick<
MessagesContext,
- "deleteMessage" | "updateMessage" | "updatePromptVariables"
+ "deleteMessage" | "updateMessage"
> & { message: ChatMessageWithId };
export const ChatMessageComponent: React.FC<ChatMessageProps> = ({
message,
updateMessage,
- updatePromptVariables,
deleteMessage,
}) => {
const textAreaRef = useRef<HTMLTextAreaElement | null>(null);
@@ -49,30 +48,35 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({
}, [message.content]);
return (
- <Card>
- <CardContent className="flex flex-row space-x-1 pt-6">
- <div className="min-w-[7rem]">
- <Button onClick={toggleRole} variant="outline">
+ <Card className="p-3">
+ <CardContent className="flex flex-row space-x-1 p-0">
+ <div className="min-w-[6rem]">
+ <Button
+ onClick={toggleRole}
+ type="button" // prevents submitting a form if this button is inside a form
+ variant="outline"
+ className="text-xs"
+ >
{capitalize(message.role)}
</Button>
</div>
<Textarea
ref={textAreaRef}
- className="height-[auto] min-h-10 w-full font-mono focus:outline-none"
+ className="height-[auto] min-h-8 w-full pt-3 font-mono text-xs focus:outline-none"
placeholder={placeholder}
value={message.content}
onChange={handleContentChange}
- onBlur={updatePromptVariables}
rows={textAreaRows}
/>
<Button
variant="ghost"
+ type="button" // prevents submitting a form if this button is inside a form
size="icon"
onClick={() => deleteMessage(message.id)}
disabled={message.role === ChatMessageRole.System}
>
- <MinusCircleIcon />
+ <MinusCircleIcon size={16} />
</Button>
</CardContent>
</Card>
diff --git a/web/src/features/playground/client/components/ChatMessages.tsx b/web/src/features/playground/client/components/ChatMessages.tsx
index b08e885461..53be4ea87c 100644
--- a/web/src/features/playground/client/components/ChatMessages.tsx
+++ b/web/src/features/playground/client/components/ChatMessages.tsx
@@ -2,9 +2,9 @@ import { PlusCircleIcon } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { ChatMessageComponent } from "@/src/features/playground/client/components/ChatMessageComponent";
-import { MessagesContext } from "@/src/features/playground/client/components/Messages";
+import type { MessagesContext } from "@/src/features/playground/client/components/Messages";
import { ChatMessageRole } from "@langfuse/shared";
-import { useRef, useCallback, useEffect, useState } from "react";
+import { useRef, useEffect } from "react";
type ChatMessagesProps = MessagesContext;
export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {
@@ -48,11 +48,12 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({
return (
<Button
+ type="button" // prevents submitting a form if this button is inside a form
variant="outline"
className="w-full space-x-2 py-6"
onClick={() => addMessage(nextMessageRole)}
>
- <PlusCircleIcon />
+ <PlusCircleIcon size={16} />
<p>Add message</p>
</Button>
);
diff --git a/web/src/features/playground/client/components/Messages.tsx b/web/src/features/playground/client/components/Messages.tsx
index dcca0bf46b..d42205990a 100644
--- a/web/src/features/playground/client/components/Messages.tsx
+++ b/web/src/features/playground/client/components/Messages.tsx
@@ -1,6 +1,6 @@
import { Button } from "@/src/components/ui/button";
import { usePlaygroundContext } from "@/src/features/playground/client/context";
-import { ChatMessageRole, ChatMessageWithId } from "@langfuse/shared";
+import type { ChatMessageRole, ChatMessageWithId } from "@langfuse/shared";
import { GenerationOutput } from "./GenerationOutput";
import { ChatMessages } from "@/src/features/playground/client/components/ChatMessages";
@@ -14,7 +14,6 @@ export type MessagesContext = {
key: Key,
value: ChatMessageWithId[Key],
) => void;
- updatePromptVariables: () => void;
};
export const Messages: React.FC<MessagesContext> = (props) => {
@@ -34,7 +33,7 @@ const SubmitButton = () => {
return (
<Button
variant="default"
- className="w-full space-x-2 py-6"
+ className="h-[88px] w-full space-x-2 py-3"
onClick={() => {
handleSubmit().catch((err) => console.error(err));
}}
diff --git a/web/src/features/playground/client/components/PromptVariableComponent.tsx b/web/src/features/playground/client/components/PromptVariableComponent.tsx
index 56baf865fe..6f60974f89 100644
--- a/web/src/features/playground/client/components/PromptVariableComponent.tsx
+++ b/web/src/features/playground/client/components/PromptVariableComponent.tsx
@@ -43,7 +43,7 @@ export const PromptVariableComponent: React.FC<{
onClick={handleDeleteVariable}
className="p-0"
>
- <Trash2Icon size={16} />
+ {!isUsed && <Trash2Icon size={16} />}
</Button>
</div>
);
diff --git a/web/src/features/playground/client/context/index.tsx b/web/src/features/playground/client/context/index.tsx
index 1ddd9154f3..9e0bdb7b37 100644
--- a/web/src/features/playground/client/context/index.tsx
+++ b/web/src/features/playground/client/context/index.tsx
@@ -1,25 +1,30 @@
import React, {
createContext,
- PropsWithChildren,
+ type PropsWithChildren,
useCallback,
useContext,
useEffect,
useState,
} from "react";
-import { v4 as uuidv4 } from "uuid";
-
-import { MessagesContext } from "@/src/features/playground/client/components/Messages";
-import { ModelParamsContext } from "@/src/features/playground/client/components/ModelParameters";
+import type { MessagesContext } from "@/src/features/playground/client/components/Messages";
+import type { ModelParamsContext } from "@/src/features/playground/client/components/ModelParameters";
import useCommandEnter from "@/src/features/playground/client/hooks/useCommandEnter";
import { extractVariables } from "@/src/utils/string";
import {
ChatMessageRole,
- ChatMessageWithId,
+ type ChatMessageWithId,
ModelProvider,
- PromptVariable,
- UIModelParams,
+ type PromptVariable,
+ type UIModelParams,
} from "@langfuse/shared";
+import { createEmptyMessage } from "../utils/createEmptyMessage";
+import { StringParam, useQueryParam } from "use-query-params";
+import { api } from "@/src/utils/api";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { PromptType } from "@/src/features/prompts/server/validation";
+import { ChatMessageListSchema } from "@/src/features/prompts/components/NewPromptForm/validation";
+import { v4 as uuidv4 } from "uuid";
type PlaygroundContextType = {
promptVariables: PromptVariable[];
@@ -31,6 +36,7 @@ type PlaygroundContextType = {
handleSubmit: () => Promise<void>;
isStreaming: boolean;
+ isInitializing: boolean;
} & ModelParamsContext &
MessagesContext;
@@ -51,6 +57,8 @@ export const usePlaygroundContext = () => {
export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
children,
}) => {
+ const projectId = useProjectIdFromURL();
+ const [initialPromptId] = useQueryParam("promptId", StringParam);
const [promptVariables, setPromptVariables] = useState<PromptVariable[]>([]);
const [output, setOutput] = useState("");
const [outputJson, setOutputJson] = useState("");
@@ -63,6 +71,36 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
getDefaultModelParams(ModelProvider.OpenAI),
);
+ const { data: initialPrompt, isInitialLoading } = api.prompts.byId.useQuery(
+ {
+ projectId,
+ id: initialPromptId ?? "",
+ },
+ { enabled: Boolean(initialPromptId), staleTime: Infinity }, // do not refetch as this would overwrite the user's input
+ );
+
+ useEffect(() => {
+ if (!initialPrompt) return;
+ if (initialPrompt.type === PromptType.Chat) {
+ try {
+ const initialMessages = ChatMessageListSchema.parse(
+ initialPrompt.prompt,
+ );
+ setMessages(initialMessages.map((m) => ({ ...m, id: uuidv4() })));
+ } catch (err) {
+ console.warn("Failed to parse initial chat messages", err);
+ }
+ } else {
+ const promptString = initialPrompt.prompt?.valueOf();
+ setMessages([
+ createEmptyMessage(
+ ChatMessageRole.System,
+ typeof promptString === "string" ? promptString : "",
+ ),
+ ]);
+ }
+ }, [initialPrompt]);
+
useEffect(() => {
setModelParams(getDefaultModelParams(modelParams.provider));
}, [modelParams.provider]);
@@ -130,7 +168,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
const finalMessages = getFinalMessages(promptVariables, messages);
const leftOverVariables = extractVariables(
- finalMessages.map((m) => m.content).join(""),
+ finalMessages.map((m) => m.content).join("\n"),
);
if (leftOverVariables.length > 0) {
@@ -181,7 +219,6 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
<PlaygroundContext.Provider
value={{
promptVariables,
- updatePromptVariables,
updatePromptVariableValue,
deletePromptVariable,
@@ -197,6 +234,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
outputJson,
handleSubmit,
isStreaming,
+ isInitializing: isInitialLoading,
}}
>
{children}
@@ -269,17 +307,6 @@ function getFinalMessages(
return finalMessages;
}
-function createEmptyMessage(
- role: ChatMessageRole,
- content?: string,
-): ChatMessageWithId {
- return {
- role,
- content: content ?? "",
- id: uuidv4(),
- };
-}
-
function getDefaultModelParams(provider: ModelProvider): UIModelParams {
switch (provider) {
// Docs: https://platform.openai.com/docs/api-reference/chat/create
diff --git a/web/src/features/playground/client/index.tsx b/web/src/features/playground/client/index.tsx
index 741d3715b7..9c8d4a8eda 100644
--- a/web/src/features/playground/client/index.tsx
+++ b/web/src/features/playground/client/index.tsx
@@ -6,6 +6,10 @@ import { Messages } from "./components/Messages";
export default function Playground() {
const playgroundContext = usePlaygroundContext();
+ if (playgroundContext.isInitializing) {
+ return <div>Loading...</div>;
+ }
+
return (
<div className="flex h-full flex-row space-x-8">
<div className="h-full basis-3/4 overflow-auto">
diff --git a/web/src/features/playground/client/utils/createEmptyMessage.ts b/web/src/features/playground/client/utils/createEmptyMessage.ts
new file mode 100644
index 0000000000..ffc6626353
--- /dev/null
+++ b/web/src/features/playground/client/utils/createEmptyMessage.ts
@@ -0,0 +1,13 @@
+import { v4 as uuidv4 } from "uuid";
+import type { ChatMessageRole, ChatMessageWithId } from "@langfuse/shared";
+
+export function createEmptyMessage(
+ role: ChatMessageRole,
+ content?: string,
+): ChatMessageWithId {
+ return {
+ role,
+ content: content ?? "",
+ id: uuidv4(),
+ };
+}
diff --git a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx
new file mode 100644
index 0000000000..0020d59950
--- /dev/null
+++ b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx
@@ -0,0 +1,61 @@
+import { useEffect, useState } from "react";
+import type { ControllerRenderProps } from "react-hook-form";
+import { ChatMessages } from "@/src/features/playground/client/components/ChatMessages";
+import { ChatMessageRole } from "@langfuse/shared";
+import { createEmptyMessage } from "@/src/features/playground/client/utils/createEmptyMessage";
+import type { MessagesContext } from "@/src/features/playground/client/components/Messages";
+import {
+ ChatMessageListSchema,
+ type NewPromptFormSchemaType,
+} from "./validation";
+import { v4 as uuidv4 } from "uuid";
+
+type PromptChatMessagesProps = ControllerRenderProps<
+ NewPromptFormSchemaType,
+ "chatPrompt"
+>;
+export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({
+ onChange,
+ value,
+}) => {
+ let initialMessages;
+ try {
+ if (value.length === 0) throw Error("Empty array");
+
+ initialMessages = ChatMessageListSchema.parse(value).map((message) => ({
+ ...message,
+ id: uuidv4(),
+ }));
+ } catch (err) {
+ initialMessages = [createEmptyMessage(ChatMessageRole.System)];
+ }
+
+ const [messages, setMessages] = useState(initialMessages);
+
+ const addMessage: MessagesContext["addMessage"] = (role, content) => {
+ const message = createEmptyMessage(role, content);
+ setMessages((prev) => [...prev, message]);
+
+ return message;
+ };
+
+ const updateMessage: MessagesContext["updateMessage"] = (id, key, value) => {
+ setMessages((prev) =>
+ prev.map((message) =>
+ message.id === id ? { ...message, [key]: value } : message,
+ ),
+ );
+ };
+
+ const deleteMessage: MessagesContext["deleteMessage"] = (id) => {
+ setMessages((prev) => prev.filter((message) => message.id !== id));
+ };
+
+ useEffect(() => {
+ onChange(messages);
+ }, [messages, onChange]);
+
+ return (
+ <ChatMessages {...{ messages, addMessage, deleteMessage, updateMessage }} />
+ );
+};
diff --git a/web/src/features/prompts/components/NewPromptForm/index.tsx b/web/src/features/prompts/components/NewPromptForm/index.tsx
new file mode 100644
index 0000000000..c544972a5d
--- /dev/null
+++ b/web/src/features/prompts/components/NewPromptForm/index.tsx
@@ -0,0 +1,351 @@
+import { capitalize } from "lodash";
+import router from "next/router";
+import { usePostHog } from "posthog-js/react";
+import { useState, useEffect } from "react";
+import { useForm } from "react-hook-form";
+import JsonView from "react18-json-view";
+
+import { Badge } from "@/src/components/ui/badge";
+import { Button } from "@/src/components/ui/button";
+import { Checkbox } from "@/src/components/ui/checkbox";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@/src/components/ui/tabs";
+import { Textarea } from "@/src/components/ui/textarea";
+import {
+ type CreatePromptTRPCType,
+ PromptType,
+} from "@/src/features/prompts/server/validation";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { api } from "@/src/utils/api";
+import { extractVariables } from "@/src/utils/string";
+import { jsonSchema } from "@/src/utils/zod";
+import { zodResolver } from "@hookform/resolvers/zod";
+import type { Prompt } from "@langfuse/shared/src/db";
+
+import { PromptChatMessages } from "./PromptChatMessages";
+import {
+ NewPromptFormSchema,
+ type NewPromptFormSchemaType,
+ PromptContentSchema,
+ type PromptContentType,
+} from "./validation";
+import { Input } from "@/src/components/ui/input";
+import Link from "next/link";
+import { ArrowTopRightIcon } from "@radix-ui/react-icons";
+
+type NewPromptFormProps = {
+ initialPrompt?: Prompt | null;
+ onFormSuccess?: () => void;
+};
+
+export const NewPromptForm: React.FC<NewPromptFormProps> = (props) => {
+ const { onFormSuccess, initialPrompt } = props;
+ const projectId = useProjectIdFromURL();
+ const [formError, setFormError] = useState<string | null>(null);
+ const utils = api.useUtils();
+ const posthog = usePostHog();
+
+ let initialPromptContent: PromptContentType | null;
+ try {
+ initialPromptContent = PromptContentSchema.parse({
+ type: initialPrompt?.type,
+ prompt: initialPrompt?.prompt?.valueOf(),
+ });
+ } catch (err) {
+ initialPromptContent = null;
+ }
+
+ const defaultValues: NewPromptFormSchemaType = {
+ type: initialPromptContent?.type ?? PromptType.Text,
+ chatPrompt:
+ initialPromptContent?.type === PromptType.Chat
+ ? initialPromptContent?.prompt
+ : [],
+ textPrompt:
+ initialPromptContent?.type === PromptType.Text
+ ? initialPromptContent?.prompt
+ : "",
+ name: initialPrompt?.name ?? "",
+ config: JSON.stringify(initialPrompt?.config?.valueOf()) || "{}",
+ isActive: false,
+ };
+
+ const form = useForm<NewPromptFormSchemaType>({
+ resolver: zodResolver(NewPromptFormSchema),
+ defaultValues,
+ });
+
+ const currentName = form.watch("name");
+ const currentType = form.watch("type");
+ const currentIsActive = form.watch("isActive");
+ const currentExtractedVariables = extractVariables(
+ currentType === PromptType.Text
+ ? form.watch("textPrompt")
+ : JSON.stringify(form.watch("chatPrompt"), null, 2),
+ );
+
+ const createPromptMutation = api.prompts.create.useMutation({
+ onSuccess: () => utils.prompts.invalidate(),
+ onError: (error) => setFormError(error.message),
+ });
+
+ const allPrompts = api.prompts.all.useQuery({ projectId }).data;
+
+ function onSubmit(values: NewPromptFormSchemaType) {
+ posthog.capture("prompts:new_prompt_form_submit");
+
+ const { type, textPrompt, chatPrompt } = values;
+
+ // TS does not narrow down type of 'prompt' property given the type of 'type' property in ternary operator
+ let newPrompt: CreatePromptTRPCType;
+ if (type === PromptType.Chat) {
+ newPrompt = {
+ ...values,
+ projectId,
+ type,
+ prompt: chatPrompt,
+ config: JSON.parse(values.config),
+ };
+ } else {
+ newPrompt = {
+ ...values,
+ projectId,
+ type,
+ prompt: textPrompt,
+ config: JSON.parse(values.config),
+ };
+ }
+
+ createPromptMutation
+ .mutateAsync(newPrompt)
+ .then((newPrompt) => {
+ onFormSuccess?.();
+ form.reset();
+ void router.push(
+ `/project/${projectId}/prompts/${encodeURIComponent(newPrompt.name)}`,
+ );
+ })
+ .catch((error) => {
+ console.error(error);
+ });
+ }
+
+ useEffect(() => {
+ const isNewPrompt = !allPrompts
+ ?.map((prompt) => prompt.name)
+ .includes(currentName);
+
+ if (!isNewPrompt) {
+ form.setError("name", { message: "Prompt name already exist." });
+ } else {
+ form.clearErrors("name");
+ }
+ }, [currentName, allPrompts, form]);
+
+ return (
+ <Form {...form}>
+ <form
+ onSubmit={form.handleSubmit(onSubmit)}
+ className="flex flex-col gap-6"
+ >
+ {/* Prompt name field - text vs. chat only for new prompts */}
+ {!initialPrompt ? (
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ const errorMessage = form.getFieldState("name").error?.message;
+
+ return (
+ <div>
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Input placeholder="Select a prompt name" {...field} />
+ </FormControl>
+ {/* Custom form message to include a link to the already existing prompt */}
+ {form.getFieldState("name").error ? (
+ <div className="flex flex-row space-x-1 text-sm font-medium text-destructive">
+ <p className="text-sm font-medium text-destructive">
+ {errorMessage}
+ </p>
+ {errorMessage?.includes("already exist") ? (
+ <Link
+ href={`/project/${projectId}/prompts/${currentName.trim()}`}
+ className="flex flex-row"
+ >
+ Create a new version for it here.{" "}
+ <ArrowTopRightIcon />
+ </Link>
+ ) : null}
+ </div>
+ ) : null}
+ </FormItem>
+ </div>
+ );
+ }}
+ />
+ ) : null}
+
+ {/* Prompt content field - text vs. chat */}
+ <>
+ <FormItem>
+ <FormLabel>Prompt</FormLabel>
+ <Tabs
+ value={form.watch("type")}
+ onValueChange={(e) => {
+ form.setValue("type", e as PromptType);
+ }}
+ className="min-h-[240px]"
+ >
+ {!initialPrompt ? (
+ <TabsList className="flex w-full">
+ <TabsTrigger
+ disabled={
+ Boolean(initialPromptContent) &&
+ initialPromptContent?.type !== PromptType.Text
+ }
+ className="flex-1"
+ value={PromptType.Text}
+ >
+ {capitalize(PromptType.Text)}
+ </TabsTrigger>
+ <TabsTrigger
+ disabled={
+ Boolean(initialPromptContent) &&
+ initialPromptContent?.type !== PromptType.Chat
+ }
+ className="flex-1"
+ value={PromptType.Chat}
+ >
+ {capitalize(PromptType.Chat)}
+ </TabsTrigger>
+ </TabsList>
+ ) : null}
+ <TabsContent value={PromptType.Text}>
+ <FormField
+ control={form.control}
+ name="textPrompt"
+ render={({ field }) => (
+ <>
+ <FormControl>
+ <Textarea
+ {...field}
+ className="min-h-[150px] flex-1 font-mono text-xs"
+ />
+ </FormControl>
+ <FormMessage />
+ </>
+ )}
+ />
+ </TabsContent>
+ <TabsContent value={PromptType.Chat}>
+ <FormField
+ control={form.control}
+ name="chatPrompt"
+ render={({ field }) => (
+ <>
+ <PromptChatMessages {...field} />
+ <FormMessage />
+ </>
+ )}
+ />
+ </TabsContent>
+ </Tabs>
+ </FormItem>
+ <p className="text-sm text-gray-500">
+ You can use <code className="text-xs">{"{{variable}}"}</code> to
+ insert variables into your prompt.
+ {currentExtractedVariables.length > 0
+ ? " The following variables are available:"
+ : ""}
+ </p>
+ <div className="flex min-h-6 flex-wrap gap-2">
+ {currentExtractedVariables.map((variable) => (
+ <Badge key={variable} variant="outline">
+ {variable}
+ </Badge>
+ ))}
+ </div>
+ </>
+
+ {/* Prompt Config field */}
+ <FormField
+ control={form.control}
+ name="config"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Config</FormLabel>
+ <JsonView
+ src={jsonSchema.parse(JSON.parse(field.value))}
+ onEdit={(edit) => {
+ field.onChange(JSON.stringify(edit.src));
+ }}
+ editable
+ className="rounded-md border border-gray-200 p-2 text-sm"
+ />
+ <FormDescription>
+ Track configs for LLM API calls such as function definitions or
+ LLM parameters.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ {/* Activate prompt field */}
+ <FormField
+ control={form.control}
+ name="isActive"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center space-x-3 space-y-0 rounded-md border p-4">
+ <FormControl>
+ <Checkbox
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ <div className="space-y-1 leading-none">
+ <FormLabel>Activate prompt</FormLabel>
+ </div>
+ {currentIsActive ? (
+ <div className="text-xs text-gray-500">
+ Activating the prompt will make it available to the SDKs
+ immediately.
+ </div>
+ ) : null}
+ </FormItem>
+ )}
+ />
+ <Button
+ type="submit"
+ loading={createPromptMutation.isLoading}
+ className="w-full"
+ disabled={Boolean(
+ !initialPrompt && form.formState.errors.name?.message,
+ )} // Disable button if prompt name already exists. Check is dynamic and not part of zod schema
+ >
+ Create prompt
+ </Button>
+ </form>
+ {formError && (
+ <p className="text-red text-center">
+ <span className="font-bold">Error:</span> {formError}
+ </p>
+ )}
+ </Form>
+ );
+};
diff --git a/web/src/features/prompts/components/NewPromptForm/validation.ts b/web/src/features/prompts/components/NewPromptForm/validation.ts
new file mode 100644
index 0000000000..a59d719ae5
--- /dev/null
+++ b/web/src/features/prompts/components/NewPromptForm/validation.ts
@@ -0,0 +1,79 @@
+import { z } from "zod";
+import { extractVariables } from "@/src/utils/string";
+import { PromptType } from "@/src/features/prompts/server/validation";
+import { ChatMessageRole } from "@langfuse/shared";
+
+const ChatMessageSchema = z.object({
+ role: z.nativeEnum(ChatMessageRole),
+ content: z.string(),
+});
+
+export const ChatMessageListSchema = z.array(ChatMessageSchema);
+export const TextPromptSchema = z
+ .string()
+ .min(1, "Enter a prompt")
+ .refine(
+ validateVariables,
+ "Variables must only contain letters and underscores (_)",
+ );
+
+const NewPromptBaseSchema = z.object({
+ name: z.string().min(1, "Enter a name"),
+ isActive: z.boolean({
+ required_error: "Enter whether the prompt should go live",
+ }),
+ config: z.string().refine(validateJson, "Config needs to be valid JSON"),
+});
+
+const NewChatPromptSchema = NewPromptBaseSchema.extend({
+ type: z.literal(PromptType.Chat),
+ chatPrompt: ChatMessageListSchema.refine(
+ (messages) => messages.every((message) => message.content.length > 0),
+ "Enter a chat message or remove the empty message",
+ ).refine(
+ (messages) => validateVariables(messages.map((m) => m.content).join("\n")),
+ "Variables must only contain letters and underscores (_)",
+ ),
+ textPrompt: z.string(),
+});
+
+const NewTextPromptSchema = NewPromptBaseSchema.extend({
+ type: z.literal(PromptType.Text),
+ chatPrompt: z.array(z.any()),
+ textPrompt: TextPromptSchema,
+});
+
+export const NewPromptFormSchema = z.union([
+ NewChatPromptSchema,
+ NewTextPromptSchema,
+]);
+export type NewPromptFormSchemaType = z.infer<typeof NewPromptFormSchema>;
+
+export const PromptContentSchema = z.union([
+ z.object({
+ type: z.literal(PromptType.Chat),
+ prompt: ChatMessageListSchema,
+ }),
+ z.object({
+ type: z.literal(PromptType.Text),
+ prompt: z.string(),
+ }),
+]);
+export type PromptContentType = z.infer<typeof PromptContentSchema>;
+
+function validateVariables(content: string): boolean {
+ const variables = extractVariables(content);
+ const charOrUnderscore = /^[A-Za-z_]+$/;
+
+ return variables.every((variable) => charOrUnderscore.test(variable));
+}
+
+function validateJson(content: string): boolean {
+ try {
+ JSON.parse(content);
+
+ return true;
+ } catch (e) {
+ return false;
+ }
+}
diff --git a/web/src/features/prompts/components/new-prompt-button.tsx b/web/src/features/prompts/components/new-prompt-button.tsx
deleted file mode 100644
index 4cf927f26a..0000000000
--- a/web/src/features/prompts/components/new-prompt-button.tsx
+++ /dev/null
@@ -1,318 +0,0 @@
-import { Button } from "@/src/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@/src/components/ui/dialog";
-import { useState } from "react";
-import { DialogTrigger } from "@radix-ui/react-dialog";
-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
-import {
- FormField,
- FormItem,
- FormLabel,
- FormControl,
- FormMessage,
- Form,
- FormDescription,
-} from "@/src/components/ui/form";
-import { api } from "@/src/utils/api";
-import { zodResolver } from "@hookform/resolvers/zod";
-
-import { usePostHog } from "posthog-js/react";
-import { z } from "zod";
-import { useForm } from "react-hook-form";
-import { Textarea } from "@/src/components/ui/textarea";
-import { Checkbox } from "@/src/components/ui/checkbox";
-import { extractVariables } from "@/src/utils/string";
-import { Badge } from "@/src/components/ui/badge";
-import router from "next/router";
-import { AutoComplete } from "@/src/features/prompts/components/auto-complete";
-import { type AutoCompleteOption } from "@/src/features/prompts/components/auto-complete";
-import JsonView from "react18-json-view";
-import { jsonSchema } from "@/src/utils/zod";
-
-export const CreatePromptDialog = (props: {
- projectId: string;
- title: string;
- promptName?: string;
- promptText?: string;
- subtitle?: string;
- promptConfig?: z.infer<typeof jsonSchema>;
- children?: React.ReactNode;
-}) => {
- const [open, setOpen] = useState(false);
-
- const hasAccess = useHasAccess({
- projectId: props.projectId,
- scope: "datasets:CUD",
- });
-
- return (
- <Dialog open={hasAccess && open} onOpenChange={setOpen}>
- <DialogTrigger asChild>{props.children}</DialogTrigger>
- <DialogContent className="max-h-screen overflow-auto sm:max-w-3xl">
- <DialogHeader>
- <DialogTitle className="mb-5">
- {props.title}
- {props.subtitle ? (
- <p className="mt-3 text-sm font-normal">{props.subtitle}</p>
- ) : null}
- </DialogTitle>
- </DialogHeader>
- <NewPromptForm
- projectId={props.projectId}
- promptName={props.promptName}
- promptText={props.promptText}
- promptConfig={props.promptConfig}
- onFormSuccess={() => setOpen(false)}
- />
- </DialogContent>
- </Dialog>
- );
-};
-
-const formSchema = z.object({
- name: z.string().min(1, "Enter a name"),
- prompt: z
- .string()
- .min(1, "Enter a prompt")
- .refine((val) => {
- const variables = extractVariables(val);
- const matches = variables.map((variable) => {
- // check regex here
- if (variable.match(/^[A-Za-z_]+$/)) {
- return true;
- }
- return false;
- });
- return !matches.includes(false);
- }, "Variables must only contain letters and underscores (_)"),
- isActive: z.boolean({
- required_error: "Enter whether the prompt should go live",
- }),
- // string as we keep the state in string to avoid recursive zod parsing issues
- config: z.string().refine(
- (value) => {
- try {
- JSON.parse(value);
- return true;
- } catch (e) {
- return false;
- }
- },
- {
- message: "Config needs to be valid JSON",
- },
- ),
-});
-
-export const NewPromptForm = (props: {
- projectId: string;
- onFormSuccess?: () => void;
- promptName?: string;
- promptText?: string;
- promptConfig?: z.infer<typeof jsonSchema>;
-}) => {
- const [formError, setFormError] = useState<string | null>(null);
-
- const posthog = usePostHog();
-
- const form = useForm<z.infer<typeof formSchema>>({
- resolver: zodResolver(formSchema),
- defaultValues: {
- isActive: false,
- name: props.promptName ?? "",
- prompt: props.promptText ?? "",
- config: props.promptConfig ? JSON.stringify(props.promptConfig) : "{}",
- },
- });
-
- const prompts = api.prompts.all.useQuery({
- projectId: props.projectId,
- });
-
- const utils = api.useUtils();
-
- const createPromptMutation = api.prompts.create.useMutation({
- onSuccess: () => utils.prompts.invalidate(),
- onError: (error) => setFormError(error.message),
- });
-
- const comboboxOptions =
- prompts.data
- ?.map((prompt) => {
- return { label: prompt.name, value: prompt.name };
- })
- .filter(
- (prompt, i, arr) =>
- arr.findIndex((t) => t.label === prompt.label) === i,
- ) ?? [];
-
- const currentName = form.watch("name");
-
- const matchingOptions = comboboxOptions.filter((option) =>
- option.label.toLowerCase().includes(currentName.toLowerCase()),
- );
-
- const extractedVariables = extractVariables(form.watch("prompt"));
- const promptIsActivated = form.watch("isActive");
-
- function onSubmit(values: z.infer<typeof formSchema>) {
- posthog.capture("prompts:new_prompt_form_submit");
-
- createPromptMutation
- .mutateAsync({
- ...values,
- projectId: props.projectId,
- name: values.name,
- prompt: values.prompt,
- isActive: values.isActive,
- // we keep the config in state as string. need to convert it to JSON before sending it to the API
- // zod parsing necessary to align with TRPC schema
- config: jsonSchema.parse(JSON.parse(values.config)),
- })
- .then((newPrompt) => {
- props.onFormSuccess?.();
- form.reset();
- // go to the following page after creating the prompt
- void router.push(
- `/project/${props.projectId}/prompts/${encodeURIComponent(newPrompt.name)}`,
- );
- })
- .catch((error) => {
- console.error(error);
- });
- }
-
- return (
- <Form {...form}>
- <form
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
- onSubmit={form.handleSubmit(onSubmit)}
- className="flex flex-col gap-6"
- >
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => {
- const setNameValue = (value: AutoCompleteOption) => {
- field.onChange(value.value);
- };
-
- return (
- <div>
- <FormItem>
- <FormLabel>Name</FormLabel>
- <FormControl>
- <AutoComplete
- {...field}
- options={matchingOptions}
- placeholder="Select a prompt name"
- onValueChange={setNameValue}
- value={{ value: field.value, label: field.value }}
- disabled={false}
- createLabel="Create a new prompt name"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- </div>
- );
- }}
- />
-
- <FormField
- control={form.control}
- name="prompt"
- render={({ field }) => (
- <>
- <FormItem>
- <FormLabel>Prompt</FormLabel>
- <FormControl>
- <Textarea
- {...field}
- className="min-h-[150px] flex-1 font-mono text-xs"
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- <p className="text-sm text-gray-500">
- You can use <code className="text-xs">{"{{variable}}"}</code> to
- insert variables into your prompt. The following variables are
- available:
- </p>
- <div className="flex flex-wrap gap-2">
- {extractedVariables.map((variable) => (
- <Badge key={variable} variant="outline">
- {variable}
- </Badge>
- ))}
- </div>
- </>
- )}
- />
- <FormField
- control={form.control}
- name="config"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Config</FormLabel>
- <JsonView
- // need to convert string in state to JSON for the JSONView component
- src={jsonSchema.parse(JSON.parse(field.value))}
- onEdit={(edit) => {
- // need to put string back into the state
- field.onChange(JSON.stringify(edit.src));
- }}
- editable
- className="rounded-md border border-gray-200 p-2 text-sm"
- />
- <FormDescription>
- Track configs for LLM API calls such as function definitions or
- LLM parameters.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="isActive"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center space-x-3 space-y-0 rounded-md border p-4">
- <FormControl>
- <Checkbox
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- <div className="space-y-1 leading-none">
- <FormLabel>Activate prompt</FormLabel>
- </div>
- {promptIsActivated ? (
- <div className="text-xs text-gray-500">
- Activating the prompt will make it available to the SDKs
- immediately.
- </div>
- ) : null}
- </FormItem>
- )}
- />
- <Button
- type="submit"
- loading={createPromptMutation.isLoading}
- className="w-full"
- >
- Create prompt
- </Button>
- </form>
- {formError ? (
- <p className="text-red text-center">
- <span className="font-bold">Error:</span> {formError}
- </p>
- ) : null}
- </Form>
- );
-};
diff --git a/web/src/features/prompts/components/prompt-detail.tsx b/web/src/features/prompts/components/prompt-detail.tsx
index a34d9fc07a..f0efd32b5a 100644
--- a/web/src/features/prompts/components/prompt-detail.tsx
+++ b/web/src/features/prompts/components/prompt-detail.tsx
@@ -1,43 +1,61 @@
+import { Pencil, Terminal } from "lucide-react";
+import Link from "next/link";
+import router, { useRouter } from "next/router";
+import { NumberParam, useQueryParam } from "use-query-params";
+import type { z } from "zod";
+
import Header from "@/src/components/layouts/header";
+import {
+ ChatMlArraySchema,
+ OpenAiMessageView,
+} from "@/src/components/trace/IOPreview";
import { Badge } from "@/src/components/ui/badge";
import { Button } from "@/src/components/ui/button";
-import { CodeView } from "@/src/components/ui/code";
+import { CodeView, JSONView } from "@/src/components/ui/code";
import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
-import { CreatePromptDialog } from "@/src/features/prompts/components/new-prompt-button";
+import { DeletePromptVersion } from "@/src/features/prompts/components/delete-prompt-version";
+import { PromotePrompt } from "@/src/features/prompts/components/promote-prompt";
+import { PromptType } from "@/src/features/prompts/server/validation";
import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import { api } from "@/src/utils/api";
import { extractVariables } from "@/src/utils/string";
import { type Prompt } from "@langfuse/shared/src/db";
-import { Pencil } from "lucide-react";
-import { PromptHistoryNode } from "./prompt-history";
-import { PromotePrompt } from "@/src/features/prompts/components/promote-prompt";
import { ScrollArea } from "@radix-ui/react-scroll-area";
-import { useQueryParam, NumberParam } from "use-query-params";
-import router from "next/router";
-import { JSONView } from "@/src/components/ui/code";
-import { DeletePromptVersion } from "@/src/features/prompts/components/delete-prompt-version";
-import { jsonSchema } from "@/src/utils/zod";
-export type PromptDetailProps = {
- projectId: string;
- promptName: string;
-};
+import { PromptHistoryNode } from "./prompt-history";
+import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";
-export const PromptDetail = (props: PromptDetailProps) => {
+export const PromptDetail = () => {
+ const projectId = useProjectIdFromURL();
+ const isPlaygroundEnabled = useIsFeatureEnabled("playground");
+ const promptName = decodeURIComponent(useRouter().query.promptName as string);
const [currentPromptVersion, setCurrentPromptVersion] = useQueryParam(
"version",
NumberParam,
);
const promptHistory = api.prompts.allVersions.useQuery({
- name: props.promptName,
- projectId: props.projectId,
+ name: promptName,
+ projectId,
});
const prompt = currentPromptVersion
? promptHistory.data?.find(
(prompt) => prompt.version === currentPromptVersion,
)
: promptHistory.data?.[0];
- const extractedVariables = prompt ? extractVariables(prompt.prompt) : [];
+
+ const promptString = JSON.stringify(prompt?.prompt?.valueOf(), null, 2);
+ const extractedVariables = prompt ? extractVariables(promptString) : [];
+
+ let chatMessages: z.infer<typeof ChatMlArraySchema> | null = null;
+ try {
+ chatMessages = ChatMlArraySchema.parse(prompt?.prompt);
+ } catch (error) {
+ console.warn(
+ "Could not parse returned chat prompt to pretty ChatML",
+ error,
+ );
+ }
if (!promptHistory.data || !prompt) {
return <div>Loading...</div>;
@@ -52,45 +70,56 @@ export const PromptDetail = (props: PromptDetailProps) => {
breadcrumb={[
{
name: "Prompts",
- href: `/project/${props.projectId}/prompts/`,
+ href: `/project/${projectId}/prompts/`,
},
{
name: prompt.name,
- href: `/project/${props.projectId}/prompts/${encodeURIComponent(props.promptName)}`,
+ href: `/project/${projectId}/prompts/${encodeURIComponent(promptName)}`,
},
{ name: `Version ${prompt.version}` },
]}
actionButtons={
<>
<PromotePrompt
- projectId={props.projectId}
+ projectId={projectId}
promptId={prompt.id}
promptName={prompt.name}
disabled={prompt.isActive}
variant="outline"
/>
- <CreatePromptDialog
- projectId={props.projectId}
- title="Update Prompt"
- subtitle="We do not update prompts, instead we create a new version of the prompt."
- promptName={prompt.name}
- promptText={prompt.prompt}
- promptConfig={jsonSchema.parse(prompt.config)}
+
+ {isPlaygroundEnabled ? (
+ <Link
+ href={`/project/${projectId}/playground?promptId=${encodeURIComponent(prompt.id)}`}
+ >
+ <Button
+ variant="outline"
+ title="Test in prompt playground"
+ size="icon"
+ >
+ <Terminal className="h-5 w-5" />
+ </Button>
+ </Link>
+ ) : null}
+
+ <Link
+ href={`/project/${projectId}/prompts/new?promptId=${encodeURIComponent(prompt.id)}`}
>
<Button variant="outline" size="icon">
<Pencil className="h-5 w-5" />
</Button>
- </CreatePromptDialog>
+ </Link>
+
<DeletePromptVersion
- projectId={props.projectId}
+ projectId={projectId}
promptVersionId={prompt.id}
version={prompt.version}
countVersions={promptHistory.data.length}
/>
<DetailPageNav
key="nav"
- currentId={props.promptName}
- path={(name) => `/project/${props.projectId}/prompts/${name}`}
+ currentId={promptName}
+ path={(name) => `/project/${projectId}/prompts/${name}`}
listKey="prompts"
/>
</>
@@ -98,7 +127,11 @@ export const PromptDetail = (props: PromptDetailProps) => {
/>
</div>
<div className="col-span-2 md:h-full">
- <CodeView content={prompt.prompt} title="Prompt" />
+ {prompt.type === PromptType.Chat && chatMessages ? (
+ <OpenAiMessageView title="Chat prompt" messages={chatMessages} />
+ ) : (
+ <CodeView content={promptString} title="Text prompt" />
+ )}
<div className="mx-auto mt-5 w-full rounded-lg border text-base leading-7">
<div className="border-b px-3 py-1 text-xs font-medium">
Variables
diff --git a/web/src/features/prompts/components/prompt-new.tsx b/web/src/features/prompts/components/prompt-new.tsx
new file mode 100644
index 0000000000..bebc7a8904
--- /dev/null
+++ b/web/src/features/prompts/components/prompt-new.tsx
@@ -0,0 +1,71 @@
+import { StringParam, useQueryParam } from "use-query-params";
+
+import Header from "@/src/components/layouts/header";
+import { NewPromptForm } from "@/src/features/prompts/components/NewPromptForm";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
+import { api } from "@/src/utils/api";
+
+export const NewPrompt = () => {
+ const projectId = useProjectIdFromURL();
+ const [initialPromptId] = useQueryParam("promptId", StringParam);
+
+ const { data: initialPrompt, isInitialLoading } = api.prompts.byId.useQuery(
+ {
+ projectId,
+ id: initialPromptId ?? "",
+ },
+ { enabled: Boolean(initialPromptId) },
+ );
+
+ if (isInitialLoading) {
+ return <div>Loading...</div>;
+ }
+
+ const breadcrumb: { name: string; href?: string }[] = [
+ {
+ name: "Prompts",
+ href: `/project/${projectId}/prompts/`,
+ },
+ {
+ name: "New prompt",
+ },
+ ];
+
+ if (initialPrompt) {
+ breadcrumb.pop(); // Remove "New prompt"
+ breadcrumb.push(
+ {
+ name: initialPrompt.name,
+ href: `/project/${projectId}/prompts/${encodeURIComponent(initialPrompt.name)}`,
+ },
+ { name: "New version" },
+ );
+ }
+
+ return (
+ <div className="xl:container">
+ <Header
+ title={
+ initialPrompt
+ ? `${initialPrompt.name} \u2014 New version`
+ : "Create new prompt"
+ }
+ help={{
+ description:
+ "Manage and version your prompts in Langfuse. Edit and update them via the UI and SDK. Retrieve the production version via the SDKs. Learn more in the docs.",
+ href: "https://langfuse.com/docs/prompts",
+ }}
+ breadcrumb={breadcrumb}
+ />
+ {initialPrompt ? (
+ <p className="text-sm text-gray-500">
+ Prompts are immutable in Langfuse. To update a prompt, create a new
+ version.
+ </p>
+ ) : null}
+ <div className="my-8 max-w-screen-md">
+ <NewPromptForm {...{ initialPrompt }} />
+ </div>
+ </div>
+ );
+};
diff --git a/web/src/features/prompts/components/prompts-table.tsx b/web/src/features/prompts/components/prompts-table.tsx
index 29767f37af..d003f38d0c 100644
--- a/web/src/features/prompts/components/prompts-table.tsx
+++ b/web/src/features/prompts/components/prompts-table.tsx
@@ -1,16 +1,18 @@
+import { capitalize } from "lodash";
+import { LockIcon, PlusIcon } from "lucide-react";
+import Link from "next/link";
+import { useEffect } from "react";
+
import { DataTable } from "@/src/components/table/data-table";
import TableLink from "@/src/components/table/table-link";
import { type LangfuseColumnDef } from "@/src/components/table/types";
import { Button } from "@/src/components/ui/button";
import { useDetailPageLists } from "@/src/features/navigate-detail-pages/context";
-import { CreatePromptDialog } from "@/src/features/prompts/components/new-prompt-button";
-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { DeletePrompt } from "@/src/features/prompts/components/delete-prompt";
-
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import { api } from "@/src/utils/api";
import { type RouterOutput } from "@/src/utils/types";
-import { LockIcon, PlusIcon } from "lucide-react";
-import { useEffect } from "react";
type RowData = {
name: string;
@@ -18,17 +20,19 @@ type RowData = {
id: string;
createdAt: Date;
isActive: boolean;
+ type: string;
numberOfObservations: number;
};
-export function PromptTable(props: { projectId: string }) {
+export function PromptTable() {
+ const projectId = useProjectIdFromURL();
const { setDetailPageList } = useDetailPageLists();
const prompts = api.prompts.all.useQuery({
- projectId: props.projectId,
+ projectId,
});
const hasCUDAccess = useHasAccess({
- projectId: props.projectId,
+ projectId,
scope: "prompts:CUD",
});
@@ -50,7 +54,7 @@ export function PromptTable(props: { projectId: string }) {
const name: string = row.getValue("name");
return name ? (
<TableLink
- path={`/project/${props.projectId}/prompts/${encodeURIComponent(name)}`}
+ path={`/project/${projectId}/prompts/${encodeURIComponent(name)}`}
value={name}
truncateAt={50}
/>
@@ -65,6 +69,13 @@ export function PromptTable(props: { projectId: string }) {
return version;
},
},
+ {
+ accessorKey: "type",
+ header: "Type",
+ cell: ({ row }) => {
+ return capitalize(row.getValue("type"));
+ },
+ },
{
accessorKey: "createdAt",
header: "Latest Version Created At",
@@ -86,7 +97,7 @@ export function PromptTable(props: { projectId: string }) {
);
return (
<TableLink
- path={`/project/${props.projectId}/generations?filter=${numberOfObservations ? filter : ""}`}
+ path={`/project/${projectId}/generations?filter=${numberOfObservations ? filter : ""}`}
value={numberOfObservations.toLocaleString()}
/>
);
@@ -98,7 +109,7 @@ export function PromptTable(props: { projectId: string }) {
cell: ({ row }) => {
return (
<DeletePrompt
- projectId={props.projectId}
+ projectId={projectId}
promptName={row.getValue("name")}
/>
);
@@ -114,6 +125,7 @@ export function PromptTable(props: { projectId: string }) {
name: item.name,
version: item.version,
createdAt: item.createdAt,
+ type: item.type,
isActive: item.isActive,
numberOfObservations: Number(item.observationCount),
};
@@ -139,7 +151,7 @@ export function PromptTable(props: { projectId: string }) {
}
}
/>
- <CreatePromptDialog projectId={props.projectId} title="Create Prompt">
+ <Link href={`/project/${projectId}/prompts/new`}>
<Button
variant="secondary"
className="mt-4"
@@ -153,7 +165,7 @@ export function PromptTable(props: { projectId: string }) {
)}
New prompt
</Button>
- </CreatePromptDialog>
+ </Link>
</div>
);
}
diff --git a/web/src/features/prompts/server/createPrompt.ts b/web/src/features/prompts/server/createPrompt.ts
new file mode 100644
index 0000000000..e7d0a1fb0d
--- /dev/null
+++ b/web/src/features/prompts/server/createPrompt.ts
@@ -0,0 +1,68 @@
+import {
+ type CreatePromptTRPCType,
+ PromptType,
+} from "@/src/features/prompts/server/validation";
+import { ValidationError } from "@/src/server/errors/ValidationError";
+import { jsonSchema } from "@/src/utils/zod";
+import { type PrismaClient } from "@langfuse/shared/src/db";
+
+export const createPrompt = async ({
+ projectId,
+ name,
+ prompt,
+ type = PromptType.Text,
+ isActive = true,
+ config,
+ createdBy,
+ prisma,
+}: CreatePromptTRPCType & {
+ createdBy: string;
+ prisma: PrismaClient;
+}) => {
+ const latestPrompt = await prisma.prompt.findFirst({
+ where: { projectId, name },
+ orderBy: [{ version: "desc" }],
+ });
+
+ if (latestPrompt && latestPrompt.type !== type) {
+ throw new ValidationError(
+ "Previous versions have different prompt type. Create a new prompt with a different name.",
+ );
+ }
+
+ const latestActivePrompt = await prisma.prompt.findFirst({
+ where: { projectId, name, isActive: true },
+ orderBy: [{ version: "desc" }],
+ });
+
+ const create = [
+ prisma.prompt.create({
+ data: {
+ prompt,
+ name,
+ createdBy,
+ isActive,
+ type,
+ version: latestPrompt?.version ? latestPrompt.version + 1 : 1,
+ project: { connect: { id: projectId } },
+ config: jsonSchema.parse(config),
+ },
+ }),
+ ];
+ if (latestActivePrompt && isActive)
+ // If we're creating a new active prompt, we need to deactivate the old one
+ create.push(
+ prisma.prompt.update({
+ where: {
+ id: latestActivePrompt.id,
+ },
+ data: {
+ isActive: false,
+ },
+ }),
+ );
+
+ const [createdPrompt] = await prisma.$transaction(create);
+
+ return createdPrompt;
+};
diff --git a/web/src/features/prompts/server/prompt-router.ts b/web/src/features/prompts/server/prompt-router.ts
index 748e67959a..cec52b4ea5 100644
--- a/web/src/features/prompts/server/prompt-router.ts
+++ b/web/src/features/prompts/server/prompt-router.ts
@@ -1,22 +1,16 @@
import { z } from "zod";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { CreatePromptTRPCSchema } from "@/src/features/prompts/server/validation";
+import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
import {
createTRPCRouter,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
-import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
-import { type Prompt, type PrismaClient } from "@langfuse/shared/src/db";
-import { jsonSchema } from "@/src/utils/zod";
-import { auditLog } from "@/src/features/audit-logs/auditLog";
import { DB } from "@/src/server/db";
+import { type Prompt } from "@langfuse/shared/src/db";
-export const CreatePrompt = z.object({
- projectId: z.string(),
- name: z.string(),
- isActive: z.boolean(),
- prompt: z.string(),
- config: jsonSchema,
-});
+import { createPrompt } from "./createPrompt";
export const promptRouter = createTRPCRouter({
all: protectedProjectProcedure
@@ -36,7 +30,8 @@ export const promptRouter = createTRPCRouter({
SELECT
id,
name,
- version,
+ version,
+ type,
project_id AS "projectId",
prompt,
updated_at AS "updatedAt",
@@ -102,7 +97,7 @@ export const promptRouter = createTRPCRouter({
});
}),
create: protectedProjectProcedure
- .input(CreatePrompt)
+ .input(CreatePromptTRPCSchema)
.mutation(async ({ input, ctx }) => {
try {
throwIfNoAccess({
@@ -112,13 +107,9 @@ export const promptRouter = createTRPCRouter({
});
const prompt = await createPrompt({
- projectId: input.projectId,
- name: input.name,
- prompt: input.prompt,
- isActive: input.isActive,
- createdBy: ctx.session.user.id,
- config: jsonSchema.parse(input.config),
+ ...input,
prisma: ctx.prisma,
+ createdBy: ctx.session.user.id,
});
if (!prompt) {
@@ -349,68 +340,3 @@ export const promptRouter = createTRPCRouter({
return joinedPromptAndUsers;
}),
});
-
-export const createPrompt = async ({
- projectId,
- name,
- prompt,
- isActive = true,
- createdBy,
- config,
- prisma,
-}: {
- projectId: string;
- name: string;
- prompt: string;
- isActive?: boolean;
- createdBy: string;
- config: z.infer<typeof jsonSchema>;
- prisma: PrismaClient;
-}) => {
- const latestPrompt = await prisma.prompt.findFirst({
- where: {
- projectId: projectId,
- name: name,
- },
- orderBy: [{ version: "desc" }],
- });
-
- const latestActivePrompt = await prisma.prompt.findFirst({
- where: {
- projectId: projectId,
- name: name,
- isActive: true,
- },
- orderBy: [{ version: "desc" }],
- });
-
- const create = [
- prisma.prompt.create({
- data: {
- prompt: prompt,
- name: name,
- version: latestPrompt?.version ? latestPrompt.version + 1 : 1,
- isActive: isActive,
- project: { connect: { id: projectId } },
- createdBy: createdBy,
- config: jsonSchema.parse(config),
- },
- }),
- ];
- if (latestActivePrompt && isActive)
- // If we're creating a new active prompt, we need to deactivate the old one
- create.push(
- prisma.prompt.update({
- where: {
- id: latestActivePrompt.id,
- },
- data: {
- isActive: false,
- },
- }),
- );
-
- const [createdPrompt] = await prisma.$transaction(create);
-
- return createdPrompt;
-};
diff --git a/web/src/features/prompts/server/validation.ts b/web/src/features/prompts/server/validation.ts
new file mode 100644
index 0000000000..260ba50302
--- /dev/null
+++ b/web/src/features/prompts/server/validation.ts
@@ -0,0 +1,96 @@
+import { z } from "zod";
+import { jsonSchema } from "@/src/utils/zod";
+import type { Prompt } from "@langfuse/shared/src/db";
+
+export const ChatMessageSchema = z.object({
+ role: z.string(),
+ content: z.string(),
+});
+
+export enum PromptType {
+ Chat = "chat",
+ Text = "text",
+}
+
+export const CreateTextPromptSchema = z.object({
+ name: z.string(),
+ isActive: z.boolean(),
+ type: z.literal(PromptType.Text).optional(),
+ prompt: z.string(),
+ config: jsonSchema.nullable().default({}),
+});
+
+export const CreateChatPromptSchema = z.object({
+ name: z.string(),
+ isActive: z.boolean(),
+ type: z.literal(PromptType.Chat),
+ prompt: z.array(ChatMessageSchema),
+ config: jsonSchema.nullable().default({}),
+});
+
+export const CreatePromptSchema = z.union([
+ CreateTextPromptSchema,
+ CreateChatPromptSchema,
+]);
+
+export type CreatePromptType = z.infer<typeof CreatePromptSchema>;
+
+// TRPC route requires projectId
+const CreateTextPromptTRPCSchema = CreateTextPromptSchema.extend({
+ projectId: z.string(),
+});
+const CreateChatPromptTRPCSchema = CreateChatPromptSchema.extend({
+ projectId: z.string(),
+});
+export const CreatePromptTRPCSchema = z.union([
+ CreateTextPromptTRPCSchema,
+ CreateChatPromptTRPCSchema,
+]);
+
+export type CreatePromptTRPCType = z.infer<typeof CreatePromptTRPCSchema>;
+
+export const GetPromptSchema = z.object({
+ name: z.string(),
+ version: z.coerce.number().int().nullish(),
+});
+
+export const TextPromptSchema = z.object({
+ id: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ projectId: z.string(),
+ createdBy: z.string(),
+ version: z.number(),
+ name: z.string(),
+ isActive: z.boolean(),
+ type: z.literal(PromptType.Text),
+ prompt: z.string(),
+ config: jsonSchema,
+});
+
+export type TextPromptType =
+ z.infer<typeof TextPromptSchema> extends Prompt
+ ? z.infer<typeof TextPromptSchema>
+ : never;
+
+export const ChatPromptSchema = z.object({
+ id: z.string(),
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ projectId: z.string(),
+ createdBy: z.string(),
+ version: z.number(),
+ name: z.string(),
+ isActive: z.boolean(),
+ type: z.literal(PromptType.Chat),
+ prompt: z.array(ChatMessageSchema),
+ config: jsonSchema,
+});
+
+export type ChatPromptType =
+ z.infer<typeof ChatPromptSchema> extends Prompt
+ ? z.infer<typeof ChatPromptSchema>
+ : never;
+
+export const PromptSchema = z.union([TextPromptSchema, ChatPromptSchema]);
+export type ValidatedPrompt = z.infer<typeof PromptSchema>;
diff --git a/web/src/hooks/useProjectIdFromURL.ts b/web/src/hooks/useProjectIdFromURL.ts
new file mode 100644
index 0000000000..32bda69b79
--- /dev/null
+++ b/web/src/hooks/useProjectIdFromURL.ts
@@ -0,0 +1,11 @@
+import { useRouter } from "next/router";
+
+export default function useProjectIdFromURL() {
+ const router = useRouter();
+
+ if (!router.query.projectId) {
+ throw new Error("useProjectId must be used within a project route");
+ }
+
+ return router.query.projectId as string;
+}
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index c370117a63..19dc5f480d 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -27,6 +27,13 @@ import { telemetry } from "@/src/features/telemetry";
import { jsonSchema } from "@/src/utils/zod";
import * as Sentry from "@sentry/nextjs";
import { isPrismaException } from "@/src/utils/exceptions";
+import {
+ ValidationError,
+ MethodNotAllowedError,
+ BaseError,
+ ForbiddenError,
+ UnauthorizedError,
+} from "@/src/server/errors";
export const config = {
api: {
@@ -43,19 +50,14 @@ export default async function handler(
try {
await runMiddleware(req, res, cors);
- if (req.method !== "POST") {
- return res.status(405).json({ message: "Method not allowed" });
- }
+ if (req.method !== "POST") throw new MethodNotAllowedError();
// CHECK AUTH FOR ALL EVENTS
const authCheck = await verifyAuthHeaderAndReturnScope(
req.headers.authorization,
);
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
+ if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
const batchType = z.object({
batch: z.array(z.unknown()),
@@ -72,20 +74,20 @@ export default async function handler(
});
}
- const errors: { id: string; error: unknown }[] = [];
+ const validationErrors: { id: string; error: unknown }[] = [];
const batch: (z.infer<typeof ingestionEvent> | undefined)[] =
parsedSchema.data.batch.map((event) => {
const parsed = ingestionEvent.safeParse(event);
if (!parsed.success) {
- errors.push({
+ validationErrors.push({
id:
typeof event === "object" && event && "id" in event
? typeof event.id === "string"
? event.id
: "unknown"
: "unknown",
- error: new BadRequestError(parsed.error.message),
+ error: new ValidationError(parsed.error.message),
});
return undefined;
} else {
@@ -105,18 +107,27 @@ export default async function handler(
authCheck,
);
- handleBatchResult([...errors, ...result.errors], result.results, res);
+ handleBatchResult(
+ [...validationErrors, ...result.errors],
+ result.results,
+ res,
+ );
} catch (error: unknown) {
console.error(error);
+ if (error instanceof BaseError) {
+ return res.status(error.httpCode).json({
+ error: error.name,
+ message: error.message,
+ });
+ }
+
if (isPrismaException(error)) {
- console.log("Internal Server error", error);
return res.status(500).json({
error: "Internal Server Error",
});
}
if (error instanceof z.ZodError) {
- console.log("Invalid request data", error.errors);
return res.status(400).json({
message: "Invalid request data",
error: error.errors,
@@ -156,7 +167,7 @@ export const handleBatch = async (
) => {
console.log("handling ingestion event", JSON.stringify(events, null, 2));
- if (!authCheck.validKey) throw new AuthenticationError(authCheck.error);
+ if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
const results = []; // Array to store the results
const errors = []; // Array to store the errors
@@ -187,7 +198,7 @@ async function retry<T>(request: () => Promise<T>): Promise<T> {
return await backOff(request, {
numOfAttempts: 3,
retry: (e: Error, attemptNumber: number) => {
- if (e instanceof AuthenticationError) {
+ if (e instanceof UnauthorizedError || e instanceof ForbiddenError) {
console.log("not retrying auth error");
return false;
}
@@ -196,9 +207,9 @@ async function retry<T>(request: () => Promise<T>): Promise<T> {
},
});
}
-export const getBadRequestError = (errors: Array<unknown>): BadRequestError[] =>
+export const getBadRequestError = (errors: Array<unknown>): ValidationError[] =>
errors.filter(
- (error): error is BadRequestError => error instanceof BadRequestError,
+ (error): error is ValidationError => error instanceof ValidationError,
);
export const getResourceNotFoundError = (
@@ -210,7 +221,7 @@ export const getResourceNotFoundError = (
);
export const hasBadRequestError = (errors: Array<unknown>) =>
- errors.some((error) => error instanceof BadRequestError);
+ errors.some((error) => error instanceof ValidationError);
const handleSingleEvent = async (
event: z.infer<typeof ingestionEvent>,
@@ -260,30 +271,12 @@ const handleSingleEvent = async (
// Deny access to non-score events if the access level is not "all"
// This is an additional safeguard to auth checks in EventProcessor
if (apiScope.accessLevel !== "all" && type !== eventTypes.SCORE_CREATE) {
- throw new AuthenticationError("Access denied. Event type not allowed.");
+ throw new ForbiddenError("Access denied. Event type not allowed.");
}
return await processor.process(apiScope);
};
-class BadRequestError extends Error {
- constructor(msg: string) {
- super(msg);
-
- // Set the prototype explicitly.
- Object.setPrototypeOf(this, BadRequestError.prototype);
- }
-}
-
-export class AuthenticationError extends Error {
- constructor(msg: string) {
- super(msg);
-
- // Set the prototype explicitly.
- Object.setPrototypeOf(this, AuthenticationError.prototype);
- }
-}
-
export const handleBatchResult = (
errors: Array<{ id: string; error: unknown }>,
results: Array<{ id: string; result: unknown }>,
@@ -302,14 +295,14 @@ export const handleBatchResult = (
}[] = [];
errors.forEach((error) => {
- if (error.error instanceof BadRequestError) {
+ if (error.error instanceof ValidationError) {
returnedErrors.push({
id: error.id,
status: 400,
message: "Invalid request data",
error: error.error.message,
});
- } else if (error.error instanceof AuthenticationError) {
+ } else if (error.error instanceof UnauthorizedError) {
returnedErrors.push({
id: error.id,
status: 401,
diff --git a/web/src/pages/api/public/prompts.ts b/web/src/pages/api/public/prompts.ts
index 588b69cb06..ca117f9664 100644
--- a/web/src/pages/api/public/prompts.ts
+++ b/web/src/pages/api/public/prompts.ts
@@ -1,23 +1,21 @@
-import { createPrompt } from "@/src/features/prompts/server/prompt-router";
+import { createPrompt } from "@/src/features/prompts/server/createPrompt";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
-import { jsonSchema } from "@/src/utils/zod";
import { isPrismaException } from "@/src/utils/exceptions";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
-
-const PromptGetSchema = z.object({
- name: z.string(),
- version: z.coerce.number().int().nullish(),
-});
-
-const PromptCreateSchema = z.object({
- name: z.string(),
- prompt: z.string(),
- isActive: z.boolean(),
- config: jsonSchema.nullable().default({}),
-});
+import {
+ CreatePromptSchema,
+ GetPromptSchema,
+} from "@/src/features/prompts/server/validation";
+import {
+ UnauthorizedError,
+ NotFoundError,
+ BaseError,
+ MethodNotAllowedError,
+ ForbiddenError,
+} from "@/src/server/errors";
export default async function handler(
req: NextApiRequest,
@@ -25,131 +23,76 @@ export default async function handler(
) {
await runMiddleware(req, res, cors);
- if (req.method === "GET") {
- // CHECK AUTH
+ try {
+ // Authentication and authorization
const authCheck = await verifyAuthHeaderAndReturnScope(
req.headers.authorization,
);
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
-
- try {
- console.log(
- "trying to get prompt, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.query, null, 2),
+ if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
+ if (authCheck.scope.accessLevel !== "all")
+ throw new ForbiddenError(
+ `Access denied - need to use basic auth with secret key to ${req.method} prompts`,
);
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
-
- const searchParams = PromptGetSchema.parse(req.query);
-
+ // Handle GET requests
+ if (req.method === "GET") {
+ const searchParams = GetPromptSchema.parse(req.query);
const prompt = await prisma.prompt.findFirst({
where: {
projectId: authCheck.scope.projectId,
name: searchParams.name,
- version: searchParams.version ?? undefined,
- // if no version is given, we take the latest active prompt
- // if no prompt is active, there will be no prompt available
- isActive: !searchParams.version ? true : undefined,
+ version: searchParams.version ?? undefined, // if no version is given, we take the latest active prompt
+ isActive: !searchParams.version ? true : undefined, // if no prompt is active, there will be no prompt available
},
});
- if (prompt === null) {
- return res.status(404).json({
- message: "Prompt not found",
- });
- }
+ if (!prompt) throw new NotFoundError("Prompt not found");
return res.status(200).json(prompt);
- } catch (error: unknown) {
- console.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
- message: "Invalid request data",
- error: errorMessage,
- });
}
- } else if (req.method === "POST") {
- // CHECK AUTH
- const authCheck = await verifyAuthHeaderAndReturnScope(
- req.headers.authorization,
- );
- if (!authCheck.validKey)
- return res.status(401).json({
- message: authCheck.error,
- });
- // END CHECK AUTH
-
- try {
- console.log(
- "trying to create prompt, project ",
- authCheck.scope.projectId,
- ", body:",
- JSON.stringify(req.body, null, 2),
- );
-
- if (authCheck.scope.accessLevel !== "all") {
- return res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- }
-
- const input = PromptCreateSchema.parse(req.body);
+ // Handle POST requests
+ if (req.method === "POST") {
+ const input = CreatePromptSchema.parse(req.body);
const prompt = await createPrompt({
+ ...input,
+ config: input.config ?? {}, // Config can be null in which case zod default value is not used
projectId: authCheck.scope.projectId,
- name: input.name,
- prompt: input.prompt,
- isActive: input.isActive,
createdBy: "API",
- config: input.config ?? {},
prisma: prisma,
});
- console.log("created prompt", prompt);
- return res.status(200).json(prompt);
- } catch (error: unknown) {
- console.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- if (error instanceof z.ZodError) {
- return res.status(400).json({
- message: "Invalid request data",
- error: error.errors,
- });
- }
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(500).json({
+
+ return res.status(201).json(prompt);
+ }
+
+ throw new MethodNotAllowedError();
+ } catch (error: unknown) {
+ console.error(error);
+
+ if (error instanceof BaseError) {
+ return res.status(error.httpCode).json({
+ error: error.name,
+ message: error.message,
+ });
+ }
+
+ if (isPrismaException(error)) {
+ return res.status(500).json({
+ error: "Internal Server Error",
+ });
+ }
+
+ if (error instanceof z.ZodError) {
+ return res.status(400).json({
message: "Invalid request data",
- error: errorMessage,
+ error: error.errors,
});
}
- } else {
- console.error(req.method, req.body, req.query);
- return res.status(405).json({ message: "Method not allowed" });
+
+ return res.status(500).json({
+ message: "Invalid request data",
+ error:
+ error instanceof Error ? error.message : "An unknown error occurred",
+ });
}
}
diff --git a/web/src/pages/auth/sign-in.tsx b/web/src/pages/auth/sign-in.tsx
index 87fb99122f..a1919f82de 100644
--- a/web/src/pages/auth/sign-in.tsx
+++ b/web/src/pages/auth/sign-in.tsx
@@ -19,7 +19,7 @@ import { TbBrandAzure } from "react-icons/tb";
import { signIn } from "next-auth/react";
import Head from "next/head";
import Link from "next/link";
-import { useState, useRef } from "react";
+import { useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { usePostHog } from "posthog-js/react";
diff --git a/web/src/pages/project/[projectId]/playground.tsx b/web/src/pages/project/[projectId]/playground.tsx
index 2d94473952..3b73e32b9e 100644
--- a/web/src/pages/project/[projectId]/playground.tsx
+++ b/web/src/pages/project/[projectId]/playground.tsx
@@ -1,3 +1,7 @@
+// NOTE: There is a possibility that this feature might transition from the MIT licensed version to the
+// enterprise version in the future. Please consider this when planning long-term use and integration of
+// this functionality into your projects.
+
import Header from "@/src/components/layouts/header";
import Playground from "@/src/features/playground/client";
import { PlaygroundProvider } from "@/src/features/playground/client/context";
diff --git a/web/src/pages/project/[projectId]/prompts/[promptName]/index.tsx b/web/src/pages/project/[projectId]/prompts/[promptName]/index.tsx
index c8d7a033e6..b2b9af5942 100644
--- a/web/src/pages/project/[projectId]/prompts/[promptName]/index.tsx
+++ b/web/src/pages/project/[projectId]/prompts/[promptName]/index.tsx
@@ -1,10 +1,3 @@
import { PromptDetail } from "@/src/features/prompts/components/prompt-detail";
-import { useRouter } from "next/router";
-export default function PromptDetailPage() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
- const promptName = decodeURIComponent(router.query.promptName as string);
-
- return <PromptDetail projectId={projectId} promptName={promptName} />;
-}
+export default PromptDetail;
diff --git a/web/src/pages/project/[projectId]/prompts/index.tsx b/web/src/pages/project/[projectId]/prompts/index.tsx
index 75d55f7264..1985aac92f 100644
--- a/web/src/pages/project/[projectId]/prompts/index.tsx
+++ b/web/src/pages/project/[projectId]/prompts/index.tsx
@@ -1,11 +1,7 @@
import Header from "@/src/components/layouts/header";
import { PromptTable } from "@/src/features/prompts/components/prompts-table";
-import { useRouter } from "next/router";
export default function Prompts() {
- const router = useRouter();
- const projectId = router.query.projectId as string;
-
return (
<div className="xl:container">
<Header
@@ -16,7 +12,7 @@ export default function Prompts() {
href: "https://langfuse.com/docs/prompts",
}}
/>
- <PromptTable projectId={projectId} />
+ <PromptTable />
</div>
);
}
diff --git a/web/src/pages/project/[projectId]/prompts/new.tsx b/web/src/pages/project/[projectId]/prompts/new.tsx
new file mode 100644
index 0000000000..5ada985998
--- /dev/null
+++ b/web/src/pages/project/[projectId]/prompts/new.tsx
@@ -0,0 +1,3 @@
+import { NewPrompt } from "@/src/features/prompts/components/prompt-new";
+
+export default NewPrompt;
diff --git a/web/src/server/api/routers/generations/exportQuery/index.ts b/web/src/server/api/routers/generations/exportQuery/index.ts
index eeeb34965e..1e02e8a076 100644
--- a/web/src/server/api/routers/generations/exportQuery/index.ts
+++ b/web/src/server/api/routers/generations/exportQuery/index.ts
@@ -12,7 +12,7 @@ import { type ObservationView } from "@langfuse/shared/src/db";
import { DatabaseReadStream } from "../db/DatabaseReadStream";
import {
- FullObservations,
+ type FullObservations,
getAllGenerations as getAllGenerations,
} from "../db/getAllGenerationsSqlQuery";
import { GenerationTableOptions } from "../utils/GenerationTableOptions";
diff --git a/web/src/server/api/services/EventProcessor.ts b/web/src/server/api/services/EventProcessor.ts
index 2c922d72a6..afdfc112f8 100644
--- a/web/src/server/api/services/EventProcessor.ts
+++ b/web/src/server/api/services/EventProcessor.ts
@@ -1,7 +1,6 @@
import { tokenCount } from "@/src/features/ingest/lib/usage";
import { checkApiAccessScope } from "@/src/features/public-api/server/apiScope";
import { type ApiAccessScope } from "@/src/features/public-api/server/types";
-import { AuthenticationError } from "@/src/pages/api/public/ingestion";
import {
type legacyObservationCreateEvent,
eventTypes,
@@ -29,6 +28,7 @@ import { v4 } from "uuid";
import { type z } from "zod";
import { jsonSchema } from "@/src/utils/zod";
import { sendToBetterstack } from "@/src/features/betterstack/server/betterstack-webhook";
+import { ForbiddenError } from "@/src/server/errors";
export interface EventProcessor {
process(
@@ -370,7 +370,7 @@ export class ObservationProcessor implements EventProcessor {
async process(apiScope: ApiAccessScope): Promise<Observation> {
if (apiScope.accessLevel !== "all")
- throw new AuthenticationError("Access denied for observation creation");
+ throw new ForbiddenError("Access denied for observation creation");
const existingObservation = this.event.body.id
? await prisma.observation.findFirst({
@@ -382,7 +382,7 @@ export class ObservationProcessor implements EventProcessor {
existingObservation &&
existingObservation.projectId !== apiScope.projectId
) {
- throw new AuthenticationError(
+ throw new ForbiddenError(
`Access denied for observation creation ${existingObservation.projectId} `,
);
}
@@ -413,7 +413,7 @@ export class TraceProcessor implements EventProcessor {
const { body } = this.event;
if (apiScope.accessLevel !== "all")
- throw new AuthenticationError(
+ throw new ForbiddenError(
`Access denied for trace creation, ${apiScope.accessLevel}`,
);
@@ -433,7 +433,7 @@ export class TraceProcessor implements EventProcessor {
});
if (existingTrace && existingTrace.projectId !== apiScope.projectId) {
- throw new AuthenticationError(
+ throw new ForbiddenError(
`Access denied for trace creation ${existingTrace.projectId} `,
);
}
@@ -526,7 +526,7 @@ export class ScoreProcessor implements EventProcessor {
"score",
);
if (!accessCheck)
- throw new AuthenticationError("Access denied for score creation");
+ throw new ForbiddenError("Access denied for score creation");
const id = body.id ?? v4();
diff --git a/web/src/server/errors/BaseError.ts b/web/src/server/errors/BaseError.ts
new file mode 100644
index 0000000000..28b4f514b4
--- /dev/null
+++ b/web/src/server/errors/BaseError.ts
@@ -0,0 +1,21 @@
+export class BaseError extends Error {
+ public readonly name: string;
+ public readonly httpCode: number;
+ public readonly isOperational: boolean;
+
+ constructor(
+ name: string,
+ httpCode: number,
+ description: string,
+ isOperational: boolean,
+ ) {
+ super(description);
+ Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
+
+ this.name = name;
+ this.httpCode = httpCode;
+ this.isOperational = isOperational; // if error is part of known errors that our application can anticipate
+
+ Error.captureStackTrace(this);
+ }
+}
diff --git a/web/src/server/errors/ForbiddenError.ts b/web/src/server/errors/ForbiddenError.ts
new file mode 100644
index 0000000000..8a63fb0cc9
--- /dev/null
+++ b/web/src/server/errors/ForbiddenError.ts
@@ -0,0 +1,7 @@
+import { BaseError } from "./BaseError";
+
+export class ForbiddenError extends BaseError {
+ constructor(description = "Forbidden") {
+ super("ForbiddenError", 403, description, true);
+ }
+}
diff --git a/web/src/server/errors/MethodNotAllowedError.ts b/web/src/server/errors/MethodNotAllowedError.ts
new file mode 100644
index 0000000000..3fe16e9c03
--- /dev/null
+++ b/web/src/server/errors/MethodNotAllowedError.ts
@@ -0,0 +1,7 @@
+import { BaseError } from "./BaseError";
+
+export class MethodNotAllowedError extends BaseError {
+ constructor(description = "Method not allowed") {
+ super("MethodNotAllowedError", 405, description, true);
+ }
+}
diff --git a/web/src/server/errors/NotFoundError.ts b/web/src/server/errors/NotFoundError.ts
new file mode 100644
index 0000000000..4dc7368a88
--- /dev/null
+++ b/web/src/server/errors/NotFoundError.ts
@@ -0,0 +1,7 @@
+import { BaseError } from "./BaseError";
+
+export class NotFoundError extends BaseError {
+ constructor(description = "Not Found") {
+ super("NotFoundError", 404, description, true);
+ }
+}
diff --git a/web/src/server/errors/UnauthorizedError.ts b/web/src/server/errors/UnauthorizedError.ts
new file mode 100644
index 0000000000..e5d657c9b2
--- /dev/null
+++ b/web/src/server/errors/UnauthorizedError.ts
@@ -0,0 +1,7 @@
+import { BaseError } from "./BaseError";
+
+export class UnauthorizedError extends BaseError {
+ constructor(description = "Unauthorized") {
+ super("UnauthorizedError", 401, description, true);
+ }
+}
diff --git a/web/src/server/errors/ValidationError.ts b/web/src/server/errors/ValidationError.ts
new file mode 100644
index 0000000000..85b2fb51ad
--- /dev/null
+++ b/web/src/server/errors/ValidationError.ts
@@ -0,0 +1,7 @@
+import { BaseError } from "./BaseError";
+
+export class ValidationError extends BaseError {
+ constructor(description = "Validation Error") {
+ super("ValidationError", 400, description, true);
+ }
+}
diff --git a/web/src/server/errors/index.ts b/web/src/server/errors/index.ts
new file mode 100644
index 0000000000..d15db4a86c
--- /dev/null
+++ b/web/src/server/errors/index.ts
@@ -0,0 +1,6 @@
+export { BaseError } from "./BaseError";
+export { NotFoundError } from "./NotFoundError";
+export { ValidationError } from "./ValidationError";
+export { UnauthorizedError } from "./UnauthorizedError";
+export { ForbiddenError } from "./ForbiddenError";
+export { MethodNotAllowedError } from "./MethodNotAllowedError";
diff --git a/web/src/utils/string.ts b/web/src/utils/string.ts
index 88892c3121..7cf052bbc3 100644
--- a/web/src/utils/string.ts
+++ b/web/src/utils/string.ts
@@ -11,20 +11,12 @@ export function truncate(str: string, n: number = 16) {
}
export function extractVariables(mustacheString: string): string[] {
- // Regular expression to match Mustache variables
- const regex: RegExp = /\{\{(.*?)\}\}/g;
+ const mustacheRegex = /\{\{(.*?)\}\}/g;
+ const uniqueVariables = new Set<string>();
- let match: RegExpExecArray | null;
- const variables: string[] = [];
-
- // Iterate over all matches
- while ((match = regex.exec(mustacheString)) !== null) {
- // Push each variable to the array if it's not already present
- const variable = match[1];
- if (variable && !variables.includes(variable)) {
- variables.push(variable);
- }
+ for (const match of mustacheString.matchAll(mustacheRegex)) {
+ uniqueVariables.add(match[1]);
}
- return variables;
+ return Array.from(uniqueVariables);
}