Skip to content

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

Feature/lf 176 simplify generation api route (#19)

Maximilian Deichmannc758c588f8cd
diff --git a/fern/server/definition/event.yml b/fern/server/definition/event.yml
index b8f77be4cd..1a501c8d50 100644
--- a/fern/server/definition/event.yml
+++ b/fern/server/definition/event.yml
@@ -17,7 +17,7 @@ types:
traceId: string
name: string
startTime: datetime
- attributes: unknown
+ metadata: unknown
parentObservationId: optional<string>
Event:
properties:
@@ -26,5 +26,5 @@ types:
type: string
name: string
startTime: datetime
- attributes: unknown
+ metadata: unknown
parentObservationId: optional<string>
diff --git a/fern/server/definition/generations.yml b/fern/server/definition/generations.yml
new file mode 100644
index 0000000000..4a9449854f
--- /dev/null
+++ b/fern/server/definition/generations.yml
@@ -0,0 +1,49 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ log:
+ method: POST
+ path: /generations
+ request: CreateLog
+ response: Log
+
+types:
+ CreateLog:
+ properties:
+ traceId: optional<string>
+ startTime: optional<datetime>
+ endTime: optional<datetime>
+ name: optional<string>
+ model: optional<string>
+ modelParameters: optional<map<string, MapValue>>
+ prompt: optional<unknown>
+ metadata: optional<unknown>
+ completion: optional<string>
+ usage: optional<LLMUsage>
+ parentObservationId: optional<string>
+
+ Log:
+ properties:
+ id: string
+ traceId: string
+ type: string
+ name: optional<string>
+ startTime: optional<datetime>
+ endTime: optional<datetime>
+ attributes: unknown
+ parentObservationId: optional<string>
+
+ LLMUsage:
+ properties:
+ promptTokens: optional<integer>
+ completionTokens: optional<integer>
+
+ MapValue:
+ discriminated: false
+ union:
+ - optional<string>
+ - optional<integer>
+ - optional<boolean>
diff --git a/fern/server/definition/span.yml b/fern/server/definition/span.yml
index a9f134397f..3e35e685a2 100644
--- a/fern/server/definition/span.yml
+++ b/fern/server/definition/span.yml
@@ -4,18 +4,6 @@ service:
auth: true
base-path: /api/public
endpoints:
- createLLMCall:
- docs: a
- method: POST
- path: /llm-span
- request: CreateLLMSpanRequest
- response: Span
- updateLLMCall:
- docs: Update a span to the database
- method: PATCH
- path: /llm-span
- request: UpdateLLMSpanRequest
- response: Span
create:
docs: Add a span to the database
method: POST
@@ -35,7 +23,7 @@ types:
traceId: optional<string>
name: string
startTime: datetime
- attributes: unknown
+ metadata: unknown
parentObservationId: optional<string>
UpdateSpanRequest:
@@ -43,12 +31,6 @@ types:
spanId: string
endTime: datetime
- UpdateLLMSpanRequest:
- properties:
- spanId: string
- endTime: datetime
- attributes: LLMAttributes
-
Span:
properties:
id: string
@@ -57,34 +39,5 @@ types:
name: string
startTime: datetime
endTime: optional<datetime>
- attributes: unknown
- parentObservationId: optional<string>
-
- CreateLLMSpanRequest:
- properties:
- traceId: optional<string>
- name: string
- startTime: datetime
- endTime: optional<datetime>
+ metadata: unknown
parentObservationId: optional<string>
- attributes: LLMAttributes
-
- LLMAttributes:
- properties:
- model: optional<string>
- temperature: optional<double>
- maxTokens: optional<integer>
- topP: optional<double>
- prompt: optional<list<LLMPrompt>>
- completion: optional<string>
- tokens: optional<LLMTokens>
-
- LLMPrompt:
- properties:
- role: string
- content: string
-
- LLMTokens:
- properties:
- promptAmount: optional<integer>
- completionAmount: optional<integer>
diff --git a/fern/server/definition/trace.yml b/fern/server/definition/trace.yml
index 7971fd9733..c863cc0501 100644
--- a/fern/server/definition/trace.yml
+++ b/fern/server/definition/trace.yml
@@ -15,10 +15,10 @@ types:
CreateTraceRequest:
properties:
name: string
- attributes: unknown
+ metadata: unknown
Trace:
properties:
id: string
timestamp: datetime
name: string
- attributes: unknown
+ metadata: unknown
diff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.yml
index 09b6b4ea9c..66be76c93c 100644
--- a/generated/openapi-server/openapi.yml
+++ b/generated/openapi-server/openapi.yml
@@ -25,12 +25,11 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/CreateEventRequest'
- /api/public/scores:
+ /api/public/generations:
post:
- description: Add a score to the database
- operationId: score_create
+ operationId: generations_log
tags:
- - Score
+ - Generations
parameters: []
responses:
'200':
@@ -38,40 +37,20 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/Score'
+ $ref: '#/components/schemas/Log'
security: *ref_0
requestBody:
required: true
content:
application/json:
schema:
- $ref: '#/components/schemas/CreateScoreRequest'
- /api/public/llm-span:
+ $ref: '#/components/schemas/CreateLog'
+ /api/public/scores:
post:
- description: a
- operationId: span_createLLMCall
- tags:
- - Span
- parameters: []
- responses:
- '200':
- description: ''
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/Span'
- security: *ref_0
- requestBody:
- required: true
- content:
- application/json:
- schema:
- $ref: '#/components/schemas/CreateLLMSpanRequest'
- patch:
- description: Update a span to the database
- operationId: span_updateLLMCall
+ description: Add a score to the database
+ operationId: score_create
tags:
- - Span
+ - Score
parameters: []
responses:
'200':
@@ -79,14 +58,14 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/Span'
+ $ref: '#/components/schemas/Score'
security: *ref_0
requestBody:
required: true
content:
application/json:
schema:
- $ref: '#/components/schemas/UpdateLLMSpanRequest'
+ $ref: '#/components/schemas/CreateScoreRequest'
/api/public/spans:
post:
description: Add a span to the database
@@ -162,14 +141,14 @@ components:
startTime:
type: string
format: date-time
- attributes: {}
+ metadata: {}
parentObservationId:
type: string
required:
- traceId
- name
- startTime
- - attributes
+ - metadata
Event:
title: Event
type: object
@@ -185,7 +164,7 @@ components:
startTime:
type: string
format: date-time
- attributes: {}
+ metadata: {}
parentObservationId:
type: string
required:
@@ -194,7 +173,75 @@ components:
- type
- name
- startTime
+ - metadata
+ CreateLog:
+ title: CreateLog
+ type: object
+ properties:
+ traceId:
+ type: string
+ startTime:
+ type: string
+ format: date-time
+ endTime:
+ type: string
+ format: date-time
+ name:
+ type: string
+ model:
+ type: string
+ modelParameters:
+ type: object
+ additionalProperties:
+ $ref: '#/components/schemas/MapValue'
+ prompt: {}
+ metadata: {}
+ completion:
+ type: string
+ usage:
+ $ref: '#/components/schemas/LLMUsage'
+ parentObservationId:
+ type: string
+ Log:
+ title: Log
+ type: object
+ properties:
+ id:
+ type: string
+ traceId:
+ type: string
+ type:
+ type: string
+ name:
+ type: string
+ startTime:
+ type: string
+ format: date-time
+ endTime:
+ type: string
+ format: date-time
+ attributes: {}
+ parentObservationId:
+ type: string
+ required:
+ - id
+ - traceId
+ - type
- attributes
+ LLMUsage:
+ title: LLMUsage
+ type: object
+ properties:
+ promptTokens:
+ type: integer
+ completionTokens:
+ type: integer
+ MapValue:
+ title: MapValue
+ oneOf:
+ - type: string
+ - type: integer
+ - type: boolean
CreateScoreRequest:
title: CreateScoreRequest
type: object
@@ -242,13 +289,13 @@ components:
startTime:
type: string
format: date-time
- attributes: {}
+ metadata: {}
parentObservationId:
type: string
required:
- name
- startTime
- - attributes
+ - metadata
UpdateSpanRequest:
title: UpdateSpanRequest
type: object
@@ -261,21 +308,6 @@ components:
required:
- spanId
- endTime
- UpdateLLMSpanRequest:
- title: UpdateLLMSpanRequest
- type: object
- properties:
- spanId:
- type: string
- endTime:
- type: string
- format: date-time
- attributes:
- $ref: '#/components/schemas/LLMAttributes'
- required:
- - spanId
- - endTime
- - attributes
Span:
title: Span
type: object
@@ -294,7 +326,7 @@ components:
endTime:
type: string
format: date-time
- attributes: {}
+ metadata: {}
parentObservationId:
type: string
required:
@@ -303,80 +335,17 @@ components:
- type
- name
- startTime
- - attributes
- CreateLLMSpanRequest:
- title: CreateLLMSpanRequest
- type: object
- properties:
- traceId:
- type: string
- name:
- type: string
- startTime:
- type: string
- format: date-time
- endTime:
- type: string
- format: date-time
- parentObservationId:
- type: string
- attributes:
- $ref: '#/components/schemas/LLMAttributes'
- required:
- - name
- - startTime
- - attributes
- LLMAttributes:
- title: LLMAttributes
- type: object
- properties:
- model:
- type: string
- temperature:
- type: number
- format: double
- maxTokens:
- type: integer
- topP:
- type: number
- format: double
- prompt:
- type: array
- items:
- $ref: '#/components/schemas/LLMPrompt'
- completion:
- type: string
- tokens:
- $ref: '#/components/schemas/LLMTokens'
- LLMPrompt:
- title: LLMPrompt
- type: object
- properties:
- role:
- type: string
- content:
- type: string
- required:
- - role
- - content
- LLMTokens:
- title: LLMTokens
- type: object
- properties:
- promptAmount:
- type: integer
- completionAmount:
- type: integer
+ - metadata
CreateTraceRequest:
title: CreateTraceRequest
type: object
properties:
name:
type: string
- attributes: {}
+ metadata: {}
required:
- name
- - attributes
+ - metadata
Trace:
title: Trace
type: object
@@ -388,12 +357,12 @@ components:
format: date-time
name:
type: string
- attributes: {}
+ metadata: {}
required:
- id
- timestamp
- name
- - attributes
+ - metadata
securitySchemes:
BasicAuth:
type: http
diff --git a/prisma/migrations/20230620181114_restructure/migration.sql b/prisma/migrations/20230620181114_restructure/migration.sql
new file mode 100644
index 0000000000..c1ccb8f95f
--- /dev/null
+++ b/prisma/migrations/20230620181114_restructure/migration.sql
@@ -0,0 +1,28 @@
+/*
+ Warnings:
+ - THIS IS BREAKING
+
+*/
+-- AlterEnum
+BEGIN;
+CREATE TYPE "ObservationType_new" AS ENUM ('SPAN', 'EVENT', 'GENERATION');
+ALTER TABLE "observations" ALTER COLUMN "type" TYPE "ObservationType_new" USING ("type"::text::"ObservationType_new");
+ALTER TYPE "ObservationType" RENAME TO "ObservationType_old";
+ALTER TYPE "ObservationType_new" RENAME TO "ObservationType";
+DROP TYPE "ObservationType_old";
+COMMIT;
+
+-- AlterTable
+ALTER TABLE "observations" DROP COLUMN "attributes",
+ADD COLUMN "completion" TEXT,
+ADD COLUMN "metadata" JSONB,
+ADD COLUMN "model" TEXT,
+ADD COLUMN "modelParameters" JSONB,
+ADD COLUMN "prompt" JSONB,
+ADD COLUMN "usage" JSONB,
+ALTER COLUMN "name" DROP NOT NULL;
+
+-- AlterTable
+ALTER TABLE "traces" DROP COLUMN "attributes",
+ADD COLUMN "metadata" JSONB,
+ALTER COLUMN "name" DROP NOT NULL;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index bd43c91d90..92296a0089 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -112,12 +112,12 @@ enum MembershipRole {
}
model Trace {
- id String @id @default(cuid())
- timestamp DateTime @default(now())
- name String
- attributes Json
- projectId String @map("project_id")
- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+ id String @id @default(cuid())
+ timestamp DateTime @default(now())
+ name String?
+ metadata Json?
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
observations Observation[]
scores Score[]
@@ -130,14 +130,22 @@ model Observation {
traceId String @map("trace_id")
trace Trace @relation(fields: [traceId], references: [id], onDelete: Cascade)
type ObservationType
- name String
startTime DateTime @default(now()) @map("start_time")
endTime DateTime? @map("end_time")
- attributes Json
+ name String?
+ metadata Json?
parentObservationId String? @map("parent_observation_id")
- parent Observation? @relation("ParentChilds", fields: [parentObservationId], references: [id])
- childs Observation[] @relation("ParentChilds")
- scores Score[]
+
+ // GENERATION ONLY
+ model String?
+ modelParameters Json?
+ prompt Json?
+ completion String?
+ usage Json?
+
+ parent Observation? @relation("ParentChilds", fields: [parentObservationId], references: [id])
+ childs Observation[] @relation("ParentChilds")
+ scores Score[]
@@map("observations")
}
@@ -145,7 +153,7 @@ model Observation {
enum ObservationType {
SPAN
EVENT
- LLMCALL
+ GENERATION
}
model Score {
diff --git a/prisma/seed.ts b/prisma/seed.ts
index 9930d83435..251c2a124e 100755
--- a/prisma/seed.ts
+++ b/prisma/seed.ts
@@ -40,12 +40,12 @@ async function main() {
},
});
- for (let i = 0; i < 1000; i++) {
+ for (let i = 0; i < 10; i++) {
// print progress to console with a progress bar that refreshes every 10 iterations
if (i % 10 === 0) {
process.stdout.clearLine(0);
process.stdout.cursorTo(0);
- process.stdout.write(`Seeding ${i} of 1000`);
+ process.stdout.write(`Seeding ${i} of 10`);
}
// random date within last 90 days, with a linear bias towards more recent dates
const traceTs = new Date(
@@ -59,7 +59,7 @@ async function main() {
name: ["generate-outreach", "label-inbound", "draft-response"][
i % 3
] as string,
- attributes: {
+ metadata: {
user: `user-${i}@langfuse.com`,
},
project: {
@@ -114,7 +114,7 @@ async function main() {
startTime: spanTsStart,
endTime: spanTsEnd,
name: `span-${i}-${j}`,
- attributes: {
+ metadata: {
user: `user-${i}@langfuse.com`,
},
trace: {
@@ -141,35 +141,55 @@ async function main() {
for (let k = 0; k < Math.floor(Math.random() * 2) + 1; k++) {
// random start and end times within span
- const llmCallTsStart = new Date(
+ const generationTsStart = new Date(
spanTsStart.getTime() +
Math.floor(
Math.random() * (spanTsEnd.getTime() - spanTsStart.getTime())
)
);
- const llmCallTsEnd = new Date(
- llmCallTsStart.getTime() +
+ const generationTsEnd = new Date(
+ generationTsStart.getTime() +
Math.floor(
- Math.random() * (spanTsEnd.getTime() - llmCallTsStart.getTime())
+ Math.random() *
+ (spanTsEnd.getTime() - generationTsStart.getTime())
)
);
await prisma.observation.create({
data: {
- type: "LLMCALL",
- id: `llm-call-${Math.floor(Math.random() * 1000000000)}`,
- startTime: llmCallTsStart,
- endTime: llmCallTsEnd,
- name: `llm-call-${i}-${j}-${k}`,
- attributes: {
- user: `user-${i}@langfuse.com`,
- prompt: [
- {
- role: "user",
- content: "How can i create a React component?",
- },
- ],
- completion: `Creating a React component can be done in two ways: as a functional component or as a class component. Let's start with a basic example of both.
+ type: "GENERATION",
+ id: `generation-${Math.floor(Math.random() * 1000000000)}`,
+ startTime: generationTsStart,
+ endTime: generationTsEnd,
+ name: `generation-${i}-${j}-${k}`,
+ prompt:
+ Math.random() > 0.5
+ ? [
+ {
+ role: "system",
+ content: "Be a helpful assistant",
+ },
+ {
+ role: "user",
+ content: "How can i create a React component?",
+ },
+ ]
+ : {
+ input: "How can i create a React component?",
+ retrievedDocuments: [
+ {
+ title: "How to create a React component",
+ url: "https://www.google.com",
+ description: "A guide to creating React components",
+ },
+ {
+ title: "React component creation",
+ url: "https://www.google.com",
+ description: "A guide to creating React components",
+ },
+ ],
+ },
+ completion: `Creating a React component can be done in two ways: as a functional component or as a class component. Let's start with a basic example of both.
1. **Functional Component**:
@@ -198,7 +218,8 @@ async function main() {
With the advent of hooks in React, functional components can do everything that class components can do and hence, the community has been favoring functional components over class components.
Remember to import React at the top of your file whenever you're creating a component, because JSX transpiles to 'React.createElement' calls under the hood.`,
- model: Math.random() > 0.5 ? "gpt-3.5-turbo" : "gpt-4",
+ model: Math.random() > 0.5 ? "gpt-3.5-turbo" : "gpt-4",
+ modelParameters: {
temperature:
Math.random() > 0.9 ? undefined : Math.random().toFixed(2),
topP: Math.random() > 0.9 ? undefined : Math.random().toFixed(2),
@@ -206,10 +227,13 @@ async function main() {
Math.random() > 0.9
? undefined
: Math.floor(Math.random() * 1000),
- tokens: {
- promptAmount: Math.floor(Math.random() * 1000) + 300,
- completionAmount: Math.floor(Math.random() * 500) + 100,
- },
+ },
+ metadata: {
+ user: `user-${i}@langfuse.com`,
+ },
+ usage: {
+ promptTokens: Math.floor(Math.random() * 1000) + 300,
+ completionTokens: Math.floor(Math.random() * 500) + 100,
},
parent: {
connect: {
@@ -239,7 +263,7 @@ async function main() {
id: `event-${Math.floor(Math.random() * 1000000000)}`,
startTime: eventTs,
name: `event-${i}-${j}-${k}-${l}`,
- attributes: {
+ metadata: {
user: `user-${i}@langfuse.com`,
},
parent: {
diff --git a/src/components/layouts/layout.tsx b/src/components/layouts/layout.tsx
index 4d27ffbbfa..6e196a196f 100644
--- a/src/components/layouts/layout.tsx
+++ b/src/components/layouts/layout.tsx
@@ -49,8 +49,8 @@ export default function Layout(props: PropsWithChildren) {
icon: UsersIcon,
},
{
- name: "LLM Calls",
- pathname: `/project/[projectId]/llm-calls`,
+ name: "Generations",
+ pathname: `/project/[projectId]/generations`,
icon: DocumentDuplicateIcon,
},
{
@@ -69,9 +69,9 @@ export default function Layout(props: PropsWithChildren) {
...nav,
href: nav.pathname.replace("[projectId]", projectId ?? ""),
}))
- .map((staticAttributes) => ({
- ...staticAttributes,
- current: router.pathname === staticAttributes.pathname,
+ .map((params) => ({
+ ...params,
+ current: router.pathname === params.pathname,
}));
const session = useSession();
diff --git a/src/components/observation-display.tsx b/src/components/observation-display.tsx
index 9d34e7911a..5b6138c425 100644
--- a/src/components/observation-display.tsx
+++ b/src/components/observation-display.tsx
@@ -37,10 +37,10 @@ export default function ObservationDisplay(props: {
<span className="sr-only">Toggle</span>
</Button>
</CollapsibleTrigger>
- {props.obs.type === "LLMCALL" ? (
+ {props.obs.type === "GENERATION" ? (
<Button size="sm" variant="ghost" asChild>
<Link
- href={`/project/${props.projectId}/llm-calls/${props.obs.id}`}
+ href={`/project/${props.projectId}/generations/${props.obs.id}`}
>
<ArrowUpRight className="h-4 w-4" />
</Link>
@@ -49,8 +49,8 @@ export default function ObservationDisplay(props: {
</div>
<CollapsibleContent>
<div className="mb-4 space-y-2">
- <span className="text-sm font-semibold">Attributes</span>
- <JSONview json={props.obs.attributes} />
+ <span className="text-sm font-semibold">Metadata</span>
+ <JSONview json={props.obs.metadata} />
</div>
</CollapsibleContent>
</Collapsible>
diff --git a/src/components/prompts.tsx b/src/components/prompts.tsx
index d6cfaf024d..d06e3180b1 100644
--- a/src/components/prompts.tsx
+++ b/src/components/prompts.tsx
@@ -1,7 +1,7 @@
import { CodeView } from "@/src/components/ui/code";
-import { type LLMMessages } from "@/src/utils/types";
+import { type LLMChatMessages } from "@/src/utils/types";
-export default function Prompt(props: { messages: LLMMessages[] }) {
+export default function Prompt(props: { messages: LLMChatMessages[] }) {
return (
<>
{props.messages.map((message, index) => (
diff --git a/src/components/ui/code.tsx b/src/components/ui/code.tsx
index e4c4659f5f..1b9d0e816d 100644
--- a/src/components/ui/code.tsx
+++ b/src/components/ui/code.tsx
@@ -13,7 +13,7 @@ export function JSONview(props: { json: string | unknown }) {
}
export function CodeView(props: {
- children: string | undefined;
+ children: string | undefined | null;
className?: string;
}) {
const [isCopied, setIsCopied] = useState(false);
diff --git a/src/features/dashboard/components/charts.tsx b/src/features/dashboard/components/charts.tsx
index 7f96dd0aa8..82c7e1a0e5 100644
--- a/src/features/dashboard/components/charts.tsx
+++ b/src/features/dashboard/components/charts.tsx
@@ -10,11 +10,11 @@ import { BaseTimeSeriesChart } from "./BaseTimeSeriesChart";
import { type DateTimeAggregationOption } from "@/src/features/dashboard/lib/timeseriesAggregation";
import { Loader } from "lucide-react";
-export function ChartLlmCalls(props: {
+export function ChartGenerations(props: {
agg: DateTimeAggregationOption;
projectId: string;
}) {
- const data = api.dashboard.llmCalls.useQuery({
+ const data = api.dashboard.generations.useQuery({
agg: props.agg,
projectId: props.projectId,
});
@@ -22,7 +22,7 @@ export function ChartLlmCalls(props: {
return (
<Card>
<CardHeader className="relative">
- <CardTitle>LLM calls</CardTitle>
+ <CardTitle>Generations</CardTitle>
<CardDescription>Count</CardDescription>
{data.isLoading ? (
<div className="absolute right-5 top-5 ">
diff --git a/src/features/dashboard/server/dashboardRouter.ts b/src/features/dashboard/server/dashboardRouter.ts
index affcb424c7..5d8fd57d69 100644
--- a/src/features/dashboard/server/dashboardRouter.ts
+++ b/src/features/dashboard/server/dashboardRouter.ts
@@ -10,7 +10,7 @@ import {
} from "@/src/server/api/trpc";
export const dashboardRouter = createTRPCRouter({
- llmCalls: protectedProjectProcedure
+ generations: protectedProjectProcedure
.input(
z.object({
projectId: z.string(),
@@ -47,7 +47,7 @@ export const dashboardRouter = createTRPCRouter({
LEFT JOIN traces ON observations.trace_id = traces.id
WHERE
- type = 'LLMCALL'
+ type = 'GENERATION'
AND start_time > NOW() - INTERVAL '${input.agg}'
AND traces.project_id = '${input.projectId}'
diff --git a/src/pages/api/public/events.ts b/src/pages/api/public/events.ts
index 56e2d283a2..e6a201b5cf 100644
--- a/src/pages/api/public/events.ts
+++ b/src/pages/api/public/events.ts
@@ -10,7 +10,7 @@ const ObservationSchema = z.object({
traceId: z.string(),
name: z.string(),
startTime: z.string().datetime(),
- attributes: z.record(z.string(), z.any()),
+ metadata: z.record(z.string(), z.any()),
parentObservationId: z.string().optional(),
});
@@ -36,7 +36,7 @@ export default async function handler(
// END CHECK AUTH
try {
- const { traceId, name, startTime, attributes, parentObservationId } =
+ const { traceId, name, startTime, metadata, parentObservationId } =
ObservationSchema.parse(req.body);
// CHECK ACCESS SCOPE
@@ -59,7 +59,7 @@ export default async function handler(
type: ObservationType.EVENT,
name,
startTime: new Date(startTime),
- attributes,
+ metadata,
parent: parentObservationId
? { connect: { id: parentObservationId } }
: undefined,
diff --git a/src/pages/api/public/llm-span.ts b/src/pages/api/public/generations.ts
similarity index 51%
rename from src/pages/api/public/llm-span.ts
rename to src/pages/api/public/generations.ts
index 1f39d224b5..fd9b8e7ac3 100644
--- a/src/pages/api/public/llm-span.ts
+++ b/src/pages/api/public/generations.ts
@@ -3,56 +3,38 @@ import { ObservationType, Prisma } from "@prisma/client";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { cors, runMiddleware } from "./cors";
-import { merge } from "lodash";
import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/apiAuth";
import { checkApiAccessScope } from "@/src/features/publicApi/server/apiScope";
-const LLMSpanCreateSchema = z.object({
+const GenerationsCreateSchema = z.object({
traceId: z.string().nullish(),
- name: z.string(),
- startTime: z.string().datetime(),
+ name: z.string().nullish(),
+ startTime: z.string().datetime().nullish(),
endTime: z.string().datetime().nullish(),
- attributes: z.object({
- prompt: z
- .array(z.object({ role: z.string(), content: z.string() }))
- .nullish(),
- completion: z.string().nullish(),
- tokens: z
- .object({
- promptAmount: z.number().nullish(),
- completionAmount: z.number().nullish(),
- })
- .nullish(),
- model: z.string().nullish(),
- temperature: z.number().nullish(),
- topP: z.number().nullish(),
- maxTokens: z.number().nullish(),
+ model: z.string().nullish(),
+ modelParameters: z
+ .record(
+ z.string(),
+ z.union([z.string(), z.number(), z.boolean()]).nullish()
+ )
+ .nullish(),
+ prompt: z.unknown().nullish(),
+ completion: z.string().nullish(),
+ usage: z.object({
+ promptTokens: z.number().nullish(),
+ completionTokens: z.number().nullish(),
}),
+ metadata: z.unknown().nullish(),
parentObservationId: z.string().nullish(),
});
-const LLMSpanUpdateSchema = z.object({
- spanId: z.string(),
- endTime: z.string().datetime(),
- attributes: z.object({
- prompt: z.string().nullish(),
- completion: z.string().nullish(),
- tokens: z
- .object({
- promptAmount: z.number().nullish(),
- completionAmount: z.number().nullish(),
- })
- .nullish(),
- }),
-});
-
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
await runMiddleware(req, res, cors);
- if (req.method !== "POST" && req.method !== "PATCH") {
+ if (req.method !== "POST") {
return res.status(405).json({ message: "Method not allowed" });
}
@@ -69,16 +51,21 @@ export default async function handler(
if (req.method === "POST") {
try {
+ console.log(JSON.stringify(req.body));
+
const {
traceId,
name,
startTime,
endTime,
- attributes,
+ model,
+ modelParameters,
+ prompt,
+ completion,
+ usage,
+ metadata,
parentObservationId,
- } = LLMSpanCreateSchema.parse(req.body);
-
- console.log("attributes", attributes);
+ } = GenerationsCreateSchema.parse(req.body);
// CHECK ACCESS SCOPE
const accessCheck = await checkApiAccessScope(authCheck.scope, [
@@ -94,6 +81,40 @@ export default async function handler(
});
// END CHECK ACCESS SCOPE
+ console.log(
+ JSON.stringify(
+ {
+ data: {
+ ...(traceId
+ ? { trace: { connect: { id: traceId } } }
+ : {
+ trace: {
+ create: {
+ name: name,
+ attributes: Prisma.JsonNull,
+ project: { connect: { id: authCheck.scope.projectId } },
+ },
+ },
+ }),
+ type: ObservationType.GENERATION,
+ name,
+ startTime: startTime ? new Date(startTime) : undefined,
+ endTime: endTime ? new Date(endTime) : undefined,
+ metadata: metadata ? metadata : undefined,
+ model: model ? model : undefined,
+ modelParameters: modelParameters ? modelParameters : undefined,
+ prompt: prompt ? prompt : undefined,
+ completion: completion ? completion : undefined,
+ usage: usage ? usage : undefined,
+ parent: parentObservationId
+ ? { connect: { id: parentObservationId } }
+ : undefined,
+ },
+ },
+ null,
+ 2
+ )
+ );
const newObservation = await prisma.observation.create({
data: {
...(traceId
@@ -107,62 +128,22 @@ export default async function handler(
},
},
}),
- type: ObservationType.LLMCALL,
+ type: ObservationType.GENERATION,
name,
- startTime: new Date(startTime),
+ startTime: startTime ? new Date(startTime) : undefined,
endTime: endTime ? new Date(endTime) : undefined,
- attributes,
+ metadata: metadata ? metadata : undefined,
+ model: model ? model : undefined,
+ modelParameters: modelParameters ? modelParameters : undefined,
+ prompt: prompt ? prompt : undefined,
+ completion: completion ? completion : undefined,
+ usage: usage ? usage : undefined,
parent: parentObservationId
? { connect: { id: parentObservationId } }
: undefined,
},
});
- res.status(201).json(newObservation);
- } catch (error: unknown) {
- const errorMessage =
- error instanceof Error ? error.message : "An unknown error occurred";
- res.status(400).json({
- success: false,
- message: "Invalid request data",
- error: errorMessage,
- });
- }
- } else if (req.method === "PATCH") {
- try {
- const { spanId, endTime, attributes } = LLMSpanUpdateSchema.parse(
- req.body
- );
-
- // CHECK ACCESS SCOPE
- const accessCheck = await checkApiAccessScope(authCheck.scope, [
- { type: "observation", id: spanId },
- ]);
- if (!accessCheck)
- return res.status(403).json({
- success: false,
- message: "Access denied",
- });
- // END CHECK ACCESS SCOPE
-
- const existingObservation = await prisma.observation.findUnique({
- where: { id: spanId },
- });
-
- if (!existingObservation) {
- return res.status(404).json({ message: "Span not found" });
- }
-
- const mergedAttributes = merge(
- existingObservation.attributes,
- attributes
- );
-
- const newObservation = await prisma.observation.update({
- where: { id: spanId },
- data: { endTime: new Date(endTime), attributes: mergedAttributes },
- });
-
res.status(201).json(newObservation);
} catch (error: unknown) {
const errorMessage =
diff --git a/src/pages/api/public/spans.ts b/src/pages/api/public/spans.ts
index 920ad655a7..97fca5006b 100644
--- a/src/pages/api/public/spans.ts
+++ b/src/pages/api/public/spans.ts
@@ -10,7 +10,7 @@ const SpanPostSchema = z.object({
traceId: z.string(),
name: z.string(),
startTime: z.string().datetime(),
- attributes: z.record(z.string(), z.any()),
+ metadata: z.record(z.string(), z.any()),
parentObservationId: z.string().optional(),
});
@@ -42,7 +42,7 @@ export default async function handler(
if (req.method === "POST") {
try {
- const { traceId, name, startTime, attributes, parentObservationId } =
+ const { traceId, name, startTime, metadata, parentObservationId } =
SpanPostSchema.parse(req.body);
// CHECK ACCESS SCOPE
@@ -65,7 +65,7 @@ export default async function handler(
type: ObservationType.SPAN,
name,
startTime: new Date(startTime),
- attributes,
+ metadata,
parent: parentObservationId
? { connect: { id: parentObservationId } }
: undefined,
diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.ts
index a4f2fe53b1..e9e40d0fdc 100644
--- a/src/pages/api/public/traces.ts
+++ b/src/pages/api/public/traces.ts
@@ -6,7 +6,7 @@ import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/
const CreateTraceSchema = z.object({
name: z.string(),
- attributes: z.record(z.string(), z.any()),
+ metadata: z.record(z.string(), z.any()).optional(),
});
export default async function handler(
@@ -32,7 +32,7 @@ export default async function handler(
// END CHECK AUTH
try {
- const { name, attributes } = CreateTraceSchema.parse(req.body);
+ const { name, metadata } = CreateTraceSchema.parse(req.body);
// CHECK ACCESS SCOPE
if (authCheck.scope.accessLevel !== "all")
@@ -47,7 +47,7 @@ export default async function handler(
timestamp: new Date(),
projectId: authCheck.scope.projectId,
name,
- attributes,
+ metadata,
},
});
diff --git a/src/pages/project/[projectId]/llm-calls.tsx b/src/pages/project/[projectId]/generations.tsx
similarity index 65%
rename from src/pages/project/[projectId]/llm-calls.tsx
rename to src/pages/project/[projectId]/generations.tsx
index 42e5aa9a88..9a499b49fd 100644
--- a/src/pages/project/[projectId]/llm-calls.tsx
+++ b/src/pages/project/[projectId]/generations.tsx
@@ -4,54 +4,50 @@ import { type ColumnDef } from "@tanstack/react-table";
import { DataTable } from "@/src/components/table/data-table";
import TableLink from "@/src/components/table/table-link";
import { DataTableToolbar } from "@/src/components/table/data-table-toolbar";
-import {
- type RouterOutput,
- type RouterInput,
- type LLMMessages,
-} from "@/src/utils/types";
+import { type RouterOutput, type RouterInput } from "@/src/utils/types";
import { useState } from "react";
import { type TableRowOptions } from "@/src/components/table/types";
import { useRouter } from "next/router";
-import Prompt from "@/src/components/prompts";
-type LlmCallTableRow = {
+// TODO Marc
+type GenerationTableRow = {
id: string;
traceId: string;
- startTime: Date;
- endTime?: Date;
- name: string;
- prompt?: LLMMessages[];
- completion?: string;
+ startTime: string;
+ endTime?: string;
+ name?: string;
+ // prompt?: string;
+ // completion?: string;
model?: string;
};
-export type LlmCallFilterInput = Omit<
- RouterInput["llmCalls"]["all"],
+export type GenerationFilterInput = Omit<
+ RouterInput["generations"]["all"],
"projectId"
>;
-export default function Traces() {
+export default function Generations() {
const router = useRouter();
const projectId = router.query.projectId as string;
- const [queryOptions, setQueryOptions] = useState<LlmCallFilterInput>({
+ const [queryOptions, setQueryOptions] = useState<GenerationFilterInput>({
traceId: null,
id: null,
});
- const llmCalls = api.llmCalls.all.useQuery(
+ const generations = api.generations.all.useQuery(
{ ...queryOptions, projectId },
{
refetchInterval: 5000,
}
);
- const llmCallOptions = api.llmCalls.availableFilterOptions.useQuery(
+ const generationOptions = api.generations.availableFilterOptions.useQuery(
{ ...queryOptions, projectId },
{ refetchInterval: 5000 }
);
- const columns: ColumnDef<LlmCallTableRow>[] = [
+ const columns: ColumnDef<GenerationTableRow>[] = [
{
accessorKey: "id",
header: "ID",
@@ -60,7 +56,7 @@ export default function Traces() {
const value = row.getValue("id");
return typeof value === "string" ? (
<TableLink
- path={`/project/${projectId}/llm-calls/${value}`}
+ path={`/project/${projectId}/generations/${value}`}
value={value}
/>
) : undefined;
@@ -112,22 +108,22 @@ export default function Traces() {
accessorKey: "name",
header: "Name",
},
- {
- accessorKey: "prompt",
- header: "Prompt",
- cell: ({ row }) => {
- const messages: LLMMessages[] = row.getValue("prompt");
- if (!messages || messages.length === 0) {
- return <>No prompt</>;
- }
+ // {
+ // accessorKey: "prompt",
+ // header: "Prompt",
+ // cell: ({ row }) => {
+ // const messages: LLMChatMessages[] = row.getValue("prompt");
+ // if (!messages || messages.length === 0) {
+ // return <>No prompt</>;
+ // }
- return <Prompt messages={messages} />;
- },
- },
- {
- accessorKey: "completion",
- header: "Completion",
- },
+ // return <Prompt messages={messages} />;
+ // },
+ // },
+ // {
+ // accessorKey: "completion",
+ // header: "Completion",
+ // },
{
accessorKey: "model",
header: "Model",
@@ -135,7 +131,7 @@ export default function Traces() {
];
const convertToOptions = (
- options: RouterOutput["llmCalls"]["availableFilterOptions"]
+ options: RouterOutput["generations"]["availableFilterOptions"]
): TableRowOptions[] => {
return options.map((o) => {
return {
@@ -147,30 +143,30 @@ export default function Traces() {
});
};
- const tableOptions = llmCallOptions.isLoading
+ const tableOptions = generationOptions.isLoading
? { isLoading: true, isError: false }
- : llmCallOptions.isError
+ : generationOptions.isError
? {
isLoading: false,
isError: true,
- error: llmCallOptions.error.message,
+ error: generationOptions.error.message,
}
: {
isLoading: false,
isError: false,
- data: convertToOptions(llmCallOptions.data),
+ data: convertToOptions(generationOptions.data),
};
- const rows: LlmCallTableRow[] = llmCalls.isSuccess
- ? llmCalls.data.map((llmCall) => ({
- id: llmCall.id,
- traceId: llmCall.traceId,
- startTime: llmCall.startTime,
- endTime: llmCall.endTime ?? undefined,
- name: llmCall.name,
- prompt: llmCall.attributes.prompt,
- completion: llmCall.attributes.completion,
- model: JSON.stringify(llmCall.attributes.model),
+ const rows: GenerationTableRow[] = generations.isSuccess
+ ? generations.data.map((generation) => ({
+ id: generation.id,
+ traceId: generation.traceId,
+ startTime: generation.startTime.toISOString(),
+ endTime: generation.endTime?.toISOString() ?? undefined,
+ name: generation.name ?? undefined,
+ // prompt: JSON.stringify(generation.prompt),
+ // completion: generation.completion ?? undefined,
+ model: JSON.stringify(generation.model),
}))
: [];
@@ -185,7 +181,7 @@ export default function Traces() {
return (
<div className="container">
- <Header title="LLM Calls" live />
+ <Header title="Generations" live />
{tableOptions.data ? (
<div className="my-2">
<DataTableToolbar
@@ -199,13 +195,13 @@ export default function Traces() {
<DataTable
columns={columns}
data={
- llmCalls.isLoading
+ generations.isLoading
? { isLoading: true, isError: false }
- : llmCalls.isError
+ : generations.isError
? {
isLoading: false,
isError: true,
- error: llmCalls.error.message,
+ error: generations.error.message,
}
: {
isLoading: false,
diff --git a/src/pages/project/[projectId]/llm-calls/[llmCallId].tsx b/src/pages/project/[projectId]/generations/[generationId].tsx
similarity index 55%
rename from src/pages/project/[projectId]/llm-calls/[llmCallId].tsx
rename to src/pages/project/[projectId]/generations/[generationId].tsx
index 9ba4d49311..44496a4a2b 100644
--- a/src/pages/project/[projectId]/llm-calls/[llmCallId].tsx
+++ b/src/pages/project/[projectId]/generations/[generationId].tsx
@@ -1,5 +1,5 @@
import { Button } from "@/src/components/ui/button";
-import { CodeView } from "@/src/components/ui/code";
+import { CodeView, JSONview } from "@/src/components/ui/code";
import DescriptionList from "@/src/components/ui/description-lists";
import { ArrowUpRight } from "lucide-react";
import Link from "next/link";
@@ -8,50 +8,54 @@ import Header from "@/src/components/layouts/header";
import { api } from "@/src/utils/api";
import StatsCards from "@/src/components/stats-cards";
-import Prompt from "@/src/components/prompts";
+// import Prompt from "@/src/components/prompts";
-export default function LlmCallPage() {
+export default function GenerationPage() {
const router = useRouter();
- const llmCallId = router.query.llmCallId as string;
+ const generationId = router.query.generationId as string;
const projectId = router.query.projectId as string;
- const llmCall = api.llmCalls.byId.useQuery(llmCallId, {
- enabled: llmCallId !== undefined,
+ const generation = api.generations.byId.useQuery(generationId, {
+ enabled: generationId !== undefined,
});
const obsMetrics =
- llmCall.data?.scores.filter(
- (score) => score.observationId === llmCall.data.id
+ generation.data?.scores.filter(
+ (score) => score.observationId === generation.data.id
) ?? [];
const traceScores =
- llmCall.data?.scores.filter((score) => !obsMetrics?.includes(score)) ?? [];
+ generation.data?.scores.filter((score) => !obsMetrics?.includes(score)) ??
+ [];
const statProps = [
- { name: "Model", stat: llmCall.data?.attributes.model ?? "-" },
+ { name: "Model", stat: generation.data?.model ?? "-" },
{
name: "Temperature",
- stat: llmCall.data?.attributes.temperature?.toString() ?? "-",
+ stat: generation.data?.modelParameters?.temperature?.toString() ?? "-",
},
{
name: "Max Tokens",
- stat: llmCall.data?.attributes.maxTokens?.toString() ?? "-",
+ stat: generation.data?.modelParameters?.maxTokens?.toString() ?? "-",
+ },
+ {
+ name: "Top P",
+ stat: generation.data?.modelParameters?.topP?.toString() ?? "-",
},
- { name: "Top P", stat: llmCall.data?.attributes.topP?.toString() ?? "-" },
];
return (
<div className="container">
<Header
- title="LLM Call"
+ title="Generation"
breadcrumb={[
- { name: "LLM Calls", href: `/project/${projectId}/llm-calls` },
- { name: llmCallId },
+ { name: "Generations", href: `/project/${projectId}/generations` },
+ { name: generationId },
]}
/>
<div className="my-10">
<StatsCards stats={statProps} />
</div>
- {llmCall.data ? (
+ {generation.data ? (
<DescriptionList
items={[
{
@@ -59,9 +63,9 @@ export default function LlmCallPage() {
value: (
<Button variant="secondary" asChild>
<Link
- href={`/project/${projectId}/traces/${llmCall.data.traceId}`}
+ href={`/project/${projectId}/traces/${generation.data.traceId}`}
>
- {llmCall.data.traceId}
+ {generation.data.traceId}
<ArrowUpRight className="ml-2 h-4 w-4" />
</Link>
</Button>
@@ -70,38 +74,42 @@ export default function LlmCallPage() {
{
label: "Time",
value:
- llmCall.data.startTime.toLocaleString() +
- (llmCall.data.endTime
+ generation.data.startTime.toLocaleString() +
+ (generation.data.endTime
? ` - ${
- llmCall.data.endTime.getTime() -
- llmCall.data.startTime.getTime()
+ generation.data.endTime.getTime() -
+ generation.data.startTime.getTime()
}ms`
: ""),
},
{
label: "Name",
- value: llmCall.data.name,
+ value: generation.data.name,
},
{
label: "Tokens",
value: [
- llmCall.data.attributes.tokens?.promptAmount &&
- `${llmCall.data.attributes.tokens.promptAmount} prompt tokens`,
- llmCall.data.attributes.tokens?.completionAmount &&
- `${llmCall.data.attributes.tokens.completionAmount} completion tokens`,
+ generation.data.usage?.promptTokens &&
+ `${generation.data.usage.promptTokens} prompt tokens`,
+ generation.data.usage?.completionTokens &&
+ `${generation.data.usage.completionTokens} completion tokens`,
]
.filter(Boolean)
.join(", "),
},
{
label: "Prompt",
- value: llmCall.data.attributes.prompt ? (
- <Prompt messages={llmCall.data.attributes.prompt} />
+ value: generation.data.prompt ? (
+ <JSONview json={generation.data.prompt} />
) : undefined,
},
{
label: "Completion",
- value: <CodeView>{llmCall.data.attributes.completion}</CodeView>,
+ value: <CodeView>{generation.data.completion}</CodeView>,
+ },
+ {
+ label: "Metadata",
+ value: <JSONview json={generation.data.metadata} />,
},
{
label: "Metrics (observation)",
diff --git a/src/pages/project/[projectId]/index.tsx b/src/pages/project/[projectId]/index.tsx
index 7fbdf18603..2960197a6c 100644
--- a/src/pages/project/[projectId]/index.tsx
+++ b/src/pages/project/[projectId]/index.tsx
@@ -6,7 +6,7 @@ import {
type DateTimeAggregationOption,
} from "@/src/features/dashboard/lib/timeseriesAggregation";
import {
- ChartLlmCalls,
+ ChartGenerations,
ChartScores,
ChartTraces,
} from "@/src/features/dashboard/components/charts";
@@ -35,7 +35,7 @@ export default function Start() {
</Tabs>
<div className="grid gap-4 xl:grid-cols-2">
<ChartTraces agg={agg} projectId={projectId} />
- <ChartLlmCalls agg={agg} projectId={projectId} />
+ <ChartGenerations agg={agg} projectId={projectId} />
<div className="col-span-full">
<ChartScores agg={agg} projectId={projectId} />
</div>
diff --git a/src/pages/project/[projectId]/scores.tsx b/src/pages/project/[projectId]/scores.tsx
index 96adc9fe18..ecb893bc18 100644
--- a/src/pages/project/[projectId]/scores.tsx
+++ b/src/pages/project/[projectId]/scores.tsx
@@ -14,7 +14,7 @@ import { useRouter } from "next/router";
type RowData = {
id: string;
traceId: string;
- timestamp: Date;
+ timestamp: string;
name: string;
value: number;
observationId?: string;
@@ -40,7 +40,7 @@ export default function ScoresPage() {
}
);
- const llmCallOptions = api.llmCalls.availableFilterOptions.useQuery(
+ const generationOptions = api.generations.availableFilterOptions.useQuery(
{
...queryOptions,
projectId,
@@ -127,24 +127,24 @@ export default function ScoresPage() {
});
};
- const tableOptions = llmCallOptions.isLoading
+ const tableOptions = generationOptions.isLoading
? { isLoading: true, isError: false }
- : llmCallOptions.isError
+ : generationOptions.isError
? {
isLoading: false,
isError: true,
- error: llmCallOptions.error.message,
+ error: generationOptions.error.message,
}
: {
isLoading: false,
isError: false,
- data: convertToOptions(llmCallOptions.data),
+ data: convertToOptions(generationOptions.data),
};
const convertToTableRow = (score: Score): RowData => {
return {
id: score.id,
- timestamp: score.timestamp,
+ timestamp: score.timestamp.toISOString(),
name: score.name,
value: score.value,
observationId: score.observationId ?? undefined,
diff --git a/src/pages/project/[projectId]/traces.tsx b/src/pages/project/[projectId]/traces.tsx
index eb0b97f815..a0c1fbb268 100644
--- a/src/pages/project/[projectId]/traces.tsx
+++ b/src/pages/project/[projectId]/traces.tsx
@@ -32,9 +32,9 @@ export type TableScore = {
export type TraceTableRow = {
id: string;
- timestamp: Date;
+ timestamp: string;
name: string;
- attributes?: string;
+ metadata?: string;
scores: TableScore[];
};
@@ -77,9 +77,9 @@ export default function Traces() {
): TraceTableRow => {
return {
id: trace.id,
- timestamp: trace.timestamp,
- name: trace.name,
- attributes: JSON.stringify(trace.attributes),
+ timestamp: trace.timestamp.toISOString(),
+ name: trace.name ?? "",
+ metadata: JSON.stringify(trace.metadata),
scores: trace.scores.map((score) => {
return {
name: score.name,
@@ -147,8 +147,8 @@ export default function Traces() {
},
},
{
- accessorKey: "attributes",
- header: "Attributes",
+ accessorKey: "metadata",
+ header: "Metadata",
},
{
accessorKey: "scores",
diff --git a/src/pages/project/[projectId]/traces/[traceId].tsx b/src/pages/project/[projectId]/traces/[traceId].tsx
index c636b69f82..67562a1371 100644
--- a/src/pages/project/[projectId]/traces/[traceId].tsx
+++ b/src/pages/project/[projectId]/traces/[traceId].tsx
@@ -44,8 +44,8 @@ export default function TracePage() {
),
},
{
- label: "Attributes",
- value: <JSONview json={trace.data.attributes} />,
+ label: "Metadata",
+ value: <JSONview json={trace.data.metadata} />,
},
{
label: "Detailed trace",
diff --git a/src/server/api/root.ts b/src/server/api/root.ts
index 55b6154c0d..941a61be11 100644
--- a/src/server/api/root.ts
+++ b/src/server/api/root.ts
@@ -1,6 +1,6 @@
import { createTRPCRouter } from "@/src/server/api/trpc";
import { traceRouter } from "./routers/traces";
-import { llmCallRouter } from "./routers/llmCalls";
+import { generationsRouter } from "./routers/generations";
import { scoresRouter } from "./routers/scores";
import { dashboardRouter } from "@/src/features/dashboard/server/dashboardRouter";
import { projectsRouter } from "@/src/features/projects/server/projectsRouter";
@@ -13,7 +13,7 @@ import { apiKeysRouter } from "@/src/features/publicApi/server/apiKeyRouter";
*/
export const appRouter = createTRPCRouter({
traces: traceRouter,
- llmCalls: llmCallRouter,
+ generations: generationsRouter,
scores: scoresRouter,
dashboard: dashboardRouter,
projects: projectsRouter,
diff --git a/src/server/api/routers/llmCalls.ts b/src/server/api/routers/generations.ts
similarity index 80%
rename from src/server/api/routers/llmCalls.ts
rename to src/server/api/routers/generations.ts
index f5e2aa6768..f9b3a3a6d6 100644
--- a/src/server/api/routers/llmCalls.ts
+++ b/src/server/api/routers/generations.ts
@@ -5,21 +5,21 @@ import {
protectedProcedure,
protectedProjectProcedure,
} from "@/src/server/api/trpc";
-import { type LlmCall } from "@/src/utils/types";
+import { type Generation } from "@/src/utils/types";
-const LLMFilterOptions = z.object({
+const GenerationFilterOptions = z.object({
traceId: z.array(z.string()).nullable(),
id: z.array(z.string()).nullable(),
projectId: z.string(), // Required for protectedProjectProcedure
});
-export const llmCallRouter = createTRPCRouter({
+export const generationsRouter = createTRPCRouter({
all: protectedProjectProcedure
- .input(LLMFilterOptions)
+ .input(GenerationFilterOptions)
.query(async ({ input, ctx }) => {
- const llmCalls = (await ctx.prisma.observation.findMany({
+ const generations = (await ctx.prisma.observation.findMany({
where: {
- type: "LLMCALL",
+ type: "GENERATION",
trace: {
projectId: input.projectId,
},
@@ -38,13 +38,13 @@ export const llmCallRouter = createTRPCRouter({
startTime: "desc",
},
take: 100, // TODO: pagination
- })) as LlmCall[];
+ })) as Generation[];
- return llmCalls;
+ return generations;
}),
availableFilterOptions: protectedProjectProcedure
- .input(LLMFilterOptions)
+ .input(GenerationFilterOptions)
.query(async ({ input, ctx }) => {
const filter = {
trace: {
@@ -65,7 +65,7 @@ export const llmCallRouter = createTRPCRouter({
const [ids, traceIds] = await Promise.all([
ctx.prisma.observation.groupBy({
where: {
- type: "LLMCALL",
+ type: "GENERATION",
...filter,
},
by: ["id"],
@@ -75,7 +75,7 @@ export const llmCallRouter = createTRPCRouter({
}),
ctx.prisma.observation.groupBy({
where: {
- type: "LLMCALL",
+ type: "GENERATION",
...filter,
},
by: ["traceId"],
@@ -102,10 +102,10 @@ export const llmCallRouter = createTRPCRouter({
}),
byId: protectedProcedure.input(z.string()).query(async ({ input, ctx }) => {
// also works for other observations
- const llmCall = (await ctx.prisma.observation.findFirstOrThrow({
+ const generation = (await ctx.prisma.observation.findFirstOrThrow({
where: {
id: input,
- type: "LLMCALL",
+ type: "GENERATION",
trace: {
project: {
members: {
@@ -116,15 +116,15 @@ export const llmCallRouter = createTRPCRouter({
},
},
},
- })) as LlmCall;
+ })) as Generation;
// No need to check for permissions as user has access to the trace
const scores = await ctx.prisma.score.findMany({
where: {
- traceId: llmCall.traceId,
+ traceId: generation.traceId,
},
});
- return { ...llmCall, scores };
+ return { ...generation, scores };
}),
});
diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.ts
index 860f6afba1..2539066c1f 100644
--- a/src/server/api/routers/traces.ts
+++ b/src/server/api/routers/traces.ts
@@ -141,7 +141,7 @@ export const traceRouter = createTRPCRouter({
{
key: "name",
occurrences: names.map((i) => {
- return { key: i.name, count: i._count };
+ return { key: i.name ?? "undefined", count: i._count };
}),
},
{
diff --git a/src/utils/types.ts b/src/utils/types.ts
index aa0342f937..6dcadf92c6 100644
--- a/src/utils/types.ts
+++ b/src/utils/types.ts
@@ -6,7 +6,7 @@ export type NestedObservation = Observation & {
children: NestedObservation[];
};
-export type TypedObservation = Event | Span | LlmCall;
+export type TypedObservation = Event | Span | Generation;
export type Event = Observation & {
type: "EVENT";
@@ -17,21 +17,17 @@ export type Span = Observation & {
endTime: Date; // not null
};
-export type LLMMessages = { role: string; content: string };
+export type LLMChatMessages = { role: string; content: string };
-export type LlmCall = Observation & {
- type: "LLMCALL";
- attributes: {
- prompt?: LLMMessages[];
- completion?: string;
- tokens?: {
- promptAmount?: number;
- completionAmount?: number;
- };
- model?: string;
- temperature?: number;
- topP?: number;
- maxTokens?: number;
+export type Generation = Observation & {
+ type: "GENERATION";
+ usage: {
+ promptTokens?: number;
+ completionTokens?: number;
+ totalTokens?: number;
+ };
+ modelParameters: {
+ [key: string]: string | number | boolean;
};
};