Skip to content

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

feat: prompt management (#777)

Max Deichmann8574d028c08e
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index 953e6ca988..e9a67fe200 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -59,6 +59,7 @@ types:
level: ObservationLevel
statusMessage: optional<string>
parentObservationId: optional<string>
+ promptId: optional<string>
Usage:
properties:
input: optional<integer>
diff --git a/fern/apis/server/definition/ingestion.yml b/fern/apis/server/definition/ingestion.yml
index 4933d65396..1ec634b8f9 100644
--- a/fern/apis/server/definition/ingestion.yml
+++ b/fern/apis/server/definition/ingestion.yml
@@ -92,6 +92,8 @@ types:
model: optional<string>
modelParameters: optional<map<string, commons.MapValue>>
usage: optional<IngestionUsage>
+ promptName: optional<string>
+ promptVersion: optional<integer>
UpdateGenerationBody:
extends: UpdateSpanBody
@@ -100,6 +102,8 @@ types:
model: optional<string>
modelParameters: optional<map<string, commons.MapValue>>
usage: optional<IngestionUsage>
+ promptName: optional<string>
+ promptVersion: optional<integer>
ObservationBody:
properties:
diff --git a/fern/apis/server/definition/prompts.yml b/fern/apis/server/definition/prompts.yml
new file mode 100644
index 0000000000..324e0452eb
--- /dev/null
+++ b/fern/apis/server/definition/prompts.yml
@@ -0,0 +1,36 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ commons: ./commons.yml
+ pagination: ./utils/pagination.yml
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ get:
+ docs: Get a specific prompt
+ method: GET
+ path: /prompts
+ request:
+ name: GetParameterRequest
+ query-parameters:
+ name: string
+ version: optional<integer>
+ response: Prompt
+ create:
+ docs: Create a specific prompt
+ method: POST
+ path: /prompts
+ request: CreatePromptRequest
+ response: Prompt
+
+types:
+ CreatePromptRequest:
+ properties:
+ name: string
+ isActive: boolean
+ prompt: string
+ Prompt:
+ properties:
+ name: string
+ version: integer
+ prompt: string
diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.yml
index 3d542e64f0..a672249f55 100644
--- a/generated/openapi-server/openapi.yml
+++ b/generated/openapi-server/openapi.yml
@@ -551,6 +551,102 @@ paths:
application/json:
schema: {}
security: *ref_0
+ /api/public/prompts:
+ get:
+ description: Get a specific prompt
+ operationId: prompts_get
+ tags:
+ - Prompts
+ parameters:
+ - name: name
+ in: query
+ required: true
+ schema:
+ type: string
+ - name: version
+ in: query
+ required: false
+ schema:
+ type: integer
+ nullable: true
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Prompt'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security: *ref_0
+ post:
+ description: Create a specific prompt
+ operationId: prompts_create
+ tags:
+ - Prompts
+ parameters: []
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Prompt'
+ '400':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '401':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '403':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '404':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ '405':
+ description: ''
+ content:
+ application/json:
+ schema: {}
+ security: *ref_0
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/CreatePromptRequest'
/api/public/scores:
post:
description: Add a score to the database, upserts on id
@@ -972,6 +1068,9 @@ components:
parentObservationId:
type: string
nullable: true
+ promptId:
+ type: string
+ nullable: true
required:
- id
- type
@@ -1431,6 +1530,12 @@ components:
usage:
$ref: '#/components/schemas/IngestionUsage'
nullable: true
+ promptName:
+ type: string
+ nullable: true
+ promptVersion:
+ type: integer
+ nullable: true
allOf:
- $ref: '#/components/schemas/CreateSpanBody'
UpdateGenerationBody:
@@ -1452,6 +1557,12 @@ components:
usage:
$ref: '#/components/schemas/IngestionUsage'
nullable: true
+ promptName:
+ type: string
+ nullable: true
+ promptVersion:
+ type: integer
+ nullable: true
allOf:
- $ref: '#/components/schemas/UpdateSpanBody'
ObservationBody:
@@ -1764,6 +1875,34 @@ components:
required:
- id
- name
+ CreatePromptRequest:
+ title: CreatePromptRequest
+ type: object
+ properties:
+ name:
+ type: string
+ isActive:
+ type: boolean
+ prompt:
+ type: string
+ required:
+ - name
+ - isActive
+ - prompt
+ Prompt:
+ title: Prompt
+ type: object
+ properties:
+ name:
+ type: string
+ version:
+ type: integer
+ prompt:
+ type: string
+ required:
+ - name
+ - version
+ - prompt
CreateScoreRequest:
title: CreateScoreRequest
type: object
diff --git a/generated/postman/collection.json b/generated/postman/collection.json
index 718f362443..061d780691 100644
--- a/generated/postman/collection.json
+++ b/generated/postman/collection.json
@@ -464,6 +464,82 @@
}
]
},
+ {
+ "_type": "container",
+ "description": null,
+ "name": "Prompts",
+ "item": [
+ {
+ "_type": "endpoint",
+ "name": "Get",
+ "request": {
+ "description": "Get a specific prompt",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/prompts?name=&version=",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "prompts"
+ ],
+ "query": [
+ {
+ "key": "name",
+ "value": "",
+ "description": null
+ },
+ {
+ "key": "version",
+ "value": "",
+ "description": null
+ }
+ ],
+ "variable": []
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Create",
+ "request": {
+ "description": "Create a specific prompt",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/prompts",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "prompts"
+ ],
+ "query": [],
+ "variable": []
+ },
+ "header": [],
+ "method": "POST",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"name\": \"example\",\n \"isActive\": true,\n \"prompt\": \"example\"\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ }
+ ]
+ },
{
"_type": "container",
"description": null,
diff --git a/package-lock.json b/package-lock.json
index 65ee11c5da..0c86772ecf 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -20,6 +20,8 @@
"@hookform/resolvers": "^3.3.2",
"@next-auth/prisma-adapter": "^1.0.7",
"@prisma/client": "^5.7.1",
+ "@radix-ui/react-accordion": "^1.1.2",
+ "@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-avatar": "^1.0.4",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-collapsible": "^1.0.3",
@@ -66,6 +68,7 @@
"js-yaml": "^4.1.0",
"lodash": "^4.17.21",
"lucide-react": "^0.302.0",
+ "mustache": "^4.2.0",
"next": "^14.0.4",
"next-auth": "^4.24.5",
"next-query-params": "^5.0.0",
@@ -3160,6 +3163,65 @@
"@babel/runtime": "^7.13.10"
}
},
+ "node_modules/@radix-ui/react-accordion": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-accordion/-/react-accordion-1.1.2.tgz",
+ "integrity": "sha512-fDG7jcoNKVjSK6yfmuAs0EnPDro0WMXIhMtXdTBWqEioVW206ku+4Lw07e+13lUkFkpoEQ2PdeMIAGpdqEAmDg==",
+ "dependencies": {
+ "@babel/runtime": "^7.13.10",
+ "@radix-ui/primitive": "1.0.1",
+ "@radix-ui/react-collapsible": "1.0.3",
+ "@radix-ui/react-collection": "1.0.3",
+ "@radix-ui/react-compose-refs": "1.0.1",
+ "@radix-ui/react-context": "1.0.1",
+ "@radix-ui/react-direction": "1.0.1",
+ "@radix-ui/react-id": "1.0.1",
+ "@radix-ui/react-primitive": "1.0.3",
+ "@radix-ui/react-use-controllable-state": "1.0.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0",
+ "react-dom": "^16.8 || ^17.0 || ^18.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-alert-dialog": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-alert-dialog/-/react-alert-dialog-1.0.5.tgz",
+ "integrity": "sha512-OrVIOcZL0tl6xibeuGt5/+UxoT2N27KCFOPjFyfXMnchxSHZ/OW7cCX2nGlIYJrbHK/fczPcFzAwvNBB6XBNMA==",
+ "dependencies": {
+ "@babel/runtime": "^7.13.10",
+ "@radix-ui/primitive": "1.0.1",
+ "@radix-ui/react-compose-refs": "1.0.1",
+ "@radix-ui/react-context": "1.0.1",
+ "@radix-ui/react-dialog": "1.0.5",
+ "@radix-ui/react-primitive": "1.0.3",
+ "@radix-ui/react-slot": "1.0.2"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0",
+ "react-dom": "^16.8 || ^17.0 || ^18.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-arrow": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@radix-ui/react-arrow/-/react-arrow-1.0.3.tgz",
@@ -13150,6 +13212,14 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
+ "node_modules/mustache": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz",
+ "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==",
+ "bin": {
+ "mustache": "bin/mustache"
+ }
+ },
"node_modules/mute-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-1.0.0.tgz",
diff --git a/package.json b/package.json
index 43ecaede49..17fe0af9a3 100644
--- a/package.json
+++ b/package.json
@@ -35,6 +35,8 @@
"@hookform/resolvers": "^3.3.2",
"@next-auth/prisma-adapter": "^1.0.7",
"@prisma/client": "^5.7.1",
+ "@radix-ui/react-accordion": "^1.1.2",
+ "@radix-ui/react-alert-dialog": "^1.0.5",
"@radix-ui/react-avatar": "^1.0.4",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-collapsible": "^1.0.3",
@@ -81,6 +83,7 @@
"js-yaml": "^4.1.0",
"lodash": "^4.17.21",
"lucide-react": "^0.302.0",
+ "mustache": "^4.2.0",
"next": "^14.0.4",
"next-auth": "^4.24.5",
"next-query-params": "^5.0.0",
diff --git a/prisma/migrations/20231230151856_add_prompt_table/migration.sql b/prisma/migrations/20231230151856_add_prompt_table/migration.sql
new file mode 100644
index 0000000000..bc04acf99b
--- /dev/null
+++ b/prisma/migrations/20231230151856_add_prompt_table/migration.sql
@@ -0,0 +1,29 @@
+-- AlterTable
+ALTER TABLE "observations" ADD COLUMN "prompt_id" TEXT;
+
+-- CreateTable
+CREATE TABLE "prompts" (
+ "id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "project_id" TEXT NOT NULL,
+ "created_by" TEXT NOT NULL,
+ "prompt" TEXT NOT NULL,
+ "name" TEXT NOT NULL,
+ "version" INTEGER NOT NULL,
+ "is_active" BOOLEAN NOT NULL,
+
+ CONSTRAINT "prompts_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "prompts_project_id_name_version_idx" ON "prompts"("project_id", "name", "version");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "prompts_project_id_name_version_key" ON "prompts"("project_id", "name", "version");
+
+-- AddForeignKey
+ALTER TABLE "observations" ADD CONSTRAINT "observations_prompt_id_fkey" FOREIGN KEY ("prompt_id") REFERENCES "prompts"("id") ON DELETE SET NULL ON UPDATE CASCADE;
+
+-- AddForeignKey
+ALTER TABLE "prompts" ADD CONSTRAINT "prompts_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 6a48916c72..d4eefa80a5 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -91,6 +91,7 @@ model Project {
RawEvents Events[]
invitations MembershipInvitation[]
sessions TraceSession[]
+ Prompt Prompt[]
@@map("projects")
}
@@ -229,6 +230,9 @@ model Observation {
derivedDatasetItems DatasetItem[]
datasetRunItems DatasetRunItems[]
+ promptId String? @map("prompt_id")
+ prompt Prompt? @relation(fields: [promptId], onDelete: SetNull, references: [id])
+
@@unique([id, projectId])
@@index([traceId])
@@index([type])
@@ -385,3 +389,24 @@ model Events {
@@index(projectId)
@@map("events")
}
+
+model Prompt {
+ id String @id @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ createdBy String @map("created_by")
+
+ prompt String
+ name String
+ version Int
+ isActive Boolean @map("is_active")
+ Observation Observation[]
+
+ @@unique([projectId, name, version])
+ @@index([projectId, name, version])
+ @@map("prompts")
+}
diff --git a/prisma/seed.ts b/prisma/seed.ts
index 657da621c3..8ec93ddb50 100755
--- a/prisma/seed.ts
+++ b/prisma/seed.ts
@@ -53,6 +53,25 @@ async function main() {
},
});
+ const prompt = await prisma.prompt.upsert({
+ where: {
+ projectId_name_version: {
+ projectId: seedProjectId,
+ name: "summary-prompt",
+ version: 1,
+ },
+ },
+ create: {
+ name: "summary-prompt",
+ project: { connect: { id: seedProjectId } },
+ prompt: "prompt {{variable}} {{anotherVariable}}",
+ isActive: true,
+ version: 1,
+ createdBy: "user-1",
+ },
+ update: {},
+ });
+
const seedApiKey = {
id: "seed-api-key",
secret: process.env.SEED_SECRET_KEY ?? "sk-lf-1234567890",
@@ -326,6 +345,11 @@ async function main() {
totalTokens: promptTokens + completionTokens,
parentObservationId: span.id,
traceId: trace.id,
+ ...{
+ ...(Math.random() > 0.5 && trace.projectId === prompt.projectId
+ ? { prompt: { connect: { id: prompt.id } } }
+ : {}),
+ },
},
});
if (Math.random() > 0.6)
diff --git a/src/__tests__/prompts.servertest.ts b/src/__tests__/prompts.servertest.ts
new file mode 100644
index 0000000000..cbe7da0a37
--- /dev/null
+++ b/src/__tests__/prompts.servertest.ts
@@ -0,0 +1,294 @@
+/** @jest-environment node */
+
+import { prisma } from "@/src/server/db";
+import { makeAPICall, pruneDatabase } from "@/src/__tests__/test-utils";
+import { v4 as uuidv4, v4 } from "uuid";
+import { type Prompt } from "@prisma/client";
+
+describe("/api/public/prompts API Endpoint", () => {
+ beforeEach(async () => await pruneDatabase());
+
+ it("should fetch a prompt", async () => {
+ const promptId = uuidv4();
+
+ await prisma.prompt.create({
+ data: {
+ id: promptId,
+ name: "prompt-name",
+ prompt: "prompt",
+ isActive: true,
+ version: 1,
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ createdBy: "user-1",
+ },
+ });
+
+ const fetchedObservations = await makeAPICall(
+ "GET",
+ "/api/public/prompts?name=prompt-name&version=1",
+ undefined,
+ );
+
+ expect(fetchedObservations.status).toBe(200);
+
+ if (!isPrompt(fetchedObservations.body)) {
+ throw new Error("Expected body to be a prompt");
+ }
+
+ expect(fetchedObservations.body.id).toBe(promptId);
+ expect(fetchedObservations.body.name).toBe("prompt-name");
+ expect(fetchedObservations.body.prompt).toBe("prompt");
+ expect(fetchedObservations.body.version).toBe(1);
+ expect(fetchedObservations.body.isActive).toBe(true);
+ expect(fetchedObservations.body.createdBy).toBe("user-1");
+ });
+
+ it("should fetch active prompt only", async () => {
+ const promptId = uuidv4();
+
+ await prisma.prompt.create({
+ data: {
+ id: promptId,
+ name: "prompt-name",
+ prompt: "prompt",
+ isActive: false,
+ version: 1,
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ createdBy: "user-1",
+ },
+ });
+
+ const fetchedObservations = await makeAPICall(
+ "GET",
+ "/api/public/prompts?name=prompt-name&version=1",
+ undefined,
+ );
+
+ expect(fetchedObservations.status).toBe(404);
+ });
+
+ it("should fetch active prompt when multiple exist", async () => {
+ const promptIdOne = uuidv4();
+ const promptIdTwo = uuidv4();
+
+ await prisma.prompt.create({
+ data: {
+ id: promptIdOne,
+ name: "prompt-name",
+ prompt: "prompt",
+ isActive: false,
+ version: 1,
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ createdBy: "user-1",
+ },
+ });
+
+ await prisma.prompt.create({
+ data: {
+ id: promptIdTwo,
+ name: "prompt-name",
+ prompt: "prompt",
+ isActive: true,
+ version: 2,
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ createdBy: "user-1",
+ },
+ });
+
+ const fetchedObservations = await makeAPICall(
+ "GET",
+ "/api/public/prompts?name=prompt-name",
+ undefined,
+ );
+
+ expect(fetchedObservations.status).toBe(200);
+
+ if (!isPrompt(fetchedObservations.body)) {
+ throw new Error("Expected body to be a prompt");
+ }
+
+ expect(fetchedObservations.body.id).toBe(promptIdTwo);
+ expect(fetchedObservations.body.name).toBe("prompt-name");
+ expect(fetchedObservations.body.prompt).toBe("prompt");
+ expect(fetchedObservations.body.version).toBe(2);
+ expect(fetchedObservations.body.isActive).toBe(true);
+ expect(fetchedObservations.body.createdBy).toBe("user-1");
+ });
+
+ it("should create and fetch a prompt", async () => {
+ await makeAPICall("POST", "/api/public/prompts", {
+ name: "prompt-name",
+ prompt: "prompt",
+ isActive: true,
+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ });
+
+ const fetchedObservations = await makeAPICall(
+ "GET",
+ "/api/public/prompts?name=prompt-name&version=1",
+ undefined,
+ );
+
+ expect(fetchedObservations.status).toBe(200);
+
+ if (!isPrompt(fetchedObservations.body)) {
+ throw new Error("Expected body to be an array of observations");
+ }
+
+ expect(fetchedObservations.body.name).toBe("prompt-name");
+ expect(fetchedObservations.body.prompt).toBe("prompt");
+ expect(fetchedObservations.body.version).toBe(1);
+ expect(fetchedObservations.body.isActive).toBe(true);
+ expect(fetchedObservations.body.createdBy).toBe("API");
+ });
+
+ it("should relate generation to prompt", async () => {
+ const traceId = v4();
+ const generationId = v4();
+
+ const promptId = uuidv4();
+
+ await prisma.prompt.create({
+ data: {
+ id: promptId,
+ name: "prompt-name",
+ prompt: "prompt",
+ isActive: true,
+ version: 1,
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ createdBy: "user-1",
+ },
+ });
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ metadata: {
+ sdk_verion: "1.0.0",
+ sdk_name: "python",
+ },
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ },
+ },
+ {
+ id: v4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ name: "generation-name",
+ promptName: "prompt-name",
+ promptVersion: 1,
+ },
+ },
+ ],
+ });
+
+ expect(response.status).toBe(207);
+
+ console.log("response body", response.body);
+
+ const dbGeneration = await prisma.observation.findUnique({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(dbGeneration?.id).toBe(generationId);
+ expect(dbGeneration?.promptId).toBe(promptId);
+ });
+
+ it("should fail if prompt version is missing", async () => {
+ const traceId = v4();
+ const generationId = v4();
+
+ const promptId = uuidv4();
+
+ await prisma.prompt.create({
+ data: {
+ id: promptId,
+ name: "prompt-name",
+ prompt: "prompt",
+ isActive: true,
+ version: 1,
+ project: {
+ connect: { id: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a" },
+ },
+ createdBy: "user-1",
+ },
+ });
+
+ const response = await makeAPICall("POST", "/api/public/ingestion", {
+ metadata: {
+ sdk_verion: "1.0.0",
+ sdk_name: "python",
+ },
+ batch: [
+ {
+ id: v4(),
+ type: "trace-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: traceId,
+ name: "trace-name",
+ },
+ },
+ {
+ id: v4(),
+ type: "generation-create",
+ timestamp: new Date().toISOString(),
+ body: {
+ id: generationId,
+ traceId: traceId,
+ type: "GENERATION",
+ name: "generation-name",
+ promptName: "prompt-name",
+ },
+ },
+ ],
+ });
+
+ expect(response.status).toBe(207);
+
+ console.log("response body", response.body);
+
+ const dbGeneration = await prisma.observation.findUnique({
+ where: {
+ id: generationId,
+ },
+ });
+
+ expect(dbGeneration).toBeNull();
+ });
+});
+
+const isPrompt = (x: unknown): x is Prompt => {
+ if (typeof x !== "object" || x === null) return false;
+ const prompt = x as Prompt;
+ return (
+ typeof prompt.id === "string" &&
+ typeof prompt.name === "string" &&
+ typeof prompt.version === "number" &&
+ typeof prompt.prompt === "string" &&
+ typeof prompt.isActive === "boolean" &&
+ typeof prompt.projectId === "string" &&
+ typeof prompt.createdBy === "string"
+ );
+};
diff --git a/src/__tests__/test-utils.ts b/src/__tests__/test-utils.ts
index 63b387596b..ce6edc519f 100644
--- a/src/__tests__/test-utils.ts
+++ b/src/__tests__/test-utils.ts
@@ -12,6 +12,8 @@ export const pruneDatabase = async () => {
await prisma.datasetItem.deleteMany();
await prisma.dataset.deleteMany();
await prisma.datasetRuns.deleteMany();
+ await prisma.prompt.deleteMany();
+ await prisma.events.deleteMany();
};
export function createBasicAuthHeader(
diff --git a/src/components/layouts/header.tsx b/src/components/layouts/header.tsx
index 1e3e081980..ef64bc351a 100644
--- a/src/components/layouts/header.tsx
+++ b/src/components/layouts/header.tsx
@@ -3,6 +3,7 @@ import Link from "next/link";
import { useRouter } from "next/router";
import { useSession } from "next-auth/react";
import DocPopup from "@/src/components/layouts/doc-popup";
+import { StatusBadge } from "./live-badge";
export default function Header(props: {
title: string;
@@ -95,15 +96,7 @@ export default function Header(props: {
/>
) : null}
</div>
- {props.live ? (
- <div className="flex items-center gap-2 rounded-sm bg-green-100 px-3 text-green-600">
- <span className="relative flex h-2 w-2 ">
- <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-green-500 opacity-75"></span>
- <span className="relative inline-flex h-2 w-2 rounded-full bg-green-600"></span>
- </span>
- Live
- </div>
- ) : null}
+ {props.live ? <StatusBadge type="live" /> : null}
</div>
<div className="flex items-center gap-3">
{props.actionButtons ?? null}
diff --git a/src/components/layouts/live-badge.tsx b/src/components/layouts/live-badge.tsx
new file mode 100644
index 0000000000..de24244995
--- /dev/null
+++ b/src/components/layouts/live-badge.tsx
@@ -0,0 +1,35 @@
+import { cn } from "@/src/utils/tailwind";
+
+export const StatusBadge = (props: {
+ className?: string;
+
+ type: "live" | "disabled";
+}) => {
+ return (
+ <div
+ className={cn(
+ "flex items-center gap-2 rounded-sm px-3",
+ props.type === "live"
+ ? " bg-green-100 text-green-600"
+ : "bg-gray-100 text-gray-800",
+ props.className,
+ )}
+ >
+ <span className="relative flex h-2 w-2 ">
+ <span
+ className={cn(
+ "absolute inline-flex h-full w-full rounded-full opacity-75",
+ props.type === "live" ? "animate-ping bg-green-500" : "bg-gray-500",
+ )}
+ ></span>
+ <span
+ className={cn(
+ "relative inline-flex h-2 w-2 rounded-full ",
+ props.type === "live" ? "bg-green-600" : "bg-gray-600",
+ )}
+ ></span>
+ </span>
+ {props.type === "live" ? "Live" : "Disabled"}
+ </div>
+ );
+};
diff --git a/src/components/layouts/routes.ts b/src/components/layouts/routes.ts
index 37fb8f8ea2..b16445e0ba 100644
--- a/src/components/layouts/routes.ts
+++ b/src/components/layouts/routes.ts
@@ -10,6 +10,7 @@ import {
TextSelect,
UsersIcon,
Route,
+ PenSquareIcon,
} from "lucide-react";
export const ROUTES: Array<{
@@ -49,6 +50,12 @@ export const ROUTES: Array<{
pathname: `/project/[projectId]/users`,
icon: UsersIcon,
},
+ {
+ name: "Prompts",
+ pathname: "/project/[projectId]/prompts",
+ icon: PenSquareIcon,
+ featureFlag: "promptFlag",
+ },
{
name: "Datasets",
pathname: `/project/[projectId]/datasets`,
diff --git a/src/components/trace/ObservationPreview.tsx b/src/components/trace/ObservationPreview.tsx
index 4db7bfbf34..0f61451c08 100644
--- a/src/components/trace/ObservationPreview.tsx
+++ b/src/components/trace/ObservationPreview.tsx
@@ -22,6 +22,7 @@ import { type ObservationReturnType } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
import { IOPreview } from "@/src/components/trace/IOPreview";
import { formatInterval } from "@/src/utils/dates";
+import Link from "next/link";
export const ObservationPreview = (props: {
observations: Array<ObservationReturnType>;
@@ -54,6 +55,12 @@ export const ObservationPreview = (props: {
{preloadedObservation.startTime.toLocaleString()}
</CardDescription>
<div className="flex flex-wrap gap-2">
+ {preloadedObservation.promptId ? (
+ <PromptBadge
+ promptId={preloadedObservation.promptId}
+ projectId={preloadedObservation.projectId}
+ />
+ ) : undefined}
{preloadedObservation.endTime ? (
<Badge variant="outline">
{formatInterval(
@@ -83,6 +90,7 @@ export const ObservationPreview = (props: {
{preloadedObservation.price.toString()} USD
</Badge>
) : undefined}
+
{preloadedObservation.modelParameters &&
typeof preloadedObservation.modelParameters === "object"
? Object.entries(preloadedObservation.modelParameters)
@@ -173,3 +181,22 @@ export const ObservationPreview = (props: {
</Card>
);
};
+
+const PromptBadge = (props: { promptId: string; projectId: string }) => {
+ const prompt = api.prompts.byId.useQuery({
+ id: props.promptId,
+ projectId: props.projectId,
+ });
+
+ if (prompt.isLoading) return null;
+
+ return (
+ <Link href={`/project/${props.projectId}/prompts/${props.promptId}`}>
+ <Badge>
+ Prompt: {prompt.data?.name}
+ {" - "}
+ {prompt.data?.version}
+ </Badge>
+ </Link>
+ );
+};
diff --git a/src/components/ui/command.tsx b/src/components/ui/command.tsx
index 30f7356643..0fd39c9586 100644
--- a/src/components/ui/command.tsx
+++ b/src/components/ui/command.tsx
@@ -5,8 +5,8 @@ import { type DialogProps } from "@radix-ui/react-dialog";
import { Command as CommandPrimitive } from "cmdk";
import { Search } from "lucide-react";
-import { cn } from "@/src/utils/tailwind";
import { Dialog, DialogContent } from "@/src/components/ui/dialog";
+import { cn } from "@/src/utils/tailwind";
const Command = React.forwardRef<
React.ElementRef<typeof CommandPrimitive>,
@@ -15,7 +15,7 @@ const Command = React.forwardRef<
<CommandPrimitive
ref={ref}
className={cn(
- "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
+ "flex h-full w-full flex-col overflow-hidden rounded-md bg-white text-slate-950 dark:bg-slate-950 dark:text-slate-50",
className,
)}
{...props}
@@ -29,7 +29,7 @@ const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
return (
<Dialog {...props}>
<DialogContent className="overflow-hidden p-0 shadow-lg">
- <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
+ <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-slate-500 dark:[&_[cmdk-group-heading]]:text-slate-400 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
{children}
</Command>
</DialogContent>
@@ -41,12 +41,15 @@ const CommandInput = React.forwardRef<
React.ElementRef<typeof CommandPrimitive.Input>,
React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
>(({ className, ...props }, ref) => (
- <div className="flex items-center border-b px-3" cmdk-input-wrapper="">
+ <div
+ className="flex items-center rounded-lg border px-3"
+ cmdk-input-wrapper=""
+ >
<Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
ref={ref}
className={cn(
- "flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
+ "flex h-11 w-full rounded-md border-transparent bg-transparent py-3 text-sm outline-none placeholder:text-slate-500 focus:border-0 focus:border-none focus:border-transparent focus:ring-0 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-slate-400 ",
className,
)}
{...props}
@@ -89,7 +92,7 @@ const CommandGroup = React.forwardRef<
<CommandPrimitive.Group
ref={ref}
className={cn(
- "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
+ "overflow-hidden p-1 text-slate-950 dark:text-slate-50 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-slate-500 dark:[&_[cmdk-group-heading]]:text-slate-400",
className,
)}
{...props}
@@ -104,7 +107,7 @@ const CommandSeparator = React.forwardRef<
>(({ className, ...props }, ref) => (
<CommandPrimitive.Separator
ref={ref}
- className={cn("-mx-1 h-px bg-border", className)}
+ className={cn("-mx-1 h-px bg-slate-200 dark:bg-slate-800", className)}
{...props}
/>
));
@@ -117,7 +120,7 @@ const CommandItem = React.forwardRef<
<CommandPrimitive.Item
ref={ref}
className={cn(
- "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-accent aria-selected:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ "relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-slate-100 aria-selected:text-slate-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50 dark:aria-selected:bg-slate-800 dark:aria-selected:text-slate-50",
className,
)}
{...props}
@@ -133,7 +136,7 @@ const CommandShortcut = ({
return (
<span
className={cn(
- "ml-auto text-xs tracking-widest text-muted-foreground",
+ "ml-auto text-xs tracking-widest text-slate-500 dark:text-slate-400",
className,
)}
{...props}
diff --git a/src/features/feature-flags/available-flags.ts b/src/features/feature-flags/available-flags.ts
index 276ffb57fe..d8b1d52ecd 100644
--- a/src/features/feature-flags/available-flags.ts
+++ b/src/features/feature-flags/available-flags.ts
@@ -1 +1 @@
-export const availableFlags = ["templateFlag"] as const;
+export const availableFlags = ["templateFlag", "promptFlag"] as const;
diff --git a/src/features/prompts/components/auto-complete.tsx b/src/features/prompts/components/auto-complete.tsx
new file mode 100644
index 0000000000..46d8760fd8
--- /dev/null
+++ b/src/features/prompts/components/auto-complete.tsx
@@ -0,0 +1,180 @@
+"use client";
+
+import {
+ CommandGroup,
+ CommandItem,
+ CommandList,
+ CommandInput,
+} from "@/src/components/ui/command";
+import { Command as CommandPrimitive } from "cmdk";
+import { useState, useRef, useCallback, type KeyboardEvent } from "react";
+
+import { Check } from "lucide-react";
+import { cn } from "@/src/utils/tailwind";
+
+export type Option = Record<"value" | "label", string> & Record<string, string>;
+
+type AutoCompleteProps = {
+ options: Option[];
+ value: Option;
+ onValueChange?: (value: Option) => void;
+ disabled?: boolean;
+ placeholder?: string;
+};
+
+export const AutoComplete = ({
+ options,
+ placeholder,
+ value,
+ onValueChange,
+ disabled,
+}: AutoCompleteProps) => {
+ const inputRef = useRef<HTMLInputElement>(null);
+ const [isOpen, setOpen] = useState(false);
+ const [selected, setSelected] = useState<Option>(value);
+ const [inputValue, setInputValue] = useState<string>(value.label || "");
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ const input = inputRef.current;
+ if (!input) {
+ return;
+ }
+
+ // Keep the options displayed when the user is typing
+ if (!isOpen) {
+ setOpen(true);
+ }
+
+ // This is not a default behaviour of the <input /> field
+ if (event.key === "Enter" && input.value !== "") {
+ const optionToSelect = options.find(
+ (option) => option.label === input.value,
+ );
+ if (optionToSelect) {
+ setSelected(optionToSelect);
+ onValueChange?.(optionToSelect);
+ }
+ }
+
+ if (event.key === "Escape") {
+ input.blur();
+ }
+ },
+ [isOpen, options, onValueChange],
+ );
+
+ const handleBlur = useCallback(() => {
+ setOpen(false);
+ setInputValue(selected.label);
+ }, [selected]);
+
+ const handleSelectOption = useCallback(
+ (selectedOption: Option) => {
+ setInputValue(selectedOption.label);
+
+ setSelected(selectedOption);
+ onValueChange?.(selectedOption);
+
+ // This is a hack to prevent the input from being focused after the user selects an option
+ // We can call this hack: "The next tick"
+ setTimeout(() => {
+ inputRef.current?.blur();
+ }, 0);
+ },
+ [onValueChange],
+ );
+
+ return (
+ <CommandPrimitive onKeyDown={handleKeyDown}>
+ <div>
+ <CommandInput
+ ref={inputRef}
+ value={inputValue}
+ onValueChange={setInputValue}
+ onBlur={handleBlur}
+ onFocus={() => setOpen(true)}
+ placeholder={placeholder}
+ disabled={disabled}
+ className="text-base"
+ />
+ </div>
+ <div className="relative mt-1">
+ {isOpen ? (
+ <div className="absolute top-0 z-10 w-full rounded-xl bg-stone-50 outline-none animate-in fade-in-0 zoom-in-95">
+ <CommandList className="rounded-lg ring-1 ring-slate-200">
+ {options.length > 0 ? (
+ <CommandGroup>
+ {options.map((option) => {
+ const isSelected = selected.value === option.value;
+ return (
+ <CommandItem
+ key={option.value}
+ value={option.label}
+ onMouseDown={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ onSelect={() => handleSelectOption(option)}
+ className={cn(
+ "flex w-full items-center gap-2",
+ !isSelected ? "pl-8" : null,
+ )}
+ >
+ {isSelected ? <Check className="w-4" /> : null}
+ {option.label}
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ ) : null}
+ <CommandItemCreate
+ onMouseDown={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ onSelect={() =>
+ handleSelectOption({ value: inputValue, label: inputValue })
+ }
+ {...{ inputValue, options }}
+ />
+ </CommandList>
+ </div>
+ ) : null}
+ </div>
+ </CommandPrimitive>
+ );
+};
+
+const CommandItemCreate = ({
+ inputValue,
+ options,
+ onSelect,
+ onMouseDown,
+}: {
+ inputValue: string;
+ options: Option[];
+ onSelect: () => void;
+ onMouseDown: (event: React.MouseEvent<HTMLElement>) => void;
+}) => {
+ const hasNoOption = !options
+ .map(({ value }) => value)
+ .includes(inputValue.toLowerCase());
+
+ const render = inputValue !== "" && hasNoOption;
+
+ if (!render) return null;
+
+ return (
+ <CommandItem
+ key={inputValue}
+ value={inputValue}
+ className="text-muted-foreground"
+ onSelect={onSelect}
+ onMouseDown={onMouseDown}
+ >
+ <div className={cn("m-2 h-4 w-4")} />
+ Create new prompt name: &quot;{inputValue}&quot;
+ </CommandItem>
+ );
+};
diff --git a/src/features/prompts/components/new-prompt-button.tsx b/src/features/prompts/components/new-prompt-button.tsx
new file mode 100644
index 0000000000..2dcbc051cb
--- /dev/null
+++ b/src/features/prompts/components/new-prompt-button.tsx
@@ -0,0 +1,271 @@
+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,
+} 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 Option } from "@/src/features/prompts/components/auto-complete";
+
+export const CreatePromptDialog = (props: {
+ projectId: string;
+ title: string;
+ promptName?: string;
+ promptText?: string;
+ subtitle?: string;
+ 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="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}
+ 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"),
+ isActive: z.boolean({
+ required_error: "Enter whether the prompt should go live",
+ }),
+});
+
+export const NewPromptForm = (props: {
+ projectId: string;
+ onFormSuccess?: () => void;
+ promptName?: string;
+ promptText?: string;
+}) => {
+ 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 ?? "",
+ },
+ });
+
+ 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,
+ })
+ .then((newPrompt) => {
+ props.onFormSuccess?.();
+ form.reset();
+ // go to the following page after creating the prompt
+ if (newPrompt) {
+ void router.push(
+ `/project/${props.projectId}/prompts/${newPrompt.id}`,
+ );
+ }
+ })
+ .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: Option) => {
+ 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}
+ />
+ </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="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/src/features/prompts/components/promote-prompt.tsx b/src/features/prompts/components/promote-prompt.tsx
new file mode 100644
index 0000000000..22bf410bc9
--- /dev/null
+++ b/src/features/prompts/components/promote-prompt.tsx
@@ -0,0 +1,77 @@
+import { Button } from "@/src/components/ui/button";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { api } from "@/src/utils/api";
+import { PlayIcon } from "lucide-react";
+import { useState } from "react";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/src/components/ui/popover";
+import { usePostHog } from "posthog-js/react";
+
+export function PromotePrompt({
+ promptId,
+ projectId,
+ promptName,
+ disabled,
+}: {
+ promptId: string;
+ projectId: string;
+ promptName: string;
+ disabled: boolean;
+}) {
+ const [isPromoted, setIsPromoted] = useState(false);
+ const utils = api.useUtils();
+ const posthog = usePostHog();
+
+ const hasAccess = useHasAccess({ projectId, scope: "prompts:CUD" });
+
+ const mutPromotePrompt = api.prompts.promote.useMutation({
+ onSuccess: () => {
+ setIsPromoted(true);
+ void utils.prompts.invalidate();
+ },
+ });
+
+ if (!hasAccess) {
+ return null;
+ }
+
+ return (
+ <Popover key={promptId}>
+ <PopoverTrigger asChild>
+ <Button variant="ghost" size="xs" disabled={disabled}>
+ <PlayIcon className="h-4 w-4" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent>
+ <h2 className="text-md mb-3 font-semibold">Please confirm</h2>
+ <p className="mb-3 text-sm">
+ This action cannot be undone and promotes the prompt to production.
+ SDKs requesting a prompt with name{" "}
+ <code className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-sm font-semibold">
+ {promptName}
+ </code>
+ , will receive this prompt once confirmed.
+ </p>
+ <div className="flex justify-end space-x-4">
+ <Button
+ type="button"
+ variant="destructive"
+ loading={mutPromotePrompt.isLoading || isPromoted}
+ onClick={() => {
+ void mutPromotePrompt.mutateAsync({
+ promptId,
+ projectId,
+ });
+ posthog.capture("prompt:promote");
+ }}
+ >
+ Promote Prompt
+ </Button>
+ </div>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/features/prompts/components/prompt-detail.tsx b/src/features/prompts/components/prompt-detail.tsx
new file mode 100644
index 0000000000..24a5f9ab4a
--- /dev/null
+++ b/src/features/prompts/components/prompt-detail.tsx
@@ -0,0 +1,121 @@
+import Header from "@/src/components/layouts/header";
+import { Badge } from "@/src/components/ui/badge";
+import { Button } from "@/src/components/ui/button";
+import { DetailPageNav } from "@/src/features/navigate-detail-pages/DetailPageNav";
+import { CreatePromptDialog } from "@/src/features/prompts/components/new-prompt-button";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { api } from "@/src/utils/api";
+import { extractVariables } from "@/src/utils/string";
+import { type Prompt } from "@prisma/client";
+import { Pencil } from "lucide-react";
+import router from "next/router";
+
+export type PromptDetailProps = {
+ projectId: string;
+ promptId: string;
+};
+
+export const PromptDetail = (props: PromptDetailProps) => {
+ const prompt = api.prompts.byId.useQuery({
+ id: props.promptId,
+ projectId: props.projectId,
+ });
+
+ const extractedVariables = prompt.data
+ ? extractVariables(prompt.data.prompt)
+ : [];
+
+ return (
+ <div className="flex flex-col overflow-hidden xl:container md:h-[calc(100vh-100px)] xl:h-[calc(100vh-40px)]">
+ <Header
+ title={
+ prompt.data
+ ? prompt.data.name + " - " + prompt.data.version
+ : "Loading"
+ }
+ live={prompt.data?.isActive}
+ breadcrumb={[
+ {
+ name: "Prompts",
+ href: `/project/${props.projectId}/prompts/`,
+ },
+ { name: props.promptId },
+ ]}
+ actionButtons={
+ <>
+ <CreatePromptDialog
+ projectId={props.projectId}
+ title="Update Prompt"
+ subtitle="We do not update prompts, instead we create a new version of the prompt."
+ promptName={prompt.data?.name}
+ promptText={prompt.data?.prompt}
+ >
+ <Button variant="outline" size="icon">
+ <Pencil className="h-5 w-5" />
+ </Button>
+ </CreatePromptDialog>
+ <DetailPageNav
+ key="nav"
+ currentId={props.promptId}
+ path={(id) =>
+ `/project/${router.query.projectId as string}/prompts/${id}`
+ }
+ listKey="prompts"
+ />
+ </>
+ }
+ />
+
+ <div className="mx-auto w-full rounded-lg border text-base leading-7 text-gray-700">
+ <div className="border-b px-3 py-1 text-xs font-medium">Prompt</div>
+ <p className="p-3 text-sm leading-8">
+ {prompt.data?.prompt ?? "Loading"}
+ </p>
+ </div>
+ <div className="mx-auto mt-10 w-full rounded-lg border text-base leading-7 text-gray-700">
+ <div className="border-b px-3 py-1 text-xs font-medium">Variables</div>
+ <div className="flex flex-wrap gap-2 p-3">
+ {extractedVariables.map((variable) => (
+ <Badge key={variable} variant="outline">
+ {variable}
+ </Badge>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export function UpdatePrompt({
+ projectId,
+ prompt,
+ isLoading,
+}: {
+ projectId: string;
+ prompt: Prompt | undefined;
+ isLoading: boolean;
+}) {
+ const hasAccess = useHasAccess({ projectId, scope: "prompts:CUD" });
+
+ const handlePromptEdit = () => {
+ void router.push(
+ `/project/${projectId}/prompts/${prompt?.id}/edit`,
+ undefined,
+ {
+ shallow: true,
+ },
+ );
+ };
+
+ return (
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={() => handlePromptEdit()}
+ disabled={!hasAccess}
+ loading={isLoading}
+ >
+ <Pencil className="h-5 w-5" />
+ </Button>
+ );
+}
diff --git a/src/features/prompts/components/prompts-table.tsx b/src/features/prompts/components/prompts-table.tsx
new file mode 100644
index 0000000000..31fed3a637
--- /dev/null
+++ b/src/features/prompts/components/prompts-table.tsx
@@ -0,0 +1,174 @@
+import { StatusBadge } from "@/src/components/layouts/live-badge";
+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 { PromotePrompt } from "@/src/features/prompts/components/promote-prompt";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+
+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 = {
+ id: string;
+ name: string;
+ version: number;
+ isActive: boolean;
+ createdBy: string;
+ createdAt: Date;
+};
+
+export function PromptTable(props: { projectId: string }) {
+ const { setDetailPageList } = useDetailPageLists();
+
+ const prompts = api.prompts.all.useQuery({
+ projectId: props.projectId,
+ });
+
+ const hasAccess = useHasAccess({
+ projectId: props.projectId,
+ scope: "datasets:CUD",
+ });
+
+ useEffect(() => {
+ if (prompts.isSuccess) {
+ setDetailPageList(
+ "prompts",
+ prompts.data.map((t) => t.id),
+ );
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [prompts.isSuccess, prompts.data]);
+
+ const columns: LangfuseColumnDef<RowData>[] = [
+ {
+ accessorKey: "isActive",
+ header: "Status",
+ cell: ({ row }) => {
+ const isActive = row.getValue("isActive");
+ return isActive ? (
+ <StatusBadge type="live" className="h-6 w-24" />
+ ) : (
+ <StatusBadge type="disabled" className="h-6 w-24" />
+ );
+ },
+ },
+ {
+ accessorKey: "id",
+ header: "ID",
+ cell: ({ row }) => {
+ const value = row.getValue("id");
+ return value && typeof value === "string" ? (
+ <TableLink
+ path={`/project/${props.projectId}/prompts/${value}`}
+ value={value}
+ />
+ ) : undefined;
+ },
+ },
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => {
+ const name = row.getValue("name");
+ return name;
+ },
+ },
+ {
+ accessorKey: "version",
+ header: "Version",
+ cell: ({ row }) => {
+ const version = row.getValue("version");
+ return version;
+ },
+ },
+ {
+ accessorKey: "createdBy",
+ header: "Created By",
+ cell: ({ row }) => {
+ const createdBy = row.getValue("createdBy");
+ return createdBy;
+ },
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created At",
+ cell: ({ row }) => {
+ const createdAt: Date = row.getValue("createdAt");
+ return createdAt.toLocaleString();
+ },
+ },
+ {
+ accessorKey: "action",
+ header: "Action",
+ cell: ({ row }) => {
+ const promptId = row.getValue("id");
+ const promptName = row.getValue("name");
+ const isActive = row.getValue("isActive");
+ return promptId &&
+ typeof promptId === "string" &&
+ isActive !== undefined &&
+ typeof isActive === "boolean" &&
+ promptName &&
+ typeof promptName === "string" ? (
+ <PromotePrompt
+ promptId={promptId}
+ projectId={props.projectId}
+ promptName={promptName}
+ disabled={isActive}
+ />
+ ) : undefined;
+ },
+ },
+ ];
+
+ const convertToTableRow = (
+ item: RouterOutput["prompts"]["all"][number],
+ ): RowData => {
+ return {
+ id: item.id,
+ name: item.name,
+ version: item.version,
+ isActive: item.isActive,
+ createdBy: item.createdBy,
+ createdAt: item.createdAt,
+ };
+ };
+
+ return (
+ <div>
+ <DataTable
+ columns={columns}
+ data={
+ prompts.isLoading
+ ? { isLoading: true, isError: false }
+ : prompts.isError
+ ? {
+ isLoading: false,
+ isError: true,
+ error: prompts.error.message,
+ }
+ : {
+ isLoading: false,
+ isError: false,
+ data: prompts.data.map((t) => convertToTableRow(t)),
+ }
+ }
+ />
+ <CreatePromptDialog projectId={props.projectId} title="Create Prompt">
+ <Button variant="secondary" className="mt-4" disabled={!hasAccess}>
+ {hasAccess ? (
+ <PlusIcon className="-ml-0.5 mr-1.5" aria-hidden="true" />
+ ) : (
+ <LockIcon className="-ml-0.5 mr-1.5 h-3 w-3" aria-hidden="true" />
+ )}
+ New prompt
+ </Button>
+ </CreatePromptDialog>
+ </div>
+ );
+}
diff --git a/src/features/prompts/server/prompt-router.ts b/src/features/prompts/server/prompt-router.ts
new file mode 100644
index 0000000000..4ea26f732a
--- /dev/null
+++ b/src/features/prompts/server/prompt-router.ts
@@ -0,0 +1,193 @@
+import { z } from "zod";
+
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+import { throwIfNoAccess } from "@/src/features/rbac/utils/checkAccess";
+import { type PrismaClient } from "@prisma/client";
+
+export const CreatePrompt = z.object({
+ projectId: z.string(),
+ name: z.string(),
+ isActive: z.boolean(),
+ prompt: z.string(),
+});
+
+export const promptRouter = createTRPCRouter({
+ all: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.prisma.prompt.findMany({
+ where: {
+ projectId: input.projectId,
+ },
+ orderBy: [{ name: "asc" }, { version: "desc" }],
+ });
+ }),
+ byId: protectedProjectProcedure
+ .input(
+ z.object({
+ projectId: z.string(),
+ id: z.string(),
+ }),
+ )
+ .query(async ({ input, ctx }) => {
+ return ctx.prisma.prompt.findFirst({
+ where: {
+ id: input.id,
+ projectId: input.projectId,
+ },
+ });
+ }),
+ create: protectedProjectProcedure
+ .input(CreatePrompt)
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:CUD",
+ });
+
+ return await createPrompt({
+ projectId: input.projectId,
+ name: input.name,
+ prompt: input.prompt,
+ isActive: input.isActive,
+ createdBy: ctx.session.user.id,
+ prisma: ctx.prisma,
+ });
+ } catch (e) {
+ console.log(e);
+ throw e;
+ }
+ }),
+ promote: protectedProjectProcedure
+ .input(z.object({ promptId: z.string(), projectId: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ try {
+ throwIfNoAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "prompts:CUD",
+ });
+
+ const toBePromotedPrompt = await ctx.prisma.prompt.findUniqueOrThrow({
+ where: {
+ id: input.promptId,
+ },
+ });
+
+ const latestActivePrompt = await ctx.prisma.prompt.findMany({
+ where: {
+ projectId: input.projectId,
+ name: toBePromotedPrompt.name,
+ isActive: true,
+ },
+ orderBy: [{ version: "desc" }],
+ take: 1,
+ });
+
+ if (latestActivePrompt.length > 1) {
+ throw new Error(
+ `Expected exactly zero or one active prompt of name '${toBePromotedPrompt.name}', got ${latestActivePrompt.length}`,
+ );
+ }
+
+ const toBeExecuted = [
+ ctx.prisma.prompt.update({
+ where: {
+ id: toBePromotedPrompt.id,
+ },
+ data: {
+ isActive: true,
+ },
+ }),
+ ];
+ if (latestActivePrompt.length === 1)
+ toBeExecuted.push(
+ ctx.prisma.prompt.update({
+ where: {
+ id: latestActivePrompt[0]?.id,
+ },
+ data: {
+ isActive: false,
+ },
+ }),
+ );
+ await ctx.prisma.$transaction(toBeExecuted);
+ } catch (e) {
+ console.log(e);
+ throw e;
+ }
+ }),
+});
+
+export const createPrompt = async ({
+ projectId,
+ name,
+ prompt,
+ isActive = true,
+ createdBy,
+ prisma,
+}: {
+ projectId: string;
+ name: string;
+ prompt: string;
+ isActive?: boolean;
+ createdBy: string;
+ prisma: PrismaClient;
+}) => {
+ const latestPrompt = await prisma.prompt.findFirst({
+ where: {
+ projectId: projectId,
+ name: name,
+ },
+ orderBy: [{ version: "desc" }],
+ take: 1,
+ });
+
+ const latestActivePrompt = await prisma.prompt.findFirst({
+ where: {
+ projectId: projectId,
+ name: name,
+ isActive: true,
+ },
+ orderBy: [{ version: "desc" }],
+ take: 1,
+ });
+
+ 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,
+ },
+ }),
+ ];
+ 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/src/features/public-api/server/ingestion-api-schema.ts b/src/features/public-api/server/ingestion-api-schema.ts
index fbf05e8477..b70574b737 100644
--- a/src/features/public-api/server/ingestion-api-schema.ts
+++ b/src/features/public-api/server/ingestion-api-schema.ts
@@ -99,6 +99,14 @@ export const CreateGenerationBody = CreateSpanBody.extend({
)
.nullish(),
usage: usage,
+ promptName: z.string().nullish(),
+ promptVersion: z.number().int().nullish(),
+}).refine((value) => {
+ // ensure that either promptName and promptVersion are set, or none
+
+ if (!value.promptName && !value.promptVersion) return true;
+ if (value.promptName && value.promptVersion) return true;
+ return false;
});
export const UpdateGenerationBody = UpdateSpanBody.extend({
@@ -111,6 +119,14 @@ export const UpdateGenerationBody = UpdateSpanBody.extend({
)
.nullish(),
usage: usage,
+ promptName: z.string().nullish(),
+ promptVersion: z.number().int().nullish(),
+}).refine((value) => {
+ // ensure that either promptName and promptVersion are set, or none
+
+ if (!value.promptName && !value.promptVersion) return true;
+ if (value.promptName && value.promptVersion) return true;
+ return false;
});
export const ScoreBody = z.object({
diff --git a/src/features/rbac/constants/roleAccessRights.ts b/src/features/rbac/constants/roleAccessRights.ts
index c76d02e5fd..4525bfc434 100644
--- a/src/features/rbac/constants/roleAccessRights.ts
+++ b/src/features/rbac/constants/roleAccessRights.ts
@@ -21,6 +21,9 @@ const scopes = [
"project:transfer",
"datasets:CUD",
+
+ "prompts:CUD",
+ "prompts:read",
] as const;
// type string of all Resource:Action, e.g. "members:read"
@@ -42,6 +45,8 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"project:update",
"project:transfer",
"datasets:CUD",
+ "prompts:CUD",
+ "prompts:read",
],
ADMIN: [
"project:update",
@@ -56,6 +61,8 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"traces:delete",
"scores:CUD",
"datasets:CUD",
+ "prompts:CUD",
+ "prompts:read",
],
MEMBER: [
"members:read",
@@ -63,6 +70,8 @@ export const roleAccessRights: Record<MembershipRole, Scope[]> = {
"objects:bookmark",
"scores:CUD",
"datasets:CUD",
+ "prompts:CUD",
+ "prompts:read",
],
VIEWER: [],
};
diff --git a/src/pages/api/public/prompts.ts b/src/pages/api/public/prompts.ts
new file mode 100644
index 0000000000..b158a66da3
--- /dev/null
+++ b/src/pages/api/public/prompts.ts
@@ -0,0 +1,128 @@
+import { createPrompt } from "@/src/features/prompts/server/prompt-router";
+import { verifyAuthHeaderAndReturnScope } from "@/src/features/public-api/server/apiAuth";
+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { prisma } from "@/src/server/db";
+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(),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ if (req.method === "GET") {
+ // 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 get prompts, project ",
+ authCheck.scope.projectId,
+ ", body:",
+ JSON.stringify(req.query, null, 2),
+ );
+
+ if (authCheck.scope.accessLevel !== "all") {
+ return res.status(401).json({
+ message:
+ "Access denied - need to use basic auth with secret key to GET prompts",
+ });
+ }
+
+ const searchParams = PromptGetSchema.parse(req.query);
+
+ const prompt = await prisma.prompt.findFirst({
+ where: {
+ projectId: authCheck.scope.projectId,
+ name: searchParams.name,
+ version: searchParams.version ?? undefined,
+ isActive: true,
+ },
+ });
+
+ if (prompt === null) {
+ return res.status(404).json({
+ message: "Prompt not found",
+ });
+ }
+
+ return res.status(200).json(prompt);
+ } catch (error: unknown) {
+ console.error(error);
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(400).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 to POST prompts",
+ });
+ }
+
+ const input = PromptCreateSchema.parse(req.body);
+
+ const prompt = await createPrompt({
+ projectId: authCheck.scope.projectId,
+ name: input.name,
+ prompt: input.prompt,
+ isActive: input.isActive,
+ createdBy: "API",
+ prisma: prisma,
+ });
+ return res.status(200).json(prompt);
+ } catch (error: unknown) {
+ console.error(error);
+ const errorMessage =
+ error instanceof Error ? error.message : "An unknown error occurred";
+ res.status(400).json({
+ message: "Invalid request data",
+ error: errorMessage,
+ });
+ }
+ } else {
+ console.error(req.method, req.body, req.query);
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+}
diff --git a/src/pages/project/[projectId]/prompts/[prompt_id].tsx b/src/pages/project/[projectId]/prompts/[prompt_id].tsx
new file mode 100644
index 0000000000..fd2f5600f9
--- /dev/null
+++ b/src/pages/project/[projectId]/prompts/[prompt_id].tsx
@@ -0,0 +1,10 @@
+import { PromptDetail } from "@/src/features/prompts/components/prompt-detail";
+import { useRouter } from "next/router";
+
+export default function PromptDetailPage() {
+ const router = useRouter();
+ const prompt_id = router.query.prompt_id as string;
+ const projectId = router.query.projectId as string;
+
+ return <PromptDetail projectId={projectId} promptId={prompt_id} />;
+}
diff --git a/src/pages/project/[projectId]/prompts/index.tsx b/src/pages/project/[projectId]/prompts/index.tsx
new file mode 100644
index 0000000000..ef6c306a60
--- /dev/null
+++ b/src/pages/project/[projectId]/prompts/index.tsx
@@ -0,0 +1,15 @@
+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>
+ <Header title="Prompts" />
+ <PromptTable projectId={projectId} />
+ </div>
+ );
+}
diff --git a/src/server/api/root.ts b/src/server/api/root.ts
index 6e03c6f3af..94b669f433 100644
--- a/src/server/api/root.ts
+++ b/src/server/api/root.ts
@@ -12,6 +12,7 @@ import { environmentRouter } from "@/src/server/api/routers/environment";
import { usageMeteringRouter } from "@/src/features/usage-metering/server/usageMeteringRouter";
import { observationsRouter } from "@/src/server/api/routers/observations";
import { sessionRouter } from "@/src/server/api/routers/sessions";
+import { promptRouter } from "@/src/features/prompts/server/prompt-router";
/**
* This is the primary router for your server.
@@ -32,6 +33,7 @@ export const appRouter = createTRPCRouter({
environment: environmentRouter,
usageMetering: usageMeteringRouter,
observations: observationsRouter,
+ prompts: promptRouter,
});
// export type definition of API
diff --git a/src/server/api/services/EventProcessor.ts b/src/server/api/services/EventProcessor.ts
index 2c03e83c47..9011d99e85 100644
--- a/src/server/api/services/EventProcessor.ts
+++ b/src/server/api/services/EventProcessor.ts
@@ -124,6 +124,20 @@ export class ObservationProcessor implements EventProcessor {
metadata ?? undefined,
);
+ const prompts =
+ "promptName" in this.event.body &&
+ typeof this.event.body.promptName === "string" &&
+ "promptVersion" in this.event.body &&
+ typeof this.event.body.promptVersion === "number"
+ ? await prisma.prompt.findMany({
+ where: {
+ projectId: apiScope.projectId,
+ name: this.event.body.promptName,
+ version: this.event.body.promptVersion,
+ },
+ })
+ : undefined;
+
const observationId = id ?? v4();
return {
id: observationId,
@@ -161,6 +175,9 @@ export class ObservationProcessor implements EventProcessor {
parentObservationId: body.parentObservationId ?? undefined,
version: body.version ?? undefined,
project: { connect: { id: apiScope.projectId } },
+ ...(prompts && prompts.length === 1
+ ? { prompt: { connect: { id: prompts[0]?.id } } }
+ : undefined),
},
update: {
name,
@@ -192,6 +209,9 @@ export class ObservationProcessor implements EventProcessor {
statusMessage: body.statusMessage ?? undefined,
parentObservationId: body.parentObservationId ?? undefined,
version: body.version ?? undefined,
+ ...(prompts && prompts.length === 1
+ ? { prompt: { connect: { id: prompts[0]?.id } } }
+ : undefined),
},
};
}
diff --git a/src/utils/string.ts b/src/utils/string.ts
index f564dedb1e..b62d5352da 100644
--- a/src/utils/string.ts
+++ b/src/utils/string.ts
@@ -1,3 +1,20 @@
export function lastCharacters(str: string, n: number) {
return str.substring(str.length - n);
}
+
+export function extractVariables(mustacheString: string): string[] {
+ // Regular expression to match Mustache variables
+ const regex: RegExp = /\{\{(.*?)\}\}/g;
+
+ let match: RegExpExecArray | null;
+ const variables: string[] = [];
+
+ // Iterate over all matches
+ while ((match = regex.exec(mustacheString)) !== null) {
+ // Push each variable to the array
+ const variable = match[1];
+ if (variable) variables.push(variable);
+ }
+
+ return variables;
+}