Skip to content

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

fix: run prettier on my changes (#7685)

Nimar5dfc821575cf
diff --git a/web/sentry.client.config.ts b/web/sentry.client.config.ts
index 34ad1be294..765696d708 100644
--- a/web/sentry.client.config.ts
+++ b/web/sentry.client.config.ts
@@ -1,6 +1,9 @@
import * as Sentry from "@sentry/nextjs";
-const isEuOrUsRegionNonHipaa = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined ? ["EU", "US"].includes(process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) : false;
+const isEuOrUsRegionNonHipaa =
+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== undefined
+ ? ["EU", "US"].includes(process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)
+ : false;
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
diff --git a/web/src/__tests__/async/prompts.v2.servertest.ts b/web/src/__tests__/async/prompts.v2.servertest.ts
index ab7bc5e2ec..f29e591f24 100644
--- a/web/src/__tests__/async/prompts.v2.servertest.ts
+++ b/web/src/__tests__/async/prompts.v2.servertest.ts
@@ -1250,7 +1250,12 @@ describe("/api/public/v2/prompts API Endpoint", () => {
expect(body.meta.totalItems).toBe(1);
// Test with a different name
- const response2 = await makeAPICall("GET", `${baseURI}?name=prompt-2`, undefined, auth);
+ const response2 = await makeAPICall(
+ "GET",
+ `${baseURI}?name=prompt-2`,
+ undefined,
+ auth,
+ );
expect(response2.status).toBe(200);
const body2 = response2.body as unknown as PromptsMetaResponse;
diff --git a/web/src/__tests__/compileChatMessages.servertest.ts b/web/src/__tests__/compileChatMessages.servertest.ts
index d6d55c3ab9..c63876ddc0 100644
--- a/web/src/__tests__/compileChatMessages.servertest.ts
+++ b/web/src/__tests__/compileChatMessages.servertest.ts
@@ -1,6 +1,10 @@
/** @jest-environment node */
-import { ChatMessageType, compileChatMessages, extractPlaceholderNames } from "@langfuse/shared";
+import {
+ ChatMessageType,
+ compileChatMessages,
+ extractPlaceholderNames,
+} from "@langfuse/shared";
describe("compileChatMessages", () => {
it("should compile message placeholders with provided values", () => {
@@ -11,28 +15,28 @@ describe("compileChatMessages", () => {
{ role: "system", content: "You are a helpful assistant." },
{
type: ChatMessageType.Placeholder,
- name: "conversation_history"
+ name: "conversation_history",
},
- { role: "user", content: "{{user_question}}" }
+ { role: "user", content: "{{user_question}}" },
];
const placeholderValues = {
conversation_history: [
{ role: "user", content: "Hello!" },
{ role: "assistant", content: "Hi there! How can I help you?" },
- { role: "user", content: "What's the weather like?" }
- ]
+ { role: "user", content: "What's the weather like?" },
+ ],
};
const textVariables = {
- user_question: "Can you continue our conversation?"
+ user_question: "Can you continue our conversation?",
};
// Simulate compilation logic that would happen in playground/experiments
const compiledMessages = compileChatMessages(
promptTemplate,
placeholderValues,
- textVariables
+ textVariables,
);
expect(compiledMessages).toEqual([
@@ -40,7 +44,7 @@ describe("compileChatMessages", () => {
{ role: "user", content: "Hello!" },
{ role: "assistant", content: "Hi there! How can I help you?" },
{ role: "user", content: "What's the weather like?" },
- { role: "user", content: "Can you continue our conversation?" }
+ { role: "user", content: "Can you continue our conversation?" },
]);
});
@@ -49,9 +53,9 @@ describe("compileChatMessages", () => {
{ role: "system", content: "You are a helpful assistant." },
{
type: ChatMessageType.Placeholder,
- name: "missing_placeholder"
+ name: "missing_placeholder",
},
- { role: "user", content: "Hello" }
+ { role: "user", content: "Hello" },
];
const placeholderValues = {};
@@ -65,58 +69,67 @@ describe("compileChatMessages", () => {
const promptTemplate = [
{
type: ChatMessageType.Placeholder,
- name: "invalid_messages"
- }
+ name: "invalid_messages",
+ },
];
// Test missing role property
const placeholderValuesNoRole = {
- invalid_messages: [
- { content: "Hello" }
- ]
+ invalid_messages: [{ content: "Hello" }],
};
expect(() => {
compileChatMessages(promptTemplate, placeholderValuesNoRole);
- }).toThrow("Invalid message format in placeholder 'invalid_messages': messages must have 'role' and 'content' properties");
+ }).toThrow(
+ "Invalid message format in placeholder 'invalid_messages': messages must have 'role' and 'content' properties",
+ );
// Test missing content property
const placeholderValuesNoContent = {
- invalid_messages: [
- { role: "user" }
- ]
+ invalid_messages: [{ role: "user" }],
};
expect(() => {
compileChatMessages(promptTemplate, placeholderValuesNoContent);
- }).toThrow("Invalid message format in placeholder 'invalid_messages': messages must have 'role' and 'content' properties");
+ }).toThrow(
+ "Invalid message format in placeholder 'invalid_messages': messages must have 'role' and 'content' properties",
+ );
});
it("should compile placeholders without applying text substitutions when no variables provided", () => {
const promptTemplate = [
- { role: "system", content: "You are a helpful assistant. {{system_var}}" },
+ {
+ role: "system",
+ content: "You are a helpful assistant. {{system_var}}",
+ },
{
type: ChatMessageType.Placeholder,
- name: "history"
+ name: "history",
},
- { role: "user", content: "{{user_var}}" }
+ { role: "user", content: "{{user_var}}" },
];
const placeholderValues = {
history: [
{ role: "user", content: "Previous message with {{var}}" },
- { role: "assistant", content: "Response with {{another_var}}" }
- ]
+ { role: "assistant", content: "Response with {{another_var}}" },
+ ],
};
// No text variables provided
- const compiledMessages = compileChatMessages(promptTemplate, placeholderValues);
+ const compiledMessages = compileChatMessages(
+ promptTemplate,
+ placeholderValues,
+ );
expect(compiledMessages).toEqual([
- { role: "system", content: "You are a helpful assistant. {{system_var}}" },
+ {
+ role: "system",
+ content: "You are a helpful assistant. {{system_var}}",
+ },
{ role: "user", content: "Previous message with {{var}}" },
{ role: "assistant", content: "Response with {{another_var}}" },
- { role: "user", content: "{{user_var}}" }
+ { role: "user", content: "{{user_var}}" },
]);
});
@@ -125,13 +138,13 @@ describe("compileChatMessages", () => {
{ role: "system", content: "System message" },
{
type: ChatMessageType.Placeholder,
- name: "history"
+ name: "history",
},
{ role: "user", content: "User message" },
{
type: ChatMessageType.Placeholder,
- name: "context"
- }
+ name: "context",
+ },
];
const placeholderNames = extractPlaceholderNames(promptTemplate);
@@ -142,7 +155,7 @@ describe("compileChatMessages", () => {
it("should return empty array when no placeholders exist", () => {
const promptTemplate = [
{ role: "system", content: "System message" },
- { role: "user", content: "User message" }
+ { role: "user", content: "User message" },
];
const placeholderNames = extractPlaceholderNames(promptTemplate);
diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
index 5ac27a648f..a7c80ca960 100644
--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts
@@ -12,12 +12,12 @@ async function convertOtelSpanToIngestionEvent(
projectId: "test-project",
publicKey,
});
-
+
// For tests, we bypass Redis initialization and directly set the seen traces
// This is safe because we're testing the conversion logic, not the Redis caching
(processor as any).seenTraces = seenTraces;
(processor as any).isInitialized = true;
-
+
return await processor.processToIngestionEvents([resourceSpan]);
}
@@ -256,9 +256,14 @@ describe("OTel Resource Span Mapping", () => {
},
];
- const events = (await Promise.all(langfuseOtelSpans.map(async (span) =>
- await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
- ))).flat();
+ const events = (
+ await Promise.all(
+ langfuseOtelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const generationEvents = events.filter(
(e) => e.type === "generation-create",
@@ -449,9 +454,14 @@ describe("OTel Resource Span Mapping", () => {
},
];
- const events = (await Promise.all(langfuseOtelSpans.map(async (span) =>
- await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
- ))).flat();
+ const events = (
+ await Promise.all(
+ langfuseOtelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const spanEvents = events.filter((e) => e.type === "span-create");
@@ -567,9 +577,12 @@ describe("OTel Resource Span Mapping", () => {
];
await expect(
- Promise.all(langfuseOtelSpans.map(async (span) =>
- await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
- ))
+ Promise.all(
+ langfuseOtelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ),
+ ),
).rejects.toThrowError("Langfuse OTEL SDK span has different public key");
});
});
@@ -2124,18 +2137,20 @@ describe("OTel Resource Span Mapping", () => {
describe("Span Counting", () => {
it("should count spans correctly across multiple resource spans", () => {
- const processor = new OtelIngestionProcessor({ projectId: "test-project" });
-
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+
const resourceSpans = [
{
scopeSpans: [
{ spans: [{}, {}, {}] }, // 3 spans
- { spans: [{}] }, // 1 span
+ { spans: [{}] }, // 1 span
],
},
{
scopeSpans: [
- { spans: [{}, {}] }, // 2 spans
+ { spans: [{}, {}] }, // 2 spans
],
},
];
@@ -2146,22 +2161,28 @@ describe("OTel Resource Span Mapping", () => {
});
it("should handle empty resource spans", () => {
- const processor = new OtelIngestionProcessor({ projectId: "test-project" });
-
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+
const count = (processor as any).getTotalSpanCount([]);
expect(count).toBe(0);
});
it("should handle null/undefined resource spans", () => {
- const processor = new OtelIngestionProcessor({ projectId: "test-project" });
-
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+
expect((processor as any).getTotalSpanCount(null)).toBe(0);
expect((processor as any).getTotalSpanCount(undefined)).toBe(0);
});
it("should handle malformed resource spans", () => {
- const processor = new OtelIngestionProcessor({ projectId: "test-project" });
-
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+
const resourceSpans = [
{ scopeSpans: null },
{ scopeSpans: undefined },
@@ -2181,16 +2202,20 @@ describe("OTel Resource Span Mapping", () => {
});
it("should return 0 for non-array input", () => {
- const processor = new OtelIngestionProcessor({ projectId: "test-project" });
-
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+
expect((processor as any).getTotalSpanCount("not-an-array")).toBe(0);
expect((processor as any).getTotalSpanCount({})).toBe(0);
expect((processor as any).getTotalSpanCount(123)).toBe(0);
});
it("should handle deeply nested null/undefined structures", () => {
- const processor = new OtelIngestionProcessor({ projectId: "test-project" });
-
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+
const resourceSpans = [
null,
undefined,
@@ -2208,8 +2233,10 @@ describe("OTel Resource Span Mapping", () => {
});
it("should return -1 and not throw on unexpected errors", () => {
- const processor = new OtelIngestionProcessor({ projectId: "test-project" });
-
+ const processor = new OtelIngestionProcessor({
+ projectId: "test-project",
+ });
+
// Create a malicious object that throws when accessed
const maliciousResourceSpan = {
get scopeSpans() {
@@ -2217,7 +2244,9 @@ describe("OTel Resource Span Mapping", () => {
},
};
- const count = (processor as any).getTotalSpanCount([maliciousResourceSpan]);
+ const count = (processor as any).getTotalSpanCount([
+ maliciousResourceSpan,
+ ]);
expect(count).toBe(-1);
});
});
@@ -2243,8 +2272,10 @@ describe("OTel Resource Span Mapping", () => {
const expectedEndTime = "2025-04-17T07:39:54.084Z";
// Convert timestamps to ISO strings
- const actualStartTime = OtelIngestionProcessor.convertNanoTimestampToISO(positiveTimestamp);
- const actualEndTime = OtelIngestionProcessor.convertNanoTimestampToISO(negativeTimestamp);
+ const actualStartTime =
+ OtelIngestionProcessor.convertNanoTimestampToISO(positiveTimestamp);
+ const actualEndTime =
+ OtelIngestionProcessor.convertNanoTimestampToISO(negativeTimestamp);
// Verify conversions match expected values
expect(actualStartTime).toBe(expectedStartTime);
@@ -2255,9 +2286,9 @@ describe("OTel Resource Span Mapping", () => {
// Test with string timestamp (nanoseconds)
const stringTimestamp = "1744317592317227000"; // Same as positiveTimestamp above
const expectedStringResult = "2025-04-10T20:39:52.317Z";
- expect(OtelIngestionProcessor.convertNanoTimestampToISO(stringTimestamp)).toBe(
- expectedStringResult,
- );
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO(stringTimestamp),
+ ).toBe(expectedStringResult);
// Test with zero timestamp
const zeroTimestamp = {
@@ -2265,9 +2296,9 @@ describe("OTel Resource Span Mapping", () => {
high: 0,
unsigned: true,
};
- expect(OtelIngestionProcessor.convertNanoTimestampToISO(zeroTimestamp)).toBe(
- "1970-01-01T00:00:00.000Z",
- );
+ expect(
+ OtelIngestionProcessor.convertNanoTimestampToISO(zeroTimestamp),
+ ).toBe("1970-01-01T00:00:00.000Z");
});
});
@@ -2295,10 +2326,13 @@ describe("OTel Resource Span Mapping", () => {
{
traceId: {
type: "Buffer",
- data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ data: [
+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39,
+ 49, 17, 32,
+ ],
},
spanId: {
- type: "Buffer",
+ type: "Buffer",
data: [212, 62, 55, 183, 209, 126, 84, 118],
},
parentSpanId: {
@@ -2332,7 +2366,14 @@ describe("OTel Resource Span Mapping", () => {
];
// Empty seenTraces set - should create shallow trace for first span
- const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, new Set(), publicKey)))).flat();
+ const events = (
+ await Promise.all(
+ otelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const spanEvents = events.filter((e) => e.type === "span-create");
@@ -2342,7 +2383,7 @@ describe("OTel Resource Span Mapping", () => {
expect(spanEvents.length).toBe(1);
const traceEvent = traceEvents[0];
-
+
// Should create shallow trace with minimal information
expect(traceEvent.body).toMatchObject({
id: "95f3b926c7d009925bcb5dbc27311120",
@@ -2381,7 +2422,10 @@ describe("OTel Resource Span Mapping", () => {
{
traceId: {
type: "Buffer",
- data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ data: [
+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39,
+ 49, 17, 32,
+ ],
},
spanId: {
type: "Buffer",
@@ -2418,14 +2462,25 @@ describe("OTel Resource Span Mapping", () => {
];
// seenTraces contains the traceId - should NOT create trace
- const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, seenTraces, publicKey)))).flat();
+ const events = (
+ await Promise.all(
+ otelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(
+ span,
+ seenTraces,
+ publicKey,
+ ),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const spanEvents = events.filter((e) => e.type === "span-create");
expect(events.length).toBe(1);
expect(traceEvents.length).toBe(0); // No trace should be created
- expect(spanEvents.length).toBe(1); // Only span should be created
+ expect(spanEvents.length).toBe(1); // Only span should be created
const spanEvent = spanEvents[0];
expect(spanEvent.body).toMatchObject({
@@ -2460,7 +2515,10 @@ describe("OTel Resource Span Mapping", () => {
{
traceId: {
type: "Buffer",
- data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ data: [
+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39,
+ 49, 17, 32,
+ ],
},
spanId: {
type: "Buffer",
@@ -2494,7 +2552,18 @@ describe("OTel Resource Span Mapping", () => {
];
// seenTraces contains the traceId, but span is root - should still create full trace
- const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, seenTraces, publicKey)))).flat();
+ const events = (
+ await Promise.all(
+ otelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(
+ span,
+ seenTraces,
+ publicKey,
+ ),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const spanEvents = events.filter((e) => e.type === "span-create");
@@ -2504,7 +2573,7 @@ describe("OTel Resource Span Mapping", () => {
expect(spanEvents.length).toBe(1);
const traceEvent = traceEvents[0];
-
+
// Should create full trace with name and metadata since it's a root span
expect(traceEvent.body).toMatchObject({
id: "95f3b926c7d009925bcb5dbc27311120",
@@ -2540,7 +2609,10 @@ describe("OTel Resource Span Mapping", () => {
{
traceId: {
type: "Buffer",
- data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ data: [
+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39,
+ 49, 17, 32,
+ ],
},
spanId: {
type: "Buffer",
@@ -2584,7 +2656,18 @@ describe("OTel Resource Span Mapping", () => {
},
];
- const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, seenTraces, publicKey)))).flat();
+ const events = (
+ await Promise.all(
+ otelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(
+ span,
+ seenTraces,
+ publicKey,
+ ),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
expect(traceEvents.length).toBe(1);
@@ -2617,7 +2700,10 @@ describe("OTel Resource Span Mapping", () => {
{
traceId: {
type: "Buffer",
- data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ data: [
+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39,
+ 49, 17, 32,
+ ],
},
spanId: {
type: "Buffer",
@@ -2661,7 +2747,18 @@ describe("OTel Resource Span Mapping", () => {
},
];
- const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, seenTraces, publicKey)))).flat();
+ const events = (
+ await Promise.all(
+ otelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(
+ span,
+ seenTraces,
+ publicKey,
+ ),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
expect(traceEvents.length).toBe(1);
@@ -2694,7 +2791,10 @@ describe("OTel Resource Span Mapping", () => {
{
traceId: {
type: "Buffer",
- data: [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32],
+ data: [
+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39,
+ 49, 17, 32,
+ ],
},
spanId: {
type: "Buffer",
@@ -2735,7 +2835,18 @@ describe("OTel Resource Span Mapping", () => {
];
// seenTraces contains the traceId, but span has trace updates - should still create full trace
- const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, seenTraces, publicKey)))).flat();
+ const events = (
+ await Promise.all(
+ otelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(
+ span,
+ seenTraces,
+ publicKey,
+ ),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const spanEvents = events.filter((e) => e.type === "span-create");
@@ -2745,7 +2856,7 @@ describe("OTel Resource Span Mapping", () => {
expect(spanEvents.length).toBe(1);
const traceEvent = traceEvents[0];
-
+
// Should create full trace with trace updates
expect(traceEvent.body).toMatchObject({
id: "95f3b926c7d009925bcb5dbc27311120",
@@ -2759,7 +2870,9 @@ describe("OTel Resource Span Mapping", () => {
});
it("should create only ONE trace when multiple spans share the same traceId with empty seenTraces", async () => {
- const sharedTraceId = [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32];
+ const sharedTraceId = [
+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32,
+ ];
const otelSpans = [
{
@@ -2884,7 +2997,14 @@ describe("OTel Resource Span Mapping", () => {
];
// Empty seenTraces set - should create only ONE trace despite multiple spans with same traceId
- const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, new Set(), publicKey)))).flat();
+ const events = (
+ await Promise.all(
+ otelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const spanEvents = events.filter((e) => e.type === "span-create");
@@ -2894,7 +3014,7 @@ describe("OTel Resource Span Mapping", () => {
expect(spanEvents.length).toBe(3); // All three spans should be created
const traceEvent = traceEvents[0];
-
+
// Should create shallow trace with minimal information (from first span processed)
expect(traceEvent.body).toMatchObject({
id: "95f3b926c7d009925bcb5dbc27311120",
@@ -2914,7 +3034,9 @@ describe("OTel Resource Span Mapping", () => {
});
it("should filter out shallow traces when full traces exist for the same traceId in same batch", async () => {
- const sharedTraceId = [149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32];
+ const sharedTraceId = [
+ 149, 243, 185, 38, 199, 208, 9, 146, 91, 203, 93, 188, 39, 49, 17, 32,
+ ];
const otelSpans = [
{
@@ -2995,7 +3117,14 @@ describe("OTel Resource Span Mapping", () => {
];
// Empty seenTraces set - both spans would normally create traces
- const events = (await Promise.all(otelSpans.map(async (span) => await convertOtelSpanToIngestionEvent(span, new Set(), publicKey)))).flat();
+ const events = (
+ await Promise.all(
+ otelSpans.map(
+ async (span) =>
+ await convertOtelSpanToIngestionEvent(span, new Set(), publicKey),
+ ),
+ )
+ ).flat();
const traceEvents = events.filter((e) => e.type === "trace-create");
const spanEvents = events.filter((e) => e.type === "span-create");
@@ -3005,7 +3134,7 @@ describe("OTel Resource Span Mapping", () => {
expect(spanEvents.length).toBe(2); // Both spans should be created
const traceEvent = traceEvents[0];
-
+
// Should be the FULL trace (from root span), not the shallow one
expect(traceEvent.body).toMatchObject({
id: "95f3b926c7d009925bcb5dbc27311120",
diff --git a/web/src/app/layout.tsx b/web/src/app/layout.tsx
index a14e64fcd5..5ff842ef07 100644
--- a/web/src/app/layout.tsx
+++ b/web/src/app/layout.tsx
@@ -1,16 +1,16 @@
export const metadata = {
- title: 'Next.js',
- description: 'Generated by Next.js',
-}
+ title: "Next.js",
+ description: "Generated by Next.js",
+};
export default function RootLayout({
children,
}: {
- children: React.ReactNode
+ children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
- )
+ );
}
diff --git a/web/src/components/ChatMessages/ChatMessageComponent.tsx b/web/src/components/ChatMessages/ChatMessageComponent.tsx
index 1699289578..9951e185bc 100644
--- a/web/src/components/ChatMessages/ChatMessageComponent.tsx
+++ b/web/src/components/ChatMessages/ChatMessageComponent.tsx
@@ -96,7 +96,7 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({
const toggleRole = () => {
// Only allow role toggling for messages that have a role property (not placeholder messages)
- if (!('role' in message)) return;
+ if (!("role" in message)) return;
// if user has set custom roles, available roles will be non-empty and we toggle through custom and default roles (assistant, user)
if (!!availableRoles && Boolean(availableRoles.length)) {
@@ -119,7 +119,9 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({
(toolCallIds && toolCallIds.length > 0),
);
const currentIndex = eligibleRoles.indexOf(
- ('role' in message ? message.role : ChatMessageRole.User) as ChatMessageRole,
+ ("role" in message
+ ? message.role
+ : ChatMessageRole.User) as ChatMessageRole,
);
const nextRole =
eligibleRoles[(currentIndex + 1) % eligibleRoles.length];
@@ -221,7 +223,9 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({
[message.id, message.type, updateMessage],
);
- const showDragHandle = !('role' in message && SYSTEM_ROLES.includes(message.role));
+ const showDragHandle = !(
+ "role" in message && SYSTEM_ROLES.includes(message.role)
+ );
const showToolCallSelect = message.type === ChatMessageType.ToolResult;
const isPlaceholder = message.type === ChatMessageType.Placeholder;
@@ -255,7 +259,7 @@ export const ChatMessageComponent: React.FC<ChatMessageProps> = ({
>
<div className="flex w-[4rem] flex-shrink-0 flex-col gap-1">
{isPlaceholder ? (
- <span className="inline-flex items-center justify-center font-mono h-6 w-full text-[9px] rounded-md bg-accent px-4 text-muted-foreground">
+ <span className="inline-flex h-6 w-full items-center justify-center rounded-md bg-accent px-4 font-mono text-[9px] text-muted-foreground">
placeholder
</span>
) : (
diff --git a/web/src/components/ChatMessages/index.tsx b/web/src/components/ChatMessages/index.tsx
index 0875792be2..016841fccc 100644
--- a/web/src/components/ChatMessages/index.tsx
+++ b/web/src/components/ChatMessages/index.tsx
@@ -69,7 +69,10 @@ export const ChatMessages: React.FC<ChatMessagesProps> = (props) => {
}
// prevent reordering system messages, placeholders can be reordered
const targetMessage = messages[newIndex];
- if (targetMessage.type !== ChatMessageType.Placeholder && SYSTEM_ROLES.includes(targetMessage.role)) {
+ if (
+ targetMessage.type !== ChatMessageType.Placeholder &&
+ SYSTEM_ROLES.includes(targetMessage.role)
+ ) {
return;
}
const newMessages = arrayMove(messages, oldIndex, newIndex);
@@ -123,7 +126,13 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({
addMessage,
}) => {
// Skip placeholder messages when determining last roles
- const lastMessageWithRole = messages.slice().reverse().find((msg): msg is ChatMessageWithId & { role: string } => msg.type !== ChatMessageType.Placeholder);
+ const lastMessageWithRole = messages
+ .slice()
+ .reverse()
+ .find(
+ (msg): msg is ChatMessageWithId & { role: string } =>
+ msg.type !== ChatMessageType.Placeholder,
+ );
const lastMessageRole = lastMessageWithRole?.role;
const nextMessageRole =
lastMessageRole === ChatMessageRole.User
@@ -178,7 +187,11 @@ const AddMessageButton: React.FC<AddMessageButtonProps> = ({
</Button>
</TooltipTrigger>
<TooltipContent>
- <p className="text-xs">Adds a placeholder to inject message pairs, e.g. a message history (with &quot;role&quot;, &quot;content&quot; pairs) when compiling the message in the SDK.</p>
+ <p className="text-xs">
+ Adds a placeholder to inject message pairs, e.g. a message history
+ (with &quot;role&quot;, &quot;content&quot; pairs) when compiling
+ the message in the SDK.
+ </p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
diff --git a/web/src/components/ChatMessages/types.ts b/web/src/components/ChatMessages/types.ts
index 33c205bcdc..7557d1c832 100644
--- a/web/src/components/ChatMessages/types.ts
+++ b/web/src/components/ChatMessages/types.ts
@@ -1,4 +1,8 @@
-import type { ChatMessage, ChatMessageWithId, PlaceholderMessage } from "@langfuse/shared";
+import type {
+ ChatMessage,
+ ChatMessageWithId,
+ PlaceholderMessage,
+} from "@langfuse/shared";
export type MessagesContext = {
messages: ChatMessageWithId[];
diff --git a/web/src/components/ChatMessages/utils/createEmptyMessage.ts b/web/src/components/ChatMessages/utils/createEmptyMessage.ts
index e4c3208fbc..31303231ca 100644
--- a/web/src/components/ChatMessages/utils/createEmptyMessage.ts
+++ b/web/src/components/ChatMessages/utils/createEmptyMessage.ts
@@ -1,7 +1,12 @@
import { v4 as uuidv4 } from "uuid";
-import { type ChatMessage, type ChatMessageWithIdNoPlaceholders } from "@langfuse/shared";
+import {
+ type ChatMessage,
+ type ChatMessageWithIdNoPlaceholders,
+} from "@langfuse/shared";
-export function createEmptyMessage(message: ChatMessage): ChatMessageWithIdNoPlaceholders {
+export function createEmptyMessage(
+ message: ChatMessage,
+): ChatMessageWithIdNoPlaceholders {
return {
...message,
content: message.content ?? "",
diff --git a/web/src/components/nav/sidebar-notifications.tsx b/web/src/components/nav/sidebar-notifications.tsx
index 0779d7ff5c..ccb275612c 100644
--- a/web/src/components/nav/sidebar-notifications.tsx
+++ b/web/src/components/nav/sidebar-notifications.tsx
@@ -111,7 +111,7 @@ const notifications: SidebarNotification[] = [
linkContent: (
// eslint-disable-next-line @next/next/no-img-element
<img
- alt="Langfuse GitHub stars"
+ alt="Langfuse GitHub stars"
src="https://img.shields.io/github/stars/langfuse/langfuse?label=langfuse&amp;style=social"
/>
),
diff --git a/web/src/components/table/peek/peek-dataset-compare-detail.tsx b/web/src/components/table/peek/peek-dataset-compare-detail.tsx
index ada5640fe4..fe77ebb7cd 100644
--- a/web/src/components/table/peek/peek-dataset-compare-detail.tsx
+++ b/web/src/components/table/peek/peek-dataset-compare-detail.tsx
@@ -187,7 +187,11 @@ export const PeekDatasetCompareDetail = ({
? `/project/${projectId}/traces/${encodeURIComponent(run.traceId)}?observation=${encodeURIComponent(run.observationId)}`
: `/project/${projectId}/traces/${encodeURIComponent(run.traceId)}`;
const pathnameWithBasePath = `${process.env.NEXT_PUBLIC_BASE_PATH ?? ""}${pathname}`;
- window.open(pathnameWithBasePath, "_blank", "noopener noreferrer");
+ window.open(
+ pathnameWithBasePath,
+ "_blank",
+ "noopener noreferrer",
+ );
}}
>
<ListTree className="h-4 w-4" />
diff --git a/web/src/components/trace/IOPreview.tsx b/web/src/components/trace/IOPreview.tsx
index e6c1fa8c47..c7a3a59d09 100644
--- a/web/src/components/trace/IOPreview.tsx
+++ b/web/src/components/trace/IOPreview.tsx
@@ -235,13 +235,16 @@ export const OpenAiMessageView: React.FC<{
};
const isPlaceholderMessage = (message: ChatMlMessageSchema) => {
- return message.type === 'placeholder';
+ return message.type === "placeholder";
};
const messagesToRender = useMemo(
() =>
messages.filter(
- (message) => shouldRenderContent(message) || shouldRenderJson(message) || isPlaceholderMessage(message),
+ (message) =>
+ shouldRenderContent(message) ||
+ shouldRenderJson(message) ||
+ isPlaceholderMessage(message),
),
[messages],
);
@@ -265,13 +268,13 @@ export const OpenAiMessageView: React.FC<{
shouldRenderMarkdown ? (
<MarkdownJsonView
title="Placeholder"
- content={message.name || 'Unnamed placeholder'}
+ content={message.name || "Unnamed placeholder"}
customCodeHeaderClassName={cn("bg-primary-foreground")}
/>
) : (
<JSONView
title="Placeholder"
- json={message.name || 'Unnamed placeholder'}
+ json={message.name || "Unnamed placeholder"}
projectIdForPromptButtons={projectIdForPromptButtons}
/>
)
@@ -282,10 +285,15 @@ export const OpenAiMessageView: React.FC<{
<MarkdownJsonView
title={message.name ?? message.role}
content={message.content || '""'}
- className={cn(!!message.json && !isPlaceholderMessage(message) && "rounded-b-none")}
+ className={cn(
+ !!message.json &&
+ !isPlaceholderMessage(message) &&
+ "rounded-b-none",
+ )}
customCodeHeaderClassName={cn(
message.role === "assistant" && "bg-secondary",
- message.role === "system" && "bg-primary-foreground",
+ message.role === "system" &&
+ "bg-primary-foreground",
)}
audio={message.audio}
/>
@@ -294,23 +302,28 @@ export const OpenAiMessageView: React.FC<{
title={message.name ?? message.role}
json={message.content}
projectIdForPromptButtons={projectIdForPromptButtons}
- className={cn(!!message.json && !isPlaceholderMessage(message) && "rounded-b-none")}
+ className={cn(
+ !!message.json &&
+ !isPlaceholderMessage(message) &&
+ "rounded-b-none",
+ )}
/>
))}
- {shouldRenderJson(message) && !isPlaceholderMessage(message) && (
- <JSONView
- title={
- message.content
- ? undefined
- : (message.name ?? message.role)
- }
- json={message.json}
- projectIdForPromptButtons={projectIdForPromptButtons}
- className={cn(
- !!message.content && "rounded-t-none border-t-0",
- )}
- />
- )}
+ {shouldRenderJson(message) &&
+ !isPlaceholderMessage(message) && (
+ <JSONView
+ title={
+ message.content
+ ? undefined
+ : (message.name ?? message.role)
+ }
+ json={message.json}
+ projectIdForPromptButtons={projectIdForPromptButtons}
+ className={cn(
+ !!message.content && "rounded-t-none border-t-0",
+ )}
+ />
+ )}
</>
)}
{isCollapsed !== null && index === 0 ? (
diff --git a/web/src/components/trace/ObservationTree.tsx b/web/src/components/trace/ObservationTree.tsx
index f334da306e..538824afea 100644
--- a/web/src/components/trace/ObservationTree.tsx
+++ b/web/src/components/trace/ObservationTree.tsx
@@ -391,13 +391,15 @@ const ObservationTreeNodeCard = ({
ref={currentObservationRef}
>
{/* Type badge and name */}
- <div className="flex items-center gap-2 flex-shrink-0">
+ <div className="flex flex-shrink-0 items-center gap-2">
<ItemBadge
type={observation.type}
isSmall
className="flex-shrink-0 scale-75"
/>
- <span className="text-sm font-medium whitespace-nowrap">{observation.name}</span>
+ <span className="whitespace-nowrap text-sm font-medium">
+ {observation.name}
+ </span>
</div>
{/* Duration and Comments */}
diff --git a/web/src/components/trace/index.tsx b/web/src/components/trace/index.tsx
index 8a38365670..790b599f97 100644
--- a/web/src/components/trace/index.tsx
+++ b/web/src/components/trace/index.tsx
@@ -10,7 +10,12 @@ import {
import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
import { api } from "@/src/utils/api";
import useLocalStorage from "@/src/components/useLocalStorage";
-import { Settings2, ChevronsUpDown, ChevronsDownUp, Download } from "lucide-react";
+import {
+ Settings2,
+ ChevronsUpDown,
+ ChevronsDownUp,
+ Download,
+} from "lucide-react";
import { useCallback, useState } from "react";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { TraceTimelineView } from "@/src/components/trace/TraceTimelineView";
@@ -210,11 +215,11 @@ export function Trace(props: {
trace: props.trace,
observations: props.observations,
};
-
+
const jsonString = JSON.stringify(exportData, null, 2);
const blob = new Blob([jsonString], { type: "application/json" });
const url = URL.createObjectURL(blob);
-
+
const link = document.createElement("a");
link.href = url;
link.download = `trace-${props.trace.id}.json`;
@@ -222,7 +227,7 @@ export function Trace(props: {
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
-
+
capture("trace_detail:download_button_click");
}, [props.trace, props.observations, capture]);
diff --git a/web/src/components/ui/CodeJsonViewer.tsx b/web/src/components/ui/CodeJsonViewer.tsx
index 416df0ccd5..98ef27072a 100644
--- a/web/src/components/ui/CodeJsonViewer.tsx
+++ b/web/src/components/ui/CodeJsonViewer.tsx
@@ -257,7 +257,8 @@ export const IOTableCell = ({
return <JsonSkeleton className="h-full w-full overflow-hidden px-2 py-1" />;
}
- const stringifiedJson = data !== null && data !== undefined ? stringifyJsonNode(data) : undefined;
+ const stringifiedJson =
+ data !== null && data !== undefined ? stringifyJsonNode(data) : undefined;
// perf: truncate to IO_TABLE_CHAR_LIMIT characters as table becomes unresponsive attempting to render large JSONs with high levels of nesting
const shouldTruncate =
diff --git a/web/src/components/ui/accordion.tsx b/web/src/components/ui/accordion.tsx
index 41825a9a5d..d834b7d0d5 100644
--- a/web/src/components/ui/accordion.tsx
+++ b/web/src/components/ui/accordion.tsx
@@ -1,12 +1,12 @@
-"use client"
+"use client";
-import * as React from "react"
-import * as AccordionPrimitive from "@radix-ui/react-accordion"
-import { ChevronDown } from "lucide-react"
+import * as React from "react";
+import * as AccordionPrimitive from "@radix-ui/react-accordion";
+import { ChevronDown } from "lucide-react";
-import { cn } from "@/src/utils/tailwind"
+import { cn } from "@/src/utils/tailwind";
-const Accordion = AccordionPrimitive.Root
+const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Item>,
@@ -17,8 +17,8 @@ const AccordionItem = React.forwardRef<
className={cn("border-b", className)}
{...props}
/>
-))
-AccordionItem.displayName = "AccordionItem"
+));
+AccordionItem.displayName = "AccordionItem";
const AccordionTrigger = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Trigger>,
@@ -29,7 +29,7 @@ const AccordionTrigger = React.forwardRef<
ref={ref}
className={cn(
"flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",
- className
+ className,
)}
{...props}
>
@@ -37,8 +37,8 @@ const AccordionTrigger = React.forwardRef<
<ChevronDown className="h-4 w-4 shrink-0 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
-))
-AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
+));
+AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
@@ -51,8 +51,8 @@ const AccordionContent = React.forwardRef<
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
-))
+));
-AccordionContent.displayName = AccordionPrimitive.Content.displayName
+AccordionContent.displayName = AccordionPrimitive.Content.displayName;
-export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
+export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
diff --git a/web/src/components/ui/resizable.tsx b/web/src/components/ui/resizable.tsx
index 0fd3904305..cf033eaa8a 100644
--- a/web/src/components/ui/resizable.tsx
+++ b/web/src/components/ui/resizable.tsx
@@ -1,9 +1,9 @@
-"use client"
+"use client";
-import { GripVertical } from "lucide-react"
-import * as ResizablePrimitive from "react-resizable-panels"
+import { GripVertical } from "lucide-react";
+import * as ResizablePrimitive from "react-resizable-panels";
-import { cn } from "@/src/utils/tailwind"
+import { cn } from "@/src/utils/tailwind";
const ResizablePanelGroup = ({
className,
@@ -12,25 +12,25 @@ const ResizablePanelGroup = ({
<ResizablePrimitive.PanelGroup
className={cn(
"flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
- className
+ className,
)}
{...props}
/>
-)
+);
-const ResizablePanel = ResizablePrimitive.Panel
+const ResizablePanel = ResizablePrimitive.Panel;
const ResizableHandle = ({
withHandle,
className,
...props
}: React.ComponentProps<typeof ResizablePrimitive.PanelResizeHandle> & {
- withHandle?: boolean
+ withHandle?: boolean;
}) => (
<ResizablePrimitive.PanelResizeHandle
className={cn(
"relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
- className
+ className,
)}
{...props}
>
@@ -40,6 +40,6 @@ const ResizableHandle = ({
</div>
)}
</ResizablePrimitive.PanelResizeHandle>
-)
+);
-export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
+export { ResizablePanelGroup, ResizablePanel, ResizableHandle };
diff --git a/web/src/components/ui/sidebar.tsx b/web/src/components/ui/sidebar.tsx
index 767d021bc0..af1426795e 100644
--- a/web/src/components/ui/sidebar.tsx
+++ b/web/src/components/ui/sidebar.tsx
@@ -71,7 +71,10 @@ const SidebarProvider = React.forwardRef<
const [openMobile, setOpenMobile] = React.useState(false);
// Use local storage to persist sidebar state
- const [storedOpen, setStoredOpen] = useLocalStorage(SIDEBAR_STORAGE_KEY, defaultOpen);
+ const [storedOpen, setStoredOpen] = useLocalStorage(
+ SIDEBAR_STORAGE_KEY,
+ defaultOpen,
+ );
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
@@ -79,7 +82,7 @@ const SidebarProvider = React.forwardRef<
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const newValue = typeof value === "function" ? value(open) : value;
-
+
if (setOpenProp) {
return setOpenProp?.(newValue);
}
@@ -149,7 +152,7 @@ const SidebarProvider = React.forwardRef<
} as React.CSSProperties
}
className={cn(
- "group/sidebar-wrapper text-sidebar-foreground has-[[data-variant=inset]]:bg-sidebar flex min-h-svh w-full",
+ "group/sidebar-wrapper flex min-h-svh w-full text-sidebar-foreground has-[[data-variant=inset]]:bg-sidebar",
className,
)}
ref={ref}
@@ -189,7 +192,7 @@ const Sidebar = React.forwardRef<
return (
<div
className={cn(
- "bg-sidebar text-sidebar-foreground flex h-full w-[--sidebar-width] flex-col",
+ "flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",
className,
)}
ref={ref}
@@ -206,7 +209,7 @@ const Sidebar = React.forwardRef<
<SheetContent
data-sidebar="sidebar"
data-mobile="true"
- className="bg-sidebar text-sidebar-foreground w-[--sidebar-width] p-0 [&>button]:hidden"
+ className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
@@ -256,7 +259,7 @@ const Sidebar = React.forwardRef<
>
<div
data-sidebar="sidebar"
- className="bg-sidebar group-data-[variant=floating]:border-sidebar-border flex h-full w-full flex-col group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:shadow"
+ className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow"
>
{children}
</div>
@@ -308,10 +311,10 @@ const SidebarRail = React.forwardRef<
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
- "hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
+ "absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
- "group-data-[collapsible=offcanvas]:hover:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
+ "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className,
@@ -349,7 +352,7 @@ const SidebarInput = React.forwardRef<
ref={ref}
data-sidebar="input"
className={cn(
- "focus-visible:ring-sidebar-ring h-8 w-full bg-background shadow-none focus-visible:ring-2",
+ "h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
className,
)}
{...props}
@@ -366,7 +369,7 @@ const SidebarHeader = React.forwardRef<
<div
ref={ref}
data-sidebar="header"
- className={cn("flex min-h-12 md:h-fit flex-col py-2", className)}
+ className={cn("flex min-h-12 flex-col py-2 md:h-fit", className)}
{...props}
/>
);
@@ -396,7 +399,7 @@ const SidebarSeparator = React.forwardRef<
<Separator
ref={ref}
data-sidebar="separator"
- className={cn("bg-sidebar-border mx-2 w-auto", className)}
+ className={cn("mx-2 w-auto bg-sidebar-border", className)}
{...props}
/>
);
@@ -447,7 +450,7 @@ const SidebarGroupLabel = React.forwardRef<
ref={ref}
data-sidebar="group-label"
className={cn(
- "text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-none transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ "flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className,
)}
@@ -468,7 +471,7 @@ const SidebarGroupAction = React.forwardRef<
ref={ref}
data-sidebar="group-action"
className={cn(
- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-none transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ "absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"group-data-[collapsible=icon]:hidden",
@@ -619,7 +622,7 @@ const SidebarMenuAction = React.forwardRef<
ref={ref}
data-sidebar="menu-action"
className={cn(
- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-none transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ "absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"peer-data-[size=sm]/menu-button:top-1",
@@ -627,7 +630,7 @@ const SidebarMenuAction = React.forwardRef<
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
showOnHover &&
- "peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
+ "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
className,
)}
{...props}
@@ -644,7 +647,7 @@ const SidebarMenuBadge = React.forwardRef<
ref={ref}
data-sidebar="menu-badge"
className={cn(
- "text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums",
+ "pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
@@ -735,7 +738,7 @@ const SidebarMenuSubButton = React.forwardRef<
data-size={size}
data-active={isActive}
className={cn(
- "text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-none focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
diff --git a/web/src/features/dashboard/components/DashboardTable.tsx b/web/src/features/dashboard/components/DashboardTable.tsx
index ead435e9fa..98d520fd15 100644
--- a/web/src/features/dashboard/components/DashboardTable.tsx
+++ b/web/src/features/dashboard/components/DashboardTable.tsx
@@ -258,7 +258,10 @@ export function DashboardTable() {
</DropdownMenuItem>
)}
<DropdownMenuItem asChild>
- <CloneDashboardButton dashboardId={id} projectId={projectId} />
+ <CloneDashboardButton
+ dashboardId={id}
+ projectId={projectId}
+ />
</DropdownMenuItem>
{owner === "PROJECT" && (
<DropdownMenuItem asChild>
diff --git a/web/src/features/dashboard/server/dashboard-router.ts b/web/src/features/dashboard/server/dashboard-router.ts
index 2ca46ac0b7..44e624818f 100644
--- a/web/src/features/dashboard/server/dashboard-router.ts
+++ b/web/src/features/dashboard/server/dashboard-router.ts
@@ -349,7 +349,10 @@ export async function executeQuery(
} catch (error) {
// If the error is a known invalid request, return a 400 error
if (error instanceof InvalidRequestError) {
- logger.warn("Bad request in query execution", error, { projectId, query });
+ logger.warn("Bad request in query execution", error, {
+ projectId,
+ query,
+ });
throw new TRPCError({
code: "BAD_REQUEST",
message: error.message || "Invalid request",
diff --git a/web/src/features/experiments/components/CreateExperimentsForm.tsx b/web/src/features/experiments/components/CreateExperimentsForm.tsx
index 75fba8bfd7..f45b9321f4 100644
--- a/web/src/features/experiments/components/CreateExperimentsForm.tsx
+++ b/web/src/features/experiments/components/CreateExperimentsForm.tsx
@@ -646,9 +646,10 @@ export const CreateExperimentsForm = ({
))}
</ul>
<span>
- Variables (like {"{{variable}}"}) should be mapped to string values.
- Placeholders should be mapped to arrays of message objects.
- These will be used as the input to your prompt.
+ Variables (like {"{{variable}}"}) should be
+ mapped to string values. Placeholders should
+ be mapped to arrays of message objects. These
+ will be used as the input to your prompt.
</span>
</div>
) : (
@@ -722,7 +723,8 @@ export const CreateExperimentsForm = ({
<Loader2 className="h-3 w-3 animate-spin" />
</CardTitle>
<CardDescription className="text-foreground">
- Checking dataset items against prompt variables and placeholders
+ Checking dataset items against prompt variables and
+ placeholders
</CardDescription>
</CardHeader>
</Card>
@@ -748,7 +750,8 @@ export const CreateExperimentsForm = ({
<CircleCheck className="h-4 w-4" />
</CardTitle>
<div className="text-sm">
- Matches between dataset items and prompt variables/placeholders
+ Matches between dataset items and prompt
+ variables/placeholders
<ul className="my-2 ml-2 list-inside list-disc">
{Object.entries(
validationResult.data.variablesMap ?? {},
@@ -761,8 +764,8 @@ export const CreateExperimentsForm = ({
</li>
))}
</ul>
- Items missing all required variables and placeholders will be excluded from
- the experiment.
+ Items missing all required variables and placeholders will
+ be excluded from the experiment.
</div>
</CardHeader>
</Card>
diff --git a/web/src/features/experiments/hooks/useExperimentPromptData.ts b/web/src/features/experiments/hooks/useExperimentPromptData.ts
index e3751b15d0..690966778e 100644
--- a/web/src/features/experiments/hooks/useExperimentPromptData.ts
+++ b/web/src/features/experiments/hooks/useExperimentPromptData.ts
@@ -1,7 +1,12 @@
import { useMemo } from "react";
import { api } from "@/src/utils/api";
import { type UseFormReturn } from "react-hook-form";
-import { extractVariables, PromptType, extractPlaceholderNames, type PromptMessage } from "@langfuse/shared";
+import {
+ extractVariables,
+ PromptType,
+ extractPlaceholderNames,
+ type PromptMessage,
+} from "@langfuse/shared";
type ExperimentPromptDataProps = {
projectId: string;
@@ -28,10 +33,13 @@ export function useExperimentPromptData({
: JSON.stringify(prompt?.prompt),
);
- const promptMessages = prompt?.type === PromptType.Chat && Array.isArray(prompt.prompt)
- ? prompt.prompt
- : [];
- const placeholderNames = extractPlaceholderNames(promptMessages as PromptMessage[]);
+ const promptMessages =
+ prompt?.type === PromptType.Chat && Array.isArray(prompt.prompt)
+ ? prompt.prompt
+ : [];
+ const placeholderNames = extractPlaceholderNames(
+ promptMessages as PromptMessage[],
+ );
return [...extractedVariables, ...placeholderNames];
}, [promptId, promptMeta.data]);
diff --git a/web/src/features/experiments/server/router.ts b/web/src/features/experiments/server/router.ts
index c68cf9989c..4657192b71 100644
--- a/web/src/features/experiments/server/router.ts
+++ b/web/src/features/experiments/server/router.ts
@@ -99,10 +99,13 @@ export const experimentsRouter = createTRPCRouter({
: JSON.stringify(prompt.prompt),
);
- const promptMessages = prompt?.type === PromptType.Chat && Array.isArray(prompt.prompt)
- ? prompt.prompt
- : [];
- const placeholderNames = extractPlaceholderNames(promptMessages as PromptMessage[]);
+ const promptMessages =
+ prompt?.type === PromptType.Chat && Array.isArray(prompt.prompt)
+ ? prompt.prompt
+ : [];
+ const placeholderNames = extractPlaceholderNames(
+ promptMessages as PromptMessage[],
+ );
const allVariables = [...extractedVariables, ...placeholderNames];
@@ -128,10 +131,7 @@ export const experimentsRouter = createTRPCRouter({
};
}
- const variablesMap = validateDatasetItems(
- datasetItems,
- allVariables,
- );
+ const variablesMap = validateDatasetItems(datasetItems, allVariables);
if (!Boolean(Object.keys(variablesMap).length)) {
return {
diff --git a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
index 764d2e6c26..c0390bf9ef 100644
--- a/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
+++ b/web/src/features/playground/page/components/JumpToPlaygroundButton.tsx
@@ -172,7 +172,7 @@ const ParsedChatMessageListSchema = z.array(
.optional(),
}),
PlaceholderMessageSchema,
- ])
+ ]),
);
// Langchain integration has the tool definition in a tool message
@@ -207,7 +207,9 @@ const transformToPlaygroundMessage = (
(regularMessage.tool_calls || regularMessage.additional_kwargs?.tool_calls)
) {
const toolCalls =
- regularMessage.tool_calls ?? regularMessage.additional_kwargs?.tool_calls ?? [];
+ regularMessage.tool_calls ??
+ regularMessage.additional_kwargs?.tool_calls ??
+ [];
const playgroundMessage: ChatMessage = {
role: ChatMessageRole.Assistant,
diff --git a/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx b/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx
index 33c0ea8431..6817fc42f8 100644
--- a/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx
+++ b/web/src/features/playground/page/components/MessagePlaceholderComponent.tsx
@@ -2,7 +2,10 @@ import { CheckCircle2, Circle, TrashIcon } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { CodeMirrorEditor } from "@/src/components/editor";
import { useState, useCallback } from "react";
-import { type ChatMessage, PromptChatMessageListSchema } from "@langfuse/shared";
+import {
+ type ChatMessage,
+ PromptChatMessageListSchema,
+} from "@langfuse/shared";
import { usePlaygroundContext } from "../context";
import { type PlaceholderMessageFillIn } from "../types";
@@ -11,28 +14,41 @@ import { useNamingConflicts } from "../hooks/useNamingConflicts";
export const MessagePlaceholderComponent: React.FC<{
messagePlaceholder: PlaceholderMessageFillIn;
}> = ({ messagePlaceholder }) => {
- const { updateMessagePlaceholderValue, deleteMessagePlaceholder, promptVariables, messagePlaceholders } =
- usePlaygroundContext();
+ const {
+ updateMessagePlaceholderValue,
+ deleteMessagePlaceholder,
+ promptVariables,
+ messagePlaceholders,
+ } = usePlaygroundContext();
const { name, value, isUsed } = messagePlaceholder;
const [error, setError] = useState<string | null>(null);
- const { isPlaceholderConflicting } = useNamingConflicts(promptVariables, messagePlaceholders);
+ const { isPlaceholderConflicting } = useNamingConflicts(
+ promptVariables,
+ messagePlaceholders,
+ );
const hasConflict = isPlaceholderConflicting(name);
- const handleInputChange = useCallback((jsonString: string) => {
- try {
- const parsed = jsonString.trim() === "" ? [] : JSON.parse(jsonString);
- const result = PromptChatMessageListSchema.safeParse(parsed);
+ const handleInputChange = useCallback(
+ (jsonString: string) => {
+ try {
+ const parsed = jsonString.trim() === "" ? [] : JSON.parse(jsonString);
+ const result = PromptChatMessageListSchema.safeParse(parsed);
- if (result.success) {
- updateMessagePlaceholderValue(name, result.data as ChatMessage[]);
- setError(null);
- } else {
- setError(result.error.issues[0]?.message || "Invalid chat message format, ensure it has role and content keys.");
+ if (result.success) {
+ updateMessagePlaceholderValue(name, result.data as ChatMessage[]);
+ setError(null);
+ } else {
+ setError(
+ result.error.issues[0]?.message ||
+ "Invalid chat message format, ensure it has role and content keys.",
+ );
+ }
+ } catch {
+ setError("Invalid JSON format");
}
- } catch {
- setError("Invalid JSON format");
- }
- }, [name, updateMessagePlaceholderValue]);
+ },
+ [name, updateMessagePlaceholderValue],
+ );
const UsedIcon = isUsed ? CheckCircle2 : Circle;
const iconColor = isUsed ? "green" : "grey";
@@ -42,7 +58,10 @@ export const MessagePlaceholderComponent: React.FC<{
<div className="mb-1 flex flex-row items-center">
<span className="flex flex-1 flex-row space-x-2 text-xs">
<UsedIcon size={16} color={iconColor} />
- <p className={`min-w-[90px] truncate font-mono ${hasConflict ? 'text-red-500' : ''}`} title={name}>
+ <p
+ className={`min-w-[90px] truncate font-mono ${hasConflict ? "text-red-500" : ""}`}
+ title={name}
+ >
{name ? name : "Unnamed placeholder"}
</p>
</span>
@@ -59,11 +78,15 @@ export const MessagePlaceholderComponent: React.FC<{
</div>
<CodeMirrorEditor
- value={value.length === 0 ? `[\n {\n "role": "",\n "content": ""\n }\n]` : JSON.stringify(value, null, 2)}
+ value={
+ value.length === 0
+ ? `[\n {\n "role": "",\n "content": ""\n }\n]`
+ : JSON.stringify(value, null, 2)
+ }
onChange={handleInputChange}
mode="json"
minHeight="none"
- className={`max-h-[15rem] w-full resize-y p-1 font-mono text-xs focus:outline-none ${hasConflict ? 'border border-red-500' : ''}`}
+ className={`max-h-[15rem] w-full resize-y p-1 font-mono text-xs focus:outline-none ${hasConflict ? "border border-red-500" : ""}`}
editable={true}
lineNumbers={false}
placeholder={`[\n {\n "role": "user",\n "content": "Hello!"\n },\n {\n "role": "assistant",\n "content": "Hi there!"\n }\n]`}
@@ -74,9 +97,7 @@ export const MessagePlaceholderComponent: React.FC<{
Placeholder name conflicts with variable. Names must be unique.
</p>
)}
- {error && (
- <p className="mt-1 text-xs text-red-500">{error}</p>
- )}
+ {error && <p className="mt-1 text-xs text-red-500">{error}</p>}
</div>
);
};
diff --git a/web/src/features/playground/page/components/MessagePlaceholders.tsx b/web/src/features/playground/page/components/MessagePlaceholders.tsx
index f84d8ed00e..87dbe664f8 100644
--- a/web/src/features/playground/page/components/MessagePlaceholders.tsx
+++ b/web/src/features/playground/page/components/MessagePlaceholders.tsx
@@ -12,7 +12,10 @@ export const MessagePlaceholders = () => {
{messagePlaceholders.length === 0 ? (
<div className="mt-4 text-xs">
<p className="mb-2">No message placeholders defined.</p>
- <p>Placeholders can be used to e.g. inject message histories into prompts.</p>
+ <p>
+ Placeholders can be used to e.g. inject message histories into
+ prompts.
+ </p>
</div>
) : (
<div className="h-full overflow-auto">
diff --git a/web/src/features/playground/page/components/PromptVariableComponent.tsx b/web/src/features/playground/page/components/PromptVariableComponent.tsx
index 27ae81c388..6e68047648 100644
--- a/web/src/features/playground/page/components/PromptVariableComponent.tsx
+++ b/web/src/features/playground/page/components/PromptVariableComponent.tsx
@@ -9,10 +9,17 @@ import { useNamingConflicts } from "../hooks/useNamingConflicts";
export const PromptVariableComponent: React.FC<{
promptVariable: PromptVariable;
}> = ({ promptVariable }) => {
- const { updatePromptVariableValue, deletePromptVariable, promptVariables, messagePlaceholders } =
- usePlaygroundContext();
+ const {
+ updatePromptVariableValue,
+ deletePromptVariable,
+ promptVariables,
+ messagePlaceholders,
+ } = usePlaygroundContext();
const { name, value, isUsed } = promptVariable;
- const { isVariableConflicting } = useNamingConflicts(promptVariables, messagePlaceholders);
+ const { isVariableConflicting } = useNamingConflicts(
+ promptVariables,
+ messagePlaceholders,
+ );
const hasConflict = isVariableConflicting(name);
const handleInputChange = (value: string) => {
@@ -35,7 +42,10 @@ export const PromptVariableComponent: React.FC<{
<div className="mb-1 flex flex-row items-center">
<span className="flex flex-1 flex-row space-x-2 text-xs">
<p title={isUsedTooltip}>{isUsedIcon}</p>
- <p className={`min-w-[90px] truncate font-mono ${hasConflict ? 'text-red-500' : ''}`} title={name}>
+ <p
+ className={`min-w-[90px] truncate font-mono ${hasConflict ? "text-red-500" : ""}`}
+ title={name}
+ >
{name}
</p>
</span>
@@ -56,7 +66,7 @@ export const PromptVariableComponent: React.FC<{
onChange={(e) => handleInputChange(e)}
mode="prompt"
minHeight="none"
- className={`max-h-[10rem] w-full resize-y p-1 font-mono text-xs focus:outline-none ${hasConflict ? 'border border-red-500' : ''}`}
+ className={`max-h-[10rem] w-full resize-y p-1 font-mono text-xs focus:outline-none ${hasConflict ? "border border-red-500" : ""}`}
editable={true}
lineNumbers={false}
placeholder={name}
diff --git a/web/src/features/playground/page/context/index.tsx b/web/src/features/playground/page/context/index.tsx
index 6d74bb3637..6987413d7c 100644
--- a/web/src/features/playground/page/context/index.tsx
+++ b/web/src/features/playground/page/context/index.tsx
@@ -41,7 +41,6 @@ import {
} from "@/src/features/playground/page/types";
import { getFinalModelParams } from "@/src/utils/getFinalModelParams";
-
type PlaygroundContextType = {
promptVariables: PromptVariable[];
updatePromptVariableValue: (variable: string, value: string) => void;
@@ -87,7 +86,9 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
const projectId = useProjectIdFromURL();
const { playgroundCache, setPlaygroundCache } = usePlaygroundCache();
const [promptVariables, setPromptVariables] = useState<PromptVariable[]>([]);
- const [messagePlaceholders, setMessagePlaceholders] = useState<PlaceholderMessageFillIn[]>([]);
+ const [messagePlaceholders, setMessagePlaceholders] = useState<
+ PlaceholderMessageFillIn[]
+ >([]);
const [output, setOutput] = useState("");
const [outputToolCalls, setOutputToolCalls] = useState<LLMToolCall[]>([]);
const [outputJson, setOutputJson] = useState("");
@@ -171,7 +172,9 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
}, [playgroundCache, setModelParams]);
const updatePromptVariables = useCallback(() => {
- const messageContents = messages.map((m) => ('content' in m ? m.content : m.name)).join("\n");
+ const messageContents = messages
+ .map((m) => ("content" in m ? m.content : m.name))
+ .join("\n");
const variables = extractVariables(messageContents)
.map((v) => v.trim())
.filter(Boolean);
@@ -231,7 +234,10 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
return toolCallMessage;
} else if (message.type === ChatMessageType.Placeholder) {
- const placeholderMessage = { ...message, id: uuidv4() } as ChatMessageWithId;
+ const placeholderMessage = {
+ ...message,
+ id: uuidv4(),
+ } as ChatMessageWithId;
setMessages((prev) => [...prev, placeholderMessage]);
return placeholderMessage;
} else {
@@ -279,7 +285,11 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
setOutputJson("");
setOutputToolCalls([]);
- const finalMessages = getFinalMessages(promptVariables, messages, messagePlaceholders);
+ const finalMessages = getFinalMessages(
+ promptVariables,
+ messages,
+ messagePlaceholders,
+ );
const leftOverVariables = extractVariables(
finalMessages.map((m) => m.content).join("\n"),
);
@@ -411,11 +421,14 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
setPromptVariables((prev) => prev.filter((v) => v.name !== variable));
}, []);
- const updateMessagePlaceholderValue = useCallback((name: string, value: ChatMessage[]) => {
- setMessagePlaceholders((prev) =>
- prev.map((p) => (p.name === name ? { ...p, value } : p)),
- );
- }, []);
+ const updateMessagePlaceholderValue = useCallback(
+ (name: string, value: ChatMessage[]) => {
+ setMessagePlaceholders((prev) =>
+ prev.map((p) => (p.name === name ? { ...p, value } : p)),
+ );
+ },
+ [],
+ );
const deleteMessagePlaceholder = useCallback((name: string) => {
setMessagePlaceholders((prev) => prev.filter((p) => p.name !== name));
@@ -423,22 +436,30 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
const updateMessagePlaceholders = useCallback(() => {
const placeholderNames = messages
- .filter((msg): msg is ChatMessageWithId & { type: ChatMessageType.Placeholder; name: string } =>
- msg.type === ChatMessageType.Placeholder
+ .filter(
+ (
+ msg,
+ ): msg is ChatMessageWithId & {
+ type: ChatMessageType.Placeholder;
+ name: string;
+ } => msg.type === ChatMessageType.Placeholder,
)
.map((msg) => msg.name);
setMessagePlaceholders((prev) => {
// Set isUsed flag for existing placeholders and remove unused ones
- const next = prev.reduce<PlaceholderMessageFillIn[]>((updatedPlaceholders, p) => {
- const isUsed = placeholderNames.includes(p.name);
- // Remove unused placeholders
- if (!isUsed && p.value.length === 0) {
+ const next = prev.reduce<PlaceholderMessageFillIn[]>(
+ (updatedPlaceholders, p) => {
+ const isUsed = placeholderNames.includes(p.name);
+ // Remove unused placeholders
+ if (!isUsed && p.value.length === 0) {
+ return updatedPlaceholders;
+ }
+ updatedPlaceholders.push({ ...p, isUsed });
return updatedPlaceholders;
- }
- updatedPlaceholders.push({ ...p, isUsed });
- return updatedPlaceholders;
- }, []);
+ },
+ [],
+ );
// Add new placeholders
for (const name of placeholderNames) {
@@ -690,13 +711,11 @@ function getFinalMessages(
);
}
- const placeholderValues: MessagePlaceholderValues = messagePlaceholders.reduce(
- (placeholderMap, p) => {
+ const placeholderValues: MessagePlaceholderValues =
+ messagePlaceholders.reduce((placeholderMap, p) => {
placeholderMap[p.name] = p.value;
return placeholderMap;
- },
- {} as MessagePlaceholderValues,
- );
+ }, {} as MessagePlaceholderValues);
const textVariables = promptVariables.reduce(
(variableMap, v) => {
@@ -715,7 +734,8 @@ function getFinalMessages(
// Filter empty messages (except tool calls), e.g. if placeholder value was empty
return compiledMessages.filter(
(m) =>
- m.content.length > 0 || ("toolCalls" in m && m.toolCalls && m.toolCalls.length > 0),
+ m.content.length > 0 ||
+ ("toolCalls" in m && m.toolCalls && m.toolCalls.length > 0),
);
}
diff --git a/web/src/features/playground/page/hooks/useNamingConflicts.ts b/web/src/features/playground/page/hooks/useNamingConflicts.ts
index 9029379cde..ed57aa177c 100644
--- a/web/src/features/playground/page/hooks/useNamingConflicts.ts
+++ b/web/src/features/playground/page/hooks/useNamingConflicts.ts
@@ -15,14 +15,14 @@ export interface NamingConflictInfo {
*/
export const useNamingConflicts = (
variables: PromptVariable[],
- placeholders: PlaceholderMessageFillIn[]
+ placeholders: PlaceholderMessageFillIn[],
): NamingConflictInfo => {
return useMemo(() => {
- const variableNames = variables.map(v => v.name);
- const placeholderNames = placeholders.map(p => p.name);
+ const variableNames = variables.map((v) => v.name);
+ const placeholderNames = placeholders.map((p) => p.name);
- const conflictingNames = variableNames.filter(name =>
- placeholderNames.includes(name)
+ const conflictingNames = variableNames.filter((name) =>
+ placeholderNames.includes(name),
);
const hasConflicts = conflictingNames.length > 0;
diff --git a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx
index f078a7178a..ba8a60de01 100644
--- a/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx
+++ b/web/src/features/prompts/components/NewPromptForm/PromptChatMessages.tsx
@@ -53,7 +53,7 @@ export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({
parsedMessages.data.map((message) => {
const id = uuidv4();
// TODO: clean up - Placeholder messages could also be API created..
- if ('type' in message && message.type === ChatMessageType.Placeholder) {
+ if ("type" in message && message.type === ChatMessageType.Placeholder) {
return {
...message,
id,
@@ -70,7 +70,7 @@ export const PromptChatMessages: React.FC<PromptChatMessagesProps> = ({
);
const customRoles = parsedMessages.data.reduce((acc, message) => {
- if ('role' in message) {
+ if ("role" in message) {
const { role } = message;
if (ChatMessageDefaultRoleSchema.safeParse(role).error) {
acc.add(role);
diff --git a/web/src/features/prompts/components/NewPromptForm/validation.ts b/web/src/features/prompts/components/NewPromptForm/validation.ts
index b02175a424..7943aa1ea4 100644
--- a/web/src/features/prompts/components/NewPromptForm/validation.ts
+++ b/web/src/features/prompts/components/NewPromptForm/validation.ts
@@ -25,14 +25,18 @@ const NewPromptBaseSchema = z.object({
const NewChatPromptSchema = NewPromptBaseSchema.extend({
type: z.literal(PromptType.Chat),
- chatPrompt: z.array(z.any())
+ chatPrompt: z
+ .array(z.any())
.refine(
(messages: Array<{ type?: ChatMessageType; content?: string }>) =>
messages.every((message) => {
const isPlaceholder = message?.type === ChatMessageType.Placeholder;
- return !isPlaceholder || PlaceholderMessageSchema.safeParse(message).success;
+ return (
+ !isPlaceholder ||
+ PlaceholderMessageSchema.safeParse(message).success
+ );
}),
- "Placeholder name must start with a letter and contain only alphanumeric characters and underscores"
+ "Placeholder name must start with a letter and contain only alphanumeric characters and underscores",
)
.refine(
(messages: Array<{ type?: ChatMessageType; content?: string }>) =>
@@ -40,7 +44,7 @@ const NewChatPromptSchema = NewPromptBaseSchema.extend({
const isPlaceholder = message?.type === ChatMessageType.Placeholder;
return isPlaceholder || Boolean(message?.content?.trim()?.length);
}),
- "Enter a chat message or remove the empty message"
+ "Enter a chat message or remove the empty message",
),
textPrompt: z.string(),
});
diff --git a/web/src/features/prompts/server/actions/createPrompt.ts b/web/src/features/prompts/server/actions/createPrompt.ts
index 7711cfcc36..d7c03e28cd 100644
--- a/web/src/features/prompts/server/actions/createPrompt.ts
+++ b/web/src/features/prompts/server/actions/createPrompt.ts
@@ -36,20 +36,26 @@ type DuplicatePromptParams = {
const extractChatVariableAndPlaceholderNames = (
chatPrompt: Array<any>,
-): { variables: string[], placeholders: string[] } => {
+): { variables: string[]; placeholders: string[] } => {
const placeholders = extractPlaceholderNames(chatPrompt);
const variables: string[] = [];
for (const message of chatPrompt) {
- if (message && 'content' in message && typeof message.content === 'string') {
+ if (
+ message &&
+ "content" in message &&
+ typeof message.content === "string"
+ ) {
variables.push(...extractVariables(message.content));
}
}
- return { variables: [...new Set(variables)], placeholders: [...new Set(placeholders)] };
+ return {
+ variables: [...new Set(variables)],
+ placeholders: [...new Set(placeholders)],
+ };
};
-
export const createPrompt = async ({
projectId,
name,
@@ -75,11 +81,12 @@ export const createPrompt = async ({
// Prevent naming collisions between variables and placeholders
if (type === PromptType.Chat && Array.isArray(prompt)) {
- const { variables, placeholders } = extractChatVariableAndPlaceholderNames(prompt);
- const conflictingNames = variables.filter(v => placeholders.includes(v));
+ const { variables, placeholders } =
+ extractChatVariableAndPlaceholderNames(prompt);
+ const conflictingNames = variables.filter((v) => placeholders.includes(v));
if (conflictingNames.length > 0) {
throw new InvalidRequestError(
- `Cannot create prompt, variables and placeholders must be unique, the following are not: ${conflictingNames.join(", ")}`
+ `Cannot create prompt, variables and placeholders must be unique, the following are not: ${conflictingNames.join(", ")}`,
);
}
}
diff --git a/web/src/features/widgets/components/WidgetForm.tsx b/web/src/features/widgets/components/WidgetForm.tsx
index 803c9cb005..6395c22f5c 100644
--- a/web/src/features/widgets/components/WidgetForm.tsx
+++ b/web/src/features/widgets/components/WidgetForm.tsx
@@ -1030,13 +1030,14 @@ export function WidgetForm({
// Remove invalid filters based on the new view
if (newView !== "scores-categorical") {
- setUserFilterState((prev) => prev.filter(
- (filter) =>
- filter.column !== "stringValue",
- ));
+ setUserFilterState((prev) =>
+ prev.filter(
+ (filter) => filter.column !== "stringValue",
+ ),
+ );
}
if (newView === "scores-numeric") {
- setUserFilterState((prev) =>
+ setUserFilterState((prev) =>
prev.filter((filter) => filter.column !== "value"),
);
}
diff --git a/web/src/features/widgets/components/WidgetPropertySelectItem.tsx b/web/src/features/widgets/components/WidgetPropertySelectItem.tsx
index 0132e1389e..88e1e7f025 100644
--- a/web/src/features/widgets/components/WidgetPropertySelectItem.tsx
+++ b/web/src/features/widgets/components/WidgetPropertySelectItem.tsx
@@ -35,7 +35,7 @@ export const WidgetPropertySelectItem = ({
</HoverCardTrigger>
<HoverCardPortal>
<HoverCardContent hideWhenDetached align="start" side="right">
- <div className="mb-1 font-bold text-sm">{label}</div>
+ <div className="mb-1 text-sm font-bold">{label}</div>
{(unit || type) && (
<div className="mb-2 flex flex-wrap gap-2 text-xs">
{unit && (
diff --git a/web/src/pages/auth/error.tsx b/web/src/pages/auth/error.tsx
index d073edc2c3..d0fd488861 100644
--- a/web/src/pages/auth/error.tsx
+++ b/web/src/pages/auth/error.tsx
@@ -5,7 +5,7 @@ export default function AuthError() {
const router = useRouter();
const { error } = router.query;
const errorMessage = error
- ? decodeURIComponent(String(error))
+ ? decodeURIComponent(String(error))
: "An authentication error occurred. Please reach out to support.";
return (
diff --git a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
index 138a61dd14..987a85d692 100644
--- a/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
+++ b/web/src/pages/project/[projectId]/prompts/[[...folder]].tsx
@@ -18,7 +18,7 @@ export default function PromptsWithFolder() {
const projectId = router.query.projectId as string;
const routeSegments = router.query.folder;
const [queryParams] = useQueryParams({ folder: StringParam });
- const folderQueryParam = queryParams.folder || '';
+ const folderQueryParam = queryParams.folder || "";
// Determine view type based on route segments
// NOTE: there is a bug here, that if the user directly accesses a prompt name which ends in `/metrics`,
@@ -26,10 +26,15 @@ export default function PromptsWithFolder() {
// this in the UI (we URL encode here and don't strip metrics). We could resolve this with another API call
// to check the prompt name existence.
const segmentsArray = Array.isArray(routeSegments) ? routeSegments : [];
- const isMetricsPage = segmentsArray.length > 0 && segmentsArray[segmentsArray.length - 1] === 'metrics';
- const promptNameFromRoute = segmentsArray.length > 0
- ? (isMetricsPage ? segmentsArray.slice(0, -1).join('/') : segmentsArray.join('/'))
- : '';
+ const isMetricsPage =
+ segmentsArray.length > 0 &&
+ segmentsArray[segmentsArray.length - 1] === "metrics";
+ const promptNameFromRoute =
+ segmentsArray.length > 0
+ ? isMetricsPage
+ ? segmentsArray.slice(0, -1).join("/")
+ : segmentsArray.join("/")
+ : "";
const capture = usePostHogClientCapture();
const hasCUDAccess = useHasProjectAccess({
@@ -86,7 +91,7 @@ export default function PromptsWithFolder() {
<ActionButton
icon={<PlusIcon className="h-4 w-4" aria-hidden="true" />}
hasAccess={hasCUDAccess}
- href={`/project/${projectId}/prompts/new${folderQueryParam ? `?folder=${encodeURIComponent(folderQueryParam)}` : ''}`}
+ href={`/project/${projectId}/prompts/new${folderQueryParam ? `?folder=${encodeURIComponent(folderQueryParam)}` : ""}`}
variant="default"
limit={promptLimit}
limitValue={Number(count?.totalCount ?? 0)}
diff --git a/web/src/pages/project/[projectId]/prompts/metrics.tsx b/web/src/pages/project/[projectId]/prompts/metrics.tsx
index dcf0d4a276..2e327351b0 100644
--- a/web/src/pages/project/[projectId]/prompts/metrics.tsx
+++ b/web/src/pages/project/[projectId]/prompts/metrics.tsx
@@ -77,14 +77,16 @@ function joinPromptCoreAndMetricData(
return { status: "success", combinedData };
}
-export default function PromptVersionTable({ promptName: promptNameProp }: { promptName?: string } = {}) {
+export default function PromptVersionTable({
+ promptName: promptNameProp,
+}: { promptName?: string } = {}) {
const router = useRouter();
const projectId = router.query.projectId as string;
- const promptName = promptNameProp || (
- router.query.promptName
+ const promptName =
+ promptNameProp ||
+ (router.query.promptName
? decodeURIComponent(router.query.promptName as string)
- : ''
- );
+ : "");
const [paginationState, setPaginationState] = useQueryParams({
pageIndex: withDefault(NumberParam, 0),