🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
Feature/lf 146 log llm calls without having to create a trace before (#16)
Maximilian Deichmanncf0d2ab15dfb
diff --git a/fern/server/definition/span.yml b/fern/server/definition/span.ymlindex 627359a054..ae8db06062 100644--- a/fern/server/definition/span.yml+++ b/fern/server/definition/span.yml@@ -32,7 +32,7 @@ service:types:CreateSpanRequest:properties:- traceId: string+ traceId: optional<string>name: stringstartTime: datetimeattributes: unknown@@ -62,7 +62,7 @@ types:CreateLLMSpanRequest:properties:- traceId: string+ traceId: optional<string>name: stringstartTime: datetimeparentObservationId: optional<string>diff --git a/fern/server/definition/trace.yml b/fern/server/definition/trace.ymlindex 34d68f1f5e..7971fd9733 100644--- a/fern/server/definition/trace.yml+++ b/fern/server/definition/trace.yml@@ -10,36 +10,15 @@ service:path: /tracesrequest: CreateTraceRequestresponse: Trace- update:- docs: Update the status of a trace- method: PATCH- path: /traces- request: UpdateTraceRequest- response: Tracetypes:CreateTraceRequest:properties:name: stringattributes: unknown- status: TraceStatus- statusMessage: optional<string>- UpdateTraceRequest:- properties:- id: string- status: TraceStatus- statusMessage: optional<string>Trace:properties:id: stringtimestamp: datetimename: stringattributes: unknown- status: string- statusMessage: optional<string>-- TraceStatus:- enum:- - EXECUTING- - SUCCESS- - ERRORdiff --git a/generated/openapi-server/openapi.yml b/generated/openapi-server/openapi.ymlindex 19f544a9f0..615240e1cc 100644--- a/generated/openapi-server/openapi.yml+++ b/generated/openapi-server/openapi.yml@@ -149,26 +149,6 @@ paths:application/json:schema:$ref: '#/components/schemas/CreateTraceRequest'- patch:- description: Update the status of a trace- operationId: trace_update- tags:- - Trace- parameters: []- responses:- '200':- description: ''- content:- application/json:- schema:- $ref: '#/components/schemas/Trace'- security: *ref_0- requestBody:- required: true- content:- application/json:- schema:- $ref: '#/components/schemas/UpdateTraceRequest'components:schemas:CreateEventRequest:@@ -266,7 +246,6 @@ components:parentObservationId:type: stringrequired:- - traceId- name- startTime- attributes@@ -341,7 +320,6 @@ components:attributes:$ref: '#/components/schemas/LLMAttributes'required:- - traceId- name- startTime- attributes@@ -393,27 +371,9 @@ components:name:type: stringattributes: {}- status:- $ref: '#/components/schemas/TraceStatus'- statusMessage:- type: stringrequired:- name- attributes- - status- UpdateTraceRequest:- title: UpdateTraceRequest- type: object- properties:- id:- type: string- status:- $ref: '#/components/schemas/TraceStatus'- statusMessage:- type: string- required:- - id- - statusTrace:title: Tracetype: object@@ -426,23 +386,11 @@ components:name:type: stringattributes: {}- status:- type: string- statusMessage:- type: stringrequired:- id- timestamp- name- attributes- - status- TraceStatus:- title: TraceStatus- type: string- enum:- - EXECUTING- - SUCCESS- - ERRORsecuritySchemes:BasicAuth:type: httpdiff --git a/prisma/migrations/20230618125818_remove_status_from_trace/migration.sql b/prisma/migrations/20230618125818_remove_status_from_trace/migration.sqlnew file mode 100644index 0000000000..5651b88ac9--- /dev/null+++ b/prisma/migrations/20230618125818_remove_status_from_trace/migration.sql@@ -0,0 +1,10 @@+/*+ Warnings:++ - You are about to drop the column `status` on the `traces` table. All the data in the column will be lost.+ - You are about to drop the column `status_message` on the `traces` table. All the data in the column will be lost.++*/+-- AlterTable+ALTER TABLE "traces" DROP COLUMN "status",+DROP COLUMN "status_message";diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 33018fe2c9..bd43c91d90 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -112,14 +112,12 @@ enum MembershipRole {}model Trace {- id String @id @default(cuid())- timestamp DateTime @default(now())- name String- attributes Json- status String- statusMessage String? @map("status_message")- 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+ attributes Json+ projectId String @map("project_id")+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)observations Observation[]scores Score[]diff --git a/prisma/seed.ts b/prisma/seed.tsindex 0bfcdb8011..9930d83435 100755--- a/prisma/seed.ts+++ b/prisma/seed.ts@@ -62,7 +62,6 @@ async function main() {attributes: {user: `user-${i}@langfuse.com`,},- status: "success",project: {connect: {id: project.id,@@ -199,13 +198,17 @@ 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: {- name: Math.random() > 0.5 ? "gpt-3.5-turbo" : "gpt-4",- temperature: 0,- },+ model: Math.random() > 0.5 ? "gpt-3.5-turbo" : "gpt-4",+ temperature:+ Math.random() > 0.9 ? undefined : Math.random().toFixed(2),+ topP: Math.random() > 0.9 ? undefined : Math.random().toFixed(2),+ maxTokens:+ Math.random() > 0.9+ ? undefined+ : Math.floor(Math.random() * 1000),tokens: {- prompt: Math.floor(Math.random() * 1000) + 300,- completion: Math.floor(Math.random() * 500) + 100,+ promptAmount: Math.floor(Math.random() * 1000) + 300,+ completionAmount: Math.floor(Math.random() * 500) + 100,},},parent: {diff --git a/src/pages/api/public/llm-span.ts b/src/pages/api/public/llm-span.tsindex bb4444e3e5..bbe09f34c3 100644--- a/src/pages/api/public/llm-span.ts+++ b/src/pages/api/public/llm-span.ts@@ -1,5 +1,5 @@import { prisma } from "@/src/server/db";-import { ObservationType } from "@prisma/client";+import { ObservationType, Prisma } from "@prisma/client";import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";import { cors, runMiddleware } from "./cors";@@ -8,7 +8,7 @@ import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/import { checkApiAccessScope } from "@/src/features/publicApi/server/apiScope";const LLMSpanCreateSchema = z.object({- traceId: z.string(),+ traceId: z.string().nullish(),name: z.string(),startTime: z.string().datetime(),attributes: z.object({@@ -73,7 +73,7 @@ export default async function handler(// CHECK ACCESS SCOPEconst accessCheck = await checkApiAccessScope(authCheck.scope, [- { type: "trace", id: traceId },+ ...(traceId ? [{ type: "trace" as const, id: traceId }] : []),...(parentObservationId? [{ type: "observation" as const, id: parentObservationId }]: []),@@ -87,7 +87,17 @@ export default async function handler(const newObservation = await prisma.observation.create({data: {- trace: { connect: { id: traceId } },+ ...(traceId+ ? { trace: { connect: { id: traceId } } }+ : {+ trace: {+ create: {+ name: name,+ attributes: Prisma.JsonNull,+ project: { connect: { id: authCheck.scope.projectId } },+ },+ },+ }),type: ObservationType.LLMCALL,name,startTime: new Date(startTime),diff --git a/src/pages/api/public/traces.ts b/src/pages/api/public/traces.tsindex 45c894d070..a4f2fe53b1 100644--- a/src/pages/api/public/traces.ts+++ b/src/pages/api/public/traces.ts@@ -3,19 +3,10 @@ import { z } from "zod";import { cors, runMiddleware } from "./cors";import { prisma } from "@/src/server/db";import { verifyAuthHeaderAndReturnScope } from "@/src/features/publicApi/server/apiAuth";-import { checkApiAccessScope } from "@/src/features/publicApi/server/apiScope";const CreateTraceSchema = z.object({name: z.string(),attributes: z.record(z.string(), z.any()),- status: z.enum(["SUCCESS", "ERROR", "EXECUTING"]),- statusMessage: z.string().optional(),-});--const UpdateTraceSchema = z.object({- id: z.string(),- status: z.enum(["SUCCESS", "ERROR", "EXECUTING"]),- statusMessage: z.string().optional(),});export default async function handler(@@ -24,7 +15,7 @@ export default async function handler() {await runMiddleware(req, res, cors);- if (req.method !== "POST" && req.method !== "PATCH") {+ if (req.method !== "POST") {console.error(req.method, req.body);return res.status(405).json({ message: "Method not allowed" });}@@ -40,74 +31,34 @@ export default async function handler(});// END CHECK AUTH- if (req.method === "POST") {- try {- const { name, attributes, status, statusMessage } =- CreateTraceSchema.parse(req.body);-- // CHECK ACCESS SCOPE- if (authCheck.scope.accessLevel !== "all")- return res.status(403).json({- success: false,- message: "Access denied",- });- // END CHECK ACCESS SCOPE+ try {+ const { name, attributes } = CreateTraceSchema.parse(req.body);- const newTrace = await prisma.trace.create({- data: {- timestamp: new Date(),- projectId: authCheck.scope.projectId,- name,- attributes,- status,- statusMessage,- },- });-- res.status(201).json(newTrace);- } catch (error: unknown) {- const errorMessage =- error instanceof Error ? error.message : "An unknown error occurred";- res.status(400).json({+ // CHECK ACCESS SCOPE+ if (authCheck.scope.accessLevel !== "all")+ return res.status(403).json({success: false,- message: "Invalid request data",- error: errorMessage,+ message: "Access denied",});- }- } else if (req.method === "PATCH") {- try {- const { id, status, statusMessage } = UpdateTraceSchema.parse(req.body);-- // CHECK ACCESS SCOPE- const accessCheck = await checkApiAccessScope(authCheck.scope, [- { type: "trace", id },- ]);- if (!accessCheck)- return res.status(403).json({- success: false,- message: "Access denied",- });- // END CHECK ACCESS SCOPE+ // END CHECK ACCESS SCOPE- const updatedTrace = await prisma.trace.update({- where: {- id,- },- data: {- status,- statusMessage,- },- });+ const newTrace = await prisma.trace.create({+ data: {+ timestamp: new Date(),+ projectId: authCheck.scope.projectId,+ name,+ attributes,+ },+ });- res.status(201).json(updatedTrace);- } 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,- });- }+ res.status(201).json(newTrace);+ } 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,+ });}}diff --git a/src/pages/project/[projectId]/traces.tsx b/src/pages/project/[projectId]/traces.tsxindex 6a87cad238..eb0b97f815 100644--- a/src/pages/project/[projectId]/traces.tsx+++ b/src/pages/project/[projectId]/traces.tsx@@ -34,8 +34,6 @@ export type TraceTableRow = {id: string;timestamp: Date;name: string;- status: string;- statusMessage?: string;attributes?: string;scores: TableScore[];};@@ -49,7 +47,6 @@ export default function Traces() {scores: null,name: null,id: null,- status: null,});const [selectedScore, setSelectedScores] = useState<SelectedScoreFilter>({@@ -82,8 +79,6 @@ export default function Traces() {id: trace.id,timestamp: trace.timestamp,name: trace.name,- status: trace.status,- statusMessage: trace.statusMessage ?? undefined,attributes: JSON.stringify(trace.attributes),scores: trace.scores.map((score) => {return {@@ -151,25 +146,6 @@ export default function Traces() {},},},- {- accessorKey: "status",- header: "Status",- enableColumnFilter: true,- meta: {- label: "Status",- filter: {- type: "select",- values: queryOptions.status,- updateFunction: (newValues: string[] | null) => {- setQueryOptions({ ...queryOptions, status: newValues });- },- },- },- },- {- accessorKey: "statusMessage",- header: "Status Message",- },{accessorKey: "attributes",header: "Attributes",@@ -236,7 +212,6 @@ export default function Traces() {const isFiltered = () =>queryOptions.name !== null ||queryOptions.id !== null ||- queryOptions.status !== null ||queryOptions.scores !== null;const resetFilters = () => {@@ -244,7 +219,6 @@ export default function Traces() {scores: null,name: null,id: null,- status: null,});setSelectedScores({name: null,diff --git a/src/pages/project/[projectId]/traces/[traceId].tsx b/src/pages/project/[projectId]/traces/[traceId].tsxindex c89eb4dddb..c636b69f82 100644--- a/src/pages/project/[projectId]/traces/[traceId].tsx+++ b/src/pages/project/[projectId]/traces/[traceId].tsx@@ -32,14 +32,6 @@ export default function TracePage() {label: "Name",value: trace.data.name,},- {- label: "Status",- value:- trace.data.status +- (trace.data.statusMessage- ? ` (${trace.data.statusMessage})`- : ""),- },{label: "Metrics",value: (diff --git a/src/server/api/routers/traces.ts b/src/server/api/routers/traces.tsindex 90ce2a593a..860f6afba1 100644--- a/src/server/api/routers/traces.ts+++ b/src/server/api/routers/traces.ts@@ -20,7 +20,6 @@ const TraceFilterOptions = z.object({projectId: z.string(), // Required for protectedProjectProcedurename: z.array(z.string()).nullable(),id: z.array(z.string()).nullable(),- status: z.array(z.string()).nullable(),scores: ScoreFilter.nullable(),});@@ -45,13 +44,6 @@ export const traceRouter = createTRPCRouter({},}: undefined),- ...(input.status- ? {- status: {- in: input.status,- },- }- : undefined),...(input.scores? { scores: { some: createScoreCondition(input.scores) } }: undefined),@@ -90,13 +82,6 @@ export const traceRouter = createTRPCRouter({},}: undefined),- ...(input.status- ? {- status: {- in: input.status,- },- }- : undefined),...(input.scores? {scores: {@@ -106,7 +91,7 @@ export const traceRouter = createTRPCRouter({: undefined),};- const [ids, names, statuses] = await Promise.all([+ const [ids, names] = await Promise.all([ctx.prisma.trace.groupBy({where: filter,by: ["id"],@@ -122,14 +107,6 @@ export const traceRouter = createTRPCRouter({_all: true,},}),-- ctx.prisma.trace.groupBy({- where: filter,- by: ["status"],- _count: {- _all: true,- },- }),]);const scores = await ctx.prisma.score.groupBy({@@ -167,12 +144,6 @@ export const traceRouter = createTRPCRouter({return { key: i.name, count: i._count };}),},- {- key: "status",- occurrences: statuses.map((i) => {- return { key: i.status, count: i._count };- }),- },{key: "scores",occurrences: scoresArray.map((i) => {